blob: 25058d2c761d8b08ecab31596393a46c050408ce [file] [log] [blame]
Mike Reed1c5906f2018-01-30 16:01:33 -05001/*
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
11static constexpr int32_t Sk64_pin_to_s32(int64_t x) {
12 return x < SK_MinS32 ? SK_MinS32 : (x > SK_MaxS32 ? SK_MaxS32 : x);
13}
14
15static constexpr int32_t Sk32_sat_add(int32_t a, int32_t b) {
16 return Sk64_pin_to_s32((int64_t)a + (int64_t)b);
17}
18
19static constexpr int32_t Sk32_sat_sub(int32_t a, int32_t b) {
20 return Sk64_pin_to_s32((int64_t)a - (int64_t)b);
21}
22
23// To avoid UBSAN complaints about 2's compliment overflows
24//
Mike Reed36c0b572018-02-15 11:17:56 -050025static constexpr int32_t Sk32_can_overflow_add(int32_t a, int32_t b) {
26 return (int32_t)((uint32_t)a + (uint32_t)b);
27}
Mike Reed1c5906f2018-01-30 16:01:33 -050028static constexpr int32_t Sk32_can_overflow_sub(int32_t a, int32_t b) {
29 return (int32_t)((uint32_t)a - (uint32_t)b);
30}
31
32#endif