From 92614ecbf930d75ba753d453b30c93a4fbe2a44e Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Mon, 13 Sep 2021 11:42:26 +0500 Subject: [PATCH] Optimize %T in tm formatting --- include/fmt/chrono.h | 12 +++++++++++- test/chrono-test.cc | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h index f3b0a4f2..d2154469 100644 --- a/include/fmt/chrono.h +++ b/include/fmt/chrono.h @@ -549,6 +549,7 @@ template struct formatter { enum class spec { unknown, year_month_day, + hh_mm_ss, }; spec spec_ = spec::unknown; @@ -563,7 +564,10 @@ template struct formatter { while (end != ctx.end() && *end != '}') ++end; auto size = detail::to_unsigned(end - it); specs = {it, size}; - if (specs == string_view("%F", 2)) spec_ = spec::year_month_day; + if (specs == string_view("%F", 2)) + spec_ = spec::year_month_day; + else if (specs == string_view("%T", 2)) + spec_ = spec::hh_mm_ss; return end; } @@ -578,6 +582,12 @@ template struct formatter { detail::to_unsigned(tm.tm_mon + 1), detail::to_unsigned(tm.tm_mday), '-'); return std::copy_n(buf, sizeof(buf), ctx.out()); + } else if (spec_ == spec::hh_mm_ss) { + char buf[8]; + detail::write_digit2_separated(buf, detail::to_unsigned(tm.tm_hour), + detail::to_unsigned(tm.tm_min), + detail::to_unsigned(tm.tm_sec), ':'); + return std::copy_n(buf, sizeof(buf), ctx.out()); } basic_memory_buffer tm_format; tm_format.append(specs.begin(), specs.end()); diff --git a/test/chrono-test.cc b/test/chrono-test.cc index 3ed5928e..cf5c7f80 100644 --- a/test/chrono-test.cc +++ b/test/chrono-test.cc @@ -49,6 +49,7 @@ TEST(chrono_test, format_tm) { EXPECT_EQ(fmt::format("The date is {:%Y-%m-%d %H:%M:%S}.", tm), "The date is 2016-04-25 11:22:33."); EXPECT_EQ(fmt::format("{:%F}", tm), "2016-04-25"); + EXPECT_EQ(fmt::format("{:%T}", tm), "11:22:33"); } TEST(chrono_test, grow_buffer) {