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 SkSafe32_DEFINED 9 #define SkSafe32_DEFINED 10 11 #include "include/private/base/SkAssert.h" 12 #include "include/private/base/SkMath.h" 13 14 #include <cstdint> 15 Sk64_pin_to_s32(int64_t x)16static constexpr int32_t Sk64_pin_to_s32(int64_t x) { 17 return x < SK_MinS32 ? SK_MinS32 : (x > SK_MaxS32 ? SK_MaxS32 : (int32_t)x); 18 } 19 Sk32_sat_add(int32_t a,int32_t b)20static constexpr int32_t Sk32_sat_add(int32_t a, int32_t b) { 21 return Sk64_pin_to_s32((int64_t)a + (int64_t)b); 22 } 23 Sk32_sat_sub(int32_t a,int32_t b)24static constexpr int32_t Sk32_sat_sub(int32_t a, int32_t b) { 25 return Sk64_pin_to_s32((int64_t)a - (int64_t)b); 26 } 27 28 // To avoid UBSAN complaints about 2's compliment overflows 29 // Sk32_can_overflow_add(int32_t a,int32_t b)30static constexpr int32_t Sk32_can_overflow_add(int32_t a, int32_t b) { 31 return (int32_t)((uint32_t)a + (uint32_t)b); 32 } Sk32_can_overflow_sub(int32_t a,int32_t b)33static constexpr int32_t Sk32_can_overflow_sub(int32_t a, int32_t b) { 34 return (int32_t)((uint32_t)a - (uint32_t)b); 35 } 36 37 /** 38 * This is a 'safe' abs for 32-bit integers that asserts when undefined behavior would occur. 39 * SkTAbs (in SkTemplates.h) is a general purpose absolute-value function. 40 */ SkAbs32(int32_t value)41static inline int32_t SkAbs32(int32_t value) { 42 SkASSERT(value != SK_NaN32); // The most negative int32_t can't be negated. 43 if (value < 0) { 44 value = -value; 45 } 46 return value; 47 } 48 49 #endif 50