Pigweed
 
Loading...
Searching...
No Matches
checked_arithmetic.h
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <optional>
17#include <type_traits>
18
19#include "pw_preprocessor/compiler.h"
20
21namespace pw {
22
40template <typename T, typename A, typename B>
41constexpr std::optional<T> CheckedAdd(A a, B b) {
42 T result;
43
44 if (PW_ADD_OVERFLOW(a, b, &result)) {
45 return std::nullopt;
46 }
47
48 return result;
49}
50
64template <typename T, typename Inc>
65constexpr bool CheckedIncrement(T& base, Inc inc) {
66 std::optional<T> result =
67 CheckedAdd<std::remove_reference_t<decltype(base)>>(base, inc);
68 if (!result) {
69 return false;
70 }
71 base = *result;
72 return true;
73}
74
92template <typename T, typename A, typename B>
93constexpr std::optional<T> CheckedSub(A a, B b) {
94 T result;
95
96 if (PW_SUB_OVERFLOW(a, b, &result)) {
97 return std::nullopt;
98 }
99
100 return result;
101}
102
116template <typename T, typename Dec>
117constexpr bool CheckedDecrement(T& base, Dec dec) {
118 std::optional<T> result =
119 CheckedSub<std::remove_reference_t<decltype(base)>>(base, dec);
120 if (!result) {
121 return false;
122 }
123 base = *result;
124 return true;
125}
126
144template <typename T, typename A, typename B>
145constexpr std::optional<T> CheckedMul(A a, B b) {
146 T result;
147
148 if (PW_MUL_OVERFLOW(a, b, &result)) {
149 return std::nullopt;
150 }
151
152 return result;
153}
154
155} // namespace pw
#define PW_SUB_OVERFLOW(a, b, out)
Definition: compiler.h:294
#define PW_ADD_OVERFLOW(a, b, out)
Definition: compiler.h:282
#define PW_MUL_OVERFLOW(a, b, out)
Definition: compiler.h:304
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27
constexpr std::optional< T > CheckedAdd(A a, B b)
Definition: checked_arithmetic.h:41
constexpr bool CheckedDecrement(T &base, Dec dec)
Definition: checked_arithmetic.h:117
constexpr std::optional< T > CheckedSub(A a, B b)
Definition: checked_arithmetic.h:93
constexpr std::optional< T > CheckedMul(A a, B b)
Definition: checked_arithmetic.h:145
constexpr bool CheckedIncrement(T &base, Inc inc)
Definition: checked_arithmetic.h:65