From f28cf3302d69fdaeb122be612b75b73bc0883b8a Mon Sep 17 00:00:00 2001 From: sunmy2019 <59365878+sunmy2019@users.noreply.github.com> Date: Sat, 12 Jun 2021 01:52:39 +0800 Subject: [PATCH] =?UTF-8?q?adding=20a=20default=20format=20for=20std::chro?= =?UTF-8?q?no::time=5Fpoint struct formatter, Char> : formatter { + FMT_CONSTEXPR formatter() { + this->specs = {default_specs, sizeof(default_specs) / sizeof(Char)}; + } + + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + auto it = ctx.begin(); + if (it != ctx.end() && *it == ':') ++it; + auto end = it; + while (end != ctx.end() && *end != '}') ++end; + if (end != it) this->specs = {it, detail::to_unsigned(end - it)}; + return end; + } + template auto format(std::chrono::time_point val, FormatContext& ctx) -> decltype(ctx.out()) { std::tm time = localtime(val); return formatter::format(time, ctx); } + + static constexpr Char default_specs[] = {'%', 'Y', '-', '%', 'm', '-', + '%', 'd', ' ', '%', 'H', ':', + '%', 'M', ':', '%', 'S'}; }; +template +constexpr Char + formatter, + Char>::default_specs[]; + template struct formatter { template FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { diff --git a/test/chrono-test.cc b/test/chrono-test.cc index 3ba9557c..113c0fda 100644 --- a/test/chrono-test.cc +++ b/test/chrono-test.cc @@ -99,6 +99,7 @@ template auto strftime(TimePoint tp) -> std::string { TEST(chrono_test, time_point) { auto t1 = std::chrono::system_clock::now(); EXPECT_EQ(strftime(t1), fmt::format("{:%Y-%m-%d %H:%M:%S}", t1)); + EXPECT_EQ(strftime(t1), fmt::format("{}", t1)); using time_point = std::chrono::time_point; auto t2 = time_point(std::chrono::seconds(42)); diff --git a/test/compile-test.cc b/test/compile-test.cc index fb84ab28..fe2ca110 100644 --- a/test/compile-test.cc +++ b/test/compile-test.cc @@ -92,6 +92,8 @@ TEST(compile_test, format_default) { EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), "foo")); EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), std::string("foo"))); EXPECT_EQ("foo", fmt::format(FMT_COMPILE("{}"), test_formattable())); + auto t = std::chrono::system_clock::now(); + EXPECT_EQ(fmt::format("{}", t), fmt::format(FMT_COMPILE("{}"), t)); # ifdef __cpp_lib_byte EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), std::byte{42})); # endif