feat(Math): add span-safe parsers, checked_cast, and checked_mul_add (M-MATH-02)

This commit is contained in:
faumaray committed 2026-11-24 02:53:46 +03:00
1 parent 4d48f2a8f2
commit 91e2beb5d4
2 files changed
+842 -30

No files matched your search

+535 -30
View File
@@ -1,13 +1,30 @@
#pragma once
#include <bit>
#include <charconv>
#include <cmath>
#include <concepts>
#include <cstdlib>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
#include <string_view>
#include <system_error>
#include <type_traits>
#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 <typename T>
concept ArithmeticScalar =
(std::integral<T> || std::floating_point<T>) &&
!std::same_as<std::remove_cv_t<T>, bool>;
namespace detail
{
template <std::integral T>
[[nodiscard]] constexpr std::make_unsigned_t<T> abs_unsigned(T v) noexcept
{
using U = std::make_unsigned_t<T>;
if constexpr (std::is_signed_v<T>) {
if (v < T{0}) {
return static_cast<U>(U{0} - static_cast<U>(v));
}
}
return static_cast<U>(v);
}
template <std::integral T>
[[nodiscard]] constexpr bool portable_add_overflow(T a, T b, T* out) noexcept
{
using U = std::make_unsigned_t<T>;
const U ua = static_cast<U>(a);
const U ub = static_cast<U>(b);
const U ures = static_cast<U>(ua + ub);
*out = static_cast<T>(ures);
if constexpr (std::is_unsigned_v<T>) {
return ures < ua;
} else {
return (b > T{0} && a > std::numeric_limits<T>::max() - b) ||
(b < T{0} && a < std::numeric_limits<T>::min() - b);
}
}
template <std::integral T>
[[nodiscard]] constexpr bool portable_sub_overflow(T a, T b, T* out) noexcept
{
using U = std::make_unsigned_t<T>;
const U ua = static_cast<U>(a);
const U ub = static_cast<U>(b);
const U ures = static_cast<U>(ua - ub);
*out = static_cast<T>(ures);
if constexpr (std::is_unsigned_v<T>) {
return ua < ub;
} else {
return (b < T{0} && a > std::numeric_limits<T>::max() + b) ||
(b > T{0} && a < std::numeric_limits<T>::min() + b);
}
}
template <std::integral T>
[[nodiscard]] constexpr bool portable_mul_overflow(T a, T b, T* out) noexcept
{
using U = std::make_unsigned_t<T>;
using MulU = std::conditional_t<(sizeof(U) < sizeof(unsigned int)), unsigned int, U>;
const U ures = static_cast<U>(
static_cast<MulU>(static_cast<U>(a)) * static_cast<MulU>(static_cast<U>(b)));
*out = static_cast<T>(ures);
if (a == T{0} || b == T{0}) {
return false;
}
if constexpr (std::is_unsigned_v<T>) {
return static_cast<U>(a) > std::numeric_limits<U>::max() / static_cast<U>(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<T>::min())
: static_cast<U>(std::numeric_limits<T>::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 <std::integral T>
[[nodiscard]] constexpr T from_signed_magnitude(bool neg, std::uint64_t mag) noexcept
{
using U = std::make_unsigned_t<T>;
if (!neg) {
return static_cast<T>(static_cast<U>(mag));
}
const U umag = static_cast<U>(mag);
return static_cast<T>(static_cast<U>(U{0} - umag));
}
} // namespace detail
// ── Checked arithmetic ────────────────────────────────────────────────────────
template <std::integral T>
[[nodiscard]] constexpr std::expected<T, Error> 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 <std::integral T>
template <std::integral T>
[[nodiscard]] constexpr std::expected<T, Error> 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 <std::integral T>
template <std::integral T>
[[nodiscard]] constexpr std::expected<T, Error> 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 <std::integral T>
requires (!std::same_as<std::remove_cv_t<T>, bool> && sizeof(T) <= sizeof(std::uint64_t))
[[nodiscard]] constexpr std::expected<T, Error> checked_mul_add(T a, T b, T c) noexcept
{
if constexpr (std::is_unsigned_v<T>) {
detail::U128Parts acc =
detail::mul_u64(static_cast<std::uint64_t>(a), static_cast<std::uint64_t>(b));
const std::uint64_t uc = static_cast<std::uint64_t>(c);
acc.lo += uc;
if (acc.lo < uc) {
++acc.hi;
}
if (acc.hi != 0 || acc.lo > static_cast<std::uint64_t>(std::numeric_limits<T>::max())) {
return std::unexpected{Error::Overflow};
}
return static_cast<T>(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<std::uint64_t>(detail::abs_unsigned(a)),
static_cast<std::uint64_t>(detail::abs_unsigned(b)));
const bool c_neg = (c < T{0});
const std::uint64_t uc = static_cast<std::uint64_t>(detail::abs_unsigned(c));
const std::uint64_t max_pos =
static_cast<std::uint64_t>(std::numeric_limits<T>::max());
const std::uint64_t max_neg =
static_cast<std::uint64_t>(detail::abs_unsigned(std::numeric_limits<T>::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<T>(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<T>(res_neg, prod.lo);
}
return detail::from_signed_magnitude<T>(c_neg, uc - prod.lo);
}
}
template <std::integral T>
[[nodiscard]] constexpr std::expected<T, Error> checked_div(T a, T b) noexcept
{
@@ -135,32 +357,312 @@ template <typename T>
return val;
}
namespace detail
{
template <std::integral To, std::integral From>
[[nodiscard]] constexpr bool in_int_range(From v) noexcept
{
if constexpr (std::is_signed_v<From> == std::is_signed_v<To>) {
return v >= std::numeric_limits<To>::min() &&
v <= std::numeric_limits<To>::max();
} else if constexpr (std::is_signed_v<From>) {
// From signed, To unsigned
if (v < From{0}) {
return false;
}
using UFrom = std::make_unsigned_t<From>;
return static_cast<UFrom>(v) <= std::numeric_limits<To>::max();
} else {
// From unsigned, To signed
using UTo = std::make_unsigned_t<To>;
return v <= static_cast<UTo>(std::numeric_limits<To>::max());
}
}
template <std::floating_point F>
[[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 <ArithmeticScalar To, ArithmeticScalar From>
[[nodiscard]] constexpr std::expected<To, Error>
checked_cast(From value, Rounding mode = Rounding::exact) noexcept
{
if constexpr (std::same_as<std::remove_cv_t<To>, std::remove_cv_t<From>>) {
if constexpr (std::floating_point<From>) {
if (!std::isfinite(value)) {
return std::unexpected{Error::NonFinite};
}
}
return value;
} else if constexpr (std::integral<From> && std::integral<To>) {
if (!detail::in_int_range<To>(value)) {
if constexpr (std::is_signed_v<From>) {
if (value < From{0}) {
return std::unexpected{Error::Underflow};
}
}
return std::unexpected{Error::Overflow};
}
return static_cast<To>(value);
} else if constexpr (std::integral<From> && std::floating_point<To>) {
if (value == From{0}) {
return To{0};
}
const bool neg = (std::is_signed_v<From> && value < From{0});
const std::uint64_t mag = static_cast<std::uint64_t>(detail::abs_unsigned(value));
const int width = static_cast<int>(std::bit_width(mag));
const int msb = width - 1;
const int sig_bits = width - std::countr_zero(mag);
constexpr int kPrec = std::numeric_limits<To>::digits;
if (sig_bits <= kPrec) {
if (msb >= std::numeric_limits<To>::max_exponent) {
return std::unexpected{neg ? Error::Underflow : Error::Overflow};
}
return static_cast<To>(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<To>::max_exponent) {
return std::unexpected{neg ? Error::Underflow : Error::Overflow};
}
const To out_mag = std::ldexp(static_cast<To>(shifted), drop);
return neg ? -out_mag : out_mag;
} else if constexpr (std::floating_point<From> && std::integral<To>) {
if (!std::isfinite(value)) {
return std::unexpected{Error::NonFinite};
}
constexpr int kToBits = std::numeric_limits<To>::digits;
constexpr bool kHasUpper = (kToBits < std::numeric_limits<From>::max_exponent);
const From upper_excl = kHasUpper ? std::ldexp(From{1}, kToBits) : From{0};
constexpr bool kHasLower =
std::is_unsigned_v<To> || (kToBits < std::numeric_limits<From>::max_exponent);
const From lower_incl = std::is_unsigned_v<To>
? 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<To>(rounded);
} else {
// Floating -> Floating
if (!std::isfinite(value)) {
return std::unexpected{Error::NonFinite};
}
using Wide = std::conditional_t<
(std::numeric_limits<From>::max_exponent >= std::numeric_limits<To>::max_exponent),
From, To>;
const Wide wval = static_cast<Wide>(value);
if (wval > static_cast<Wide>(std::numeric_limits<To>::max())) {
return std::unexpected{Error::Overflow};
}
if (wval < static_cast<Wide>(std::numeric_limits<To>::lowest())) {
return std::unexpected{Error::Underflow};
}
To out = static_cast<To>(value);
if (!std::isfinite(out)) {
return std::unexpected{value < From{0} ? Error::Underflow : Error::Overflow};
}
if (mode == Rounding::toward_zero && static_cast<From>(out) != value) {
if ((value > From{0} && static_cast<From>(out) > value) ||
(value < From{0} && static_cast<From>(out) < value)) {
out = std::nextafter(out, To{0});
}
} else if (mode == Rounding::exact) {
if (static_cast<From>(out) != value || std::signbit(out) != std::signbit(value)) {
return std::unexpected{Error::Inexact};
}
}
return out;
}
}
// ── Numeric parsing ───────────────────────────────────────────────────────────
template <std::integral T>
requires (!std::same_as<std::remove_cv_t<T>, bool>)
[[nodiscard]] inline std::expected<T, Error>
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<T>) {
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 <std::floating_point T>
[[nodiscard]] inline std::expected<T, Error>
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<int, Error>
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<int>::max()) return std::unexpected{Error::Overflow};
if (v < std::numeric_limits<int>::min()) return std::unexpected{Error::Underflow};
return static_cast<int>(v);
return parse_integer<int>(s, base);
}
[[nodiscard]] inline std::expected<double, Error>
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<double>(s);
}
// ── Integer traits helpers ────────────────────────────────────────────────────
@@ -168,8 +670,11 @@ template <typename T>
template <std::integral T>
[[nodiscard]] constexpr bool in_range(long long v) noexcept
{
return v >= static_cast<long long>(std::numeric_limits<T>::min()) &&
v <= static_cast<long long>(std::numeric_limits<T>::max());
if constexpr (std::same_as<std::remove_cv_t<T>, bool>) {
return v == 0LL || v == 1LL;
} else {
return detail::in_int_range<T>(v);
}
}
template <std::integral T>
+307
View File
@@ -2,8 +2,12 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cfenv>
#include <cmath>
#include <cstdint>
#include <limits>
#include <string>
#include <string_view>
// ── checked_add ───────────────────────────────────────────────────────────────
@@ -190,3 +194,306 @@ Void::Testing::Test narrow_cast_out_of_range()
{
Void::Testing::expect(!Void::Numeric::narrow_cast<std::int8_t>(500LL).has_value());
}
Void::Testing::Test in_range_supports_unsigned_64()
{
Void::Testing::expect(Void::Numeric::in_range<std::uint64_t>(42LL));
Void::Testing::expect(!Void::Numeric::in_range<std::uint64_t>(-1LL));
const auto r = Void::Numeric::narrow_cast<std::uint64_t>(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>(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<double>(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<int>("") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>(" 42") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("+42") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("42 ") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("42abc") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("10", 1) == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("10", 37) == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<int>("10", 0) == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_integer<std::int8_t>("-9999xyz") == std::unexpected{Error::InvalidInput});
const std::string too_long(Void::Numeric::kMaxNumericTokenBytes + 1, '0');
Void::Testing::expect(parse_integer<int>(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<int>(exact_max_len), 42);
Void::Testing::expect_eq(*parse_integer<std::int8_t>("127"), std::int8_t{127});
Void::Testing::expect_eq(*parse_integer<std::int8_t>("-128"), std::int8_t{-128});
Void::Testing::expect(parse_integer<std::int8_t>("128") == std::unexpected{Error::Overflow});
Void::Testing::expect(parse_integer<std::int8_t>("-129") == std::unexpected{Error::Underflow});
Void::Testing::expect_eq(
*parse_integer<std::uint64_t>("18446744073709551615"),
std::numeric_limits<std::uint64_t>::max());
Void::Testing::expect(
parse_integer<std::uint64_t>("18446744073709551616") == std::unexpected{Error::Overflow});
Void::Testing::expect(
parse_integer<std::uint64_t>("-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<double>("") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>(" 1.5") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("+1.5") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("1.5 ") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("1.5xyz") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("nan") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("-nan") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("inf") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("-inf") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("INF") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("infinity") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("1e400xyz") == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("-.") == std::unexpected{Error::InvalidInput});
const std::string too_long(Void::Numeric::kMaxNumericTokenBytes + 1, '1');
Void::Testing::expect(parse_real<double>(too_long) == std::unexpected{Error::InvalidInput});
Void::Testing::expect(parse_real<double>("1e400") == std::unexpected{Error::Overflow});
Void::Testing::expect(parse_real<double>("-1e400") == std::unexpected{Error::Underflow});
Void::Testing::expect(parse_real<double>("1e-500") == std::unexpected{Error::Underflow});
const auto neg_zero = parse_real<double>("-0.0");
Void::Testing::expect(neg_zero.has_value());
Void::Testing::expect(std::signbit(*neg_zero));
const auto half_lead_dot = parse_real<double>("-.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::int16_t>(std::int32_t{-32768}).value() == -32768);
static_assert(checked_cast<std::uint32_t>(std::int32_t{-1}).error() == Error::Underflow);
static_assert(checked_cast<std::int64_t>(std::numeric_limits<std::uint64_t>::max()).error() == Error::Overflow);
Void::Testing::expect(
checked_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::min()) ==
std::unexpected{Error::Underflow});
Void::Testing::expect_eq(
*checked_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()),
static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::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<float>(std::numeric_limits<std::int64_t>::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<double>(exact_53), static_cast<double>(exact_53));
Void::Testing::expect_eq(*checked_cast<double>(exact_53 + 2ULL), static_cast<double>(exact_53) + 2.0);
Void::Testing::expect(checked_cast<double>(exact_53 + 1ULL) == std::unexpected{Error::Inexact});
Void::Testing::expect_eq(
*checked_cast<double>(exact_53 + 1ULL, Rounding::nearest_even),
static_cast<double>(exact_53));
Void::Testing::expect_eq(
*checked_cast<double>(exact_53 + 3ULL, Rounding::nearest_even),
static_cast<double>(exact_53 + 4ULL));
Void::Testing::expect_eq(
*checked_cast<double>(exact_53 + 3ULL, Rounding::toward_zero),
static_cast<double>(exact_53 + 2ULL));
const auto u64_max = std::numeric_limits<std::uint64_t>::max();
Void::Testing::expect(checked_cast<double>(u64_max) == std::unexpected{Error::Inexact});
Void::Testing::expect_eq(
*checked_cast<double>(u64_max, Rounding::nearest_even),
std::ldexp(1.0, 64));
Void::Testing::expect_eq(
*checked_cast<double>(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::int64_t>(std::numeric_limits<double>::quiet_NaN()) ==
std::unexpected{Error::NonFinite});
Void::Testing::expect(
checked_cast<std::int64_t>(std::numeric_limits<double>::infinity()) ==
std::unexpected{Error::NonFinite});
Void::Testing::expect(
checked_cast<std::int64_t>(-std::numeric_limits<double>::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<std::int64_t>(two_63) == std::unexpected{Error::Overflow});
Void::Testing::expect_eq(*checked_cast<std::int64_t>(-two_63), std::numeric_limits<std::int64_t>::min());
Void::Testing::expect(checked_cast<std::int64_t>(-two_63 - 2048.0) == std::unexpected{Error::Underflow});
Void::Testing::expect_eq(*checked_cast<std::int64_t>(two_63 - 1024.0), std::int64_t{9223372036854774784LL});
Void::Testing::expect(checked_cast<std::uint64_t>(two_64) == std::unexpected{Error::Overflow});
Void::Testing::expect_eq(*checked_cast<std::uint64_t>(two_64 - 2048.0), std::uint64_t{18446744073709549568ULL});
Void::Testing::expect_eq(*checked_cast<std::uint64_t>(-0.0), std::uint64_t{0});
Void::Testing::expect(checked_cast<std::uint64_t>(-1.0) == std::unexpected{Error::Underflow});
// Exact vs toward_zero vs nearest_even (independent of FE_ROUND).
Void::Testing::expect(checked_cast<int>(1.5) == std::unexpected{Error::Inexact});
Void::Testing::expect_eq(*checked_cast<int>(1.9, Rounding::toward_zero), 1);
Void::Testing::expect_eq(*checked_cast<int>(-1.9, Rounding::toward_zero), -1);
const int saved_round = std::fegetround();
std::fesetround(FE_DOWNWARD);
Void::Testing::expect_eq(*checked_cast<int>(0.5, Rounding::nearest_even), 0);
Void::Testing::expect_eq(*checked_cast<int>(1.5, Rounding::nearest_even), 2);
Void::Testing::expect_eq(*checked_cast<int>(2.5, Rounding::nearest_even), 2);
Void::Testing::expect_eq(*checked_cast<int>(-0.5, Rounding::nearest_even), 0);
Void::Testing::expect_eq(*checked_cast<int>(-1.5, Rounding::nearest_even), -2);
Void::Testing::expect_eq(*checked_cast<int>(-2.5, Rounding::nearest_even), -2);
std::fesetround(FE_UPWARD);
Void::Testing::expect_eq(*checked_cast<std::int8_t>(127.5, Rounding::toward_zero), std::int8_t{127});
Void::Testing::expect(
checked_cast<std::int8_t>(127.5, Rounding::nearest_even) ==
std::unexpected{Error::Overflow});
Void::Testing::expect_eq(*checked_cast<std::int8_t>(-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<float>(std::numeric_limits<double>::quiet_NaN()) ==
std::unexpected{Error::NonFinite});
Void::Testing::expect(
checked_cast<double>(std::numeric_limits<float>::infinity()) ==
std::unexpected{Error::NonFinite});
Void::Testing::expect(checked_cast<float>(1e40) == std::unexpected{Error::Overflow});
Void::Testing::expect(checked_cast<float>(-1e40) == std::unexpected{Error::Underflow});
const auto neg_zero_f = checked_cast<float>(-0.0);
Void::Testing::expect(neg_zero_f.has_value());
Void::Testing::expect(std::signbit(*neg_zero_f));
Void::Testing::expect_eq(*checked_cast<float>(0.5), 0.5F);
Void::Testing::expect(checked_cast<float>(0.1) == std::unexpected{Error::Inexact});
Void::Testing::expect(checked_cast<float>(1e-300) == std::unexpected{Error::Inexact});
Void::Testing::expect(checked_cast<float>(0.1, Rounding::nearest_even).has_value());
const double upper_gap =
static_cast<double>(std::numeric_limits<float>::max()) + std::ldexp(1.0, 102);
Void::Testing::expect(checked_cast<float>(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<float>(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<std::int32_t>::max();
constexpr auto i32_min = std::numeric_limits<std::int32_t>::min();
static_assert(checked_mul_add<std::int32_t>(2, i32_max, i32_min).value() == i32_max - 1);
constexpr auto i64_max = std::numeric_limits<std::int64_t>::max();
constexpr auto i64_min = std::numeric_limits<std::int64_t>::min();
Void::Testing::expect_eq(
*checked_mul_add<std::int64_t>(2, i64_max, i64_min),
i64_max - 1);
Void::Testing::expect_eq(
*checked_mul_add<std::int64_t>(-2, i64_max, i64_max),
-i64_max);
Void::Testing::expect(
checked_mul_add<std::int64_t>(i64_max, 2, -1) == std::unexpected{Error::Overflow});
Void::Testing::expect(
checked_mul_add<std::int64_t>(i64_min, 2, 1) == std::unexpected{Error::Underflow});
constexpr auto u64_max = std::numeric_limits<std::uint64_t>::max();
Void::Testing::expect_eq(
*checked_mul_add<std::uint64_t>(u64_max / 2ULL, 2ULL, 1ULL),
u64_max);
Void::Testing::expect(
checked_mul_add<std::uint64_t>(u64_max, 1ULL, 1ULL) == std::unexpected{Error::Overflow});
Void::Testing::expect(
checked_mul_add<std::uint64_t>(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<std::int8_t>(127, 1, &s8)) return false;
if (!portable_add_overflow<std::int8_t>(-128, -1, &s8)) return false;
if (portable_add_overflow<std::int8_t>(127, -128, &s8) || s8 != -1) return false;
if (!portable_sub_overflow<std::int8_t>(-128, 1, &s8)) return false;
if (!portable_sub_overflow<std::int8_t>(127, -1, &s8)) return false;
if (portable_sub_overflow<std::int8_t>(-1, -128, &s8) || s8 != 127) return false;
if (!portable_mul_overflow<std::int8_t>(-128, -1, &s8)) return false;
if (!portable_mul_overflow<std::int8_t>(-65, 2, &s8)) return false;
if (portable_mul_overflow<std::int8_t>(-64, 2, &s8) || s8 != -128) return false;
std::uint16_t u16 = 0;
if (!portable_mul_overflow<std::uint16_t>(65535, 65535, &u16)) return false;
if (portable_mul_overflow<std::uint16_t>(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::uint64_t>(
std::numeric_limits<std::uint64_t>::max(), 1ULL, &u64));
Void::Testing::expect(portable_sub_overflow<std::uint64_t>(0ULL, 1ULL, &u64));
Void::Testing::expect(portable_mul_overflow<std::uint64_t>(
std::numeric_limits<std::uint64_t>::max(), 2ULL, &u64));
}