cpp-common: add vectorFastRemove
[babeltrace.git] / src / cpp-common / safe-ops.hpp
CommitLineData
e2c3fe1c
PP
1/*
2 * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com>
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7#ifndef BABELTRACE_CPP_COMMON_SAFE_OPS_HPP
8#define BABELTRACE_CPP_COMMON_SAFE_OPS_HPP
9
10#include <limits>
11#include <type_traits>
12
13#include "common/assert.h"
14
15namespace bt2_common {
16
17template <typename T>
18constexpr 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
25template <typename T>
26T 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
34template <typename T>
35constexpr 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
42template <typename T>
43T 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
51template <typename T>
52constexpr 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
59template <typename T>
60T 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 bt2_common */
69
70#endif /* BABELTRACE_CPP_COMMON_SAFE_OPS_HPP */
This page took 0.024999 seconds and 4 git commands to generate.