#pragma once #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 { // ── Error tags ──────────────────────────────────────────────────────────────── enum class Error { Overflow, 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::DivisionByZero: return "division by zero"; 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 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; } template [[nodiscard]] constexpr std::expected checked_sub(T a, T b) noexcept { 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; } template [[nodiscard]] constexpr std::expected checked_mul(T a, T b) noexcept { 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 { if (b == T{0}) return std::unexpected{Error::DivisionByZero}; if constexpr (std::is_signed_v) { if (a == std::numeric_limits::min() && b == T{-1}) { return std::unexpected{Error::Overflow}; } } return a / b; } template [[nodiscard]] constexpr std::expected checked_neg(T a) noexcept { if constexpr (std::is_unsigned_v) { if (a != T{0}) return std::unexpected{Error::Underflow}; return T{0}; } else { if (a == std::numeric_limits::min()) return std::unexpected{Error::Overflow}; return static_cast(-a); } } // ── Saturating arithmetic (never overflows, clamps to min/max) ─────────────── template [[nodiscard]] constexpr T saturating_add(T a, T b) noexcept { return checked_add(a, b).value_or( b > 0 ? std::numeric_limits::max() : std::numeric_limits::min()); } template [[nodiscard]] constexpr T saturating_sub(T a, T b) noexcept { return checked_sub(a, b).value_or( b > 0 ? std::numeric_limits::min() : std::numeric_limits::max()); } template [[nodiscard]] constexpr T saturating_mul(T a, T b) noexcept { return checked_mul(a, b).value_or( (a > 0) == (b > 0) ? std::numeric_limits::max() : std::numeric_limits::min()); } // ── Wrapping arithmetic (defined modular wrap) ─────────────────────────────── template [[nodiscard]] constexpr T wrapping_add(T a, T b) noexcept { return static_cast(a + b); } template [[nodiscard]] constexpr T wrapping_sub(T a, T b) noexcept { return static_cast(a - b); } template [[nodiscard]] constexpr T wrapping_mul(T a, T b) noexcept { return static_cast(a * b); } // ── Clamping ───────────────────────────────────────────────────────────────── template requires std::totally_ordered [[nodiscard]] constexpr T clamp(T val, T lo, T hi) noexcept { if (val < lo) return lo; if (val > hi) return hi; 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 constexpr (kPrec < 64) { 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 { return static_cast(value); } } 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 { return parse_integer(s, base); } [[nodiscard]] inline std::expected parse_double(std::string_view s) noexcept { return parse_real(s); } // ── Integer traits helpers ──────────────────────────────────────────────────── template [[nodiscard]] constexpr bool in_range(long long v) noexcept { if constexpr (std::same_as, bool>) { return v == 0LL || v == 1LL; } else { return detail::in_int_range(v); } } template [[nodiscard]] constexpr std::optional narrow_cast(long long v) noexcept { if (!in_range(v)) return std::nullopt; return static_cast(v); } } // namespace Void::Numeric