Fix handling of width when formatting int as char

This commit is contained in:
Victor Zverovich 2021-01-14 08:41:17 -08:00
parent 0fe0b15e71
commit f8c2f8480a
2 changed files with 14 additions and 13 deletions

View File

@ -1592,6 +1592,16 @@ OutputIt write_bytes(OutputIt out, string_view bytes,
});
}
template <typename Char, typename OutputIt>
constexpr OutputIt write_char(OutputIt out, Char value,
const basic_format_specs<Char>& specs) {
using iterator = remove_reference_t<decltype(reserve(out, 0))>;
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 <typename Char> struct write_int_data {
@ -1777,7 +1787,7 @@ template <typename OutputIt, typename Char, typename UInt> struct int_writer {
[=](iterator it) { return copy_str<Char>(data, data + size, it); });
}
void on_chr() { *out++ = static_cast<Char>(abs_value); }
void on_chr() { out = write_char(out, static_cast<Char>(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<Char>());
}
template <typename Char, typename OutputIt>
constexpr OutputIt write_char(OutputIt out, Char value,
const basic_format_specs<Char>& specs) {
using iterator = remove_reference_t<decltype(reserve(out, 0))>;
return write_padded(out, specs, 1, [=](iterator it) {
*it++ = value;
return it;
});
}
template <typename Char, typename OutputIt, typename UIntPtr>
OutputIt write_ptr(OutputIt out, UIntPtr value,
const basic_format_specs<Char>* specs) {

View File

@ -868,8 +868,9 @@ TEST(FormatterTest, Width) {
EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast<void*>(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<int>('x')), "x ");
}
template <typename T> inline T const_check(T value) { return value; }