5#ifndef BITCOIN_UTIL_OVERFLOW_H
6#define BITCOIN_UTIL_OVERFLOW_H
17 static_assert(std::is_integral_v<T>,
"Integral required.");
18 if constexpr (std::numeric_limits<T>::is_signed) {
19 return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
20 (i < 0 && j < std::numeric_limits<T>::min() - i);
22 return std::numeric_limits<T>::max() - i < j;
26[[nodiscard]] std::optional<T>
CheckedAdd(
const T i,
const T j)
noexcept
34template <std::
unsigned_
integral T, std::
unsigned_
integral U>
35[[nodiscard]]
constexpr bool TrySub(T& i,
const U j)
noexcept
37 if (i <
T{j})
return false;
45 if constexpr (std::numeric_limits<T>::is_signed) {
46 if (i > 0 && j > std::numeric_limits<T>::max() - i) {
47 return std::numeric_limits<T>::max();
49 if (i < 0 && j < std::numeric_limits<T>::min() - i) {
50 return std::numeric_limits<T>::min();
53 if (std::numeric_limits<T>::max() - i < j) {
54 return std::numeric_limits<T>::max();
66template <std::
integral T>
69 if (shift == 0 || input == 0)
return input;
71 if (shift >=
sizeof(
T) * CHAR_BIT)
return std::nullopt;
73 if (input > (std::numeric_limits<T>::max() >> shift))
return std::nullopt;
74 if (input < (std::numeric_limits<T>::min() >> shift))
return std::nullopt;
75 return input << shift;
85template <std::
integral T>
91 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
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.