From 6debbb4a54e98b23d0cf07a90cccdf9aaa36e05c Mon Sep 17 00:00:00 2001 From: Markus Mittendrein Date: Sun, 9 Jan 2022 20:36:40 +0100 Subject: Throw on truncation for the precision value in the floating point formatter --- include/cxxformat/formatters.hpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'include') diff --git a/include/cxxformat/formatters.hpp b/include/cxxformat/formatters.hpp index c32d2e8..b248b17 100644 --- a/include/cxxformat/formatters.hpp +++ b/include/cxxformat/formatters.hpp @@ -312,12 +312,25 @@ namespace format { assert(!"Unsupported conversion; should have been caught by formatter::conversionSupported"); } + optional_int intPrecision; + + if (precision) + { + const auto val = *precision; + constexpr auto max = std::numeric_limits::max(); + if (val > max) + { + throw std::out_of_range{"Precision is too big; maximum supported for floating point types is " + std::to_string(max)}; + } + intPrecision = static_cast(val); + } + char* data, *end; std::errc ec; - const auto call_to_chars = [format, precision, t, &data, &end, &ec](char* data_, std::size_t size) + const auto call_to_chars = [format, intPrecision, t, &data, &end, &ec](char* data_, std::size_t size) { data = data_; - const auto [end_, ec_] = precision ? std::to_chars(data, data + size, t, format, *precision) : std::to_chars(data, data + size, t, format); + const auto [end_, ec_] = intPrecision ? std::to_chars(data, data + size, t, format, *intPrecision) : std::to_chars(data, data + size, t, format); end = end_; ec = ec_; }; -- cgit v1.2.3-54-g00ecf