1 // Formatting library for C++ - chrono support
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 
8 #ifndef FMT_CHRONO_H_
9 #define FMT_CHRONO_H_
10 
11 #include <algorithm>
12 #include <chrono>
13 #include <ctime>
14 #include <locale>
15 #include <sstream>
16 
17 #include "format.h"
18 
19 FMT_BEGIN_NAMESPACE
20 
21 // Enable safe chrono durations, unless explicitly disabled.
22 #ifndef FMT_SAFE_DURATION_CAST
23 #  define FMT_SAFE_DURATION_CAST 1
24 #endif
25 #if FMT_SAFE_DURATION_CAST
26 
27 // For conversion between std::chrono::durations without undefined
28 // behaviour or erroneous results.
29 // This is a stripped down version of duration_cast, for inclusion in fmt.
30 // See https://github.com/pauldreik/safe_duration_cast
31 //
32 // Copyright Paul Dreik 2019
33 namespace safe_duration_cast {
34 
35 template <typename To, typename From,
36           FMT_ENABLE_IF(!std::is_same<From, To>::value &&
37                         std::numeric_limits<From>::is_signed ==
38                             std::numeric_limits<To>::is_signed)>
lossless_integral_conversion(const From from,int & ec)39 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
40   ec = 0;
41   using F = std::numeric_limits<From>;
42   using T = std::numeric_limits<To>;
43   static_assert(F::is_integer, "From must be integral");
44   static_assert(T::is_integer, "To must be integral");
45 
46   // A and B are both signed, or both unsigned.
47   if (F::digits <= T::digits) {
48     // From fits in To without any problem.
49   } else {
50     // From does not always fit in To, resort to a dynamic check.
51     if (from < (T::min)() || from > (T::max)()) {
52       // outside range.
53       ec = 1;
54       return {};
55     }
56   }
57   return static_cast<To>(from);
58 }
59 
60 /**
61  * converts From to To, without loss. If the dynamic value of from
62  * can't be converted to To without loss, ec is set.
63  */
64 template <typename To, typename From,
65           FMT_ENABLE_IF(!std::is_same<From, To>::value &&
66                         std::numeric_limits<From>::is_signed !=
67                             std::numeric_limits<To>::is_signed)>
lossless_integral_conversion(const From from,int & ec)68 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
69   ec = 0;
70   using F = std::numeric_limits<From>;
71   using T = std::numeric_limits<To>;
72   static_assert(F::is_integer, "From must be integral");
73   static_assert(T::is_integer, "To must be integral");
74 
75   if (detail::const_check(F::is_signed && !T::is_signed)) {
76     // From may be negative, not allowed!
77     if (fmt::detail::is_negative(from)) {
78       ec = 1;
79       return {};
80     }
81     // From is positive. Can it always fit in To?
82     if (F::digits > T::digits &&
83         from > static_cast<From>(detail::max_value<To>())) {
84       ec = 1;
85       return {};
86     }
87   }
88 
89   if (!F::is_signed && T::is_signed && F::digits >= T::digits &&
90       from > static_cast<From>(detail::max_value<To>())) {
91     ec = 1;
92     return {};
93   }
94   return static_cast<To>(from);  // Lossless conversion.
95 }
96 
97 template <typename To, typename From,
98           FMT_ENABLE_IF(std::is_same<From, To>::value)>
lossless_integral_conversion(const From from,int & ec)99 FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
100   ec = 0;
101   return from;
102 }  // function
103 
104 // clang-format off
105 /**
106  * converts From to To if possible, otherwise ec is set.
107  *
108  * input                            |    output
109  * ---------------------------------|---------------
110  * NaN                              | NaN
111  * Inf                              | Inf
112  * normal, fits in output           | converted (possibly lossy)
113  * normal, does not fit in output   | ec is set
114  * subnormal                        | best effort
115  * -Inf                             | -Inf
116  */
117 // clang-format on
118 template <typename To, typename From,
119           FMT_ENABLE_IF(!std::is_same<From, To>::value)>
safe_float_conversion(const From from,int & ec)120 FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
121   ec = 0;
122   using T = std::numeric_limits<To>;
123   static_assert(std::is_floating_point<From>::value, "From must be floating");
124   static_assert(std::is_floating_point<To>::value, "To must be floating");
125 
126   // catch the only happy case
127   if (std::isfinite(from)) {
128     if (from >= T::lowest() && from <= (T::max)()) {
129       return static_cast<To>(from);
130     }
131     // not within range.
132     ec = 1;
133     return {};
134   }
135 
136   // nan and inf will be preserved
137   return static_cast<To>(from);
138 }  // function
139 
140 template <typename To, typename From,
141           FMT_ENABLE_IF(std::is_same<From, To>::value)>
safe_float_conversion(const From from,int & ec)142 FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
143   ec = 0;
144   static_assert(std::is_floating_point<From>::value, "From must be floating");
145   return from;
146 }
147 
148 /**
149  * safe duration cast between integral durations
150  */
151 template <typename To, typename FromRep, typename FromPeriod,
152           FMT_ENABLE_IF(std::is_integral<FromRep>::value),
153           FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
safe_duration_cast(std::chrono::duration<FromRep,FromPeriod> from,int & ec)154 To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
155                       int& ec) {
156   using From = std::chrono::duration<FromRep, FromPeriod>;
157   ec = 0;
158   // the basic idea is that we need to convert from count() in the from type
159   // to count() in the To type, by multiplying it with this:
160   struct Factor
161       : std::ratio_divide<typename From::period, typename To::period> {};
162 
163   static_assert(Factor::num > 0, "num must be positive");
164   static_assert(Factor::den > 0, "den must be positive");
165 
166   // the conversion is like this: multiply from.count() with Factor::num
167   // /Factor::den and convert it to To::rep, all this without
168   // overflow/underflow. let's start by finding a suitable type that can hold
169   // both To, From and Factor::num
170   using IntermediateRep =
171       typename std::common_type<typename From::rep, typename To::rep,
172                                 decltype(Factor::num)>::type;
173 
174   // safe conversion to IntermediateRep
175   IntermediateRep count =
176       lossless_integral_conversion<IntermediateRep>(from.count(), ec);
177   if (ec) return {};
178   // multiply with Factor::num without overflow or underflow
179   if (detail::const_check(Factor::num != 1)) {
180     const auto max1 = detail::max_value<IntermediateRep>() / Factor::num;
181     if (count > max1) {
182       ec = 1;
183       return {};
184     }
185     const auto min1 =
186         (std::numeric_limits<IntermediateRep>::min)() / Factor::num;
187     if (count < min1) {
188       ec = 1;
189       return {};
190     }
191     count *= Factor::num;
192   }
193 
194   if (detail::const_check(Factor::den != 1)) count /= Factor::den;
195   auto tocount = lossless_integral_conversion<typename To::rep>(count, ec);
196   return ec ? To() : To(tocount);
197 }
198 
199 /**
200  * safe duration_cast between floating point durations
201  */
202 template <typename To, typename FromRep, typename FromPeriod,
203           FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
204           FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
safe_duration_cast(std::chrono::duration<FromRep,FromPeriod> from,int & ec)205 To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
206                       int& ec) {
207   using From = std::chrono::duration<FromRep, FromPeriod>;
208   ec = 0;
209   if (std::isnan(from.count())) {
210     // nan in, gives nan out. easy.
211     return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
212   }
213   // maybe we should also check if from is denormal, and decide what to do about
214   // it.
215 
216   // +-inf should be preserved.
217   if (std::isinf(from.count())) {
218     return To{from.count()};
219   }
220 
221   // the basic idea is that we need to convert from count() in the from type
222   // to count() in the To type, by multiplying it with this:
223   struct Factor
224       : std::ratio_divide<typename From::period, typename To::period> {};
225 
226   static_assert(Factor::num > 0, "num must be positive");
227   static_assert(Factor::den > 0, "den must be positive");
228 
229   // the conversion is like this: multiply from.count() with Factor::num
230   // /Factor::den and convert it to To::rep, all this without
231   // overflow/underflow. let's start by finding a suitable type that can hold
232   // both To, From and Factor::num
233   using IntermediateRep =
234       typename std::common_type<typename From::rep, typename To::rep,
235                                 decltype(Factor::num)>::type;
236 
237   // force conversion of From::rep -> IntermediateRep to be safe,
238   // even if it will never happen be narrowing in this context.
239   IntermediateRep count =
240       safe_float_conversion<IntermediateRep>(from.count(), ec);
241   if (ec) {
242     return {};
243   }
244 
245   // multiply with Factor::num without overflow or underflow
246   if (Factor::num != 1) {
247     constexpr auto max1 = detail::max_value<IntermediateRep>() /
248                           static_cast<IntermediateRep>(Factor::num);
249     if (count > max1) {
250       ec = 1;
251       return {};
252     }
253     constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
254                           static_cast<IntermediateRep>(Factor::num);
255     if (count < min1) {
256       ec = 1;
257       return {};
258     }
259     count *= static_cast<IntermediateRep>(Factor::num);
260   }
261 
262   // this can't go wrong, right? den>0 is checked earlier.
263   if (Factor::den != 1) {
264     using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
265     count /= static_cast<common_t>(Factor::den);
266   }
267 
268   // convert to the to type, safely
269   using ToRep = typename To::rep;
270 
271   const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
272   if (ec) {
273     return {};
274   }
275   return To{tocount};
276 }
277 }  // namespace safe_duration_cast
278 #endif
279 
280 // Prevents expansion of a preceding token as a function-style macro.
281 // Usage: f FMT_NOMACRO()
282 #define FMT_NOMACRO
283 
284 namespace detail {
285 template <typename T = void> struct null {};
FMT_NOMACRO(...)286 inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
localtime_s(...)287 inline null<> localtime_s(...) { return null<>(); }
gmtime_r(...)288 inline null<> gmtime_r(...) { return null<>(); }
gmtime_s(...)289 inline null<> gmtime_s(...) { return null<>(); }
290 
291 inline auto do_write(const std::tm& time, const std::locale& loc, char format,
292                      char modifier) -> std::string {
293   auto&& os = std::ostringstream();
294   os.imbue(loc);
295   using iterator = std::ostreambuf_iterator<char>;
296   const auto& facet = std::use_facet<std::time_put<char, iterator>>(loc);
297   auto end = facet.put(os, os, ' ', &time, format, modifier);
298   if (end.failed()) FMT_THROW(format_error("failed to format time"));
299   auto str = os.str();
300   if (!detail::is_utf8() || loc == std::locale::classic()) return str;
301     // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
302     // gcc-4.
303 #if FMT_MSC_VER != 0 || \
304     (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI))
305   // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
306   // and newer.
307   using code_unit = wchar_t;
308 #else
309   using code_unit = char32_t;
310 #endif
311   auto& f = std::use_facet<std::codecvt<code_unit, char, std::mbstate_t>>(loc);
312   auto mb = std::mbstate_t();
313   const char* from_next = nullptr;
314   code_unit* to_next = nullptr;
315   constexpr size_t buf_size = 32;
316   code_unit buf[buf_size] = {};
317   auto result = f.in(mb, str.data(), str.data() + str.size(), from_next, buf,
318                      buf + buf_size, to_next);
319   if (result != std::codecvt_base::ok)
320     FMT_THROW(format_error("failed to format time"));
321   str.clear();
322   for (code_unit* p = buf; p != to_next; ++p) {
323     uint32_t c = static_cast<uint32_t>(*p);
324     if (sizeof(code_unit) == 2 && c >= 0xd800 && c <= 0xdfff) {
325       // surrogate pair
326       ++p;
327       if (p == to_next || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) {
328         FMT_THROW(format_error("failed to format time"));
329       }
330       c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;
331     }
332     if (c < 0x80) {
333       str.push_back(static_cast<char>(c));
334     } else if (c < 0x800) {
335       str.push_back(static_cast<char>(0xc0 | (c >> 6)));
336       str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
337     } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {
338       str.push_back(static_cast<char>(0xe0 | (c >> 12)));
339       str.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
340       str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
341     } else if (c >= 0x10000 && c <= 0x10ffff) {
342       str.push_back(static_cast<char>(0xf0 | (c >> 18)));
343       str.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));
344       str.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
345       str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
346     } else {
347       FMT_THROW(format_error("failed to format time"));
348     }
349   }
350   return str;
351 }
352 
353 template <typename OutputIt>
354 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
355            char format, char modifier = 0) -> OutputIt {
356   auto str = do_write(time, loc, format, modifier);
357   return std::copy(str.begin(), str.end(), out);
358 }
359 }  // namespace detail
360 
361 FMT_MODULE_EXPORT_BEGIN
362 
363 /**
364   Converts given time since epoch as ``std::time_t`` value into calendar time,
365   expressed in local time. Unlike ``std::localtime``, this function is
366   thread-safe on most platforms.
367  */
localtime(std::time_t time)368 inline std::tm localtime(std::time_t time) {
369   struct dispatcher {
370     std::time_t time_;
371     std::tm tm_;
372 
373     dispatcher(std::time_t t) : time_(t) {}
374 
375     bool run() {
376       using namespace fmt::detail;
377       return handle(localtime_r(&time_, &tm_));
378     }
379 
380     bool handle(std::tm* tm) { return tm != nullptr; }
381 
382     bool handle(detail::null<>) {
383       using namespace fmt::detail;
384       return fallback(localtime_s(&tm_, &time_));
385     }
386 
387     bool fallback(int res) { return res == 0; }
388 
389 #if !FMT_MSC_VER
390     bool fallback(detail::null<>) {
391       using namespace fmt::detail;
392       std::tm* tm = std::localtime(&time_);
393       if (tm) tm_ = *tm;
394       return tm != nullptr;
395     }
396 #endif
397   };
398   dispatcher lt(time);
399   // Too big time values may be unsupported.
400   if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
401   return lt.tm_;
402 }
403 
localtime(std::chrono::time_point<std::chrono::system_clock> time_point)404 inline std::tm localtime(
405     std::chrono::time_point<std::chrono::system_clock> time_point) {
406   return localtime(std::chrono::system_clock::to_time_t(time_point));
407 }
408 
409 /**
410   Converts given time since epoch as ``std::time_t`` value into calendar time,
411   expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this
412   function is thread-safe on most platforms.
413  */
gmtime(std::time_t time)414 inline std::tm gmtime(std::time_t time) {
415   struct dispatcher {
416     std::time_t time_;
417     std::tm tm_;
418 
419     dispatcher(std::time_t t) : time_(t) {}
420 
421     bool run() {
422       using namespace fmt::detail;
423       return handle(gmtime_r(&time_, &tm_));
424     }
425 
426     bool handle(std::tm* tm) { return tm != nullptr; }
427 
428     bool handle(detail::null<>) {
429       using namespace fmt::detail;
430       return fallback(gmtime_s(&tm_, &time_));
431     }
432 
433     bool fallback(int res) { return res == 0; }
434 
435 #if !FMT_MSC_VER
436     bool fallback(detail::null<>) {
437       std::tm* tm = std::gmtime(&time_);
438       if (tm) tm_ = *tm;
439       return tm != nullptr;
440     }
441 #endif
442   };
443   dispatcher gt(time);
444   // Too big time values may be unsupported.
445   if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
446   return gt.tm_;
447 }
448 
gmtime(std::chrono::time_point<std::chrono::system_clock> time_point)449 inline std::tm gmtime(
450     std::chrono::time_point<std::chrono::system_clock> time_point) {
451   return gmtime(std::chrono::system_clock::to_time_t(time_point));
452 }
453 
454 FMT_BEGIN_DETAIL_NAMESPACE
455 
strftime(char * str,size_t count,const char * format,const std::tm * time)456 inline size_t strftime(char* str, size_t count, const char* format,
457                        const std::tm* time) {
458   // Assign to a pointer to suppress GCCs -Wformat-nonliteral
459   // First assign the nullptr to suppress -Wsuggest-attribute=format
460   std::size_t (*strftime)(char*, std::size_t, const char*, const std::tm*) =
461       nullptr;
462   strftime = std::strftime;
463   return strftime(str, count, format, time);
464 }
465 
strftime(wchar_t * str,size_t count,const wchar_t * format,const std::tm * time)466 inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format,
467                        const std::tm* time) {
468   // See above
469   std::size_t (*wcsftime)(wchar_t*, std::size_t, const wchar_t*,
470                           const std::tm*) = nullptr;
471   wcsftime = std::wcsftime;
472   return wcsftime(str, count, format, time);
473 }
474 
475 FMT_END_DETAIL_NAMESPACE
476 
477 template <typename Char, typename Duration>
478 struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
479                  Char> : formatter<std::tm, Char> {
480   FMT_CONSTEXPR formatter() {
481     this->specs = {default_specs, sizeof(default_specs) / sizeof(Char)};
482   }
483 
484   template <typename ParseContext>
485   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
486     auto it = ctx.begin();
487     if (it != ctx.end() && *it == ':') ++it;
488     auto end = it;
489     while (end != ctx.end() && *end != '}') ++end;
490     if (end != it) this->specs = {it, detail::to_unsigned(end - it)};
491     return end;
492   }
493 
494   template <typename FormatContext>
495   auto format(std::chrono::time_point<std::chrono::system_clock> val,
496               FormatContext& ctx) -> decltype(ctx.out()) {
497     std::tm time = localtime(val);
498     return formatter<std::tm, Char>::format(time, ctx);
499   }
500 
501   static constexpr Char default_specs[] = {'%', 'Y', '-', '%', 'm', '-',
502                                            '%', 'd', ' ', '%', 'H', ':',
503                                            '%', 'M', ':', '%', 'S'};
504 };
505 
506 template <typename Char, typename Duration>
507 constexpr Char
508     formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
509               Char>::default_specs[];
510 
511 template <typename Char> struct formatter<std::tm, Char> {
512   template <typename ParseContext>
513   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
514     auto it = ctx.begin();
515     if (it != ctx.end() && *it == ':') ++it;
516     auto end = it;
517     while (end != ctx.end() && *end != '}') ++end;
518     specs = {it, detail::to_unsigned(end - it)};
519     return end;
520   }
521 
522   template <typename FormatContext>
523   auto format(const std::tm& tm, FormatContext& ctx) const
524       -> decltype(ctx.out()) {
525     basic_memory_buffer<Char> tm_format;
526     tm_format.append(specs.begin(), specs.end());
527     // By appending an extra space we can distinguish an empty result that
528     // indicates insufficient buffer size from a guaranteed non-empty result
529     // https://github.com/fmtlib/fmt/issues/2238
530     tm_format.push_back(' ');
531     tm_format.push_back('\0');
532     basic_memory_buffer<Char> buf;
533     size_t start = buf.size();
534     for (;;) {
535       size_t size = buf.capacity() - start;
536       size_t count = detail::strftime(&buf[start], size, &tm_format[0], &tm);
537       if (count != 0) {
538         buf.resize(start + count);
539         break;
540       }
541       const size_t MIN_GROWTH = 10;
542       buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH));
543     }
544     // Remove the extra space.
545     return std::copy(buf.begin(), buf.end() - 1, ctx.out());
546   }
547 
548   basic_string_view<Char> specs;
549 };
550 
551 FMT_BEGIN_DETAIL_NAMESPACE
552 
553 template <typename Period> FMT_CONSTEXPR inline const char* get_units() {
554   if (std::is_same<Period, std::atto>::value) return "as";
555   if (std::is_same<Period, std::femto>::value) return "fs";
556   if (std::is_same<Period, std::pico>::value) return "ps";
557   if (std::is_same<Period, std::nano>::value) return "ns";
558   if (std::is_same<Period, std::micro>::value) return "µs";
559   if (std::is_same<Period, std::milli>::value) return "ms";
560   if (std::is_same<Period, std::centi>::value) return "cs";
561   if (std::is_same<Period, std::deci>::value) return "ds";
562   if (std::is_same<Period, std::ratio<1>>::value) return "s";
563   if (std::is_same<Period, std::deca>::value) return "das";
564   if (std::is_same<Period, std::hecto>::value) return "hs";
565   if (std::is_same<Period, std::kilo>::value) return "ks";
566   if (std::is_same<Period, std::mega>::value) return "Ms";
567   if (std::is_same<Period, std::giga>::value) return "Gs";
568   if (std::is_same<Period, std::tera>::value) return "Ts";
569   if (std::is_same<Period, std::peta>::value) return "Ps";
570   if (std::is_same<Period, std::exa>::value) return "Es";
571   if (std::is_same<Period, std::ratio<60>>::value) return "m";
572   if (std::is_same<Period, std::ratio<3600>>::value) return "h";
573   return nullptr;
574 }
575 
576 enum class numeric_system {
577   standard,
578   // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
579   alternative
580 };
581 
582 // Parses a put_time-like format string and invokes handler actions.
583 template <typename Char, typename Handler>
584 FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
585                                               const Char* end,
586                                               Handler&& handler) {
587   auto ptr = begin;
588   while (ptr != end) {
589     auto c = *ptr;
590     if (c == '}') break;
591     if (c != '%') {
592       ++ptr;
593       continue;
594     }
595     if (begin != ptr) handler.on_text(begin, ptr);
596     ++ptr;  // consume '%'
597     if (ptr == end) FMT_THROW(format_error("invalid format"));
598     c = *ptr++;
599     switch (c) {
600     case '%':
601       handler.on_text(ptr - 1, ptr);
602       break;
603     case 'n': {
604       const Char newline[] = {'\n'};
605       handler.on_text(newline, newline + 1);
606       break;
607     }
608     case 't': {
609       const Char tab[] = {'\t'};
610       handler.on_text(tab, tab + 1);
611       break;
612     }
613     // Day of the week:
614     case 'a':
615       handler.on_abbr_weekday();
616       break;
617     case 'A':
618       handler.on_full_weekday();
619       break;
620     case 'w':
621       handler.on_dec0_weekday(numeric_system::standard);
622       break;
623     case 'u':
624       handler.on_dec1_weekday(numeric_system::standard);
625       break;
626     // Month:
627     case 'b':
628       handler.on_abbr_month();
629       break;
630     case 'B':
631       handler.on_full_month();
632       break;
633     // Hour, minute, second:
634     case 'H':
635       handler.on_24_hour(numeric_system::standard);
636       break;
637     case 'I':
638       handler.on_12_hour(numeric_system::standard);
639       break;
640     case 'M':
641       handler.on_minute(numeric_system::standard);
642       break;
643     case 'S':
644       handler.on_second(numeric_system::standard);
645       break;
646     // Other:
647     case 'c':
648       handler.on_datetime(numeric_system::standard);
649       break;
650     case 'x':
651       handler.on_loc_date(numeric_system::standard);
652       break;
653     case 'X':
654       handler.on_loc_time(numeric_system::standard);
655       break;
656     case 'D':
657       handler.on_us_date();
658       break;
659     case 'F':
660       handler.on_iso_date();
661       break;
662     case 'r':
663       handler.on_12_hour_time();
664       break;
665     case 'R':
666       handler.on_24_hour_time();
667       break;
668     case 'T':
669       handler.on_iso_time();
670       break;
671     case 'p':
672       handler.on_am_pm();
673       break;
674     case 'Q':
675       handler.on_duration_value();
676       break;
677     case 'q':
678       handler.on_duration_unit();
679       break;
680     case 'z':
681       handler.on_utc_offset();
682       break;
683     case 'Z':
684       handler.on_tz_name();
685       break;
686     // Alternative representation:
687     case 'E': {
688       if (ptr == end) FMT_THROW(format_error("invalid format"));
689       c = *ptr++;
690       switch (c) {
691       case 'c':
692         handler.on_datetime(numeric_system::alternative);
693         break;
694       case 'x':
695         handler.on_loc_date(numeric_system::alternative);
696         break;
697       case 'X':
698         handler.on_loc_time(numeric_system::alternative);
699         break;
700       default:
701         FMT_THROW(format_error("invalid format"));
702       }
703       break;
704     }
705     case 'O':
706       if (ptr == end) FMT_THROW(format_error("invalid format"));
707       c = *ptr++;
708       switch (c) {
709       case 'w':
710         handler.on_dec0_weekday(numeric_system::alternative);
711         break;
712       case 'u':
713         handler.on_dec1_weekday(numeric_system::alternative);
714         break;
715       case 'H':
716         handler.on_24_hour(numeric_system::alternative);
717         break;
718       case 'I':
719         handler.on_12_hour(numeric_system::alternative);
720         break;
721       case 'M':
722         handler.on_minute(numeric_system::alternative);
723         break;
724       case 'S':
725         handler.on_second(numeric_system::alternative);
726         break;
727       default:
728         FMT_THROW(format_error("invalid format"));
729       }
730       break;
731     default:
732       FMT_THROW(format_error("invalid format"));
733     }
734     begin = ptr;
735   }
736   if (begin != ptr) handler.on_text(begin, ptr);
737   return ptr;
738 }
739 
740 template <typename Derived> struct null_chrono_spec_handler {
741   FMT_CONSTEXPR void unsupported() {
742     static_cast<Derived*>(this)->unsupported();
743   }
744   FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }
745   FMT_CONSTEXPR void on_full_weekday() { unsupported(); }
746   FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }
747   FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }
748   FMT_CONSTEXPR void on_abbr_month() { unsupported(); }
749   FMT_CONSTEXPR void on_full_month() { unsupported(); }
750   FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }
751   FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }
752   FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }
753   FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }
754   FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }
755   FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }
756   FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }
757   FMT_CONSTEXPR void on_us_date() { unsupported(); }
758   FMT_CONSTEXPR void on_iso_date() { unsupported(); }
759   FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }
760   FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }
761   FMT_CONSTEXPR void on_iso_time() { unsupported(); }
762   FMT_CONSTEXPR void on_am_pm() { unsupported(); }
763   FMT_CONSTEXPR void on_duration_value() { unsupported(); }
764   FMT_CONSTEXPR void on_duration_unit() { unsupported(); }
765   FMT_CONSTEXPR void on_utc_offset() { unsupported(); }
766   FMT_CONSTEXPR void on_tz_name() { unsupported(); }
767 };
768 
769 struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
770   FMT_NORETURN void unsupported() { FMT_THROW(format_error("no date")); }
771 
772   template <typename Char>
773   FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
774   FMT_CONSTEXPR void on_24_hour(numeric_system) {}
775   FMT_CONSTEXPR void on_12_hour(numeric_system) {}
776   FMT_CONSTEXPR void on_minute(numeric_system) {}
777   FMT_CONSTEXPR void on_second(numeric_system) {}
778   FMT_CONSTEXPR void on_12_hour_time() {}
779   FMT_CONSTEXPR void on_24_hour_time() {}
780   FMT_CONSTEXPR void on_iso_time() {}
781   FMT_CONSTEXPR void on_am_pm() {}
782   FMT_CONSTEXPR void on_duration_value() {}
783   FMT_CONSTEXPR void on_duration_unit() {}
784 };
785 
786 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
787 inline bool isnan(T) {
788   return false;
789 }
790 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
791 inline bool isnan(T value) {
792   return std::isnan(value);
793 }
794 
795 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
796 inline bool isfinite(T) {
797   return true;
798 }
799 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
800 inline bool isfinite(T value) {
801   return std::isfinite(value);
802 }
803 
804 // Converts value to int and checks that it's in the range [0, upper).
805 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
806 inline int to_nonnegative_int(T value, int upper) {
807   FMT_ASSERT(value >= 0 && to_unsigned(value) <= to_unsigned(upper),
808              "invalid value");
809   (void)upper;
810   return static_cast<int>(value);
811 }
812 template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
813 inline int to_nonnegative_int(T value, int upper) {
814   FMT_ASSERT(
815       std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)),
816       "invalid value");
817   (void)upper;
818   return static_cast<int>(value);
819 }
820 
821 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
822 inline T mod(T x, int y) {
823   return x % static_cast<T>(y);
824 }
825 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
826 inline T mod(T x, int y) {
827   return std::fmod(x, static_cast<T>(y));
828 }
829 
830 // If T is an integral type, maps T to its unsigned counterpart, otherwise
831 // leaves it unchanged (unlike std::make_unsigned).
832 template <typename T, bool INTEGRAL = std::is_integral<T>::value>
833 struct make_unsigned_or_unchanged {
834   using type = T;
835 };
836 
837 template <typename T> struct make_unsigned_or_unchanged<T, true> {
838   using type = typename std::make_unsigned<T>::type;
839 };
840 
841 #if FMT_SAFE_DURATION_CAST
842 // throwing version of safe_duration_cast
843 template <typename To, typename FromRep, typename FromPeriod>
844 To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) {
845   int ec;
846   To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
847   if (ec) FMT_THROW(format_error("cannot format duration"));
848   return to;
849 }
850 #endif
851 
852 template <typename Rep, typename Period,
853           FMT_ENABLE_IF(std::is_integral<Rep>::value)>
854 inline std::chrono::duration<Rep, std::milli> get_milliseconds(
855     std::chrono::duration<Rep, Period> d) {
856   // this may overflow and/or the result may not fit in the
857   // target type.
858 #if FMT_SAFE_DURATION_CAST
859   using CommonSecondsType =
860       typename std::common_type<decltype(d), std::chrono::seconds>::type;
861   const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d);
862   const auto d_as_whole_seconds =
863       fmt_safe_duration_cast<std::chrono::seconds>(d_as_common);
864   // this conversion should be nonproblematic
865   const auto diff = d_as_common - d_as_whole_seconds;
866   const auto ms =
867       fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
868   return ms;
869 #else
870   auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
871   return std::chrono::duration_cast<std::chrono::milliseconds>(d - s);
872 #endif
873 }
874 
875 template <typename Rep, typename Period,
876           FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
877 inline std::chrono::duration<Rep, std::milli> get_milliseconds(
878     std::chrono::duration<Rep, Period> d) {
879   using common_type = typename std::common_type<Rep, std::intmax_t>::type;
880   auto ms = mod(d.count() * static_cast<common_type>(Period::num) /
881                     static_cast<common_type>(Period::den) * 1000,
882                 1000);
883   return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms));
884 }
885 
886 template <typename Char, typename Rep, typename OutputIt,
887           FMT_ENABLE_IF(std::is_integral<Rep>::value)>
888 OutputIt format_duration_value(OutputIt out, Rep val, int) {
889   return write<Char>(out, val);
890 }
891 
892 template <typename Char, typename Rep, typename OutputIt,
893           FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
894 OutputIt format_duration_value(OutputIt out, Rep val, int precision) {
895   auto specs = basic_format_specs<Char>();
896   specs.precision = precision;
897   specs.type = precision > 0 ? 'f' : 'g';
898   return write<Char>(out, val, specs);
899 }
900 
901 template <typename Char, typename OutputIt>
902 OutputIt copy_unit(string_view unit, OutputIt out, Char) {
903   return std::copy(unit.begin(), unit.end(), out);
904 }
905 
906 template <typename OutputIt>
907 OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) {
908   // This works when wchar_t is UTF-32 because units only contain characters
909   // that have the same representation in UTF-16 and UTF-32.
910   utf8_to_utf16 u(unit);
911   return std::copy(u.c_str(), u.c_str() + u.size(), out);
912 }
913 
914 template <typename Char, typename Period, typename OutputIt>
915 OutputIt format_duration_unit(OutputIt out) {
916   if (const char* unit = get_units<Period>())
917     return copy_unit(string_view(unit), out, Char());
918   *out++ = '[';
919   out = write<Char>(out, Period::num);
920   if (const_check(Period::den != 1)) {
921     *out++ = '/';
922     out = write<Char>(out, Period::den);
923   }
924   *out++ = ']';
925   *out++ = 's';
926   return out;
927 }
928 
929 template <typename FormatContext, typename OutputIt, typename Rep,
930           typename Period>
931 struct chrono_formatter {
932   FormatContext& context;
933   OutputIt out;
934   int precision;
935   bool localized = false;
936   // rep is unsigned to avoid overflow.
937   using rep =
938       conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
939                     unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
940   rep val;
941   using seconds = std::chrono::duration<rep>;
942   seconds s;
943   using milliseconds = std::chrono::duration<rep, std::milli>;
944   bool negative;
945 
946   using char_type = typename FormatContext::char_type;
947 
948   explicit chrono_formatter(FormatContext& ctx, OutputIt o,
949                             std::chrono::duration<Rep, Period> d)
950       : context(ctx),
951         out(o),
952         val(static_cast<rep>(d.count())),
953         negative(false) {
954     if (d.count() < 0) {
955       val = 0 - val;
956       negative = true;
957     }
958 
959     // this may overflow and/or the result may not fit in the
960     // target type.
961 #if FMT_SAFE_DURATION_CAST
962     // might need checked conversion (rep!=Rep)
963     auto tmpval = std::chrono::duration<rep, Period>(val);
964     s = fmt_safe_duration_cast<seconds>(tmpval);
965 #else
966     s = std::chrono::duration_cast<seconds>(
967         std::chrono::duration<rep, Period>(val));
968 #endif
969   }
970 
971   // returns true if nan or inf, writes to out.
972   bool handle_nan_inf() {
973     if (isfinite(val)) {
974       return false;
975     }
976     if (isnan(val)) {
977       write_nan();
978       return true;
979     }
980     // must be +-inf
981     if (val > 0) {
982       write_pinf();
983     } else {
984       write_ninf();
985     }
986     return true;
987   }
988 
989   Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); }
990 
991   Rep hour12() const {
992     Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
993     return hour <= 0 ? 12 : hour;
994   }
995 
996   Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); }
997   Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); }
998 
999   std::tm time() const {
1000     auto time = std::tm();
1001     time.tm_hour = to_nonnegative_int(hour(), 24);
1002     time.tm_min = to_nonnegative_int(minute(), 60);
1003     time.tm_sec = to_nonnegative_int(second(), 60);
1004     return time;
1005   }
1006 
1007   void write_sign() {
1008     if (negative) {
1009       *out++ = '-';
1010       negative = false;
1011     }
1012   }
1013 
1014   void write(Rep value, int width) {
1015     write_sign();
1016     if (isnan(value)) return write_nan();
1017     uint32_or_64_or_128_t<int> n =
1018         to_unsigned(to_nonnegative_int(value, max_value<int>()));
1019     int num_digits = detail::count_digits(n);
1020     if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
1021     out = format_decimal<char_type>(out, n, num_digits).end;
1022   }
1023 
1024   void write_nan() { std::copy_n("nan", 3, out); }
1025   void write_pinf() { std::copy_n("inf", 3, out); }
1026   void write_ninf() { std::copy_n("-inf", 4, out); }
1027 
1028   void format_localized(const tm& time, char format, char modifier = 0) {
1029     if (isnan(val)) return write_nan();
1030     const auto& loc = localized ? context.locale().template get<std::locale>()
1031                                 : std::locale::classic();
1032     out = detail::write(out, time, loc, format, modifier);
1033   }
1034 
1035   void on_text(const char_type* begin, const char_type* end) {
1036     std::copy(begin, end, out);
1037   }
1038 
1039   // These are not implemented because durations don't have date information.
1040   void on_abbr_weekday() {}
1041   void on_full_weekday() {}
1042   void on_dec0_weekday(numeric_system) {}
1043   void on_dec1_weekday(numeric_system) {}
1044   void on_abbr_month() {}
1045   void on_full_month() {}
1046   void on_datetime(numeric_system) {}
1047   void on_loc_date(numeric_system) {}
1048   void on_loc_time(numeric_system) {}
1049   void on_us_date() {}
1050   void on_iso_date() {}
1051   void on_utc_offset() {}
1052   void on_tz_name() {}
1053 
1054   void on_24_hour(numeric_system ns) {
1055     if (handle_nan_inf()) return;
1056 
1057     if (ns == numeric_system::standard) return write(hour(), 2);
1058     auto time = tm();
1059     time.tm_hour = to_nonnegative_int(hour(), 24);
1060     format_localized(time, 'H', 'O');
1061   }
1062 
1063   void on_12_hour(numeric_system ns) {
1064     if (handle_nan_inf()) return;
1065 
1066     if (ns == numeric_system::standard) return write(hour12(), 2);
1067     auto time = tm();
1068     time.tm_hour = to_nonnegative_int(hour12(), 12);
1069     format_localized(time, 'I', 'O');
1070   }
1071 
1072   void on_minute(numeric_system ns) {
1073     if (handle_nan_inf()) return;
1074 
1075     if (ns == numeric_system::standard) return write(minute(), 2);
1076     auto time = tm();
1077     time.tm_min = to_nonnegative_int(minute(), 60);
1078     format_localized(time, 'M', 'O');
1079   }
1080 
1081   void on_second(numeric_system ns) {
1082     if (handle_nan_inf()) return;
1083 
1084     if (ns == numeric_system::standard) {
1085       write(second(), 2);
1086 #if FMT_SAFE_DURATION_CAST
1087       // convert rep->Rep
1088       using duration_rep = std::chrono::duration<rep, Period>;
1089       using duration_Rep = std::chrono::duration<Rep, Period>;
1090       auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val});
1091 #else
1092       auto tmpval = std::chrono::duration<Rep, Period>(val);
1093 #endif
1094       auto ms = get_milliseconds(tmpval);
1095       if (ms != std::chrono::milliseconds(0)) {
1096         *out++ = '.';
1097         write(ms.count(), 3);
1098       }
1099       return;
1100     }
1101     auto time = tm();
1102     time.tm_sec = to_nonnegative_int(second(), 60);
1103     format_localized(time, 'S', 'O');
1104   }
1105 
1106   void on_12_hour_time() {
1107     if (handle_nan_inf()) return;
1108     format_localized(time(), 'r');
1109   }
1110 
1111   void on_24_hour_time() {
1112     if (handle_nan_inf()) {
1113       *out++ = ':';
1114       handle_nan_inf();
1115       return;
1116     }
1117 
1118     write(hour(), 2);
1119     *out++ = ':';
1120     write(minute(), 2);
1121   }
1122 
1123   void on_iso_time() {
1124     on_24_hour_time();
1125     *out++ = ':';
1126     if (handle_nan_inf()) return;
1127     write(second(), 2);
1128   }
1129 
1130   void on_am_pm() {
1131     if (handle_nan_inf()) return;
1132     format_localized(time(), 'p');
1133   }
1134 
1135   void on_duration_value() {
1136     if (handle_nan_inf()) return;
1137     write_sign();
1138     out = format_duration_value<char_type>(out, val, precision);
1139   }
1140 
1141   void on_duration_unit() {
1142     out = format_duration_unit<char_type, Period>(out);
1143   }
1144 };
1145 
1146 FMT_END_DETAIL_NAMESPACE
1147 
1148 #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
1149 using weekday = std::chrono::weekday;
1150 #else
1151 // A fallback version of weekday.
1152 class weekday {
1153  private:
1154   unsigned char value;
1155 
1156  public:
1157   weekday() = default;
1158   explicit constexpr weekday(unsigned wd) noexcept
1159       : value(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
1160   constexpr unsigned c_encoding() const noexcept { return value; }
1161 };
1162 #endif
1163 
1164 // A rudimentary weekday formatter.
1165 template <> struct formatter<weekday> {
1166  private:
1167   bool localized = false;
1168 
1169  public:
1170   FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
1171     auto begin = ctx.begin(), end = ctx.end();
1172     if (begin != end && *begin == 'L') {
1173       ++begin;
1174       localized = true;
1175     }
1176     return begin;
1177   }
1178 
1179   auto format(weekday wd, format_context& ctx) -> decltype(ctx.out()) {
1180     auto time = std::tm();
1181     time.tm_wday = static_cast<int>(wd.c_encoding());
1182     const auto& loc = localized ? ctx.locale().template get<std::locale>()
1183                                 : std::locale::classic();
1184     return detail::write(ctx.out(), time, loc, 'a');
1185   }
1186 };
1187 
1188 template <typename Rep, typename Period, typename Char>
1189 struct formatter<std::chrono::duration<Rep, Period>, Char> {
1190  private:
1191   basic_format_specs<Char> specs;
1192   int precision = -1;
1193   using arg_ref_type = detail::arg_ref<Char>;
1194   arg_ref_type width_ref;
1195   arg_ref_type precision_ref;
1196   bool localized = false;
1197   basic_string_view<Char> format_str;
1198   using duration = std::chrono::duration<Rep, Period>;
1199 
1200   struct spec_handler {
1201     formatter& f;
1202     basic_format_parse_context<Char>& context;
1203     basic_string_view<Char> format_str;
1204 
1205     template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
1206       context.check_arg_id(arg_id);
1207       return arg_ref_type(arg_id);
1208     }
1209 
1210     FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) {
1211       context.check_arg_id(arg_id);
1212       return arg_ref_type(arg_id);
1213     }
1214 
1215     FMT_CONSTEXPR arg_ref_type make_arg_ref(detail::auto_id) {
1216       return arg_ref_type(context.next_arg_id());
1217     }
1218 
1219     void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
1220     FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
1221       f.specs.fill = fill;
1222     }
1223     FMT_CONSTEXPR void on_align(align_t align) { f.specs.align = align; }
1224     FMT_CONSTEXPR void on_width(int width) { f.specs.width = width; }
1225     FMT_CONSTEXPR void on_precision(int _precision) {
1226       f.precision = _precision;
1227     }
1228     FMT_CONSTEXPR void end_precision() {}
1229 
1230     template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
1231       f.width_ref = make_arg_ref(arg_id);
1232     }
1233 
1234     template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
1235       f.precision_ref = make_arg_ref(arg_id);
1236     }
1237   };
1238 
1239   using iterator = typename basic_format_parse_context<Char>::iterator;
1240   struct parse_range {
1241     iterator begin;
1242     iterator end;
1243   };
1244 
1245   FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) {
1246     auto begin = ctx.begin(), end = ctx.end();
1247     if (begin == end || *begin == '}') return {begin, begin};
1248     spec_handler handler{*this, ctx, format_str};
1249     begin = detail::parse_align(begin, end, handler);
1250     if (begin == end) return {begin, begin};
1251     begin = detail::parse_width(begin, end, handler);
1252     if (begin == end) return {begin, begin};
1253     if (*begin == '.') {
1254       if (std::is_floating_point<Rep>::value)
1255         begin = detail::parse_precision(begin, end, handler);
1256       else
1257         handler.on_error("precision not allowed for this argument type");
1258     }
1259     if (begin != end && *begin == 'L') {
1260       ++begin;
1261       localized = true;
1262     }
1263     end = parse_chrono_format(begin, end, detail::chrono_format_checker());
1264     return {begin, end};
1265   }
1266 
1267  public:
1268   FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
1269       -> decltype(ctx.begin()) {
1270     auto range = do_parse(ctx);
1271     format_str = basic_string_view<Char>(
1272         &*range.begin, detail::to_unsigned(range.end - range.begin));
1273     return range.end;
1274   }
1275 
1276   template <typename FormatContext>
1277   auto format(const duration& d, FormatContext& ctx) const
1278       -> decltype(ctx.out()) {
1279     auto specs_copy = specs;
1280     auto precision_copy = precision;
1281     auto begin = format_str.begin(), end = format_str.end();
1282     // As a possible future optimization, we could avoid extra copying if width
1283     // is not specified.
1284     basic_memory_buffer<Char> buf;
1285     auto out = std::back_inserter(buf);
1286     detail::handle_dynamic_spec<detail::width_checker>(specs_copy.width,
1287                                                        width_ref, ctx);
1288     detail::handle_dynamic_spec<detail::precision_checker>(precision_copy,
1289                                                            precision_ref, ctx);
1290     if (begin == end || *begin == '}') {
1291       out = detail::format_duration_value<Char>(out, d.count(), precision_copy);
1292       detail::format_duration_unit<Char, Period>(out);
1293     } else {
1294       detail::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
1295           ctx, out, d);
1296       f.precision = precision_copy;
1297       f.localized = localized;
1298       detail::parse_chrono_format(begin, end, f);
1299     }
1300     return detail::write(
1301         ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs_copy);
1302   }
1303 };
1304 
1305 FMT_MODULE_EXPORT_END
1306 FMT_END_NAMESPACE
1307 
1308 #endif  // FMT_CHRONO_H_
1309