blob: 7f597393d02619aa304076aad72e4c6ab792bde9 [file] [log] [blame]
Herb Derby35ae65d2017-08-11 14:00:50 -04001/*
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 "Test.h"
9#include "SkSafeMath.h"
10
11DEF_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}