From 91e2beb5d40655bfe8b2273c58e5e039f01085ca Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 02:53:46 +0300 Subject: [PATCH] feat(Math): add span-safe parsers, checked_cast, and checked_mul_add (M-MATH-02) --- include/Void/Math/Numeric.hpp | 565 ++++++++++++++++++++++++++++-- tests/standalone/Math/Numeric.cpp | 307 ++++++++++++++++ 2 files changed, 842 insertions(+), 30 deletions(-) diff --git a/include/Void/Math/Numeric.hpp b/include/Void/Math/Numeric.hpp index c07b0a2..130e48f 100644 --- a/include/Void/Math/Numeric.hpp +++ b/include/Void/Math/Numeric.hpp @@ -1,13 +1,30 @@ #pragma once +#include +#include +#include #include -#include +#include +#include #include #include #include #include +#include #include +#if defined(__has_builtin) +# if __has_builtin(__builtin_add_overflow) +# define VOID_NUMERIC_HAS_BUILTIN_ADD_OVERFLOW 1 +# endif +# if __has_builtin(__builtin_sub_overflow) +# define VOID_NUMERIC_HAS_BUILTIN_SUB_OVERFLOW 1 +# endif +# if __has_builtin(__builtin_mul_overflow) +# define VOID_NUMERIC_HAS_BUILTIN_MUL_OVERFLOW 1 +# endif +#endif + namespace Void::Numeric { @@ -19,27 +36,158 @@ enum class Error Underflow, DivisionByZero, InvalidInput, + Inexact, + NonFinite, }; [[nodiscard]] constexpr std::string_view to_string(Error e) noexcept { switch (e) { - case Error::Overflow: return "overflow"; - case Error::Underflow: return "underflow"; + case Error::Overflow: return "overflow"; + case Error::Underflow: return "underflow"; case Error::DivisionByZero: return "division by zero"; - case Error::InvalidInput: return "invalid input"; + case Error::InvalidInput: return "invalid input"; + case Error::Inexact: return "inexact conversion"; + case Error::NonFinite: return "non-finite floating value"; } return "unknown"; } +enum class Rounding +{ + exact, + toward_zero, + nearest_even, +}; + +inline constexpr std::size_t kMaxNumericTokenBytes = 256; + +template +concept ArithmeticScalar = + (std::integral || std::floating_point) && + !std::same_as, bool>; + +namespace detail +{ + +template +[[nodiscard]] constexpr std::make_unsigned_t abs_unsigned(T v) noexcept +{ + using U = std::make_unsigned_t; + if constexpr (std::is_signed_v) { + if (v < T{0}) { + return static_cast(U{0} - static_cast(v)); + } + } + return static_cast(v); +} + +template +[[nodiscard]] constexpr bool portable_add_overflow(T a, T b, T* out) noexcept +{ + using U = std::make_unsigned_t; + const U ua = static_cast(a); + const U ub = static_cast(b); + const U ures = static_cast(ua + ub); + *out = static_cast(ures); + if constexpr (std::is_unsigned_v) { + return ures < ua; + } else { + return (b > T{0} && a > std::numeric_limits::max() - b) || + (b < T{0} && a < std::numeric_limits::min() - b); + } +} + +template +[[nodiscard]] constexpr bool portable_sub_overflow(T a, T b, T* out) noexcept +{ + using U = std::make_unsigned_t; + const U ua = static_cast(a); + const U ub = static_cast(b); + const U ures = static_cast(ua - ub); + *out = static_cast(ures); + if constexpr (std::is_unsigned_v) { + return ua < ub; + } else { + return (b < T{0} && a > std::numeric_limits::max() + b) || + (b > T{0} && a < std::numeric_limits::min() + b); + } +} + +template +[[nodiscard]] constexpr bool portable_mul_overflow(T a, T b, T* out) noexcept +{ + using U = std::make_unsigned_t; + using MulU = std::conditional_t<(sizeof(U) < sizeof(unsigned int)), unsigned int, U>; + const U ures = static_cast( + static_cast(static_cast(a)) * static_cast(static_cast(b))); + *out = static_cast(ures); + if (a == T{0} || b == T{0}) { + return false; + } + if constexpr (std::is_unsigned_v) { + return static_cast(a) > std::numeric_limits::max() / static_cast(b); + } else { + const bool neg = (a < T{0}) != (b < T{0}); + const U ua = abs_unsigned(a); + const U ub = abs_unsigned(b); + const U limit = neg ? abs_unsigned(std::numeric_limits::min()) + : static_cast(std::numeric_limits::max()); + return ua > (limit / ub); + } +} + +struct U128Parts +{ + std::uint64_t hi; + std::uint64_t lo; +}; + +[[nodiscard]] constexpr U128Parts mul_u64(std::uint64_t a, std::uint64_t b) noexcept +{ + const std::uint64_t a_lo = a & 0xFFFFFFFFULL; + const std::uint64_t a_hi = a >> 32; + const std::uint64_t b_lo = b & 0xFFFFFFFFULL; + const std::uint64_t b_hi = b >> 32; + + const std::uint64_t p0 = a_lo * b_lo; + const std::uint64_t p1 = a_lo * b_hi; + const std::uint64_t p2 = a_hi * b_lo; + const std::uint64_t p3 = a_hi * b_hi; + + const std::uint64_t mid = + (p0 >> 32) + (p1 & 0xFFFFFFFFULL) + (p2 & 0xFFFFFFFFULL); + const std::uint64_t lo = (p0 & 0xFFFFFFFFULL) | (mid << 32); + const std::uint64_t hi = p3 + (p1 >> 32) + (p2 >> 32) + (mid >> 32); + return {hi, lo}; +} + +template +[[nodiscard]] constexpr T from_signed_magnitude(bool neg, std::uint64_t mag) noexcept +{ + using U = std::make_unsigned_t; + if (!neg) { + return static_cast(static_cast(mag)); + } + const U umag = static_cast(mag); + return static_cast(static_cast(U{0} - umag)); +} + +} // namespace detail + // ── Checked arithmetic ──────────────────────────────────────────────────────── template [[nodiscard]] constexpr std::expected checked_add(T a, T b) noexcept { - T result; - if (__builtin_add_overflow(a, b, &result)) { - return std::unexpected{b > 0 ? Error::Overflow : Error::Underflow}; + T result{}; +#if defined(VOID_NUMERIC_HAS_BUILTIN_ADD_OVERFLOW) + const bool overflow = __builtin_add_overflow(a, b, &result); +#else + const bool overflow = detail::portable_add_overflow(a, b, &result); +#endif + if (overflow) { + return std::unexpected{b > T{0} ? Error::Overflow : Error::Underflow}; } return result; } @@ -47,9 +195,14 @@ template template [[nodiscard]] constexpr std::expected checked_sub(T a, T b) noexcept { - T result; - if (__builtin_sub_overflow(a, b, &result)) { - return std::unexpected{b > 0 ? Error::Underflow : Error::Overflow}; + T result{}; +#if defined(VOID_NUMERIC_HAS_BUILTIN_SUB_OVERFLOW) + const bool overflow = __builtin_sub_overflow(a, b, &result); +#else + const bool overflow = detail::portable_sub_overflow(a, b, &result); +#endif + if (overflow) { + return std::unexpected{b > T{0} ? Error::Underflow : Error::Overflow}; } return result; } @@ -57,13 +210,82 @@ template template [[nodiscard]] constexpr std::expected checked_mul(T a, T b) noexcept { - T result; - if (__builtin_mul_overflow(a, b, &result)) { + T result{}; +#if defined(VOID_NUMERIC_HAS_BUILTIN_MUL_OVERFLOW) + const bool overflow = __builtin_mul_overflow(a, b, &result); +#else + const bool overflow = detail::portable_mul_overflow(a, b, &result); +#endif + if (overflow) { return std::unexpected{Error::Overflow}; } return result; } +template + requires (!std::same_as, bool> && sizeof(T) <= sizeof(std::uint64_t)) +[[nodiscard]] constexpr std::expected checked_mul_add(T a, T b, T c) noexcept +{ + if constexpr (std::is_unsigned_v) { + detail::U128Parts acc = + detail::mul_u64(static_cast(a), static_cast(b)); + const std::uint64_t uc = static_cast(c); + acc.lo += uc; + if (acc.lo < uc) { + ++acc.hi; + } + if (acc.hi != 0 || acc.lo > static_cast(std::numeric_limits::max())) { + return std::unexpected{Error::Overflow}; + } + return static_cast(acc.lo); + } else { + const bool prod_zero = (a == T{0} || b == T{0}); + const bool prod_neg = !prod_zero && ((a < T{0}) != (b < T{0})); + detail::U128Parts prod = prod_zero + ? detail::U128Parts{0, 0} + : detail::mul_u64( + static_cast(detail::abs_unsigned(a)), + static_cast(detail::abs_unsigned(b))); + + const bool c_neg = (c < T{0}); + const std::uint64_t uc = static_cast(detail::abs_unsigned(c)); + const std::uint64_t max_pos = + static_cast(std::numeric_limits::max()); + const std::uint64_t max_neg = + static_cast(detail::abs_unsigned(std::numeric_limits::min())); + + if (prod_zero) { + return c; + } + if (c == T{0} || prod_neg == c_neg) { + prod.lo += uc; + if (prod.lo < uc) { + ++prod.hi; + } + const std::uint64_t limit = prod_neg ? max_neg : max_pos; + if (prod.hi != 0 || prod.lo > limit) { + return std::unexpected{prod_neg ? Error::Underflow : Error::Overflow}; + } + return detail::from_signed_magnitude(prod_neg, prod.lo); + } + + if (prod.hi > 0 || prod.lo >= uc) { + if (prod.lo < uc) { + --prod.hi; + } + prod.lo -= uc; + const bool res_neg = (prod.hi != 0 || prod.lo != 0) ? prod_neg : false; + const std::uint64_t limit = res_neg ? max_neg : max_pos; + if (prod.hi != 0 || prod.lo > limit) { + return std::unexpected{res_neg ? Error::Underflow : Error::Overflow}; + } + return detail::from_signed_magnitude(res_neg, prod.lo); + } + + return detail::from_signed_magnitude(c_neg, uc - prod.lo); + } +} + template [[nodiscard]] constexpr std::expected checked_div(T a, T b) noexcept { @@ -135,32 +357,312 @@ template return val; } +namespace detail +{ + +template +[[nodiscard]] constexpr bool in_int_range(From v) noexcept +{ + if constexpr (std::is_signed_v == std::is_signed_v) { + return v >= std::numeric_limits::min() && + v <= std::numeric_limits::max(); + } else if constexpr (std::is_signed_v) { + // From signed, To unsigned + if (v < From{0}) { + return false; + } + using UFrom = std::make_unsigned_t; + return static_cast(v) <= std::numeric_limits::max(); + } else { + // From unsigned, To signed + using UTo = std::make_unsigned_t; + return v <= static_cast(std::numeric_limits::max()); + } +} + +template +[[nodiscard]] constexpr F round_nearest_even(F v) noexcept +{ + const F trunc_v = std::trunc(v); + const F frac = std::fabs(v - trunc_v); + if (frac < F{0.5}) { + return trunc_v; + } + const F step = (v >= F{0}) ? F{1} : F{-1}; + if (frac > F{0.5}) { + return trunc_v + step; + } + // Tie at .5: round toward even integer neighbor independent of FE_ROUND. + const bool is_even = (std::trunc(trunc_v * F{0.5}) * F{2}) == trunc_v; + return is_even ? trunc_v : (trunc_v + step); +} + +[[nodiscard]] inline Error classify_real_out_of_range(std::string_view s, bool neg) noexcept +{ + const std::size_t first_idx = neg ? 1u : 0u; + bool seen_dot = false; + bool seen_nonzero = false; + long long approx_exp10 = 0; + std::size_t i = first_idx; + for (; i < s.size() && s[i] != 'e' && s[i] != 'E'; ++i) { + const char ch = s[i]; + if (ch == '.') { + seen_dot = true; + continue; + } + if (!seen_dot) { + if (seen_nonzero) { + ++approx_exp10; + } else if (ch != '0') { + seen_nonzero = true; + } + } else if (!seen_nonzero) { + --approx_exp10; + if (ch != '0') { + seen_nonzero = true; + } + } + } + if (!seen_nonzero) { + return Error::Underflow; + } + long long exp_val = 0; + if (i < s.size() && (s[i] == 'e' || s[i] == 'E')) { + ++i; + bool exp_neg = false; + if (i < s.size() && (s[i] == '+' || s[i] == '-')) { + exp_neg = (s[i] == '-'); + ++i; + } + for (; i < s.size(); ++i) { + if (exp_val < 1'000'000LL) { + exp_val = exp_val * 10 + (s[i] - '0'); + } + } + if (exp_neg) { + exp_val = -exp_val; + } + } + if (approx_exp10 + exp_val < 0) { + return Error::Underflow; + } + return neg ? Error::Underflow : Error::Overflow; +} + +} // namespace detail + +// ── Checked arithmetic conversion ───────────────────────────────────────────── + +template +[[nodiscard]] constexpr std::expected + checked_cast(From value, Rounding mode = Rounding::exact) noexcept +{ + if constexpr (std::same_as, std::remove_cv_t>) { + if constexpr (std::floating_point) { + if (!std::isfinite(value)) { + return std::unexpected{Error::NonFinite}; + } + } + return value; + } else if constexpr (std::integral && std::integral) { + if (!detail::in_int_range(value)) { + if constexpr (std::is_signed_v) { + if (value < From{0}) { + return std::unexpected{Error::Underflow}; + } + } + return std::unexpected{Error::Overflow}; + } + return static_cast(value); + } else if constexpr (std::integral && std::floating_point) { + if (value == From{0}) { + return To{0}; + } + const bool neg = (std::is_signed_v && value < From{0}); + const std::uint64_t mag = static_cast(detail::abs_unsigned(value)); + const int width = static_cast(std::bit_width(mag)); + const int msb = width - 1; + const int sig_bits = width - std::countr_zero(mag); + constexpr int kPrec = std::numeric_limits::digits; + if (sig_bits <= kPrec) { + if (msb >= std::numeric_limits::max_exponent) { + return std::unexpected{neg ? Error::Underflow : Error::Overflow}; + } + return static_cast(value); + } + if (mode == Rounding::exact) { + return std::unexpected{Error::Inexact}; + } + const int drop = width - kPrec; // >= 1 + const std::uint64_t mask = (std::uint64_t{1} << drop) - std::uint64_t{1}; + const std::uint64_t rem = mag & mask; + std::uint64_t shifted = mag >> drop; + if (mode == Rounding::nearest_even) { + const std::uint64_t half = std::uint64_t{1} << (drop - 1); + if (rem > half || (rem == half && (shifted & std::uint64_t{1}) != 0)) { + ++shifted; + } + } + const int result_msb = + (shifted >= (std::uint64_t{1} << kPrec)) ? (msb + 1) : msb; + if (result_msb >= std::numeric_limits::max_exponent) { + return std::unexpected{neg ? Error::Underflow : Error::Overflow}; + } + const To out_mag = std::ldexp(static_cast(shifted), drop); + return neg ? -out_mag : out_mag; + } else if constexpr (std::floating_point && std::integral) { + if (!std::isfinite(value)) { + return std::unexpected{Error::NonFinite}; + } + constexpr int kToBits = std::numeric_limits::digits; + constexpr bool kHasUpper = (kToBits < std::numeric_limits::max_exponent); + const From upper_excl = kHasUpper ? std::ldexp(From{1}, kToBits) : From{0}; + constexpr bool kHasLower = + std::is_unsigned_v || (kToBits < std::numeric_limits::max_exponent); + const From lower_incl = std::is_unsigned_v + ? From{0} + : (kHasLower ? -std::ldexp(From{1}, kToBits) : From{0}); + + From rounded = value; + if (mode == Rounding::exact) { + if constexpr (kHasLower) { + if (value < lower_incl) { + return std::unexpected{Error::Underflow}; + } + } + if constexpr (kHasUpper) { + if (value >= upper_excl) { + return std::unexpected{Error::Overflow}; + } + } + if (std::trunc(value) != value) { + return std::unexpected{Error::Inexact}; + } + } else { + rounded = (mode == Rounding::toward_zero) + ? std::trunc(value) + : detail::round_nearest_even(value); + if constexpr (kHasLower) { + if (rounded < lower_incl) { + return std::unexpected{Error::Underflow}; + } + } + if constexpr (kHasUpper) { + if (rounded >= upper_excl) { + return std::unexpected{Error::Overflow}; + } + } + } + return static_cast(rounded); + } else { + // Floating -> Floating + if (!std::isfinite(value)) { + return std::unexpected{Error::NonFinite}; + } + using Wide = std::conditional_t< + (std::numeric_limits::max_exponent >= std::numeric_limits::max_exponent), + From, To>; + const Wide wval = static_cast(value); + if (wval > static_cast(std::numeric_limits::max())) { + return std::unexpected{Error::Overflow}; + } + if (wval < static_cast(std::numeric_limits::lowest())) { + return std::unexpected{Error::Underflow}; + } + To out = static_cast(value); + if (!std::isfinite(out)) { + return std::unexpected{value < From{0} ? Error::Underflow : Error::Overflow}; + } + if (mode == Rounding::toward_zero && static_cast(out) != value) { + if ((value > From{0} && static_cast(out) > value) || + (value < From{0} && static_cast(out) < value)) { + out = std::nextafter(out, To{0}); + } + } else if (mode == Rounding::exact) { + if (static_cast(out) != value || std::signbit(out) != std::signbit(value)) { + return std::unexpected{Error::Inexact}; + } + } + return out; + } +} + // ── Numeric parsing ─────────────────────────────────────────────────────────── +template + requires (!std::same_as, bool>) +[[nodiscard]] inline std::expected + parse_integer(std::string_view s, int base = 10) noexcept +{ + if (base < 2 || base > 36 || s.empty() || s.size() > kMaxNumericTokenBytes) { + return std::unexpected{Error::InvalidInput}; + } + if (s.front() == '+') { + return std::unexpected{Error::InvalidInput}; + } + if constexpr (std::is_unsigned_v) { + if (s.front() == '-') { + return std::unexpected{Error::InvalidInput}; + } + } + T val{}; + const char* const first = s.data(); + const char* const last = first + s.size(); + const auto res = std::from_chars(first, last, val, base); + if (res.ptr != last) { + return std::unexpected{Error::InvalidInput}; + } + if (res.ec == std::errc::result_out_of_range) { + return std::unexpected{s.front() == '-' ? Error::Underflow : Error::Overflow}; + } + if (res.ec != std::errc{}) { + return std::unexpected{Error::InvalidInput}; + } + return val; +} + +template +[[nodiscard]] inline std::expected + parse_real(std::string_view s) noexcept +{ + if (s.empty() || s.size() > kMaxNumericTokenBytes) { + return std::unexpected{Error::InvalidInput}; + } + const bool neg = (s.front() == '-'); + const std::size_t first_idx = neg ? 1u : 0u; + if (first_idx >= s.size()) { + return std::unexpected{Error::InvalidInput}; + } + const char first_ch = s[first_idx]; + if (!((first_ch >= '0' && first_ch <= '9') || first_ch == '.')) { + return std::unexpected{Error::InvalidInput}; + } + T val{}; + const char* const first = s.data(); + const char* const last = first + s.size(); + const auto res = std::from_chars(first, last, val, std::chars_format::general); + if (res.ptr != last) { + return std::unexpected{Error::InvalidInput}; + } + if (res.ec == std::errc::result_out_of_range) { + return std::unexpected{detail::classify_real_out_of_range(s, neg)}; + } + if (res.ec != std::errc{} || !std::isfinite(val)) { + return std::unexpected{Error::InvalidInput}; + } + return val; +} + [[nodiscard]] inline std::expected parse_int(std::string_view s, int base = 10) noexcept { - if (s.empty()) return std::unexpected{Error::InvalidInput}; - char* end = nullptr; - const long v = std::strtol(s.data(), &end, base); - if (end == s.data() || end != s.data() + s.size()) { - return std::unexpected{Error::InvalidInput}; - } - if (v > std::numeric_limits::max()) return std::unexpected{Error::Overflow}; - if (v < std::numeric_limits::min()) return std::unexpected{Error::Underflow}; - return static_cast(v); + return parse_integer(s, base); } [[nodiscard]] inline std::expected parse_double(std::string_view s) noexcept { - if (s.empty()) return std::unexpected{Error::InvalidInput}; - char* end = nullptr; - const double v = std::strtod(s.data(), &end); - if (end == s.data() || end != s.data() + s.size()) { - return std::unexpected{Error::InvalidInput}; - } - return v; + return parse_real(s); } // ── Integer traits helpers ──────────────────────────────────────────────────── @@ -168,8 +670,11 @@ template template [[nodiscard]] constexpr bool in_range(long long v) noexcept { - return v >= static_cast(std::numeric_limits::min()) && - v <= static_cast(std::numeric_limits::max()); + if constexpr (std::same_as, bool>) { + return v == 0LL || v == 1LL; + } else { + return detail::in_int_range(v); + } } template diff --git a/tests/standalone/Math/Numeric.cpp b/tests/standalone/Math/Numeric.cpp index 3f777a8..43d97c3 100644 --- a/tests/standalone/Math/Numeric.cpp +++ b/tests/standalone/Math/Numeric.cpp @@ -2,8 +2,12 @@ #include #include +#include +#include #include #include +#include +#include // ── checked_add ─────────────────────────────────────────────────────────────── @@ -190,3 +194,306 @@ Void::Testing::Test narrow_cast_out_of_range() { Void::Testing::expect(!Void::Numeric::narrow_cast(500LL).has_value()); } + +Void::Testing::Test in_range_supports_unsigned_64() +{ + Void::Testing::expect(Void::Numeric::in_range(42LL)); + Void::Testing::expect(!Void::Numeric::in_range(-1LL)); + const auto r = Void::Numeric::narrow_cast(42LL); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::uint64_t{42}); +} + +// ── span-safe parse_integer / parse_real ───────────────────────────────────── + +Void::Testing::Test parse_non_nul_terminated_substrings() +{ + const char int_buf[3] = {'4', '2', '9'}; + const std::string_view int_slice{int_buf, 2}; + const auto i1 = Void::Numeric::parse_integer(int_slice); + const auto i2 = Void::Numeric::parse_int(int_slice); + Void::Testing::expect(i1.has_value() && *i1 == 42); + Void::Testing::expect(i2.has_value() && *i2 == 42); + + const char real_buf[5] = {'3', '.', '1', '4', '9'}; + const std::string_view real_slice{real_buf, 4}; + const auto d1 = Void::Numeric::parse_real(real_slice); + const auto d2 = Void::Numeric::parse_double(real_slice); + Void::Testing::expect(d1.has_value() && *d1 > 3.139 && *d1 < 3.141); + Void::Testing::expect(d2.has_value() && *d2 > 3.139 && *d2 < 3.141); +} + +Void::Testing::Test parse_integer_rejections_and_bounds() +{ + using Void::Numeric::Error; + using Void::Numeric::parse_integer; + + Void::Testing::expect(parse_integer("") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer(" 42") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("+42") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("42 ") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("42abc") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("10", 1) == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("10", 37) == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("10", 0) == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_integer("-9999xyz") == std::unexpected{Error::InvalidInput}); + + const std::string too_long(Void::Numeric::kMaxNumericTokenBytes + 1, '0'); + Void::Testing::expect(parse_integer(too_long) == std::unexpected{Error::InvalidInput}); + std::string exact_max_len(Void::Numeric::kMaxNumericTokenBytes - 2, '0'); + exact_max_len += "42"; + Void::Testing::expect_eq(*parse_integer(exact_max_len), 42); + + Void::Testing::expect_eq(*parse_integer("127"), std::int8_t{127}); + Void::Testing::expect_eq(*parse_integer("-128"), std::int8_t{-128}); + Void::Testing::expect(parse_integer("128") == std::unexpected{Error::Overflow}); + Void::Testing::expect(parse_integer("-129") == std::unexpected{Error::Underflow}); + + Void::Testing::expect_eq( + *parse_integer("18446744073709551615"), + std::numeric_limits::max()); + Void::Testing::expect( + parse_integer("18446744073709551616") == std::unexpected{Error::Overflow}); + Void::Testing::expect( + parse_integer("-1") == std::unexpected{Error::InvalidInput}); +} + +Void::Testing::Test parse_real_rejections_and_bounds() +{ + using Void::Numeric::Error; + using Void::Numeric::parse_real; + + Void::Testing::expect(parse_real("") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real(" 1.5") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("+1.5") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("1.5 ") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("1.5xyz") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("nan") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("-nan") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("inf") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("-inf") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("INF") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("infinity") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("1e400xyz") == std::unexpected{Error::InvalidInput}); + Void::Testing::expect(parse_real("-.") == std::unexpected{Error::InvalidInput}); + + const std::string too_long(Void::Numeric::kMaxNumericTokenBytes + 1, '1'); + Void::Testing::expect(parse_real(too_long) == std::unexpected{Error::InvalidInput}); + + Void::Testing::expect(parse_real("1e400") == std::unexpected{Error::Overflow}); + Void::Testing::expect(parse_real("-1e400") == std::unexpected{Error::Underflow}); + Void::Testing::expect(parse_real("1e-500") == std::unexpected{Error::Underflow}); + + const auto neg_zero = parse_real("-0.0"); + Void::Testing::expect(neg_zero.has_value()); + Void::Testing::expect(std::signbit(*neg_zero)); + + const auto half_lead_dot = parse_real("-.5"); + Void::Testing::expect(half_lead_dot.has_value()); + Void::Testing::expect(*half_lead_dot == -0.5); +} + +// ── checked_cast ───────────────────────────────────────────────────────────── + +Void::Testing::Test checked_cast_int_to_int() +{ + using Void::Numeric::checked_cast; + using Void::Numeric::Error; + + static_assert(checked_cast(std::int32_t{-32768}).value() == -32768); + static_assert(checked_cast(std::int32_t{-1}).error() == Error::Underflow); + static_assert(checked_cast(std::numeric_limits::max()).error() == Error::Overflow); + + Void::Testing::expect( + checked_cast(std::numeric_limits::min()) == + std::unexpected{Error::Underflow}); + Void::Testing::expect_eq( + *checked_cast(std::numeric_limits::max()), + static_cast(std::numeric_limits::max())); +} + +Void::Testing::Test checked_cast_int_to_float() +{ + using Void::Numeric::checked_cast; + using Void::Numeric::Error; + using Void::Numeric::Rounding; + + const auto min_i64_f = checked_cast(std::numeric_limits::min()); + Void::Testing::expect(min_i64_f.has_value()); + Void::Testing::expect(*min_i64_f == -std::ldexp(1.0F, 63)); + + constexpr std::uint64_t exact_53 = (std::uint64_t{1} << 53); + Void::Testing::expect_eq(*checked_cast(exact_53), static_cast(exact_53)); + Void::Testing::expect_eq(*checked_cast(exact_53 + 2ULL), static_cast(exact_53) + 2.0); + Void::Testing::expect(checked_cast(exact_53 + 1ULL) == std::unexpected{Error::Inexact}); + Void::Testing::expect_eq( + *checked_cast(exact_53 + 1ULL, Rounding::nearest_even), + static_cast(exact_53)); + Void::Testing::expect_eq( + *checked_cast(exact_53 + 3ULL, Rounding::nearest_even), + static_cast(exact_53 + 4ULL)); + Void::Testing::expect_eq( + *checked_cast(exact_53 + 3ULL, Rounding::toward_zero), + static_cast(exact_53 + 2ULL)); + + const auto u64_max = std::numeric_limits::max(); + Void::Testing::expect(checked_cast(u64_max) == std::unexpected{Error::Inexact}); + Void::Testing::expect_eq( + *checked_cast(u64_max, Rounding::nearest_even), + std::ldexp(1.0, 64)); + Void::Testing::expect_eq( + *checked_cast(u64_max, Rounding::toward_zero), + std::ldexp(1.0, 64) - 2048.0); +} + +Void::Testing::Test checked_cast_float_to_int_boundaries_and_rounding() +{ + using Void::Numeric::checked_cast; + using Void::Numeric::Error; + using Void::Numeric::Rounding; + + Void::Testing::expect( + checked_cast(std::numeric_limits::quiet_NaN()) == + std::unexpected{Error::NonFinite}); + Void::Testing::expect( + checked_cast(std::numeric_limits::infinity()) == + std::unexpected{Error::NonFinite}); + Void::Testing::expect( + checked_cast(-std::numeric_limits::infinity()) == + std::unexpected{Error::NonFinite}); + + // Exact 2^63 / 2^64 exclusive upper boundaries. + const double two_63 = std::ldexp(1.0, 63); + const double two_64 = std::ldexp(1.0, 64); + Void::Testing::expect(checked_cast(two_63) == std::unexpected{Error::Overflow}); + Void::Testing::expect_eq(*checked_cast(-two_63), std::numeric_limits::min()); + Void::Testing::expect(checked_cast(-two_63 - 2048.0) == std::unexpected{Error::Underflow}); + Void::Testing::expect_eq(*checked_cast(two_63 - 1024.0), std::int64_t{9223372036854774784LL}); + + Void::Testing::expect(checked_cast(two_64) == std::unexpected{Error::Overflow}); + Void::Testing::expect_eq(*checked_cast(two_64 - 2048.0), std::uint64_t{18446744073709549568ULL}); + Void::Testing::expect_eq(*checked_cast(-0.0), std::uint64_t{0}); + Void::Testing::expect(checked_cast(-1.0) == std::unexpected{Error::Underflow}); + + // Exact vs toward_zero vs nearest_even (independent of FE_ROUND). + Void::Testing::expect(checked_cast(1.5) == std::unexpected{Error::Inexact}); + Void::Testing::expect_eq(*checked_cast(1.9, Rounding::toward_zero), 1); + Void::Testing::expect_eq(*checked_cast(-1.9, Rounding::toward_zero), -1); + + const int saved_round = std::fegetround(); + std::fesetround(FE_DOWNWARD); + Void::Testing::expect_eq(*checked_cast(0.5, Rounding::nearest_even), 0); + Void::Testing::expect_eq(*checked_cast(1.5, Rounding::nearest_even), 2); + Void::Testing::expect_eq(*checked_cast(2.5, Rounding::nearest_even), 2); + Void::Testing::expect_eq(*checked_cast(-0.5, Rounding::nearest_even), 0); + Void::Testing::expect_eq(*checked_cast(-1.5, Rounding::nearest_even), -2); + Void::Testing::expect_eq(*checked_cast(-2.5, Rounding::nearest_even), -2); + std::fesetround(FE_UPWARD); + Void::Testing::expect_eq(*checked_cast(127.5, Rounding::toward_zero), std::int8_t{127}); + Void::Testing::expect( + checked_cast(127.5, Rounding::nearest_even) == + std::unexpected{Error::Overflow}); + Void::Testing::expect_eq(*checked_cast(-128.5, Rounding::nearest_even), std::int8_t{-128}); + std::fesetround(saved_round); +} + +Void::Testing::Test checked_cast_float_to_float() +{ + using Void::Numeric::checked_cast; + using Void::Numeric::Error; + using Void::Numeric::Rounding; + + Void::Testing::expect( + checked_cast(std::numeric_limits::quiet_NaN()) == + std::unexpected{Error::NonFinite}); + Void::Testing::expect( + checked_cast(std::numeric_limits::infinity()) == + std::unexpected{Error::NonFinite}); + Void::Testing::expect(checked_cast(1e40) == std::unexpected{Error::Overflow}); + Void::Testing::expect(checked_cast(-1e40) == std::unexpected{Error::Underflow}); + + const auto neg_zero_f = checked_cast(-0.0); + Void::Testing::expect(neg_zero_f.has_value()); + Void::Testing::expect(std::signbit(*neg_zero_f)); + + Void::Testing::expect_eq(*checked_cast(0.5), 0.5F); + Void::Testing::expect(checked_cast(0.1) == std::unexpected{Error::Inexact}); + Void::Testing::expect(checked_cast(1e-300) == std::unexpected{Error::Inexact}); + Void::Testing::expect(checked_cast(0.1, Rounding::nearest_even).has_value()); + + const double upper_gap = + static_cast(std::numeric_limits::max()) + std::ldexp(1.0, 102); + Void::Testing::expect(checked_cast(upper_gap) == std::unexpected{Error::Overflow}); + const double trunc_src = 1.0 + std::ldexp(1.0, -24) + std::ldexp(1.0, -25); + Void::Testing::expect_eq(*checked_cast(trunc_src, Rounding::toward_zero), 1.0F); +} + +// ── checked_mul_add & portable overflow helpers ────────────────────────────── + +Void::Testing::Test checked_mul_add_handles_intermediate_and_real_overflow() +{ + using Void::Numeric::checked_mul_add; + using Void::Numeric::Error; + + // Product 2 * INT32_MAX overflows int32_t, but + INT32_MIN brings it back in range. + constexpr auto i32_max = std::numeric_limits::max(); + constexpr auto i32_min = std::numeric_limits::min(); + static_assert(checked_mul_add(2, i32_max, i32_min).value() == i32_max - 1); + + constexpr auto i64_max = std::numeric_limits::max(); + constexpr auto i64_min = std::numeric_limits::min(); + Void::Testing::expect_eq( + *checked_mul_add(2, i64_max, i64_min), + i64_max - 1); + Void::Testing::expect_eq( + *checked_mul_add(-2, i64_max, i64_max), + -i64_max); + Void::Testing::expect( + checked_mul_add(i64_max, 2, -1) == std::unexpected{Error::Overflow}); + Void::Testing::expect( + checked_mul_add(i64_min, 2, 1) == std::unexpected{Error::Underflow}); + + constexpr auto u64_max = std::numeric_limits::max(); + Void::Testing::expect_eq( + *checked_mul_add(u64_max / 2ULL, 2ULL, 1ULL), + u64_max); + Void::Testing::expect( + checked_mul_add(u64_max, 1ULL, 1ULL) == std::unexpected{Error::Overflow}); + Void::Testing::expect( + checked_mul_add(u64_max, u64_max, 0ULL) == std::unexpected{Error::Overflow}); +} + +Void::Testing::Test portable_overflow_helpers_boundary_cases() +{ + using Void::Numeric::detail::portable_add_overflow; + using Void::Numeric::detail::portable_mul_overflow; + using Void::Numeric::detail::portable_sub_overflow; + + constexpr auto verify_constexpr = []() consteval { + std::int8_t s8 = 0; + if (!portable_add_overflow(127, 1, &s8)) return false; + if (!portable_add_overflow(-128, -1, &s8)) return false; + if (portable_add_overflow(127, -128, &s8) || s8 != -1) return false; + + if (!portable_sub_overflow(-128, 1, &s8)) return false; + if (!portable_sub_overflow(127, -1, &s8)) return false; + if (portable_sub_overflow(-1, -128, &s8) || s8 != 127) return false; + + if (!portable_mul_overflow(-128, -1, &s8)) return false; + if (!portable_mul_overflow(-65, 2, &s8)) return false; + if (portable_mul_overflow(-64, 2, &s8) || s8 != -128) return false; + + std::uint16_t u16 = 0; + if (!portable_mul_overflow(65535, 65535, &u16)) return false; + if (portable_mul_overflow(257, 255, &u16) || u16 != 65535) return false; + return true; + }; + static_assert(verify_constexpr()); + + std::uint64_t u64 = 0; + Void::Testing::expect(portable_add_overflow( + std::numeric_limits::max(), 1ULL, &u64)); + Void::Testing::expect(portable_sub_overflow(0ULL, 1ULL, &u64)); + Void::Testing::expect(portable_mul_overflow( + std::numeric_limits::max(), 2ULL, &u64)); +}