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