From 6d38b88310f88330a1807f1723bbee072371749f Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 21 Jul 2026 15:08:26 -0400 Subject: [PATCH] refactor --- include/xrpl/basics/Number.h | 14 ++++++++++++++ src/libxrpl/tx/wasm/HostFuncImplFloat.cpp | 22 ++++++++-------------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index e67f1f534d..20900f044f 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -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 + checkedRoundingMode(int mode) noexcept + { + if (mode < static_cast(RoundingMode::ToNearest) || + mode > static_cast(RoundingMode::Upward)) + return std::nullopt; + return static_cast(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. diff --git a/src/libxrpl/tx/wasm/HostFuncImplFloat.cpp b/src/libxrpl/tx/wasm/HostFuncImplFloat.cpp index b9fcf63c1d..2561e72cf3 100644 --- a/src/libxrpl/tx/wasm/HostFuncImplFloat.cpp +++ b/src/libxrpl/tx/wasm/HostFuncImplFloat.cpp @@ -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 guard_; - FloatState(int32_t mode) : oldMode(Number::getround()) + explicit FloatState(int32_t mode) { - if (mode < static_cast(Number::RoundingMode::ToNearest) || - mode > static_cast(Number::RoundingMode::Upward)) - return; - Number::setround(static_cast(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(); } };