diff options
| author | 2026-07-10 13:52:08 +0100 | |
|---|---|---|
| committer | 2026-07-10 13:52:08 +0100 | |
| commit | b4899b86eefe71ab58e63dd1538b0ea6093f9b12 (patch) | |
| tree | 5bb6a87638bf9ce608c64a68efaa4f6746bb01e7 /include/utility/numeric.h | |
| parent | Use saturating adds in the xline header. (diff) | |
Fix some logic errors in saturating_{add,sub}. upstream/master
Diffstat (limited to 'include/utility/numeric.h')
| -rw-r--r-- | include/utility/numeric.h | 16 |
1 files changed, 8 insertions, 8 deletions
diff --git a/include/utility/numeric.h b/include/utility/numeric.h index 8bfe059f3..ea0d34b8c 100644 --- a/include/utility/numeric.h +++ b/include/utility/numeric.h @@ -65,15 +65,15 @@ namespace insp template <std::integral R, std::integral T1, std::integral T2> constexpr R saturating_add(T1 lhs, T2 rhs) noexcept { - if (std::cmp_greater(rhs, 0) && std::cmp_greater(lhs, std::numeric_limits<R>::max() - rhs)) + using CommonType = std::common_type_t<R, T1, T2>; + + if (std::cmp_greater(rhs, 0) && std::cmp_greater(lhs, std::numeric_limits<CommonType>::max() - rhs)) return std::numeric_limits<R>::max(); // Too big for R. - if (std::cmp_less(rhs, 0) && std::cmp_less(lhs, std::numeric_limits<R>::min() - rhs)) + if (std::cmp_less(rhs, 0) && std::cmp_less(lhs, std::numeric_limits<CommonType>::min() - rhs)) return std::numeric_limits<R>::min(); // Too small for R. - using CommonType = std::common_type_t<R, T1, T2>; const auto result = static_cast<CommonType>(lhs) + static_cast<CommonType>(rhs); - if constexpr (std::is_signed_v<T1> != std::is_signed_v<T2> || std::is_signed_v<R> != std::is_signed_v<CommonType>) { if (!std::in_range<R>(result)) @@ -96,15 +96,15 @@ namespace insp template <std::integral R, std::integral T1, std::integral T2> constexpr R saturating_sub(T1 lhs, T2 rhs) noexcept { - if (std::cmp_greater(rhs, 0) && std::cmp_less(lhs, std::numeric_limits<R>::min() + rhs)) + using CommonType = std::common_type_t<R, T1, T2>; + + if (std::cmp_greater(rhs, 0) && std::cmp_less(lhs, std::numeric_limits<CommonType>::min() + rhs)) return std::numeric_limits<R>::min(); // Too small for R. - if (std::cmp_less(rhs, 0) && std::cmp_greater(lhs, std::numeric_limits<R>::max() + rhs)) + if (std::cmp_less(rhs, 0) && std::cmp_greater(lhs, std::numeric_limits<CommonType>::max() + rhs)) return std::numeric_limits<R>::max(); // Too big for R. - using CommonType = std::common_type_t<R, T1, T2>; const auto result = static_cast<CommonType>(lhs) - static_cast<CommonType>(rhs); - if constexpr (std::is_signed_v<T1> != std::is_signed_v<T2> || std::is_signed_v<R> != std::is_signed_v<CommonType>) { if (!std::in_range<R>(result)) |
