# Math Span-Safe Parsing, Checked Cast, and Portable Overflow Task ID: M-MATH-02 Phase: P1 Status: APPROVED Contracts: C-01, C-02, C-05, C-07 ## 1. Context and baseline `include/Void/Math/Numeric.hpp` currently passes `string_view::data()` to `std::strtol`/`std::strtod` (unsafe on non-NUL-terminated substrings), uses `long long`-based `in_range`/`narrow_cast` (broken for unsigned 64-bit / floating conversions), and lacks `checked_cast`, `checked_mul_add`, and portable non-builtin overflow arithmetic. ## 2. Deliverables - Extended `include/Void/Math/Numeric.hpp`: `Error::Inexact`, `Error::NonFinite`, `Rounding`, `kMaxNumericTokenBytes = 256`, guarded `__builtin_*_overflow` + portable `constexpr` fallback, `checked_mul_add`, `checked_cast`, `parse_integer`, `parse_real`, and span-safe `parse_int`/`parse_double` adapters. - Comprehensive boundary tests in `tests/standalone/Math/Numeric.cpp`. ## 3. Exact files and interfaces - `include/Void/Math/Numeric.hpp`: - `checked_cast(value, Rounding mode = Rounding::exact) noexcept -> std::expected` across all non-`bool` arithmetic pairs. - `parse_integer(std::string_view, int base = 10) noexcept -> std::expected`. - `parse_real(std::string_view) noexcept -> std::expected`. - `checked_mul_add(T a, T b, T c) noexcept -> std::expected`. ## 4. Edge cases - Non-NUL-terminated substrings adjacent to digits (`"429"` sliced to `"42"` must parse `42`, never `429`). - `parse_integer`/`parse_real` reject empty strings, `> 256` bytes, leading whitespace, leading `'+'`, trailing characters, and `"nan"`/`"inf"`. - Float->int checks exact exclusive `2^63` (`9223372036854775808.0`) / `2^64` (`18446744073709551616.0`) boundaries, and `nearest_even` implements deterministic ties-to-even independent of `FE_ROUND`. - Int->float exactness checks significant bits without UB when negating `INT64_MIN`; preserves `-0.0` sign on float narrowing. ## 5. Acceptance criteria - Existing `Numeric` tests plus all boundary tests pass under `-Werror` and ASan/UBSan. ## 6. Verification commands ```sh dev cpp-gcc -c cmake -S . -B /tmp/void-p1-math -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Math;Testing" -DVOID_WARNINGS_AS_ERRORS=ON dev cpp-gcc -c cmake --build /tmp/void-p1-math --parallel 4 dev cpp-gcc -c /tmp/void-p1-math/tests/VoidTests --filter "Numeric*" ```