From bd516e342969a7f5acfb36d87bba21c3e7ee9f7f Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sun, 21 Apr 2019 07:39:41 -0700 Subject: [PATCH] Convert negative precision to zero in printf (#1127) and remove redundant check in grisu2_prettify. --- include/fmt/format.h | 3 +-- include/fmt/printf.h | 2 +- test/printf-test.cc | 6 +++++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index e9f29518..0e8fb2e4 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1181,8 +1181,7 @@ It grisu2_prettify(const char* digits, int size, int exp, It it, *it++ = static_cast(params.upper ? 'E' : 'e'); return write_exponent(exp, it); } - const int exp_threshold = 21; - if (size <= full_exp && full_exp <= exp_threshold) { + if (size <= full_exp) { // 1234e7 -> 12340000000[.0+] it = copy_str(digits, digits + size, it); it = std::fill_n(it, full_exp - size, static_cast('0')); diff --git a/include/fmt/printf.h b/include/fmt/printf.h index dd553139..f75f10af 100644 --- a/include/fmt/printf.h +++ b/include/fmt/printf.h @@ -44,7 +44,7 @@ class printf_precision_handler : public function { int operator()(T value) { if (!int_checker::is_signed>::fits_in_int(value)) FMT_THROW(format_error("number is too big")); - return static_cast(value); + return (std::max)(static_cast(value), 0); } template ::value)> diff --git a/test/printf-test.cc b/test/printf-test.cc index c0108103..ab199d2c 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -520,6 +520,10 @@ TEST(PrintfTest, CheckFormatStringRegression) { check_format_string_regression("%c%s", 'x', ""); } +TEST(PrintfTest, FixedLargeExponent) { + EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21)); +} + TEST(PrintfTest, VSPrintfMakeArgsExample) { fmt::format_arg_store as{42, "something"}; @@ -599,7 +603,7 @@ std::string custom_format(const char* format_str, const Args&... args) { return custom_vformat(format_str, va); } -TEST(CustomFormatterTest, Format) { +TEST(PrintfTest, CustomFormat) { EXPECT_EQ("0.00", custom_format("%.2f", -.00001)); EXPECT_EQ("0.00", custom_format("%.2f", .00001)); EXPECT_EQ("1.00", custom_format("%.2f", 1.00001));