From b4b1657c2aa45cf08dcd7a76e2302bef60314148 Mon Sep 17 00:00:00 2001 From: Satyakam Mishra Date: Fri, 4 Sep 2026 16:17:58 +0000 Subject: [PATCH] Fix debug format width calculation (#4902) --- include/fmt/format.h | 27 ++++++++++++++++++++++----- test/format-test.cc | 2 ++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index 5fe8f47a..2cd380b5 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -2069,11 +2069,22 @@ template FMT_CONSTEXPR auto write_char(OutputIt out, Char value, const format_specs& specs) -> OutputIt { bool is_debug = specs.type() == presentation_type::debug; - return write_padded(out, specs, 1, [=](reserve_iterator it) { - if (is_debug) return write_escaped_char(it, value); - *it++ = value; - return it; - }); + Char buf[12]; + auto* begin = buf; + auto* end = begin; + size_t size = 1; + + if (is_debug) { + end = write_escaped_char(begin, value); + size = to_unsigned(end - begin); + } + + return write_padded(out, specs, size, + [=](reserve_iterator it) { + if (is_debug) return copy(begin, end, it); + *it++ = value; + return it; + }); } template class digit_grouping { @@ -2431,6 +2442,12 @@ FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, return false; }); + if (is_debug && s.size() == 0 && specs.precision != 0 && + display_width < display_width_limit) { + ++display_width; + ++size; + } + struct bounded_output_iterator { reserve_iterator underlying_iterator; size_t bound; diff --git a/test/format-test.cc b/test/format-test.cc index f944649d..772ecb09 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1006,6 +1006,7 @@ TEST(format_test, width) { TEST(format_test, debug_presentation) { EXPECT_EQ(fmt::format("{:?}", ""), R"("")"); + EXPECT_EQ(fmt::format("{:1?}", ""), R"("")"); EXPECT_EQ(fmt::format("{:*<5.0?}", "\n"), R"(*****)"); EXPECT_EQ(fmt::format("{:*<5.1?}", "\n"), R"("****)"); @@ -1748,6 +1749,7 @@ TEST(format_test, format_char) { EXPECT_EQ(fmt::format("{}", '\n'), "\n"); EXPECT_EQ(fmt::format("{:?}", '\n'), "'\\n'"); + EXPECT_EQ(fmt::format("{:6?}", 'a'), "'a' "); EXPECT_EQ(fmt::format("{:x}", '\xff'), "ff"); }