Herb Derby | 35ae65d | 2017-08-11 14:00:50 -0400 | [diff] [blame] | 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 | |
Mike Klein | c0bd9f9 | 2019-04-23 12:05:21 -0500 | [diff] [blame] | 8 | #include "src/core/SkSafeMath.h" |
| 9 | #include "tests/Test.h" |
Herb Derby | 35ae65d | 2017-08-11 14:00:50 -0400 | [diff] [blame] | 10 | |
| 11 | DEF_TEST(SafeMath, r) { |
| 12 | size_t max = std::numeric_limits<size_t>::max(); |
| 13 | |
| 14 | { |
| 15 | size_t halfMax = max >> 1; |
| 16 | size_t halfMaxPlus1 = halfMax + 1; |
| 17 | SkSafeMath safe; |
| 18 | REPORTER_ASSERT(r, safe.add(halfMax, halfMax) == 2 * halfMax); |
| 19 | REPORTER_ASSERT(r, safe); |
| 20 | REPORTER_ASSERT(r, safe.add(halfMax, halfMaxPlus1) == max); |
| 21 | REPORTER_ASSERT(r, safe); |
| 22 | REPORTER_ASSERT(r, safe.add(max, 1) == 0); |
| 23 | REPORTER_ASSERT(r, !safe); |
| 24 | } |
| 25 | |
| 26 | { |
| 27 | SkSafeMath safe; |
| 28 | (void) safe.add(max, max); |
| 29 | REPORTER_ASSERT(r, !safe); |
| 30 | } |
| 31 | |
| 32 | { |
| 33 | size_t bits = (sizeof(size_t) * 8); |
| 34 | size_t halfBits = bits / 2; |
| 35 | size_t sqrtMax = max >> halfBits; |
| 36 | size_t sqrtMaxPlus1 = sqrtMax + 1; |
| 37 | SkSafeMath safe; |
| 38 | REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMax) == sqrtMax * sqrtMax); |
| 39 | REPORTER_ASSERT(r, safe); |
| 40 | REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMaxPlus1) == sqrtMax << halfBits); |
| 41 | REPORTER_ASSERT(r, safe); |
| 42 | REPORTER_ASSERT(r, safe.mul(sqrtMaxPlus1, sqrtMaxPlus1) == 0); |
| 43 | REPORTER_ASSERT(r, !safe); |
| 44 | } |
| 45 | |
| 46 | { |
| 47 | SkSafeMath safe; |
| 48 | (void) safe.mul(max, max); |
| 49 | REPORTER_ASSERT(r, !safe); |
| 50 | } |
| 51 | } |