cpp-common/bt2c/fmt.hpp: use `wise_enum::string_type` in `EnableIfIsWiseEnum` definition
[babeltrace.git] / src / cpp-common / bt2c / safe-ops.hpp
1 /*
2 * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com>
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7 #ifndef BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP
8 #define BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP
9
10 #include <limits>
11 #include <type_traits>
12
13 #include "common/assert.h"
14
15 namespace bt2c {
16
17 template <typename T>
18 constexpr bool safeToMul(const T a, const T b)
19 {
20 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
21
22 return a == 0 || b == 0 || a < std::numeric_limits<T>::max() / b;
23 }
24
25 template <typename T>
26 T safeMul(const T a, const T b) noexcept
27 {
28 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
29
30 BT_ASSERT_DBG(safeToMul(a, b));
31 return a * b;
32 }
33
34 template <typename T>
35 constexpr bool safeToAdd(const T a, const T b)
36 {
37 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
38
39 return a <= std::numeric_limits<T>::max() - b;
40 }
41
42 template <typename T>
43 T safeAdd(const T a, const T b) noexcept
44 {
45 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
46
47 BT_ASSERT_DBG(safeToAdd(a, b));
48 return a + b;
49 }
50
51 template <typename T>
52 constexpr bool safeToSub(const T a, const T b)
53 {
54 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
55
56 return a >= b;
57 }
58
59 template <typename T>
60 T safeSub(const T a, const T b) noexcept
61 {
62 static_assert(std::is_unsigned<T>::value, "`T` is an unsigned type.");
63
64 BT_ASSERT_DBG(safeToSub(a, b));
65 return a - b;
66 }
67
68 } /* namespace bt2c */
69
70 #endif /* BABELTRACE_CPP_COMMON_BT2C_SAFE_OPS_HPP */
This page took 0.030963 seconds and 4 git commands to generate.