Bitcoin ABC 0.33.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
31template <std::unsigned_integral T, std::unsigned_integral U>
32[[nodiscard]] constexpr bool TrySub(T &i, const U j) noexcept {
33 if (i < T{j}) {
34 return false;
35 }
36 i -= T{j};
37 return true;
38}
39
46template <std::integral T>
47constexpr std::optional<T> CheckedLeftShift(T input, unsigned shift) noexcept {
48 if (shift == 0 || input == 0) {
49 return input;
50 }
51 // Avoid undefined c++ behaviour if shift is >= number of bits in T.
52 if (shift >= sizeof(T) * CHAR_BIT) {
53 return std::nullopt;
54 }
55 // If input << shift is too big to fit in T, return nullopt.
56 if (input > (std::numeric_limits<T>::max() >> shift)) {
57 return std::nullopt;
58 }
59 if (input < (std::numeric_limits<T>::min() >> shift)) {
60 return std::nullopt;
61 }
62 return input << shift;
63}
64
72template <std::integral T>
73constexpr T SaturatingLeftShift(T input, unsigned shift) noexcept {
74 if (auto result{CheckedLeftShift(input, shift)}) {
75 return *result;
76 }
77 // If input << shift is too big to fit in T, return biggest positive or
78 // negative number that fits.
79 return input < 0 ? std::numeric_limits<T>::min()
80 : std::numeric_limits<T>::max();
81}
82
83#endif // BITCOIN_UTIL_OVERFLOW_H
constexpr bool TrySub(T &i, const U j) noexcept
Definition: overflow.h:32
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:73
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:47