From 3b70966df5b88fb9c7c6a4c620ab663723802c31 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sat, 21 Sep 2024 07:39:24 -0700 Subject: [PATCH] Add width and alignment support to error_code --- include/fmt/std.h | 36 +++++++++++++++++++++++++++--------- test/std-test.cc | 8 ++++++-- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 0370f781..722b6ad9 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -413,19 +413,37 @@ FMT_END_NAMESPACE FMT_BEGIN_NAMESPACE FMT_EXPORT -template struct formatter { - FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { - return ctx.begin(); +template <> struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + char c = *it; + if ((c >= '0' && c <= '9') || c == '{') + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + return it; } template - FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const + FMT_CONSTEXPR20 auto format(const std::error_code& ec, FormatContext& ctx) const -> decltype(ctx.out()) { - auto out = ctx.out(); - out = detail::write_bytes(out, ec.category().name(), format_specs()); - out = detail::write(out, Char(':')); - out = detail::write(out, ec.value()); - return out; + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + memory_buffer buf; + buf.append(string_view(ec.category().name())); + buf.push_back(':'); + detail::write(appender(buf), ec.value()); + return detail::write(ctx.out(), string_view(buf.data(), buf.size()), + specs); } }; diff --git a/test/std-test.cc b/test/std-test.cc index 2fc1ea09..ab458ae8 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -265,9 +265,13 @@ TEST(std_test, variant) { } TEST(std_test, error_code) { + auto& generic = std::generic_category(); EXPECT_EQ("generic:42", - fmt::format(FMT_STRING("{0}"), - std::error_code(42, std::generic_category()))); + fmt::format(FMT_STRING("{0}"), std::error_code(42, generic))); + EXPECT_EQ(" generic:42", + fmt::format(FMT_STRING("{:>12}"), std::error_code(42, generic))); + EXPECT_EQ("generic:42 ", + fmt::format(FMT_STRING("{:12}"), std::error_code(42, generic))); EXPECT_EQ("system:42", fmt::format(FMT_STRING("{0}"), std::error_code(42, fmt::system_category())));