SkMath.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #ifndef SkMath_DEFINED
  8. #define SkMath_DEFINED
  9. #include "SkTypes.h"
  10. // 64bit -> 32bit utilities
  11. // Handy util that can be passed two ints, and will automatically promote to
  12. // 64bits before the multiply, so the caller doesn't have to remember to cast
  13. // e.g. (int64_t)a * b;
  14. static inline int64_t sk_64_mul(int64_t a, int64_t b) {
  15. return a * b;
  16. }
  17. ///////////////////////////////////////////////////////////////////////////////
  18. /** Given an integer and a positive (max) integer, return the value
  19. * pinned against 0 and max, inclusive.
  20. * @param value The value we want returned pinned between [0...max]
  21. * @param max The positive max value
  22. * @return 0 if value < 0, max if value > max, else value
  23. */
  24. static inline int SkClampMax(int value, int max) {
  25. // ensure that max is positive
  26. SkASSERT(max >= 0);
  27. if (value < 0) {
  28. value = 0;
  29. }
  30. if (value > max) {
  31. value = max;
  32. }
  33. return value;
  34. }
  35. /**
  36. * Returns true if value is a power of 2. Does not explicitly check for
  37. * value <= 0.
  38. */
  39. template <typename T> constexpr inline bool SkIsPow2(T value) {
  40. return (value & (value - 1)) == 0;
  41. }
  42. ///////////////////////////////////////////////////////////////////////////////
  43. /**
  44. * Return a*b/((1 << shift) - 1), rounding any fractional bits.
  45. * Only valid if a and b are unsigned and <= 32767 and shift is > 0 and <= 8
  46. */
  47. static inline unsigned SkMul16ShiftRound(U16CPU a, U16CPU b, int shift) {
  48. SkASSERT(a <= 32767);
  49. SkASSERT(b <= 32767);
  50. SkASSERT(shift > 0 && shift <= 8);
  51. unsigned prod = a*b + (1 << (shift - 1));
  52. return (prod + (prod >> shift)) >> shift;
  53. }
  54. /**
  55. * Return a*b/255, rounding any fractional bits.
  56. * Only valid if a and b are unsigned and <= 32767.
  57. */
  58. static inline U8CPU SkMulDiv255Round(U16CPU a, U16CPU b) {
  59. SkASSERT(a <= 32767);
  60. SkASSERT(b <= 32767);
  61. unsigned prod = a*b + 128;
  62. return (prod + (prod >> 8)) >> 8;
  63. }
  64. #endif