SkSafe32.h 920 B

12345678910111213141516171819202122232425262728293031323334
  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 SkSafe32_DEFINED
  8. #define SkSafe32_DEFINED
  9. #include "include/core/SkTypes.h"
  10. static constexpr int32_t Sk64_pin_to_s32(int64_t x) {
  11. return x < SK_MinS32 ? SK_MinS32 : (x > SK_MaxS32 ? SK_MaxS32 : (int32_t)x);
  12. }
  13. static constexpr int32_t Sk32_sat_add(int32_t a, int32_t b) {
  14. return Sk64_pin_to_s32((int64_t)a + (int64_t)b);
  15. }
  16. static constexpr int32_t Sk32_sat_sub(int32_t a, int32_t b) {
  17. return Sk64_pin_to_s32((int64_t)a - (int64_t)b);
  18. }
  19. // To avoid UBSAN complaints about 2's compliment overflows
  20. //
  21. static constexpr int32_t Sk32_can_overflow_add(int32_t a, int32_t b) {
  22. return (int32_t)((uint32_t)a + (uint32_t)b);
  23. }
  24. static constexpr int32_t Sk32_can_overflow_sub(int32_t a, int32_t b) {
  25. return (int32_t)((uint32_t)a - (uint32_t)b);
  26. }
  27. #endif