Implement format specs in fmt::thousands

This commit is contained in:
Victor Zverovich 2021-09-04 06:47:21 -07:00
parent 3b9c442689
commit c4d0f96a6d
2 changed files with 21 additions and 2 deletions

View File

@ -2619,11 +2619,29 @@ template <typename T> auto thousands(T value) -> thousands_view<T> {
}
template <typename T> struct formatter<thousands_view<T>> : formatter<T> {
private:
detail::dynamic_format_specs<char> specs_;
public:
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
using handler_type = detail::dynamic_specs_handler<ParseContext>;
detail::specs_checker<handler_type> 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 <typename FormatContext>
auto format(thousands_view<T> t, FormatContext& ctx) -> decltype(ctx.out()) {
detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
specs_.width_ref, ctx);
detail::handle_dynamic_spec<detail::precision_checker>(
specs_.precision, specs_.precision_ref, ctx);
return detail::write_int_localized(
ctx.out(), static_cast<detail::uint64_or_128_t<T>>(t.value), 0,
format_specs(), detail::digit_grouping<char>({"\3", ','}));
specs_, detail::digit_grouping<char>({"\3", ','}));
}
};

View File

@ -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 };