From 76cfb50b2d8df5b0193744091f2bc3c8b4f87eaa Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Mon, 3 Aug 2020 10:05:18 -0700 Subject: [PATCH] Test complex formatter --- include/fmt/format.h | 7 ++++--- test/locale-test.cc | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index 444b7887..92acb410 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -3342,6 +3342,10 @@ class bytes { }; template <> struct 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; @@ -3360,9 +3364,6 @@ template <> struct formatter { specs_.precision, specs_.precision_ref, ctx); return detail::write_bytes(ctx.out(), b.data_, specs_); } - - private: - detail::dynamic_format_specs specs_; }; template diff --git a/test/locale-test.cc b/test/locale-test.cc index b2cb8a63..87423bce 100644 --- a/test/locale-test.cc +++ b/test/locale-test.cc @@ -7,6 +7,8 @@ #include "fmt/locale.h" +#include + #include "gmock.h" using fmt::detail::max_value; @@ -101,4 +103,45 @@ TEST(LocaleTest, DoubleFormatter) { EXPECT_STREQ("12,345", buf); } +FMT_BEGIN_NAMESPACE +template struct formatter, charT> { + private: + detail::dynamic_format_specs specs_; + + public: + typename basic_format_parse_context::iterator parse( + basic_format_parse_context& ctx) { + using handler_type = + detail::dynamic_specs_handler>; + detail::specs_checker handler(handler_type(specs_, ctx), + detail::type::string_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::iterator format(const std::complex& c, + FormatContext& ctx) { + detail::handle_dynamic_spec( + specs_.precision, specs_.precision_ref, ctx); + auto format_specs = std::string(); + auto real = fmt::format(ctx.locale().template get(), + "{:" + format_specs + "}", c.real()); + auto imag = fmt::format(ctx.locale().template get(), + "{:" + format_specs + "}", c.imag()); + auto fill_align_width = std::string(); + return format_to( + ctx.out(), "{:" + fill_align_width + "}", + fmt::format(c.real() != 0 ? "({0}+{1}i)" : "{1}i", real, imag)); + } +}; +FMT_END_NAMESPACE + +TEST(FormatTest, Complex) { + std::string s = fmt::format("{}", std::complex(1, 2)); + // We might want to drop trailing zeros for consistency with to_chars. + EXPECT_EQ(s, "(1.0+2.0i)"); +} + #endif // FMT_STATIC_THOUSANDS_SEPARATOR