1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkMathPriv_DEFINED
9#define SkMathPriv_DEFINED
10
11#include "SkMath.h"
12
13#ifdef SK_BUILD_FOR_IOS
14// The iOS ARM processor discards small denormalized numbers to go faster.
15// Algorithms that rely on denormalized numbers need alternative implementations.
16#define SK_DISCARD_DENORMALIZED_FOR_SPEED
17#endif
18
19/** Returns -1 if n < 0, else returns 0
20 */
21#define SkExtractSign(n)    ((int32_t)(n) >> 31)
22
23/** If sign == -1, returns -n, else sign must be 0, and returns n.
24 Typically used in conjunction with SkExtractSign().
25 */
26static inline int32_t SkApplySign(int32_t n, int32_t sign) {
27    SkASSERT(sign == 0 || sign == -1);
28    return (n ^ sign) - sign;
29}
30
31/** Return x with the sign of y */
32static inline int32_t SkCopySign32(int32_t x, int32_t y) {
33    return SkApplySign(x, SkExtractSign(x ^ y));
34}
35
36/** Given a positive value and a positive max, return the value
37 pinned against max.
38 Note: only works as long as max - value doesn't wrap around
39 @return max if value >= max, else value
40 */
41static inline unsigned SkClampUMax(unsigned value, unsigned max) {
42    if (value > max) {
43        value = max;
44    }
45    return value;
46}
47
48///////////////////////////////////////////////////////////////////////////////
49
50/** Return a*b/255, truncating away any fractional bits. Only valid if both
51 a and b are 0..255
52 */
53static inline U8CPU SkMulDiv255Trunc(U8CPU a, U8CPU b) {
54    SkASSERT((uint8_t)a == a);
55    SkASSERT((uint8_t)b == b);
56    unsigned prod = SkMulS16(a, b) + 1;
57    return (prod + (prod >> 8)) >> 8;
58}
59
60/** Return (a*b)/255, taking the ceiling of any fractional bits. Only valid if
61 both a and b are 0..255. The expected result equals (a * b + 254) / 255.
62 */
63static inline U8CPU SkMulDiv255Ceiling(U8CPU a, U8CPU b) {
64    SkASSERT((uint8_t)a == a);
65    SkASSERT((uint8_t)b == b);
66    unsigned prod = SkMulS16(a, b) + 255;
67    return (prod + (prod >> 8)) >> 8;
68}
69
70/** Just the rounding step in SkDiv255Round: round(value / 255)
71 */
72static inline unsigned SkDiv255Round(unsigned prod) {
73    prod += 128;
74    return (prod + (prod >> 8)) >> 8;
75}
76
77#endif
78