aboutsummaryrefslogtreecommitdiff
path: root/src/util/overflow.h
diff options
context:
space:
mode:
authorMarcoFalke <falke.marco@gmail.com>2022-02-01 13:43:42 +0100
committerMarcoFalke <falke.marco@gmail.com>2022-02-21 14:32:53 +0100
commitfaa7d8a3f7cba02eca7e247108a6b98ea9daf373 (patch)
tree8826fb85e35da9fb2bee74a5da27cbf39b0c1b2a /src/util/overflow.h
parent1337b93f50d9874fa3bce7c0b5bb141aad9b1c49 (diff)
util: Add SaturatingAdd helper
Diffstat (limited to 'src/util/overflow.h')
-rw-r--r--src/util/overflow.h20
1 files changed, 19 insertions, 1 deletions
diff --git a/src/util/overflow.h b/src/util/overflow.h
index c70a8b663e..6b7dd1e8fd 100644
--- a/src/util/overflow.h
+++ b/src/util/overflow.h
@@ -13,7 +13,7 @@ template <class T>
[[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept
{
static_assert(std::is_integral<T>::value, "Integral required.");
- if (std::numeric_limits<T>::is_signed) {
+ if constexpr (std::numeric_limits<T>::is_signed) {
return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
(i < 0 && j < std::numeric_limits<T>::min() - i);
}
@@ -29,4 +29,22 @@ template <class T>
return i + j;
}
+template <class T>
+[[nodiscard]] T SaturatingAdd(const T i, const T j) noexcept
+{
+ if constexpr (std::numeric_limits<T>::is_signed) {
+ if (i > 0 && j > std::numeric_limits<T>::max() - i) {
+ return std::numeric_limits<T>::max();
+ }
+ if (i < 0 && j < std::numeric_limits<T>::min() - i) {
+ return std::numeric_limits<T>::min();
+ }
+ } else {
+ if (std::numeric_limits<T>::max() - i < j) {
+ return std::numeric_limits<T>::max();
+ }
+ }
+ return i + j;
+}
+
#endif // BITCOIN_UTIL_OVERFLOW_H