From f8c2f8480aae17906409496ff1d3b965212330f0 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Thu, 14 Jan 2021 08:41:17 -0800 Subject: [PATCH] Fix handling of width when formatting int as char --- include/fmt/format.h | 22 +++++++++++----------- test/format-test.cc | 5 +++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index e220ef97..dab19368 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1592,6 +1592,16 @@ OutputIt write_bytes(OutputIt out, string_view bytes, }); } +template +constexpr OutputIt write_char(OutputIt out, Char value, + const basic_format_specs& specs) { + using iterator = remove_reference_t; + return write_padded(out, specs, 1, [=](iterator it) { + *it++ = value; + return it; + }); +} + // Data for write_int that doesn't depend on output iterator type. It is used to // avoid template code bloat. template struct write_int_data { @@ -1777,7 +1787,7 @@ template struct int_writer { [=](iterator it) { return copy_str(data, data + size, it); }); } - void on_chr() { *out++ = static_cast(abs_value); } + void on_chr() { out = write_char(out, static_cast(abs_value), specs); } FMT_NORETURN void on_error() { FMT_THROW(format_error("invalid type specifier")); @@ -2043,16 +2053,6 @@ inline OutputIt write(OutputIt out, T value) { return write(out, value, basic_format_specs()); } -template -constexpr OutputIt write_char(OutputIt out, Char value, - const basic_format_specs& specs) { - using iterator = remove_reference_t; - return write_padded(out, specs, 1, [=](iterator it) { - *it++ = value; - return it; - }); -} - template OutputIt write_ptr(OutputIt out, UIntPtr value, const basic_format_specs* specs) { diff --git a/test/format-test.cc b/test/format-test.cc index dd3db801..860cdf69 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -868,8 +868,9 @@ TEST(FormatterTest, Width) { EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast(0xcafe))); EXPECT_EQ("x ", format("{0:11}", 'x')); EXPECT_EQ("str ", format("{0:12}", "str")); - EXPECT_EQ(fmt::format("{:*^5}", "🤡"), "**🤡**"); - EXPECT_EQ(fmt::format("{:#6}", 42.0), " 42.0"); + EXPECT_EQ(format("{:*^5}", "🤡"), "**🤡**"); + EXPECT_EQ(format("{:#6}", 42.0), " 42.0"); + EXPECT_EQ(format("{:6c}", static_cast('x')), "x "); } template inline T const_check(T value) { return value; }