SkMathPriv.h revision 586b6a5e60a1e5c0e675cc42c9a01341c688efa4
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 */
20static 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 */
26static 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 */
35static inline unsigned SkClampUMax(unsigned value, unsigned max) {
36#ifdef SK_CPU_HAS_CONDITIONAL_INSTR
37    if (value > max) {
38        value = max;
39    }
40    return value;
41#else
42    int diff = max - value;
43    // clear diff if diff is positive
44    diff &= diff >> 31;
45
46    return value + diff;
47#endif
48}
49
50/** Computes the 64bit product of a * b, and then shifts the answer down by
51 shift bits, returning the low 32bits. shift must be [0..63]
52 e.g. to perform a fixedmul, call SkMulShift(a, b, 16)
53 */
54int32_t SkMulShift(int32_t a, int32_t b, unsigned shift);
55
56/** Return the integer cube root of value, with a bias of bitBias
57 */
58int32_t SkCubeRootBits(int32_t value, int bitBias);
59
60///////////////////////////////////////////////////////////////////////////////
61
62/** Return a*b/255, truncating away any fractional bits. Only valid if both
63 a and b are 0..255
64 */
65static inline U8CPU SkMulDiv255Trunc(U8CPU a, U8CPU b) {
66    SkASSERT((uint8_t)a == a);
67    SkASSERT((uint8_t)b == b);
68    unsigned prod = SkMulS16(a, b) + 1;
69    return (prod + (prod >> 8)) >> 8;
70}
71
72/** Return (a*b)/255, taking the ceiling of any fractional bits. Only valid if
73 both a and b are 0..255. The expected result equals (a * b + 254) / 255.
74 */
75static inline U8CPU SkMulDiv255Ceiling(U8CPU a, U8CPU b) {
76    SkASSERT((uint8_t)a == a);
77    SkASSERT((uint8_t)b == b);
78    unsigned prod = SkMulS16(a, b) + 255;
79    return (prod + (prod >> 8)) >> 8;
80}
81
82/** Just the rounding step in SkDiv255Round: round(value / 255)
83 */
84static inline unsigned SkDiv255Round(unsigned prod) {
85    prod += 128;
86    return (prod + (prod >> 8)) >> 8;
87}
88
89#endif
90
91