diff --git a/include/Void/Math/Numeric.hpp b/include/Void/Math/Numeric.hpp index 130e48f..0c67480 100644 --- a/include/Void/Math/Numeric.hpp +++ b/include/Void/Math/Numeric.hpp @@ -490,26 +490,30 @@ template } 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; + 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); } - 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}; diff --git a/tests/standalone/Math/Numeric.cpp b/tests/standalone/Math/Numeric.cpp index 43d97c3..2b3fefa 100644 --- a/tests/standalone/Math/Numeric.cpp +++ b/tests/standalone/Math/Numeric.cpp @@ -344,6 +344,14 @@ Void::Testing::Test checked_cast_int_to_float() Void::Testing::expect_eq( *checked_cast(u64_max, Rounding::toward_zero), std::ldexp(1.0, 64) - 2048.0); + + const auto ld_u64 = checked_cast(u64_max); + if constexpr (std::numeric_limits::digits >= 64) { + Void::Testing::expect(ld_u64.has_value()); + Void::Testing::expect(*ld_u64 == static_cast(u64_max)); + } else { + Void::Testing::expect(ld_u64 == std::unexpected{Error::Inexact}); + } } Void::Testing::Test checked_cast_float_to_int_boundaries_and_rounding()