From 6b219a58db753ae415fbd76ac076ff90630764cd Mon Sep 17 00:00:00 2001 From: rimathia Date: Sun, 17 May 2020 13:27:18 +0200 Subject: [PATCH] fix interaction of space flag and '+' flag, as well as '-' flag and '0' flag (#1687) --- include/fmt/printf.h | 9 ++++++--- test/printf-test.cc | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/include/fmt/printf.h b/include/fmt/printf.h index 951825ed092e..71c0e2745979 100644 --- a/include/fmt/printf.h +++ b/include/fmt/printf.h @@ -405,7 +405,9 @@ void basic_printf_context::parse_flags(format_specs& specs, specs.fill[0] = '0'; break; case ' ': - specs.sign = sign::space; + if (specs.sign != sign::plus) { + specs.sign = sign::space; + } break; case '#': specs.alt = true; @@ -517,10 +519,11 @@ OutputIt basic_printf_context::format() { if (specs.alt && visit_format_arg(detail::is_zero_int(), arg)) specs.alt = false; if (specs.fill[0] == '0') { - if (arg.is_arithmetic()) + if (arg.is_arithmetic() && specs.align != align::left) specs.align = align::numeric; else - specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types. + specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-' + // flag is also present. } // Parse length and convert the argument to the required type. diff --git a/test/printf-test.cc b/test/printf-test.cc index e556ef36d27f..9dd5bdd521e8 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -151,6 +151,18 @@ TEST(PrintfTest, PlusFlag) { // '+' flag is ignored for non-numeric types. EXPECT_PRINTF("x", "%+c", 'x'); + + // '+' flag wins over space flag + EXPECT_PRINTF("+42", "%+ d", 42); + EXPECT_PRINTF("-42", "%+ d", -42); + EXPECT_PRINTF("+42", "% +d", 42); + EXPECT_PRINTF("-42", "% +d", -42); + EXPECT_PRINTF("+0042", "% +05d", 42); + EXPECT_PRINTF("+0042", "%0+ 5d", 42); + + // '+' flag and space flag are both ignored for non-numeric types. + EXPECT_PRINTF("x", "%+ c", 'x'); + EXPECT_PRINTF("x", "% +c", 'x'); } TEST(PrintfTest, MinusFlag) { @@ -160,6 +172,17 @@ TEST(PrintfTest, MinusFlag) { EXPECT_PRINTF("7 ", "%-5d", 7); EXPECT_PRINTF("97 ", "%-5hhi", 'a'); EXPECT_PRINTF("a ", "%-5c", 'a'); + + // '0' flag is ignored if '-' flag is given + EXPECT_PRINTF("7 ", "%-05d", 7); + EXPECT_PRINTF("7 ", "%0-5d", 7); + EXPECT_PRINTF("a ", "%-05c", 'a'); + EXPECT_PRINTF("a ", "%0-5c", 'a'); + EXPECT_PRINTF("97 ", "%-05hhi", 'a'); + EXPECT_PRINTF("97 ", "%0-5hhi", 'a'); + + // '-' and space flag don't interfere + EXPECT_PRINTF(" 42", "%- d", 42); } TEST(PrintfTest, SpaceFlag) {