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
+30 -18

No files matched your search

+22 -18
View File
@@ -490,26 +490,30 @@ template <ArithmeticScalar To, ArithmeticScalar From>
}
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;
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<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 {
return static_cast<To>(value);
}
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};