Fix debug format width calculation (#4902)

This commit is contained in:
Satyakam Mishra 2026-09-04 16:17:58 +00:00 committed by GitHub
parent ff4a0fdfb9
commit b4b1657c2a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 5 deletions

View File

@ -2069,11 +2069,22 @@ template <typename Char, typename OutputIt>
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<Char>(out, specs, 1, [=](reserve_iterator<OutputIt> 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<Char>(out, specs, size,
[=](reserve_iterator<OutputIt> it) {
if (is_debug) return copy<Char>(begin, end, it);
*it++ = value;
return it;
});
}
template <typename Char> class digit_grouping {
@ -2431,6 +2442,12 @@ FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> 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<OutputIt> underlying_iterator;
size_t bound;

View File

@ -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");
}