blob: 91200fbb564131ed4543a94e1ba257733c443ccd [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#ifndef SkSafeMath_DEFINED
9#define SkSafeMath_DEFINED
10
11// SkSafeMath always check that a series of operations do not overflow.
12// This must be correct for all platforms, because this is a check for safety at runtime.
13
14class SkSafeMath {
15public:
16 SkSafeMath() = default;
17
18 bool ok() const { return fOK; }
19 explicit operator bool() const { return fOK; }
20
21 size_t mul(size_t x, size_t y) {
22 return sizeof(size_t) == sizeof(uint64_t) ? mul64(x, y) : mul32(x, y);
23 }
24
25 size_t add(size_t x, size_t y) {
26 size_t result = x + y;
27 fOK &= result >= x;
28 return result;
29 }
30
31private:
32 uint32_t mul32(uint32_t x, uint32_t y) {
33 uint64_t bx = x;
34 uint64_t by = y;
35 uint64_t result = bx * by;
36 fOK &= result >> 32 == 0;
37 return result;
38 }
39
40 uint64_t mul64(uint64_t x, uint64_t y) {
41 if (x <= std::numeric_limits<uint64_t>::max() >> 32
42 && y <= std::numeric_limits<uint64_t>::max() >> 32) {
43 return x * y;
44 } else {
45 auto hi = [](uint64_t x) { return x >> 32; };
46 auto lo = [](uint64_t x) { return x & 0xFFFFFFFF; };
47
48 uint64_t lx_ly = lo(x) * lo(y);
49 uint64_t hx_ly = hi(x) * lo(y);
50 uint64_t lx_hy = lo(x) * hi(y);
51 uint64_t hx_hy = hi(x) * hi(y);
52 uint64_t result = 0;
53 result = this->add(lx_ly, (hx_ly << 32));
54 result = this->add(result, (lx_hy << 32));
55 fOK &= (hx_hy + (hx_ly >> 32) + (lx_hy >> 32)) == 0;
56
57 #if defined(SK_DEBUG) && defined(__clang__) && defined(__x86_64__)
58 auto double_check = (unsigned __int128)x * y;
59 SkASSERT(result == (double_check & 0xFFFFFFFFFFFFFFFF));
60 SkASSERT(!fOK || (double_check >> 64 == 0));
61 #endif
62
63 return result;
64 }
65 }
66 bool fOK = true;
67};
68
69#endif//SkSafeMath_DEFINED