5#ifndef BITCOIN_UTIL_OVERFLOW_H
6#define BITCOIN_UTIL_OVERFLOW_H
18 static_assert(std::is_integral_v<T>,
"Integral required.");
19 if constexpr (std::numeric_limits<T>::is_signed) {
20 return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
21 (i < 0 && j < std::numeric_limits<T>::min() - i);
23 return std::numeric_limits<T>::max() - i < j;
27[[nodiscard]] std::optional<T>
CheckedAdd(
const T i,
const T j)
noexcept
35template <std::
unsigned_
integral T, std::
unsigned_
integral U>
36[[nodiscard]]
constexpr bool TrySub(T& i,
const U j)
noexcept
38 if (i <
T{j})
return false;
46 if constexpr (std::numeric_limits<T>::is_signed) {
47 if (i > 0 && j > std::numeric_limits<T>::max() - i) {
48 return std::numeric_limits<T>::max();
50 if (i < 0 && j < std::numeric_limits<T>::min() - i) {
51 return std::numeric_limits<T>::min();
54 if (std::numeric_limits<T>::max() - i < j) {
55 return std::numeric_limits<T>::max();
69template <std::
unsigned_
integral Div
idend, std::
unsigned_
integral Divisor>
70[[nodiscard]]
constexpr auto CeilDiv(
const Dividend dividend,
const Divisor divisor)
73 return dividend / divisor + (dividend % divisor != 0);
82template <std::
integral T>
85 if (shift == 0 || input == 0)
return input;
87 if (shift >=
sizeof(
T) * CHAR_BIT)
return std::nullopt;
89 if (input > (std::numeric_limits<T>::max() >> shift))
return std::nullopt;
90 if (input < (std::numeric_limits<T>::min() >> shift))
return std::nullopt;
91 return input << shift;
101template <std::
integral T>
107 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.