Bitcoin Core  22.99.0
P2P Digital Currency
overflow.h
Go to the documentation of this file.
1 // Copyright (c) 2021 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 <limits>
9 #include <type_traits>
10 
11 template <class T>
12 [[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept
13 {
14  static_assert(std::is_integral<T>::value, "Integral required.");
15  if (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);
18  }
19  return std::numeric_limits<T>::max() - i < j;
20 }
21 
22 template <class T>
23 [[nodiscard]] std::optional<T> CheckedAdd(const T i, const T j) noexcept
24 {
25  if (AdditionOverflow(i, j)) {
26  return std::nullopt;
27  }
28  return i + j;
29 }
30 
31 #endif // BITCOIN_UTIL_OVERFLOW_H
CheckedAdd
std::optional< T > CheckedAdd(const T i, const T j) noexcept
Definition: overflow.h:23
AdditionOverflow
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:12