2 * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com>
4 * SPDX-License-Identifier: MIT
7 #ifndef BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP
8 #define BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP
11 #include <type_traits>
13 #include "common/assert.h"
18 constexpr bool safeToMul(const T a, const T b)
20 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
22 return a == 0 || b == 0 || a < std::numeric_limits<T>::max() / b;
26 T safeMul(const T a, const T b) noexcept
28 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
30 BT_ASSERT_DBG(safeToMul(a, b));
35 constexpr bool safeToAdd(const T a, const T b)
37 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
39 return a <= std::numeric_limits<T>::max() - b;
43 T safeAdd(const T a, const T b) noexcept
45 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
47 BT_ASSERT_DBG(safeToAdd(a, b));
52 constexpr bool safeToSub(const T a, const T b)
54 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
60 T safeSub(const T a, const T b) noexcept
62 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
64 BT_ASSERT_DBG(safeToSub(a, b));
68 } /* namespace bt2c */
70 #endif /* BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP */