fix(Math): guard 64-bit precision shift in checked_cast for long double

This commit is contained in:
faumaray committed 2026-11-24 02:55:35 +03:00
1 parent 91e2beb5d4
commit 6cac781f3a
2 files changed
+12

No files matched your search

+4
View File
@@ -490,6 +490,7 @@ template <ArithmeticScalar To, ArithmeticScalar From>
} }
return static_cast<To>(value); return static_cast<To>(value);
} }
if constexpr (kPrec < 64) {
if (mode == Rounding::exact) { if (mode == Rounding::exact) {
return std::unexpected{Error::Inexact}; return std::unexpected{Error::Inexact};
} }
@@ -510,6 +511,9 @@ template <ArithmeticScalar To, ArithmeticScalar From>
} }
const To out_mag = std::ldexp(static_cast<To>(shifted), drop); const To out_mag = std::ldexp(static_cast<To>(shifted), drop);
return neg ? -out_mag : out_mag; return neg ? -out_mag : out_mag;
} else {
return static_cast<To>(value);
}
} else if constexpr (std::floating_point<From> && std::integral<To>) { } else if constexpr (std::floating_point<From> && std::integral<To>) {
if (!std::isfinite(value)) { if (!std::isfinite(value)) {
return std::unexpected{Error::NonFinite}; return std::unexpected{Error::NonFinite};
+8
View File
@@ -344,6 +344,14 @@ Void::Testing::Test checked_cast_int_to_float()
Void::Testing::expect_eq( Void::Testing::expect_eq(
*checked_cast<double>(u64_max, Rounding::toward_zero), *checked_cast<double>(u64_max, Rounding::toward_zero),
std::ldexp(1.0, 64) - 2048.0); std::ldexp(1.0, 64) - 2048.0);
const auto ld_u64 = checked_cast<long double>(u64_max);
if constexpr (std::numeric_limits<long double>::digits >= 64) {
Void::Testing::expect(ld_u64.has_value());
Void::Testing::expect(*ld_u64 == static_cast<long double>(u64_max));
} else {
Void::Testing::expect(ld_u64 == std::unexpected{Error::Inexact});
}
} }
Void::Testing::Test checked_cast_float_to_int_boundaries_and_rounding() Void::Testing::Test checked_cast_float_to_int_boundaries_and_rounding()