5#ifndef BITCOIN_UTIL_OVERFLOW_H
6#define BITCOIN_UTIL_OVERFLOW_H
19 static_assert(std::is_integral_v<T>,
"Integral required.");
20 if constexpr (std::numeric_limits<T>::is_signed) {
21 return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
22 (i < 0 && j < std::numeric_limits<T>::min() - i);
24 return std::numeric_limits<T>::max() - i < j;
28[[nodiscard]] std::optional<T>
CheckedAdd(
const T i,
const T j)
noexcept
36template <std::
unsigned_
integral T, std::
unsigned_
integral U>
37[[nodiscard]]
constexpr bool TrySub(T& i,
const U j)
noexcept
39 if (i <
T{j})
return false;
47 if constexpr (std::numeric_limits<T>::is_signed) {
48 if (i > 0 && j > std::numeric_limits<T>::max() - i) {
49 return std::numeric_limits<T>::max();
51 if (i < 0 && j < std::numeric_limits<T>::min() - i) {
52 return std::numeric_limits<T>::min();
55 if (std::numeric_limits<T>::max() - i < j) {
56 return std::numeric_limits<T>::max();
70template <std::
unsigned_
integral Div
idend, std::
unsigned_
integral Divisor>
71[[nodiscard]]
constexpr auto CeilDiv(
const Dividend dividend,
const Divisor divisor)
74 return dividend / divisor + (dividend % divisor != 0);
83template <std::
integral T>
86 if (shift == 0 || input == 0)
return input;
88 if (shift >=
sizeof(
T) * CHAR_BIT)
return std::nullopt;
90 if (input > (std::numeric_limits<T>::max() >> shift))
return std::nullopt;
91 if (input < (std::numeric_limits<T>::min() >> shift))
return std::nullopt;
92 return input << shift;
102template <std::
integral T>
108 return input < 0 ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max();
#define T(expected, seed, data)
constexpr bool TrySub(T &i, const U j) noexcept
std::optional< T > CheckedAdd(const T i, const T j) noexcept
constexpr T SaturatingLeftShift(T input, unsigned shift) noexcept
Left bit shift with safe minimum and maximum values.
bool AdditionOverflow(const T i, const T j) noexcept
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
T SaturatingAdd(const T i, const T j) noexcept
constexpr std::optional< T > CheckedLeftShift(T input, unsigned shift) noexcept
Left bit shift with overflow checking.