michael@0: /* michael@0: * Copyright 2012 Google Inc. michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #ifndef SkMathPriv_DEFINED michael@0: #define SkMathPriv_DEFINED michael@0: michael@0: #include "SkMath.h" michael@0: michael@0: /** Returns -1 if n < 0, else returns 0 michael@0: */ michael@0: #define SkExtractSign(n) ((int32_t)(n) >> 31) michael@0: michael@0: /** If sign == -1, returns -n, else sign must be 0, and returns n. michael@0: Typically used in conjunction with SkExtractSign(). michael@0: */ michael@0: static inline int32_t SkApplySign(int32_t n, int32_t sign) { michael@0: SkASSERT(sign == 0 || sign == -1); michael@0: return (n ^ sign) - sign; michael@0: } michael@0: michael@0: /** Return x with the sign of y */ michael@0: static inline int32_t SkCopySign32(int32_t x, int32_t y) { michael@0: return SkApplySign(x, SkExtractSign(x ^ y)); michael@0: } michael@0: michael@0: /** Given a positive value and a positive max, return the value michael@0: pinned against max. michael@0: Note: only works as long as max - value doesn't wrap around michael@0: @return max if value >= max, else value michael@0: */ michael@0: static inline unsigned SkClampUMax(unsigned value, unsigned max) { michael@0: if (value > max) { michael@0: value = max; michael@0: } michael@0: return value; michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: /** Return a*b/255, truncating away any fractional bits. Only valid if both michael@0: a and b are 0..255 michael@0: */ michael@0: static inline U8CPU SkMulDiv255Trunc(U8CPU a, U8CPU b) { michael@0: SkASSERT((uint8_t)a == a); michael@0: SkASSERT((uint8_t)b == b); michael@0: unsigned prod = SkMulS16(a, b) + 1; michael@0: return (prod + (prod >> 8)) >> 8; michael@0: } michael@0: michael@0: /** Return (a*b)/255, taking the ceiling of any fractional bits. Only valid if michael@0: both a and b are 0..255. The expected result equals (a * b + 254) / 255. michael@0: */ michael@0: static inline U8CPU SkMulDiv255Ceiling(U8CPU a, U8CPU b) { michael@0: SkASSERT((uint8_t)a == a); michael@0: SkASSERT((uint8_t)b == b); michael@0: unsigned prod = SkMulS16(a, b) + 255; michael@0: return (prod + (prod >> 8)) >> 8; michael@0: } michael@0: michael@0: /** Just the rounding step in SkDiv255Round: round(value / 255) michael@0: */ michael@0: static inline unsigned SkDiv255Round(unsigned prod) { michael@0: prod += 128; michael@0: return (prod + (prod >> 8)) >> 8; michael@0: } michael@0: michael@0: #endif