SkMath.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright 2008 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. #include "include/core/SkScalar.h"
  8. #include "include/private/SkFixed.h"
  9. #include "include/private/SkFloatBits.h"
  10. #include "include/private/SkFloatingPoint.h"
  11. #include "src/core/SkMathPriv.h"
  12. #include "src/core/SkSafeMath.h"
  13. #define sub_shift(zeros, x, n) \
  14. zeros -= n; \
  15. x >>= n
  16. int SkCLZ_portable(uint32_t x) {
  17. if (x == 0) {
  18. return 32;
  19. }
  20. int zeros = 31;
  21. if (x & 0xFFFF0000) {
  22. sub_shift(zeros, x, 16);
  23. }
  24. if (x & 0xFF00) {
  25. sub_shift(zeros, x, 8);
  26. }
  27. if (x & 0xF0) {
  28. sub_shift(zeros, x, 4);
  29. }
  30. if (x & 0xC) {
  31. sub_shift(zeros, x, 2);
  32. }
  33. if (x & 0x2) {
  34. sub_shift(zeros, x, 1);
  35. }
  36. return zeros;
  37. }
  38. ///////////////////////////////////////////////////////////////////////////////
  39. /* www.worldserver.com/turk/computergraphics/FixedSqrt.pdf
  40. */
  41. int32_t SkSqrtBits(int32_t x, int count) {
  42. SkASSERT(x >= 0 && count > 0 && (unsigned)count <= 30);
  43. uint32_t root = 0;
  44. uint32_t remHi = 0;
  45. uint32_t remLo = x;
  46. do {
  47. root <<= 1;
  48. remHi = (remHi<<2) | (remLo>>30);
  49. remLo <<= 2;
  50. uint32_t testDiv = (root << 1) + 1;
  51. if (remHi >= testDiv) {
  52. remHi -= testDiv;
  53. root++;
  54. }
  55. } while (--count >= 0);
  56. return root;
  57. }
  58. ///////////////////////////////////////////////////////////////////////////////////////////////////
  59. size_t SkSafeMath::Add(size_t x, size_t y) {
  60. SkSafeMath tmp;
  61. size_t sum = tmp.add(x, y);
  62. return tmp.ok() ? sum : SIZE_MAX;
  63. }
  64. size_t SkSafeMath::Mul(size_t x, size_t y) {
  65. SkSafeMath tmp;
  66. size_t prod = tmp.mul(x, y);
  67. return tmp.ok() ? prod : SIZE_MAX;
  68. }
  69. ///////////////////////////////////////////////////////////////////////////////////////////////////
  70. bool sk_floats_are_unit(const float array[], size_t count) {
  71. bool is_unit = true;
  72. for (size_t i = 0; i < count; ++i) {
  73. is_unit &= (array[i] >= 0) & (array[i] <= 1);
  74. }
  75. return is_unit;
  76. }