From c4d0f96a6da30417191b72a7444fde4b03e254be Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sat, 4 Sep 2021 06:47:21 -0700 Subject: [PATCH] Implement format specs in fmt::thousands --- include/fmt/format.h | 20 +++++++++++++++++++- test/format-test.cc | 3 ++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index cc68c116..7993b823 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -2619,11 +2619,29 @@ template auto thousands(T value) -> thousands_view { } template struct formatter> : formatter { + private: + detail::dynamic_format_specs specs_; + + public: + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + using handler_type = detail::dynamic_specs_handler; + detail::specs_checker handler(handler_type(specs_, ctx), + detail::type::int_type); + auto it = parse_format_specs(ctx.begin(), ctx.end(), handler); + detail::check_string_type_spec(specs_.type, ctx.error_handler()); + return it; + } + template auto format(thousands_view t, FormatContext& ctx) -> decltype(ctx.out()) { + detail::handle_dynamic_spec(specs_.width, + specs_.width_ref, ctx); + detail::handle_dynamic_spec( + specs_.precision, specs_.precision_ref, ctx); return detail::write_int_localized( ctx.out(), static_cast>(t.value), 0, - format_specs(), detail::digit_grouping({"\3", ','})); + specs_, detail::digit_grouping({"\3", ','})); } }; diff --git a/test/format-test.cc b/test/format-test.cc index ae129a82..93b5d308 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1596,7 +1596,8 @@ TEST(format_test, bytes) { } TEST(format_test, thousands) { - EXPECT_EQ(fmt::format("{}", fmt::thousands(1000)), "1,000"); + EXPECT_EQ(fmt::format("{}", fmt::thousands(10000000)), "10,000,000"); + EXPECT_EQ(fmt::format("{:8}", fmt::thousands(1000)), " 1,000"); } enum test_enum { foo, bar };