Skip to content

Commit

Permalink
Fix handling of width when formatting int as char
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Jan 14, 2021
1 parent 0fe0b15 commit f8c2f84
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
22 changes: 11 additions & 11 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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"));
Expand Down Expand Up @@ -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) {
Expand Down
5 changes: 3 additions & 2 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down

0 comments on commit f8c2f84

Please sign in to comment.