Skip to content

Commit

Permalink
Optimize %T in tm formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
phprus committed Sep 15, 2021
1 parent 04e3a79 commit 20c68a6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
12 changes: 11 additions & 1 deletion include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,7 @@ template <typename Char> struct formatter<std::tm, Char> {
enum class spec {
unknown,
year_month_day,
hh_mm_ss,
};
spec spec_ = spec::unknown;

Expand All @@ -563,7 +564,10 @@ template <typename Char> struct formatter<std::tm, Char> {
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;
}

Expand All @@ -578,6 +582,12 @@ template <typename Char> struct formatter<std::tm, Char> {
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<Char> tm_format;
tm_format.append(specs.begin(), specs.end());
Expand Down
1 change: 1 addition & 0 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 20c68a6

Please sign in to comment.