Mike Reed | 1c5906f | 2018-01-30 16:01:33 -0500 | [diff] [blame] | 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 | |
Mike Reed | cab2549 | 2018-05-10 10:55:43 -0400 | [diff] [blame] | 11 | #include "SkTypes.h" |
| 12 | |
Mike Reed | 1c5906f | 2018-01-30 16:01:33 -0500 | [diff] [blame] | 13 | static constexpr int32_t Sk64_pin_to_s32(int64_t x) { |
Kaloyan Donev | dfffb39 | 2018-03-20 10:38:31 +0200 | [diff] [blame] | 14 | return x < SK_MinS32 ? SK_MinS32 : (x > SK_MaxS32 ? SK_MaxS32 : (int32_t)x); |
Mike Reed | 1c5906f | 2018-01-30 16:01:33 -0500 | [diff] [blame] | 15 | } |
| 16 | |
| 17 | static constexpr int32_t Sk32_sat_add(int32_t a, int32_t b) { |
| 18 | return Sk64_pin_to_s32((int64_t)a + (int64_t)b); |
| 19 | } |
| 20 | |
| 21 | static constexpr int32_t Sk32_sat_sub(int32_t a, int32_t b) { |
| 22 | return Sk64_pin_to_s32((int64_t)a - (int64_t)b); |
| 23 | } |
| 24 | |
| 25 | // To avoid UBSAN complaints about 2's compliment overflows |
| 26 | // |
Mike Reed | 36c0b57 | 2018-02-15 11:17:56 -0500 | [diff] [blame] | 27 | static constexpr int32_t Sk32_can_overflow_add(int32_t a, int32_t b) { |
| 28 | return (int32_t)((uint32_t)a + (uint32_t)b); |
| 29 | } |
Mike Reed | 1c5906f | 2018-01-30 16:01:33 -0500 | [diff] [blame] | 30 | static constexpr int32_t Sk32_can_overflow_sub(int32_t a, int32_t b) { |
| 31 | return (int32_t)((uint32_t)a - (uint32_t)b); |
| 32 | } |
| 33 | |
| 34 | #endif |