• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
8 #include "src/base/SkSafeMath.h"
9 #include "tests/Test.h"
10 
11 #include <cstddef>
12 #include <limits>
13 
DEF_TEST(SafeMath,r)14 DEF_TEST(SafeMath, r) {
15     size_t max = std::numeric_limits<size_t>::max();
16 
17     {
18         size_t halfMax = max >> 1;
19         size_t halfMaxPlus1 = halfMax + 1;
20         SkSafeMath safe;
21         REPORTER_ASSERT(r, safe.add(halfMax, halfMax) == 2 * halfMax);
22         REPORTER_ASSERT(r, safe);
23         REPORTER_ASSERT(r, safe.add(halfMax, halfMaxPlus1) == max);
24         REPORTER_ASSERT(r, safe);
25         REPORTER_ASSERT(r, safe.add(max, 1) == 0);
26         REPORTER_ASSERT(r, !safe);
27     }
28 
29     {
30         SkSafeMath safe;
31         (void) safe.add(max, max);
32         REPORTER_ASSERT(r, !safe);
33     }
34 
35     {
36         size_t bits = (sizeof(size_t) * 8);
37         size_t halfBits = bits / 2;
38         size_t sqrtMax = max >> halfBits;
39         size_t sqrtMaxPlus1 = sqrtMax + 1;
40         SkSafeMath safe;
41         REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMax) == sqrtMax * sqrtMax);
42         REPORTER_ASSERT(r, safe);
43         REPORTER_ASSERT(r, safe.mul(sqrtMax, sqrtMaxPlus1) == sqrtMax << halfBits);
44         REPORTER_ASSERT(r, safe);
45         REPORTER_ASSERT(r, safe.mul(sqrtMaxPlus1, sqrtMaxPlus1) == 0);
46         REPORTER_ASSERT(r, !safe);
47     }
48 
49     {
50         SkSafeMath safe;
51         (void) safe.mul(max, max);
52         REPORTER_ASSERT(r, !safe);
53     }
54 }
55