1cb93a386Sopenharmony_ci/*
2cb93a386Sopenharmony_ci * Copyright 2018 Google Inc.
3cb93a386Sopenharmony_ci *
4cb93a386Sopenharmony_ci * Use of this source code is governed by a BSD-style license that can be
5cb93a386Sopenharmony_ci * found in the LICENSE file.
6cb93a386Sopenharmony_ci */
7cb93a386Sopenharmony_ci
8cb93a386Sopenharmony_ci#ifndef SkSafe32_DEFINED
9cb93a386Sopenharmony_ci#define SkSafe32_DEFINED
10cb93a386Sopenharmony_ci
11cb93a386Sopenharmony_ci#include "include/core/SkTypes.h"
12cb93a386Sopenharmony_ci
13cb93a386Sopenharmony_cistatic constexpr int32_t Sk64_pin_to_s32(int64_t x) {
14cb93a386Sopenharmony_ci    return x < SK_MinS32 ? SK_MinS32 : (x > SK_MaxS32 ? SK_MaxS32 : (int32_t)x);
15cb93a386Sopenharmony_ci}
16cb93a386Sopenharmony_ci
17cb93a386Sopenharmony_cistatic constexpr int32_t Sk32_sat_add(int32_t a, int32_t b) {
18cb93a386Sopenharmony_ci    return Sk64_pin_to_s32((int64_t)a + (int64_t)b);
19cb93a386Sopenharmony_ci}
20cb93a386Sopenharmony_ci
21cb93a386Sopenharmony_cistatic constexpr int32_t Sk32_sat_sub(int32_t a, int32_t b) {
22cb93a386Sopenharmony_ci    return Sk64_pin_to_s32((int64_t)a - (int64_t)b);
23cb93a386Sopenharmony_ci}
24cb93a386Sopenharmony_ci
25cb93a386Sopenharmony_ci// To avoid UBSAN complaints about 2's compliment overflows
26cb93a386Sopenharmony_ci//
27cb93a386Sopenharmony_cistatic constexpr int32_t Sk32_can_overflow_add(int32_t a, int32_t b) {
28cb93a386Sopenharmony_ci    return (int32_t)((uint32_t)a + (uint32_t)b);
29cb93a386Sopenharmony_ci}
30cb93a386Sopenharmony_cistatic constexpr int32_t Sk32_can_overflow_sub(int32_t a, int32_t b) {
31cb93a386Sopenharmony_ci    return (int32_t)((uint32_t)a - (uint32_t)b);
32cb93a386Sopenharmony_ci}
33cb93a386Sopenharmony_ci
34cb93a386Sopenharmony_ci#endif
35