1 /*
2  * Copyright 2018 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 SkSafeRange_DEFINED
9 #define SkSafeRange_DEFINED
10 
11 // SkSafeRange always check that a series of operations are in-range.
12 // This check is sticky, so that if any one operation fails, the object will remember that and
13 // return false from ok().
14 
15 class SkSafeRange {
16 public:
17     MOZ_IMPLICIT operator bool() const { return fOK; }
18 
ok()19     bool ok() const { return fOK; }
20 
21     // checks 0 <= value <= max.
22     // On success, returns value
23     // On failure, returns 0 and sets ok() to false
checkLE(uint64_t value,T max)24     template <typename T> T checkLE(uint64_t value, T max) {
25         SkASSERT(static_cast<int64_t>(max) >= 0);
26         if (value > static_cast<uint64_t>(max)) {
27             fOK = false;
28             value = 0;
29         }
30         return static_cast<T>(value);
31     }
32 
checkGE(int value,int min)33     int checkGE(int value, int min) {
34         if (value < min) {
35             fOK = false;
36             value = min;
37         }
38         return value;
39     }
40 
41 private:
42     bool fOK = true;
43 };
44 
45 #endif
46