• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2006 The Android Open Source Project
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 SkMath_DEFINED
9 #define SkMath_DEFINED
10 
11 #include "include/private/base/SkAssert.h"
12 #include "include/private/base/SkCPUTypes.h"
13 
14 #include <cstdint>
15 #include <climits>
16 
17 // Max Signed 16 bit value
18 static constexpr int16_t SK_MaxS16 = INT16_MAX;
19 static constexpr int16_t SK_MinS16 = -SK_MaxS16;
20 
21 static constexpr int32_t SK_MaxS32 = INT32_MAX;
22 static constexpr int32_t SK_MinS32 = -SK_MaxS32;
23 static constexpr int32_t SK_NaN32  = INT32_MIN;
24 
25 static constexpr int64_t SK_MaxS64 = INT64_MAX;
26 static constexpr int64_t SK_MinS64 = -SK_MaxS64;
27 
28 // 64bit -> 32bit utilities
29 
30 // Handy util that can be passed two ints, and will automatically promote to
31 // 64bits before the multiply, so the caller doesn't have to remember to cast
32 // e.g. (int64_t)a * b;
sk_64_mul(int64_t a,int64_t b)33 static inline int64_t sk_64_mul(int64_t a, int64_t b) {
34     return a * b;
35 }
36 
SkLeftShift(int32_t value,int32_t shift)37 static inline constexpr int32_t SkLeftShift(int32_t value, int32_t shift) {
38     return (int32_t) ((uint32_t) value << shift);
39 }
40 
SkLeftShift(int64_t value,int32_t shift)41 static inline constexpr int64_t SkLeftShift(int64_t value, int32_t shift) {
42     return (int64_t) ((uint64_t) value << shift);
43 }
44 
45 ///////////////////////////////////////////////////////////////////////////////
46 
47 /**
48  *  Returns true if value is a power of 2. Does not explicitly check for
49  *  value <= 0.
50  */
SkIsPow2(T value)51 template <typename T> constexpr inline bool SkIsPow2(T value) {
52     return (value & (value - 1)) == 0;
53 }
54 
55 ///////////////////////////////////////////////////////////////////////////////
56 
57 /**
58  *  Return a*b/((1 << shift) - 1), rounding any fractional bits.
59  *  Only valid if a and b are unsigned and <= 32767 and shift is > 0 and <= 8
60  */
SkMul16ShiftRound(U16CPU a,U16CPU b,int shift)61 static inline unsigned SkMul16ShiftRound(U16CPU a, U16CPU b, int shift) {
62     SkASSERT(a <= 32767);
63     SkASSERT(b <= 32767);
64     SkASSERT(shift > 0 && shift <= 8);
65     unsigned prod = a*b + (1 << (shift - 1));
66     return (prod + (prod >> shift)) >> shift;
67 }
68 
69 /**
70  *  Return a*b/255, rounding any fractional bits.
71  *  Only valid if a and b are unsigned and <= 32767.
72  */
SkMulDiv255Round(U16CPU a,U16CPU b)73 static inline U8CPU SkMulDiv255Round(U16CPU a, U16CPU b) {
74     return SkMul16ShiftRound(a, b, 8);
75 }
76 
77 #endif
78