This commit is contained in:
Mayukha Vadari
2026-07-21 15:08:26 -04:00
parent 412298242c
commit 6d38b88310
2 changed files with 22 additions and 14 deletions

View File

@@ -392,6 +392,20 @@ public:
static RoundingMode
setround(RoundingMode inMode);
/** Convert an integer to a RoundingMode, validating that it is in range.
*
* Returns std::nullopt if the value does not correspond to a valid
* RoundingMode.
*/
static std::optional<RoundingMode>
checkedRoundingMode(int mode) noexcept
{
if (mode < static_cast<int>(RoundingMode::ToNearest) ||
mode > static_cast<int>(RoundingMode::Upward))
return std::nullopt;
return static_cast<RoundingMode>(mode);
}
/** Returns which mantissa scale is currently in use for normalization.
*
* If you think you need to call this outside of unit tests, no you don't.

View File

@@ -81,26 +81,20 @@ floatEncode(Number const& n)
struct FloatState
{
Number::RoundingMode oldMode;
bool good = false;
// Set only when the requested mode is valid; sets the rounding mode on
// construction and restores the previous mode on destruction.
std::optional<NumberRoundModeGuard> guard_;
FloatState(int32_t mode) : oldMode(Number::getround())
explicit FloatState(int32_t mode)
{
if (mode < static_cast<int32_t>(Number::RoundingMode::ToNearest) ||
mode > static_cast<int32_t>(Number::RoundingMode::Upward))
return;
Number::setround(static_cast<Number::RoundingMode>(mode));
good = true;
}
~FloatState()
{
Number::setround(oldMode);
if (auto const rm = Number::checkedRoundingMode(mode))
guard_.emplace(*rm);
}
explicit
operator bool() const
{
return good;
return guard_.has_value();
}
};