diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h index 209cdc25..dd146fd5 100644 --- a/include/fmt/chrono.h +++ b/include/fmt/chrono.h @@ -18,7 +18,7 @@ FMT_BEGIN_NAMESPACE -namespace internal{ +namespace internal { enum class numeric_system { standard, @@ -415,7 +415,8 @@ struct formatter, Char> { if (begin == end) return begin; begin = internal::parse_width(begin, end, handler); end = parse_chrono_format(begin, end, internal::chrono_format_checker()); - format_str = basic_string_view(&*begin, internal::to_unsigned(end - begin)); + format_str = basic_string_view( + &*begin, internal::to_unsigned(end - begin)); return end; } @@ -423,6 +424,8 @@ struct formatter, Char> { auto format(const duration &d, FormatContext &ctx) -> decltype(ctx.out()) { auto begin = format_str.begin(), end = format_str.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. memory_buffer buf; typedef output_range range; basic_writer w(range(ctx.out())); @@ -433,8 +436,6 @@ struct formatter, Char> { format_to(buf, "{}[{}]s", d.count(), Period::num); else format_to(buf, "{}[{}/{}]s", d.count(), Period::num, Period::den); - internal::handle_dynamic_spec( - spec.width_, width_ref, ctx); } else { auto out = std::back_inserter(buf); internal::chrono_formatter f(ctx, out); @@ -442,6 +443,8 @@ struct formatter, Char> { f.ms = std::chrono::duration_cast(d - f.s); parse_chrono_format(begin, end, f); } + internal::handle_dynamic_spec( + spec.width_, width_ref, ctx); w.write(buf.data(), buf.size(), spec); return w.out(); } diff --git a/test/chrono-test.cc b/test/chrono-test.cc index ec6092bb..83660c21 100644 --- a/test/chrono-test.cc +++ b/test/chrono-test.cc @@ -103,6 +103,8 @@ TEST(ChronoTest, Align) { fmt::format("{:>12%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("~~03:25:45~~", fmt::format("{:~^12%H:%M:%S}", std::chrono::seconds(12345))); + EXPECT_EQ("03:25:45 ", + fmt::format("{:{}%H:%M:%S}", std::chrono::seconds(12345), 12)); }