SkSafeRange.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. #ifndef SkSafeRange_DEFINED
  8. #define SkSafeRange_DEFINED
  9. #include "include/core/SkTypes.h"
  10. #include <cstdint>
  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. class SkSafeRange {
  15. public:
  16. operator bool() const { return fOK; }
  17. bool ok() const { return fOK; }
  18. // checks 0 <= value <= max.
  19. // On success, returns value
  20. // On failure, returns 0 and sets ok() to false
  21. template <typename T> T checkLE(uint64_t value, T max) {
  22. SkASSERT(static_cast<int64_t>(max) >= 0);
  23. if (value > static_cast<uint64_t>(max)) {
  24. fOK = false;
  25. value = 0;
  26. }
  27. return static_cast<T>(value);
  28. }
  29. int checkGE(int value, int min) {
  30. if (value < min) {
  31. fOK = false;
  32. value = min;
  33. }
  34. return value;
  35. }
  36. private:
  37. bool fOK = true;
  38. };
  39. #endif