SafeMathTest.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright 2017 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. #include "src/core/SkSafeMath.h"
  8. #include "tests/Test.h"
  9. DEF_TEST(SafeMath, r) {
  10. size_t max = std::numeric_limits<size_t>::max();
  11. {
  12. size_t halfMax = max >> 1;
  13. size_t halfMaxPlus1 = halfMax + 1;
  14. SkSafeMath safe;
  15. REPORTER_ASSERT(r, safe.add(halfMax, halfMax) == 2 * halfMax);
  16. REPORTER_ASSERT(r, safe);
  17. REPORTER_ASSERT(r, safe.add(halfMax, halfMaxPlus1) == max);
  18. REPORTER_ASSERT(r, safe);
  19. REPORTER_ASSERT(r, safe.add(max, 1) == 0);
  20. REPORTER_ASSERT(r, !safe);
  21. }
  22. {
  23. SkSafeMath safe;
  24. (void) safe.add(max, max);
  25. REPORTER_ASSERT(r, !safe);
  26. }
  27. {
  28. size_t bits = (sizeof(size_t) * 8);
  29. size_t halfBits = bits / 2;
  30. size_t sqrtMax = max >> halfBits;
  31. size_t sqrtMaxPlus1 = sqrtMax + 1;
  32. SkSafeMath safe;
  33. REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMax) == sqrtMax * sqrtMax);
  34. REPORTER_ASSERT(r, safe);
  35. REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMaxPlus1) == sqrtMax << halfBits);
  36. REPORTER_ASSERT(r, safe);
  37. REPORTER_ASSERT(r, safe.mul(sqrtMaxPlus1, sqrtMaxPlus1) == 0);
  38. REPORTER_ASSERT(r, !safe);
  39. }
  40. {
  41. SkSafeMath safe;
  42. (void) safe.mul(max, max);
  43. REPORTER_ASSERT(r, !safe);
  44. }
  45. }