5#ifndef BITCOIN_UTIL_OVERFLOW_H
6#define BITCOIN_UTIL_OVERFLOW_H
13template <std::
integral T>
15 if constexpr (std::numeric_limits<T>::is_signed) {
16 return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
17 (i < 0 && j < std::numeric_limits<T>::min() - i);
19 return std::numeric_limits<T>::max() - i < j;
23[[nodiscard]] std::optional<T>
CheckedAdd(
const T i,
const T j)
noexcept {
30template <std::
integral T>
32 if constexpr (std::numeric_limits<T>::is_signed) {
33 if (i > 0 && j > std::numeric_limits<T>::max() - i) {
34 return std::numeric_limits<T>::max();
36 if (i < 0 && j < std::numeric_limits<T>::min() - i) {
37 return std::numeric_limits<T>::min();
40 if (std::numeric_limits<T>::max() - i < j) {
41 return std::numeric_limits<T>::max();
47template <std::
unsigned_
integral T, std::
unsigned_
integral U>
48[[nodiscard]]
constexpr bool TrySub(T &i,
const U j)
noexcept {
62template <std::
integral T>
64 if (shift == 0 || input == 0) {
68 if (shift >=
sizeof(T) * CHAR_BIT) {
72 if (input > (std::numeric_limits<T>::max() >> shift)) {
75 if (input < (std::numeric_limits<T>::min() >> shift)) {
78 return input << shift;
88template <std::
integral T>
95 return input < 0 ? std::numeric_limits<T>::min()
96 : std::numeric_limits<T>::max();
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.