• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /** Returns -1 if n < 0, else returns 0
14  */
15 #define SkExtractSign(n)    ((int32_t)(n) >> 31)
16 
17 /** If sign == -1, returns -n, else sign must be 0, and returns n.
18  Typically used in conjunction with SkExtractSign().
19  */
SkApplySign(int32_t n,int32_t sign)20 static inline int32_t SkApplySign(int32_t n, int32_t sign) {
21     SkASSERT(sign == 0 || sign == -1);
22     return (n ^ sign) - sign;
23 }
24 
25 /** Return x with the sign of y */
SkCopySign32(int32_t x,int32_t y)26 static inline int32_t SkCopySign32(int32_t x, int32_t y) {
27     return SkApplySign(x, SkExtractSign(x ^ y));
28 }
29 
30 /** Given a positive value and a positive max, return the value
31  pinned against max.
32  Note: only works as long as max - value doesn't wrap around
33  @return max if value >= max, else value
34  */
SkClampUMax(unsigned value,unsigned max)35 static inline unsigned SkClampUMax(unsigned value, unsigned max) {
36     if (value > max) {
37         value = max;
38     }
39     return value;
40 }
41 
42 /** Computes the 64bit product of a * b, and then shifts the answer down by
43  shift bits, returning the low 32bits. shift must be [0..63]
44  e.g. to perform a fixedmul, call SkMulShift(a, b, 16)
45  */
46 int32_t SkMulShift(int32_t a, int32_t b, unsigned shift);
47 
48 /** Return the integer cube root of value, with a bias of bitBias
49  */
50 int32_t SkCubeRootBits(int32_t value, int bitBias);
51 
52 ///////////////////////////////////////////////////////////////////////////////
53 
54 /** Return a*b/255, truncating away any fractional bits. Only valid if both
55  a and b are 0..255
56  */
SkMulDiv255Trunc(U8CPU a,U8CPU b)57 static inline U8CPU SkMulDiv255Trunc(U8CPU a, U8CPU b) {
58     SkASSERT((uint8_t)a == a);
59     SkASSERT((uint8_t)b == b);
60     unsigned prod = SkMulS16(a, b) + 1;
61     return (prod + (prod >> 8)) >> 8;
62 }
63 
64 /** Return (a*b)/255, taking the ceiling of any fractional bits. Only valid if
65  both a and b are 0..255. The expected result equals (a * b + 254) / 255.
66  */
SkMulDiv255Ceiling(U8CPU a,U8CPU b)67 static inline U8CPU SkMulDiv255Ceiling(U8CPU a, U8CPU b) {
68     SkASSERT((uint8_t)a == a);
69     SkASSERT((uint8_t)b == b);
70     unsigned prod = SkMulS16(a, b) + 255;
71     return (prod + (prod >> 8)) >> 8;
72 }
73 
74 /** Just the rounding step in SkDiv255Round: round(value / 255)
75  */
SkDiv255Round(unsigned prod)76 static inline unsigned SkDiv255Round(unsigned prod) {
77     prod += 128;
78     return (prod + (prod >> 8)) >> 8;
79 }
80 
81 #endif
82