Bitcoin ABC 0.32.6
P2P Digital Currency
overflow.h
Go to the documentation of this file.
1// Copyright (c) 2021-2022 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_UTIL_OVERFLOW_H
6#define BITCOIN_UTIL_OVERFLOW_H
7
8#include <climits>
9#include <limits>
10#include <optional>
11#include <type_traits>
12
13template <class T>
14[[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept {
15 static_assert(std::is_integral<T>::value, "Integral required.");
16 if (std::numeric_limits<T>::is_signed) {
17 return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
18 (i < 0 && j < std::numeric_limits<T>::min() - i);
19 }
20 return std::numeric_limits<T>::max() - i < j;
21}
22
23template <class T>
24[[nodiscard]] std::optional<T> CheckedAdd(const T i, const T j) noexcept {
25 if (AdditionOverflow(i, j)) {
26 return std::nullopt;
27 }
28 return i + j;
29}
30
37template <std::integral T>
38constexpr std::optional<T> CheckedLeftShift(T input, unsigned shift) noexcept {
39 if (shift == 0 || input == 0) {
40 return input;
41 }
42 // Avoid undefined c++ behaviour if shift is >= number of bits in T.
43 if (shift >= sizeof(T) * CHAR_BIT) {
44 return std::nullopt;
45 }
46 // If input << shift is too big to fit in T, return nullopt.
47 if (input > (std::numeric_limits<T>::max() >> shift)) {
48 return std::nullopt;
49 }
50 if (input < (std::numeric_limits<T>::min() >> shift)) {
51 return std::nullopt;
52 }
53 return input << shift;
54}
55
63template <std::integral T>
64constexpr T SaturatingLeftShift(T input, unsigned shift) noexcept {
65 if (auto result{CheckedLeftShift(input, shift)}) {
66 return *result;
67 }
68 // If input << shift is too big to fit in T, return biggest positive or
69 // negative number that fits.
70 return input < 0 ? std::numeric_limits<T>::min()
71 : std::numeric_limits<T>::max();
72}
73
74#endif // BITCOIN_UTIL_OVERFLOW_H
std::optional< T > CheckedAdd(const T i, const T j) noexcept
Definition: overflow.h:24
constexpr T SaturatingLeftShift(T input, unsigned shift) noexcept
Left bit shift with safe minimum and maximum values.
Definition: overflow.h:64
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:14
constexpr std::optional< T > CheckedLeftShift(T input, unsigned shift) noexcept
Left bit shift with overflow checking.
Definition: overflow.h:38