Debian Codegraph @

podofo/3rdparty/fmtlib/fmt/chrono.h

raw
1 // Formatting library for C++ - chrono support
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
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 #ifndef FMT_MODULE
12 # include <algorithm>
13 # include <chrono>
14 # include <cmath> // std::isfinite
15 # include <cstring> // std::memcpy
16 # include <ctime>
17 # include <iterator>
18 # include <locale>
19 # include <ostream>
20 # include <type_traits>
21 #endif
22
23 #include "format.h"
24
25 FMT_BEGIN_NAMESPACE
26
27 // Enable safe chrono durations, unless explicitly disabled.
28 #ifndef FMT_SAFE_DURATION_CAST
29 # define FMT_SAFE_DURATION_CAST 1
30 #endif
31 #if FMT_SAFE_DURATION_CAST
32
33 // For conversion between std::chrono::durations without undefined
34 // behaviour or erroneous results.
35 // This is a stripped down version of duration_cast, for inclusion in fmt.
36 // See https://github.com/pauldreik/safe_duration_cast
37 //
38 // Copyright Paul Dreik 2019
39 namespace safe_duration_cast {
40
41 // DEPRECATED!
42 template <typename To, typename From,
43 FMT_ENABLE_IF(!std::is_same<From, To>::value &&
44 std::numeric_limits<From>::is_signed ==
45 std::numeric_limits<To>::is_signed)>
46 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
47 -> To {
48 ec = 0;
49 using F = std::numeric_limits<From>;
50 using T = std::numeric_limits<To>;
51 static_assert(F::is_integer, "From must be integral");
52 static_assert(T::is_integer, "To must be integral");
53
54 // A and B are both signed, or both unsigned.
55 if FMT_CONSTEXPR20 (F::digits <= T::digits) {
56 // From fits in To without any problem.
57 } else {
58 // From does not always fit in To, resort to a dynamic check.
59 if (from < (T::min)() || from > (T::max)()) {
60 // outside range.
61 ec = 1;
62 return {};
63 }
64 }
65 return static_cast<To>(from);
66 }
67
68 /// Converts From to To, without loss. If the dynamic value of from
69 /// can't be converted to To without loss, ec is set.
70 template <typename To, typename From,
71 FMT_ENABLE_IF(!std::is_same<From, To>::value &&
72 std::numeric_limits<From>::is_signed !=
73 std::numeric_limits<To>::is_signed)>
74 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
75 -> To {
76 ec = 0;
77 using F = std::numeric_limits<From>;
78 using T = std::numeric_limits<To>;
79 static_assert(F::is_integer, "From must be integral");
80 static_assert(T::is_integer, "To must be integral");
81
82 if FMT_CONSTEXPR20 (F::is_signed && !T::is_signed) {
83 // From may be negative, not allowed!
84 if (fmt::detail::is_negative(from)) {
85 ec = 1;
86 return {};
87 }
88 // From is positive. Can it always fit in To?
89 if (F::digits > T::digits &&
90 from > static_cast<From>(detail::max_value<To>())) {
91 ec = 1;
92 return {};
93 }
94 }
95
96 if (!F::is_signed && T::is_signed && F::digits >= T::digits &&
97 from > static_cast<From>(detail::max_value<To>())) {
98 ec = 1;
99 return {};
100 }
101 return static_cast<To>(from); // Lossless conversion.
102 }
103
104 template <typename To, typename From,
105 FMT_ENABLE_IF(std::is_same<From, To>::value)>
106 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
107 -> To {
108 ec = 0;
109 return from;
110 } // function
111
112 // clang-format off
113 /**
114 * converts From to To if possible, otherwise ec is set.
115 *
116 * input | output
117 * ---------------------------------|---------------
118 * NaN | NaN
119 * Inf | Inf
120 * normal, fits in output | converted (possibly lossy)
121 * normal, does not fit in output | ec is set
122 * subnormal | best effort
123 * -Inf | -Inf
124 */
125 // clang-format on
126 template <typename To, typename From,
127 FMT_ENABLE_IF(!std::is_same<From, To>::value)>
128 FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
129 ec = 0;
130 using T = std::numeric_limits<To>;
131 static_assert(std::is_floating_point<From>::value, "From must be floating");
132 static_assert(std::is_floating_point<To>::value, "To must be floating");
133
134 // catch the only happy case
135 if (std::isfinite(from)) {
136 if (from >= T::lowest() && from <= (T::max)()) {
137 return static_cast<To>(from);
138 }
139 // not within range.
140 ec = 1;
141 return {};
142 }
143
144 // nan and inf will be preserved
145 return static_cast<To>(from);
146 } // function
147
148 template <typename To, typename From,
149 FMT_ENABLE_IF(std::is_same<From, To>::value)>
150 FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
151 ec = 0;
152 static_assert(std::is_floating_point<From>::value, "From must be floating");
153 return from;
154 }
155
156 /// Safe duration_cast between floating point durations
157 template <typename To, typename FromRep, typename FromPeriod,
158 FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
159 FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
160 auto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
161 int& ec) -> To {
162 using From = std::chrono::duration<FromRep, FromPeriod>;
163 ec = 0;
164
165 // the basic idea is that we need to convert from count() in the from type
166 // to count() in the To type, by multiplying it with this:
167 struct Factor
168 : std::ratio_divide<typename From::period, typename To::period> {};
169
170 static_assert(Factor::num > 0, "num must be positive");
171 static_assert(Factor::den > 0, "den must be positive");
172
173 // the conversion is like this: multiply from.count() with Factor::num
174 // /Factor::den and convert it to To::rep, all this without
175 // overflow/underflow. let's start by finding a suitable type that can hold
176 // both To, From and Factor::num
177 using IntermediateRep =
178 typename std::common_type<typename From::rep, typename To::rep,
179 decltype(Factor::num)>::type;
180
181 // force conversion of From::rep -> IntermediateRep to be safe,
182 // even if it will never happen be narrowing in this context.
183 IntermediateRep count =
184 safe_float_conversion<IntermediateRep>(from.count(), ec);
185 if (ec) {
186 return {};
187 }
188
189 // multiply with Factor::num without overflow or underflow
190 if FMT_CONSTEXPR20 (Factor::num != 1) {
191 constexpr auto max1 = detail::max_value<IntermediateRep>() /
192 static_cast<IntermediateRep>(Factor::num);
193 if (count > max1) {
194 ec = 1;
195 return {};
196 }
197 constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
198 static_cast<IntermediateRep>(Factor::num);
199 if (count < min1) {
200 ec = 1;
201 return {};
202 }
203 count *= static_cast<IntermediateRep>(Factor::num);
204 }
205
206 // this can't go wrong, right? den>0 is checked earlier.
207 if FMT_CONSTEXPR20 (Factor::den != 1) {
208 using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
209 count /= static_cast<common_t>(Factor::den);
210 }
211
212 // convert to the to type, safely
213 using ToRep = typename To::rep;
214
215 const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
216 if (ec) {
217 return {};
218 }
219 return To{tocount};
220 }
221 } // namespace safe_duration_cast
222 #endif
223
224 namespace detail {
225
226 // Check if std::chrono::utc_time is available.
227 #ifdef FMT_USE_UTC_TIME
228 // Use the provided definition.
229 #elif defined(__cpp_lib_chrono)
230 # define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)
231 #else
232 # define FMT_USE_UTC_TIME 0
233 #endif
234 #if FMT_USE_UTC_TIME
235 using utc_clock = std::chrono::utc_clock;
236 #else
237 struct utc_clock {
238 template <typename T> void to_sys(T);
239 };
240 #endif
241
242 // Check if std::chrono::local_time is available.
243 #ifdef FMT_USE_LOCAL_TIME
244 // Use the provided definition.
245 #elif defined(__cpp_lib_chrono)
246 # define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L)
247 #else
248 # define FMT_USE_LOCAL_TIME 0
249 #endif
250 #if FMT_USE_LOCAL_TIME
251 using local_t = std::chrono::local_t;
252 #else
253 struct local_t {};
254 #endif
255
256 } // namespace detail
257
258 template <typename Duration>
259 using sys_time = std::chrono::time_point<std::chrono::system_clock, Duration>;
260
261 template <typename Duration>
262 using utc_time = std::chrono::time_point<detail::utc_clock, Duration>;
263
264 template <class Duration>
265 using local_time = std::chrono::time_point<detail::local_t, Duration>;
266
267 namespace detail {
268
269 // Prevents expansion of a preceding token as a function-style macro.
270 // Usage: f FMT_NOMACRO()
271 #define FMT_NOMACRO
272
273 template <typename T = void> struct null {};
274 inline auto gmtime_r(...) -> null<> { return null<>(); }
275 inline auto gmtime_s(...) -> null<> { return null<>(); }
276
277 // It is defined here and not in ostream.h because the latter has expensive
278 // includes.
279 template <typename StreamBuf> class formatbuf : public StreamBuf {
280 private:
281 using char_type = typename StreamBuf::char_type;
282 using streamsize = decltype(std::declval<StreamBuf>().sputn(nullptr, 0));
283 using int_type = typename StreamBuf::int_type;
284 using traits_type = typename StreamBuf::traits_type;
285
286 buffer<char_type>& buffer_;
287
288 public:
289 explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}
290
291 protected:
292 // The put area is always empty. This makes the implementation simpler and has
293 // the advantage that the streambuf and the buffer are always in sync and
294 // sputc never writes into uninitialized memory. A disadvantage is that each
295 // call to sputc always results in a (virtual) call to overflow. There is no
296 // disadvantage here for sputn since this always results in a call to xsputn.
297
298 auto overflow(int_type ch) -> int_type override {
299 if (!traits_type::eq_int_type(ch, traits_type::eof()))
300 buffer_.push_back(static_cast<char_type>(ch));
301 return ch;
302 }
303
304 auto xsputn(const char_type* s, streamsize count) -> streamsize override {
305 buffer_.append(s, s + count);
306 return count;
307 }
308 };
309
310 inline auto get_classic_locale() -> const std::locale& {
311 static const auto& locale = std::locale::classic();
312 return locale;
313 }
314
315 template <typename CodeUnit> struct codecvt_result {
316 static constexpr size_t max_size = 32;
317 CodeUnit buf[max_size];
318 CodeUnit* end;
319 };
320
321 template <typename CodeUnit>
322 void write_codecvt(codecvt_result<CodeUnit>& out, string_view in,
323 const std::locale& loc) {
324 FMT_PRAGMA_CLANG(diagnostic push)
325 FMT_PRAGMA_CLANG(diagnostic ignored "-Wdeprecated")
326 auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
327 FMT_PRAGMA_CLANG(diagnostic pop)
328 auto mb = std::mbstate_t();
329 const char* from_next = nullptr;
330 auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf),
331 std::end(out.buf), out.end);
332 if (result != std::codecvt_base::ok)
333 FMT_THROW(format_error("failed to format time"));
334 }
335
336 template <typename OutputIt>
337 auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)
338 -> OutputIt {
339 if (detail::use_utf8 && loc != get_classic_locale()) {
340 // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
341 // gcc-4.
342 #if FMT_MSC_VERSION != 0 || \
343 (defined(__GLIBCXX__) && \
344 (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0))
345 // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
346 // and newer.
347 using code_unit = wchar_t;
348 #else
349 using code_unit = char32_t;
350 #endif
351
352 using unit_t = codecvt_result<code_unit>;
353 unit_t unit;
354 write_codecvt(unit, in, loc);
355 // In UTF-8 is used one to four one-byte code units.
356 auto u =
357 to_utf8<code_unit, basic_memory_buffer<char, unit_t::max_size * 4>>();
358 if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)}))
359 FMT_THROW(format_error("failed to format time"));
360 return copy<char>(u.c_str(), u.c_str() + u.size(), out);
361 }
362 return copy<char>(in.data(), in.data() + in.size(), out);
363 }
364
365 template <typename Char, typename OutputIt,
366 FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
367 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
368 -> OutputIt {
369 codecvt_result<Char> unit;
370 write_codecvt(unit, sv, loc);
371 return copy<Char>(unit.buf, unit.end, out);
372 }
373
374 template <typename Char, typename OutputIt,
375 FMT_ENABLE_IF(std::is_same<Char, char>::value)>
376 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
377 -> OutputIt {
378 return write_encoded_tm_str(out, sv, loc);
379 }
380
381 template <typename Char>
382 inline void do_write(buffer<Char>& buf, const std::tm& time,
383 const std::locale& loc, char format, char modifier) {
384 auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
385 auto&& os = std::basic_ostream<Char>(&format_buf);
386 os.imbue(loc);
387 const auto& facet = std::use_facet<std::time_put<Char>>(loc);
388 auto end = facet.put(os, os, Char(' '), &time, format, modifier);
389 if (end.failed()) FMT_THROW(format_error("failed to format time"));
390 }
391
392 template <typename Char, typename OutputIt,
393 FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
394 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
395 char format, char modifier = 0) -> OutputIt {
396 auto&& buf = get_buffer<Char>(out);
397 do_write<Char>(buf, time, loc, format, modifier);
398 return get_iterator(buf, out);
399 }
400
401 template <typename Char, typename OutputIt,
402 FMT_ENABLE_IF(std::is_same<Char, char>::value)>
403 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
404 char format, char modifier = 0) -> OutputIt {
405 auto&& buf = basic_memory_buffer<Char>();
406 do_write<char>(buf, time, loc, format, modifier);
407 return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);
408 }
409
410 template <typename T, typename U>
411 using is_similar_arithmetic_type =
412 bool_constant<(std::is_integral<T>::value && std::is_integral<U>::value) ||
413 (std::is_floating_point<T>::value &&
414 std::is_floating_point<U>::value)>;
415
416 FMT_NORETURN inline void throw_duration_error() {
417 FMT_THROW(format_error("cannot format duration"));
418 }
419
420 // Cast one integral duration to another with an overflow check.
421 template <typename To, typename FromRep, typename FromPeriod,
422 FMT_ENABLE_IF(std::is_integral<FromRep>::value&&
423 std::is_integral<typename To::rep>::value)>
424 auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
425 #if !FMT_SAFE_DURATION_CAST
426 return std::chrono::duration_cast<To>(from);
427 #else
428 // The conversion factor: to.count() == factor * from.count().
429 using factor = std::ratio_divide<FromPeriod, typename To::period>;
430
431 using common_rep = typename std::common_type<FromRep, typename To::rep,
432 decltype(factor::num)>::type;
433 common_rep count = from.count(); // This conversion is lossless.
434
435 // Multiply from.count() by factor and check for overflow.
436 if FMT_CONSTEXPR20 (factor::num != 1) {
437 if (count > max_value<common_rep>() / factor::num) throw_duration_error();
438 const auto min = (std::numeric_limits<common_rep>::min)() / factor::num;
439 if (!std::is_unsigned<common_rep>::value && count < min)
440 throw_duration_error();
441 count *= factor::num;
442 }
443 if FMT_CONSTEXPR20 (factor::den != 1) count /= factor::den;
444 int ec = 0;
445 auto to =
446 To(safe_duration_cast::lossless_integral_conversion<typename To::rep>(
447 count, ec));
448 if (ec) throw_duration_error();
449 return to;
450 #endif
451 }
452
453 template <typename To, typename FromRep, typename FromPeriod,
454 FMT_ENABLE_IF(std::is_floating_point<FromRep>::value&&
455 std::is_floating_point<typename To::rep>::value)>
456 auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
457 #if FMT_SAFE_DURATION_CAST
458 // Preserve infinity and NaN.
459 if (!isfinite(from.count())) return static_cast<To>(from.count());
460 // Throwing version of safe_duration_cast is only available for
461 // integer to integer or float to float casts.
462 int ec;
463 To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
464 if (ec) throw_duration_error();
465 return to;
466 #else
467 // Standard duration cast, may overflow.
468 return std::chrono::duration_cast<To>(from);
469 #endif
470 }
471
472 template <typename To, typename FromRep, typename FromPeriod,
473 FMT_ENABLE_IF(
474 !is_similar_arithmetic_type<FromRep, typename To::rep>::value)>
475 auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
476 // Mixed integer <-> float cast is not supported by safe duration_cast.
477 return std::chrono::duration_cast<To>(from);
478 }
479
480 template <typename Duration>
481 auto to_time_t(sys_time<Duration> time_point) -> std::time_t {
482 // Cannot use std::chrono::system_clock::to_time_t since this would first
483 // require a cast to std::chrono::system_clock::time_point, which could
484 // overflow.
485 return detail::duration_cast<std::chrono::duration<std::time_t>>(
486 time_point.time_since_epoch())
487 .count();
488 }
489
490 } // namespace detail
491
492 FMT_BEGIN_EXPORT
493
494 /**
495 * Converts given time since epoch as `std::time_t` value into calendar time,
496 * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this
497 * function is thread-safe on most platforms.
498 */
499 inline auto gmtime(std::time_t time) -> std::tm {
500 struct dispatcher {
501 std::time_t time_;
502 std::tm tm_;
503
504 inline dispatcher(std::time_t t) : time_(t) {}
505
506 inline auto run() -> bool {
507 using namespace fmt::detail;
508 return handle(gmtime_r(&time_, &tm_));
509 }
510
511 inline auto handle(std::tm* tm) -> bool { return tm != nullptr; }
512
513 inline auto handle(detail::null<>) -> bool {
514 using namespace fmt::detail;
515 return fallback(gmtime_s(&tm_, &time_));
516 }
517
518 inline auto fallback(int res) -> bool { return res == 0; }
519
520 #if !FMT_MSC_VERSION
521 inline auto fallback(detail::null<>) -> bool {
522 std::tm* tm = std::gmtime(&time_);
523 if (tm) tm_ = *tm;
524 return tm != nullptr;
525 }
526 #endif
527 };
528 auto gt = dispatcher(time);
529 // Too big time values may be unsupported.
530 if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
531 return gt.tm_;
532 }
533
534 template <typename Duration>
535 inline auto gmtime(sys_time<Duration> time_point) -> std::tm {
536 return gmtime(detail::to_time_t(time_point));
537 }
538
539 namespace detail {
540
541 // Writes two-digit numbers a, b and c separated by sep to buf.
542 // The method by Pavel Novikov based on
543 // https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.
544 inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
545 unsigned c, char sep) {
546 ullong digits = a | (b << 24) | (static_cast<ullong>(c) << 48);
547 // Convert each value to BCD.
548 // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.
549 // The difference is
550 // y - x = a * 6
551 // a can be found from x:
552 // a = floor(x / 10)
553 // then
554 // y = x + a * 6 = x + floor(x / 10) * 6
555 // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).
556 digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;
557 // Put low nibbles to high bytes and high nibbles to low bytes.
558 digits = ((digits & 0x00f00000f00000f0) >> 4) |
559 ((digits & 0x000f00000f00000f) << 8);
560 auto usep = static_cast<ullong>(sep);
561 // Add ASCII '0' to each digit byte and insert separators.
562 digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
563
564 constexpr size_t len = 8;
565 if (is_big_endian()) {
566 char tmp[len];
567 std::memcpy(tmp, &digits, len);
568 std::reverse_copy(tmp, tmp + len, buf);
569 } else {
570 std::memcpy(buf, &digits, len);
571 }
572 }
573
574 template <typename Period>
575 FMT_CONSTEXPR inline auto get_units() -> const char* {
576 if (std::is_same<Period, std::atto>::value) return "as";
577 if (std::is_same<Period, std::femto>::value) return "fs";
578 if (std::is_same<Period, std::pico>::value) return "ps";
579 if (std::is_same<Period, std::nano>::value) return "ns";
580 if (std::is_same<Period, std::micro>::value)
581 return detail::use_utf8 ? "µs" : "us";
582 if (std::is_same<Period, std::milli>::value) return "ms";
583 if (std::is_same<Period, std::centi>::value) return "cs";
584 if (std::is_same<Period, std::deci>::value) return "ds";
585 if (std::is_same<Period, std::ratio<1>>::value) return "s";
586 if (std::is_same<Period, std::deca>::value) return "das";
587 if (std::is_same<Period, std::hecto>::value) return "hs";
588 if (std::is_same<Period, std::kilo>::value) return "ks";
589 if (std::is_same<Period, std::mega>::value) return "Ms";
590 if (std::is_same<Period, std::giga>::value) return "Gs";
591 if (std::is_same<Period, std::tera>::value) return "Ts";
592 if (std::is_same<Period, std::peta>::value) return "Ps";
593 if (std::is_same<Period, std::exa>::value) return "Es";
594 if (std::is_same<Period, std::ratio<60>>::value) return "min";
595 if (std::is_same<Period, std::ratio<3600>>::value) return "h";
596 if (std::is_same<Period, std::ratio<86400>>::value) return "d";
597 return nullptr;
598 }
599
600 enum class numeric_system {
601 standard,
602 // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
603 alternative
604 };
605
606 // Glibc extensions for formatting numeric values.
607 enum class pad_type {
608 // Pad a numeric result string with zeros (the default).
609 zero,
610 // Do not pad a numeric result string.
611 none,
612 // Pad a numeric result string with spaces.
613 space,
614 };
615
616 template <typename OutputIt>
617 auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt {
618 if (pad == pad_type::none) return out;
619 return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0');
620 }
621
622 template <typename OutputIt>
623 auto write_padding(OutputIt out, pad_type pad) -> OutputIt {
624 if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0';
625 return out;
626 }
627
628 // Parses a put_time-like format string and invokes handler actions.
629 template <typename Char, typename Handler>
630 FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end,
631 Handler&& handler) -> const Char* {
632 if (begin == end || *begin == '}') return begin;
633 if (*begin != '%') FMT_THROW(format_error("invalid format"));
634 auto ptr = begin;
635 while (ptr != end) {
636 pad_type pad = pad_type::zero;
637 auto c = *ptr;
638 if (c == '}') break;
639 if (c != '%') {
640 ++ptr;
641 continue;
642 }
643 if (begin != ptr) handler.on_text(begin, ptr);
644 ++ptr; // consume '%'
645 if (ptr == end) FMT_THROW(format_error("invalid format"));
646 c = *ptr;
647 switch (c) {
648 case '_':
649 pad = pad_type::space;
650 ++ptr;
651 break;
652 case '-':
653 pad = pad_type::none;
654 ++ptr;
655 break;
656 }
657 if (ptr == end) FMT_THROW(format_error("invalid format"));
658 c = *ptr++;
659 switch (c) {
660 case '%': handler.on_text(ptr - 1, ptr); break;
661 case 'n': {
662 const Char newline[] = {'\n'};
663 handler.on_text(newline, newline + 1);
664 break;
665 }
666 case 't': {
667 const Char tab[] = {'\t'};
668 handler.on_text(tab, tab + 1);
669 break;
670 }
671 // Year:
672 case 'Y': handler.on_year(numeric_system::standard, pad); break;
673 case 'y': handler.on_short_year(numeric_system::standard); break;
674 case 'C': handler.on_century(numeric_system::standard); break;
675 case 'G': handler.on_iso_week_based_year(); break;
676 case 'g': handler.on_iso_week_based_short_year(); break;
677 // Day of the week:
678 case 'a': handler.on_abbr_weekday(); break;
679 case 'A': handler.on_full_weekday(); break;
680 case 'w': handler.on_dec0_weekday(numeric_system::standard); break;
681 case 'u': handler.on_dec1_weekday(numeric_system::standard); break;
682 // Month:
683 case 'b':
684 case 'h': handler.on_abbr_month(); break;
685 case 'B': handler.on_full_month(); break;
686 case 'm': handler.on_dec_month(numeric_system::standard, pad); break;
687 // Day of the year/month:
688 case 'U':
689 handler.on_dec0_week_of_year(numeric_system::standard, pad);
690 break;
691 case 'W':
692 handler.on_dec1_week_of_year(numeric_system::standard, pad);
693 break;
694 case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break;
695 case 'j': handler.on_day_of_year(pad); break;
696 case 'd': handler.on_day_of_month(numeric_system::standard, pad); break;
697 case 'e':
698 handler.on_day_of_month(numeric_system::standard, pad_type::space);
699 break;
700 // Hour, minute, second:
701 case 'H': handler.on_24_hour(numeric_system::standard, pad); break;
702 case 'I': handler.on_12_hour(numeric_system::standard, pad); break;
703 case 'M': handler.on_minute(numeric_system::standard, pad); break;
704 case 'S': handler.on_second(numeric_system::standard, pad); break;
705 // Other:
706 case 'c': handler.on_datetime(numeric_system::standard); break;
707 case 'x': handler.on_loc_date(numeric_system::standard); break;
708 case 'X': handler.on_loc_time(numeric_system::standard); break;
709 case 'D': handler.on_us_date(); break;
710 case 'F': handler.on_iso_date(); break;
711 case 'r': handler.on_12_hour_time(); break;
712 case 'R': handler.on_24_hour_time(); break;
713 case 'T': handler.on_iso_time(); break;
714 case 'p': handler.on_am_pm(); break;
715 case 'Q': handler.on_duration_value(); break;
716 case 'q': handler.on_duration_unit(); break;
717 case 'z': handler.on_utc_offset(numeric_system::standard); break;
718 case 'Z': handler.on_tz_name(); break;
719 // Alternative representation:
720 case 'E': {
721 if (ptr == end) FMT_THROW(format_error("invalid format"));
722 c = *ptr++;
723 switch (c) {
724 case 'Y': handler.on_year(numeric_system::alternative, pad); break;
725 case 'y': handler.on_offset_year(); break;
726 case 'C': handler.on_century(numeric_system::alternative); break;
727 case 'c': handler.on_datetime(numeric_system::alternative); break;
728 case 'x': handler.on_loc_date(numeric_system::alternative); break;
729 case 'X': handler.on_loc_time(numeric_system::alternative); break;
730 case 'z': handler.on_utc_offset(numeric_system::alternative); break;
731 default: FMT_THROW(format_error("invalid format"));
732 }
733 break;
734 }
735 case 'O':
736 if (ptr == end) FMT_THROW(format_error("invalid format"));
737 c = *ptr++;
738 switch (c) {
739 case 'y': handler.on_short_year(numeric_system::alternative); break;
740 case 'm': handler.on_dec_month(numeric_system::alternative, pad); break;
741 case 'U':
742 handler.on_dec0_week_of_year(numeric_system::alternative, pad);
743 break;
744 case 'W':
745 handler.on_dec1_week_of_year(numeric_system::alternative, pad);
746 break;
747 case 'V':
748 handler.on_iso_week_of_year(numeric_system::alternative, pad);
749 break;
750 case 'd':
751 handler.on_day_of_month(numeric_system::alternative, pad);
752 break;
753 case 'e':
754 handler.on_day_of_month(numeric_system::alternative, pad_type::space);
755 break;
756 case 'w': handler.on_dec0_weekday(numeric_system::alternative); break;
757 case 'u': handler.on_dec1_weekday(numeric_system::alternative); break;
758 case 'H': handler.on_24_hour(numeric_system::alternative, pad); break;
759 case 'I': handler.on_12_hour(numeric_system::alternative, pad); break;
760 case 'M': handler.on_minute(numeric_system::alternative, pad); break;
761 case 'S': handler.on_second(numeric_system::alternative, pad); break;
762 case 'z': handler.on_utc_offset(numeric_system::alternative); break;
763 default: FMT_THROW(format_error("invalid format"));
764 }
765 break;
766 default: FMT_THROW(format_error("invalid format"));
767 }
768 begin = ptr;
769 }
770 if (begin != ptr) handler.on_text(begin, ptr);
771 return ptr;
772 }
773
774 template <typename Derived> struct null_chrono_spec_handler {
775 FMT_CONSTEXPR void unsupported() {
776 static_cast<Derived*>(this)->unsupported();
777 }
778 FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); }
779 FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }
780 FMT_CONSTEXPR void on_offset_year() { unsupported(); }
781 FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }
782 FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }
783 FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }
784 FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }
785 FMT_CONSTEXPR void on_full_weekday() { unsupported(); }
786 FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }
787 FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }
788 FMT_CONSTEXPR void on_abbr_month() { unsupported(); }
789 FMT_CONSTEXPR void on_full_month() { unsupported(); }
790 FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); }
791 FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {
792 unsupported();
793 }
794 FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {
795 unsupported();
796 }
797 FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {
798 unsupported();
799 }
800 FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); }
801 FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {
802 unsupported();
803 }
804 FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }
805 FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }
806 FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }
807 FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }
808 FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }
809 FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }
810 FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }
811 FMT_CONSTEXPR void on_us_date() { unsupported(); }
812 FMT_CONSTEXPR void on_iso_date() { unsupported(); }
813 FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }
814 FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }
815 FMT_CONSTEXPR void on_iso_time() { unsupported(); }
816 FMT_CONSTEXPR void on_am_pm() { unsupported(); }
817 FMT_CONSTEXPR void on_duration_value() { unsupported(); }
818 FMT_CONSTEXPR void on_duration_unit() { unsupported(); }
819 FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); }
820 FMT_CONSTEXPR void on_tz_name() { unsupported(); }
821 };
822
823 class tm_format_checker : public null_chrono_spec_handler<tm_format_checker> {
824 private:
825 bool has_timezone_ = false;
826
827 public:
828 constexpr explicit tm_format_checker(bool has_timezone)
829 : has_timezone_(has_timezone) {}
830
831 FMT_NORETURN inline void unsupported() {
832 FMT_THROW(format_error("no format"));
833 }
834
835 template <typename Char>
836 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
837 FMT_CONSTEXPR void on_year(numeric_system, pad_type) {}
838 FMT_CONSTEXPR void on_short_year(numeric_system) {}
839 FMT_CONSTEXPR void on_offset_year() {}
840 FMT_CONSTEXPR void on_century(numeric_system) {}
841 FMT_CONSTEXPR void on_iso_week_based_year() {}
842 FMT_CONSTEXPR void on_iso_week_based_short_year() {}
843 FMT_CONSTEXPR void on_abbr_weekday() {}
844 FMT_CONSTEXPR void on_full_weekday() {}
845 FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}
846 FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}
847 FMT_CONSTEXPR void on_abbr_month() {}
848 FMT_CONSTEXPR void on_full_month() {}
849 FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {}
850 FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {}
851 FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {}
852 FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {}
853 FMT_CONSTEXPR void on_day_of_year(pad_type) {}
854 FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {}
855 FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
856 FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
857 FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
858 FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
859 FMT_CONSTEXPR void on_datetime(numeric_system) {}
860 FMT_CONSTEXPR void on_loc_date(numeric_system) {}
861 FMT_CONSTEXPR void on_loc_time(numeric_system) {}
862 FMT_CONSTEXPR void on_us_date() {}
863 FMT_CONSTEXPR void on_iso_date() {}
864 FMT_CONSTEXPR void on_12_hour_time() {}
865 FMT_CONSTEXPR void on_24_hour_time() {}
866 FMT_CONSTEXPR void on_iso_time() {}
867 FMT_CONSTEXPR void on_am_pm() {}
868 FMT_CONSTEXPR void on_utc_offset(numeric_system) {
869 if (!has_timezone_) FMT_THROW(format_error("no timezone"));
870 }
871 FMT_CONSTEXPR void on_tz_name() {
872 if (!has_timezone_) FMT_THROW(format_error("no timezone"));
873 }
874 };
875
876 inline auto tm_wday_full_name(int wday) -> const char* {
877 static constexpr const char* full_name_list[] = {
878 "Sunday", "Monday", "Tuesday", "Wednesday",
879 "Thursday", "Friday", "Saturday"};
880 return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?";
881 }
882 inline auto tm_wday_short_name(int wday) -> const char* {
883 static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed",
884 "Thu", "Fri", "Sat"};
885 return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???";
886 }
887
888 inline auto tm_mon_full_name(int mon) -> const char* {
889 static constexpr const char* full_name_list[] = {
890 "January", "February", "March", "April", "May", "June",
891 "July", "August", "September", "October", "November", "December"};
892 return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?";
893 }
894 inline auto tm_mon_short_name(int mon) -> const char* {
895 static constexpr const char* short_name_list[] = {
896 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
897 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
898 };
899 return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???";
900 }
901
902 template <typename T, typename = void>
903 struct has_tm_gmtoff : std::false_type {};
904 template <typename T>
905 struct has_tm_gmtoff<T, void_t<decltype(T::tm_gmtoff)>> : std::true_type {};
906
907 template <typename T, typename = void> struct has_tm_zone : std::false_type {};
908 template <typename T>
909 struct has_tm_zone<T, void_t<decltype(T::tm_zone)>> : std::true_type {};
910
911 template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>
912 auto set_tm_zone(T& time, char* tz) -> bool {
913 time.tm_zone = tz;
914 return true;
915 }
916 template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>
917 auto set_tm_zone(T&, char*) -> bool {
918 return false;
919 }
920
921 inline auto utc() -> char* {
922 static char tz[] = "UTC";
923 return tz;
924 }
925
926 // Converts value to Int and checks that it's in the range [0, upper).
927 template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
928 inline auto to_nonnegative_int(T value, Int upper) -> Int {
929 if (!std::is_unsigned<Int>::value &&
930 (value < 0 || to_unsigned(value) > to_unsigned(upper))) {
931 FMT_THROW(format_error("chrono value is out of range"));
932 }
933 return static_cast<Int>(value);
934 }
935 template <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>
936 inline auto to_nonnegative_int(T value, Int upper) -> Int {
937 auto int_value = static_cast<Int>(value);
938 if (int_value < 0 || value > static_cast<T>(upper))
939 FMT_THROW(format_error("invalid value"));
940 return int_value;
941 }
942
943 constexpr auto pow10(std::uint32_t n) -> long long {
944 return n == 0 ? 1 : 10 * pow10(n - 1);
945 }
946
947 // Counts the number of fractional digits in the range [0, 18] according to the
948 // C++20 spec. If more than 18 fractional digits are required then returns 6 for
949 // microseconds precision.
950 template <long long Num, long long Den, int N = 0,
951 bool Enabled = (N < 19) && (Num <= max_value<long long>() / 10)>
952 struct count_fractional_digits {
953 static constexpr int value =
954 Num % Den == 0 ? N : count_fractional_digits<Num * 10, Den, N + 1>::value;
955 };
956
957 // Base case that doesn't instantiate any more templates
958 // in order to avoid overflow.
959 template <long long Num, long long Den, int N>
960 struct count_fractional_digits<Num, Den, N, false> {
961 static constexpr int value = (Num % Den == 0) ? N : 6;
962 };
963
964 // Format subseconds which are given as an integer type with an appropriate
965 // number of digits.
966 template <typename Char, typename OutputIt, typename Duration>
967 void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {
968 constexpr auto num_fractional_digits =
969 count_fractional_digits<Duration::period::num,
970 Duration::period::den>::value;
971
972 using subsecond_precision = std::chrono::duration<
973 typename std::common_type<typename Duration::rep,
974 std::chrono::seconds::rep>::type,
975 std::ratio<1, pow10(num_fractional_digits)>>;
976
977 const auto fractional = d - detail::duration_cast<std::chrono::seconds>(d);
978 const auto subseconds =
979 std::chrono::treat_as_floating_point<
980 typename subsecond_precision::rep>::value
981 ? fractional.count()
982 : detail::duration_cast<subsecond_precision>(fractional).count();
983 auto n = static_cast<uint32_or_64_or_128_t<long long>>(subseconds);
984 const int num_digits = count_digits(n);
985
986 int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits);
987 if (precision < 0) {
988 FMT_ASSERT(!std::is_floating_point<typename Duration::rep>::value, "");
989 if (std::ratio_less<typename subsecond_precision::period,
990 std::chrono::seconds::period>::value) {
991 *out++ = '.';
992 out = detail::fill_n(out, leading_zeroes, '0');
993 out = format_decimal<Char>(out, n, num_digits);
994 }
995 } else if (precision > 0) {
996 *out++ = '.';
997 leading_zeroes = min_of(leading_zeroes, precision);
998 int remaining = precision - leading_zeroes;
999 out = detail::fill_n(out, leading_zeroes, '0');
1000 if (remaining < num_digits) {
1001 int num_truncated_digits = num_digits - remaining;
1002 n /= to_unsigned(pow10(to_unsigned(num_truncated_digits)));
1003 if (n != 0) out = format_decimal<Char>(out, n, remaining);
1004 return;
1005 }
1006 if (n != 0) {
1007 out = format_decimal<Char>(out, n, num_digits);
1008 remaining -= num_digits;
1009 }
1010 out = detail::fill_n(out, remaining, '0');
1011 }
1012 }
1013
1014 // Format subseconds which are given as a floating point type with an
1015 // appropriate number of digits. We cannot pass the Duration here, as we
1016 // explicitly need to pass the Rep value in the duration_formatter.
1017 template <typename Duration>
1018 void write_floating_seconds(memory_buffer& buf, Duration duration,
1019 int num_fractional_digits = -1) {
1020 using rep = typename Duration::rep;
1021 FMT_ASSERT(std::is_floating_point<rep>::value, "");
1022
1023 auto val = duration.count();
1024
1025 if (num_fractional_digits < 0) {
1026 // For `std::round` with fallback to `round`:
1027 // On some toolchains `std::round` is not available (e.g. GCC 6).
1028 using namespace std;
1029 num_fractional_digits =
1030 count_fractional_digits<Duration::period::num,
1031 Duration::period::den>::value;
1032 if (num_fractional_digits < 6 && static_cast<rep>(round(val)) != val)
1033 num_fractional_digits = 6;
1034 }
1035
1036 fmt::format_to(std::back_inserter(buf), FMT_STRING("{:.{}f}"),
1037 std::fmod(val * static_cast<rep>(Duration::period::num) /
1038 static_cast<rep>(Duration::period::den),
1039 static_cast<rep>(60)),
1040 num_fractional_digits);
1041 }
1042
1043 template <typename OutputIt, typename Char,
1044 typename Duration = std::chrono::seconds>
1045 class tm_writer {
1046 private:
1047 static constexpr int days_per_week = 7;
1048
1049 const std::locale& loc_;
1050 bool is_classic_;
1051 OutputIt out_;
1052 const Duration* subsecs_;
1053 const std::tm& tm_;
1054
1055 auto tm_sec() const noexcept -> int {
1056 FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, "");
1057 return tm_.tm_sec;
1058 }
1059 auto tm_min() const noexcept -> int {
1060 FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, "");
1061 return tm_.tm_min;
1062 }
1063 auto tm_hour() const noexcept -> int {
1064 FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, "");
1065 return tm_.tm_hour;
1066 }
1067 auto tm_mday() const noexcept -> int {
1068 FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, "");
1069 return tm_.tm_mday;
1070 }
1071 auto tm_mon() const noexcept -> int {
1072 FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, "");
1073 return tm_.tm_mon;
1074 }
1075 auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }
1076 auto tm_wday() const noexcept -> int {
1077 FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, "");
1078 return tm_.tm_wday;
1079 }
1080 auto tm_yday() const noexcept -> int {
1081 FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, "");
1082 return tm_.tm_yday;
1083 }
1084
1085 auto tm_hour12() const noexcept -> int {
1086 auto h = tm_hour();
1087 auto z = h < 12 ? h : h - 12;
1088 return z == 0 ? 12 : z;
1089 }
1090
1091 // POSIX and the C Standard are unclear or inconsistent about what %C and %y
1092 // do if the year is negative or exceeds 9999. Use the convention that %C
1093 // concatenated with %y yields the same output as %Y, and that %Y contains at
1094 // least 4 characters, with more only if necessary.
1095 auto split_year_lower(long long year) const noexcept -> int {
1096 auto l = year % 100;
1097 if (l < 0) l = -l; // l in [0, 99]
1098 return static_cast<int>(l);
1099 }
1100
1101 // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date.
1102 auto iso_year_weeks(long long curr_year) const noexcept -> int {
1103 auto prev_year = curr_year - 1;
1104 auto curr_p =
1105 (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %
1106 days_per_week;
1107 auto prev_p =
1108 (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %
1109 days_per_week;
1110 return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);
1111 }
1112 auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {
1113 return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /
1114 days_per_week;
1115 }
1116 auto tm_iso_week_year() const noexcept -> long long {
1117 auto year = tm_year();
1118 auto w = iso_week_num(tm_yday(), tm_wday());
1119 if (w < 1) return year - 1;
1120 if (w > iso_year_weeks(year)) return year + 1;
1121 return year;
1122 }
1123 auto tm_iso_week_of_year() const noexcept -> int {
1124 auto year = tm_year();
1125 auto w = iso_week_num(tm_yday(), tm_wday());
1126 if (w < 1) return iso_year_weeks(year - 1);
1127 if (w > iso_year_weeks(year)) return 1;
1128 return w;
1129 }
1130
1131 void write1(int value) {
1132 *out_++ = static_cast<char>('0' + to_unsigned(value) % 10);
1133 }
1134 void write2(int value) {
1135 const char* d = digits2(to_unsigned(value) % 100);
1136 *out_++ = *d++;
1137 *out_++ = *d;
1138 }
1139 void write2(int value, pad_type pad) {
1140 unsigned int v = to_unsigned(value) % 100;
1141 if (v >= 10) {
1142 const char* d = digits2(v);
1143 *out_++ = *d++;
1144 *out_++ = *d;
1145 } else {
1146 out_ = detail::write_padding(out_, pad);
1147 *out_++ = static_cast<char>('0' + v);
1148 }
1149 }
1150
1151 void write_year_extended(long long year, pad_type pad) {
1152 // At least 4 characters.
1153 int width = 4;
1154 bool negative = year < 0;
1155 if (negative) {
1156 year = 0 - year;
1157 --width;
1158 }
1159 uint32_or_64_or_128_t<long long> n = to_unsigned(year);
1160 const int num_digits = count_digits(n);
1161 if (negative && pad == pad_type::zero) *out_++ = '-';
1162 if (width > num_digits)
1163 out_ = detail::write_padding(out_, pad, width - num_digits);
1164 if (negative && pad != pad_type::zero) *out_++ = '-';
1165 out_ = format_decimal<Char>(out_, n, num_digits);
1166 }
1167 void write_year(long long year, pad_type pad) {
1168 write_year_extended(year, pad);
1169 }
1170
1171 void write_utc_offset(long long offset, numeric_system ns) {
1172 if (offset < 0) {
1173 *out_++ = '-';
1174 offset = -offset;
1175 } else {
1176 *out_++ = '+';
1177 }
1178 offset /= 60;
1179 write2(static_cast<int>(offset / 60));
1180 if (ns != numeric_system::standard) *out_++ = ':';
1181 write2(static_cast<int>(offset % 60));
1182 }
1183
1184 template <typename T, FMT_ENABLE_IF(has_tm_gmtoff<T>::value)>
1185 void format_utc_offset(const T& tm, numeric_system ns) {
1186 write_utc_offset(tm.tm_gmtoff, ns);
1187 }
1188 template <typename T, FMT_ENABLE_IF(!has_tm_gmtoff<T>::value)>
1189 void format_utc_offset(const T&, numeric_system ns) {
1190 write_utc_offset(0, ns);
1191 }
1192
1193 template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>
1194 void format_tz_name(const T& tm) {
1195 if (!tm.tm_zone) FMT_THROW(format_error("no timezone"));
1196 out_ = write_tm_str<Char>(out_, tm.tm_zone, loc_);
1197 }
1198 template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>
1199 void format_tz_name(const T&) {
1200 out_ = std::copy_n(utc(), 3, out_);
1201 }
1202
1203 void format_localized(char format, char modifier = 0) {
1204 out_ = write<Char>(out_, tm_, loc_, format, modifier);
1205 }
1206
1207 public:
1208 tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm,
1209 const Duration* subsecs = nullptr)
1210 : loc_(loc),
1211 is_classic_(loc_ == get_classic_locale()),
1212 out_(out),
1213 subsecs_(subsecs),
1214 tm_(tm) {}
1215
1216 auto out() const -> OutputIt { return out_; }
1217
1218 FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
1219 out_ = copy<Char>(begin, end, out_);
1220 }
1221
1222 void on_abbr_weekday() {
1223 if (is_classic_)
1224 out_ = write(out_, tm_wday_short_name(tm_wday()));
1225 else
1226 format_localized('a');
1227 }
1228 void on_full_weekday() {
1229 if (is_classic_)
1230 out_ = write(out_, tm_wday_full_name(tm_wday()));
1231 else
1232 format_localized('A');
1233 }
1234 void on_dec0_weekday(numeric_system ns) {
1235 if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());
1236 format_localized('w', 'O');
1237 }
1238 void on_dec1_weekday(numeric_system ns) {
1239 if (is_classic_ || ns == numeric_system::standard) {
1240 auto wday = tm_wday();
1241 write1(wday == 0 ? days_per_week : wday);
1242 } else {
1243 format_localized('u', 'O');
1244 }
1245 }
1246
1247 void on_abbr_month() {
1248 if (is_classic_)
1249 out_ = write(out_, tm_mon_short_name(tm_mon()));
1250 else
1251 format_localized('b');
1252 }
1253 void on_full_month() {
1254 if (is_classic_)
1255 out_ = write(out_, tm_mon_full_name(tm_mon()));
1256 else
1257 format_localized('B');
1258 }
1259
1260 void on_datetime(numeric_system ns) {
1261 if (is_classic_) {
1262 on_abbr_weekday();
1263 *out_++ = ' ';
1264 on_abbr_month();
1265 *out_++ = ' ';
1266 on_day_of_month(numeric_system::standard, pad_type::space);
1267 *out_++ = ' ';
1268 on_iso_time();
1269 *out_++ = ' ';
1270 on_year(numeric_system::standard, pad_type::space);
1271 } else {
1272 format_localized('c', ns == numeric_system::standard ? '\0' : 'E');
1273 }
1274 }
1275 void on_loc_date(numeric_system ns) {
1276 if (is_classic_)
1277 on_us_date();
1278 else
1279 format_localized('x', ns == numeric_system::standard ? '\0' : 'E');
1280 }
1281 void on_loc_time(numeric_system ns) {
1282 if (is_classic_)
1283 on_iso_time();
1284 else
1285 format_localized('X', ns == numeric_system::standard ? '\0' : 'E');
1286 }
1287 void on_us_date() {
1288 char buf[8];
1289 write_digit2_separated(buf, to_unsigned(tm_mon() + 1),
1290 to_unsigned(tm_mday()),
1291 to_unsigned(split_year_lower(tm_year())), '/');
1292 out_ = copy<Char>(std::begin(buf), std::end(buf), out_);
1293 }
1294 void on_iso_date() {
1295 auto year = tm_year();
1296 char buf[10];
1297 size_t offset = 0;
1298 if (year >= 0 && year < 10000) {
1299 write2digits(buf, static_cast<size_t>(year / 100));
1300 } else {
1301 offset = 4;
1302 write_year_extended(year, pad_type::zero);
1303 year = 0;
1304 }
1305 write_digit2_separated(buf + 2, static_cast<unsigned>(year % 100),
1306 to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),
1307 '-');
1308 out_ = copy<Char>(std::begin(buf) + offset, std::end(buf), out_);
1309 }
1310
1311 void on_utc_offset(numeric_system ns) { format_utc_offset(tm_, ns); }
1312 void on_tz_name() { format_tz_name(tm_); }
1313
1314 void on_year(numeric_system ns, pad_type pad) {
1315 if (is_classic_ || ns == numeric_system::standard)
1316 return write_year(tm_year(), pad);
1317 format_localized('Y', 'E');
1318 }
1319 void on_short_year(numeric_system ns) {
1320 if (is_classic_ || ns == numeric_system::standard)
1321 return write2(split_year_lower(tm_year()));
1322 format_localized('y', 'O');
1323 }
1324 void on_offset_year() {
1325 if (is_classic_) return write2(split_year_lower(tm_year()));
1326 format_localized('y', 'E');
1327 }
1328
1329 void on_century(numeric_system ns) {
1330 if (is_classic_ || ns == numeric_system::standard) {
1331 auto year = tm_year();
1332 auto upper = year / 100;
1333 if (year >= -99 && year < 0) {
1334 // Zero upper on negative year.
1335 *out_++ = '-';
1336 *out_++ = '0';
1337 } else if (upper >= 0 && upper < 100) {
1338 write2(static_cast<int>(upper));
1339 } else {
1340 out_ = write<Char>(out_, upper);
1341 }
1342 } else {
1343 format_localized('C', 'E');
1344 }
1345 }
1346
1347 void on_dec_month(numeric_system ns, pad_type pad) {
1348 if (is_classic_ || ns == numeric_system::standard)
1349 return write2(tm_mon() + 1, pad);
1350 format_localized('m', 'O');
1351 }
1352
1353 void on_dec0_week_of_year(numeric_system ns, pad_type pad) {
1354 if (is_classic_ || ns == numeric_system::standard)
1355 return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week,
1356 pad);
1357 format_localized('U', 'O');
1358 }
1359 void on_dec1_week_of_year(numeric_system ns, pad_type pad) {
1360 if (is_classic_ || ns == numeric_system::standard) {
1361 auto wday = tm_wday();
1362 write2((tm_yday() + days_per_week -
1363 (wday == 0 ? (days_per_week - 1) : (wday - 1))) /
1364 days_per_week,
1365 pad);
1366 } else {
1367 format_localized('W', 'O');
1368 }
1369 }
1370 void on_iso_week_of_year(numeric_system ns, pad_type pad) {
1371 if (is_classic_ || ns == numeric_system::standard)
1372 return write2(tm_iso_week_of_year(), pad);
1373 format_localized('V', 'O');
1374 }
1375
1376 void on_iso_week_based_year() {
1377 write_year(tm_iso_week_year(), pad_type::zero);
1378 }
1379 void on_iso_week_based_short_year() {
1380 write2(split_year_lower(tm_iso_week_year()));
1381 }
1382
1383 void on_day_of_year(pad_type pad) {
1384 auto yday = tm_yday() + 1;
1385 auto digit1 = yday / 100;
1386 if (digit1 != 0)
1387 write1(digit1);
1388 else
1389 out_ = detail::write_padding(out_, pad);
1390 write2(yday % 100, pad);
1391 }
1392
1393 void on_day_of_month(numeric_system ns, pad_type pad) {
1394 if (is_classic_ || ns == numeric_system::standard)
1395 return write2(tm_mday(), pad);
1396 format_localized('d', 'O');
1397 }
1398
1399 void on_24_hour(numeric_system ns, pad_type pad) {
1400 if (is_classic_ || ns == numeric_system::standard)
1401 return write2(tm_hour(), pad);
1402 format_localized('H', 'O');
1403 }
1404 void on_12_hour(numeric_system ns, pad_type pad) {
1405 if (is_classic_ || ns == numeric_system::standard)
1406 return write2(tm_hour12(), pad);
1407 format_localized('I', 'O');
1408 }
1409 void on_minute(numeric_system ns, pad_type pad) {
1410 if (is_classic_ || ns == numeric_system::standard)
1411 return write2(tm_min(), pad);
1412 format_localized('M', 'O');
1413 }
1414
1415 void on_second(numeric_system ns, pad_type pad) {
1416 if (is_classic_ || ns == numeric_system::standard) {
1417 write2(tm_sec(), pad);
1418 if (subsecs_) {
1419 if (std::is_floating_point<typename Duration::rep>::value) {
1420 auto buf = memory_buffer();
1421 write_floating_seconds(buf, *subsecs_);
1422 if (buf.size() > 1) {
1423 // Remove the leading "0", write something like ".123".
1424 out_ = copy<Char>(buf.begin() + 1, buf.end(), out_);
1425 }
1426 } else {
1427 write_fractional_seconds<Char>(out_, *subsecs_);
1428 }
1429 }
1430 } else {
1431 // Currently no formatting of subseconds when a locale is set.
1432 format_localized('S', 'O');
1433 }
1434 }
1435
1436 void on_12_hour_time() {
1437 if (is_classic_) {
1438 char buf[8];
1439 write_digit2_separated(buf, to_unsigned(tm_hour12()),
1440 to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');
1441 out_ = copy<Char>(std::begin(buf), std::end(buf), out_);
1442 *out_++ = ' ';
1443 on_am_pm();
1444 } else {
1445 format_localized('r');
1446 }
1447 }
1448 void on_24_hour_time() {
1449 write2(tm_hour());
1450 *out_++ = ':';
1451 write2(tm_min());
1452 }
1453 void on_iso_time() {
1454 on_24_hour_time();
1455 *out_++ = ':';
1456 on_second(numeric_system::standard, pad_type::zero);
1457 }
1458
1459 void on_am_pm() {
1460 if (is_classic_) {
1461 *out_++ = tm_hour() < 12 ? 'A' : 'P';
1462 *out_++ = 'M';
1463 } else {
1464 format_localized('p');
1465 }
1466 }
1467
1468 // These apply to chrono durations but not tm.
1469 void on_duration_value() {}
1470 void on_duration_unit() {}
1471 };
1472
1473 struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
1474 bool has_precision_integral = false;
1475
1476 FMT_NORETURN inline void unsupported() { FMT_THROW(format_error("no date")); }
1477
1478 template <typename Char>
1479 FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
1480 FMT_CONSTEXPR void on_day_of_year(pad_type) {}
1481 FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
1482 FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
1483 FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
1484 FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
1485 FMT_CONSTEXPR void on_12_hour_time() {}
1486 FMT_CONSTEXPR void on_24_hour_time() {}
1487 FMT_CONSTEXPR void on_iso_time() {}
1488 FMT_CONSTEXPR void on_am_pm() {}
1489 FMT_CONSTEXPR void on_duration_value() const {
1490 if (has_precision_integral)
1491 FMT_THROW(format_error("precision not allowed for this argument type"));
1492 }
1493 FMT_CONSTEXPR void on_duration_unit() {}
1494 };
1495
1496 template <typename T,
1497 FMT_ENABLE_IF(std::is_integral<T>::value&& has_isfinite<T>::value)>
1498 inline auto isfinite(T) -> bool {
1499 return true;
1500 }
1501
1502 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
1503 inline auto mod(T x, int y) -> T {
1504 return x % static_cast<T>(y);
1505 }
1506 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1507 inline auto mod(T x, int y) -> T {
1508 return std::fmod(x, static_cast<T>(y));
1509 }
1510
1511 // If T is an integral type, maps T to its unsigned counterpart, otherwise
1512 // leaves it unchanged (unlike std::make_unsigned).
1513 template <typename T, bool INTEGRAL = std::is_integral<T>::value>
1514 struct make_unsigned_or_unchanged {
1515 using type = T;
1516 };
1517
1518 template <typename T> struct make_unsigned_or_unchanged<T, true> {
1519 using type = typename std::make_unsigned<T>::type;
1520 };
1521
1522 template <typename Rep, typename Period,
1523 FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1524 inline auto get_milliseconds(std::chrono::duration<Rep, Period> d)
1525 -> std::chrono::duration<Rep, std::milli> {
1526 // This may overflow and/or the result may not fit in the target type.
1527 #if FMT_SAFE_DURATION_CAST
1528 using common_seconds_type =
1529 typename std::common_type<decltype(d), std::chrono::seconds>::type;
1530 auto d_as_common = detail::duration_cast<common_seconds_type>(d);
1531 auto d_as_whole_seconds =
1532 detail::duration_cast<std::chrono::seconds>(d_as_common);
1533 // This conversion should be nonproblematic.
1534 auto diff = d_as_common - d_as_whole_seconds;
1535 auto ms = detail::duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
1536 return ms;
1537 #else
1538 auto s = detail::duration_cast<std::chrono::seconds>(d);
1539 return detail::duration_cast<std::chrono::milliseconds>(d - s);
1540 #endif
1541 }
1542
1543 template <typename Char, typename Rep, typename OutputIt,
1544 FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1545 auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt {
1546 return write<Char>(out, val);
1547 }
1548
1549 template <typename Char, typename Rep, typename OutputIt,
1550 FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
1551 auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt {
1552 auto specs = format_specs();
1553 specs.precision = precision;
1554 specs.set_type(precision >= 0 ? presentation_type::fixed
1555 : presentation_type::general);
1556 return write<Char>(out, val, specs);
1557 }
1558
1559 template <typename Char, typename OutputIt>
1560 auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt {
1561 return copy<Char>(unit.begin(), unit.end(), out);
1562 }
1563
1564 template <typename OutputIt>
1565 auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt {
1566 // This works when wchar_t is UTF-32 because units only contain characters
1567 // that have the same representation in UTF-16 and UTF-32.
1568 utf8_to_utf16 u(unit);
1569 return copy<wchar_t>(u.c_str(), u.c_str() + u.size(), out);
1570 }
1571
1572 template <typename Char, typename Period, typename OutputIt>
1573 auto format_duration_unit(OutputIt out) -> OutputIt {
1574 if (const char* unit = get_units<Period>())
1575 return copy_unit(string_view(unit), out, Char());
1576 *out++ = '[';
1577 out = write<Char>(out, Period::num);
1578 if FMT_CONSTEXPR20 (Period::den != 1) {
1579 *out++ = '/';
1580 out = write<Char>(out, Period::den);
1581 }
1582 *out++ = ']';
1583 *out++ = 's';
1584 return out;
1585 }
1586
1587 class get_locale {
1588 private:
1589 union {
1590 std::locale locale_;
1591 };
1592 bool has_locale_ = false;
1593
1594 public:
1595 inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) {
1596 if (!localized) return;
1597 ignore_unused(loc);
1598 ::new (&locale_) std::locale(
1599 #if FMT_USE_LOCALE
1600 loc.template get<std::locale>()
1601 #endif
1602 );
1603 }
1604 inline ~get_locale() {
1605 if (has_locale_) locale_.~locale();
1606 }
1607 inline operator const std::locale&() const {
1608 return has_locale_ ? locale_ : get_classic_locale();
1609 }
1610 };
1611
1612 template <typename Char, typename Rep, typename Period>
1613 struct duration_formatter {
1614 using iterator = basic_appender<Char>;
1615 iterator out;
1616 // rep is unsigned to avoid overflow.
1617 using rep =
1618 conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
1619 unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
1620 rep val;
1621 int precision;
1622 locale_ref locale;
1623 bool localized = false;
1624 using seconds = std::chrono::duration<rep>;
1625 seconds s;
1626 using milliseconds = std::chrono::duration<rep, std::milli>;
1627 bool negative;
1628
1629 using tm_writer_type = tm_writer<iterator, Char>;
1630
1631 duration_formatter(iterator o, std::chrono::duration<Rep, Period> d,
1632 locale_ref loc)
1633 : out(o), val(static_cast<rep>(d.count())), locale(loc), negative(false) {
1634 if (d.count() < 0) {
1635 val = 0 - val;
1636 negative = true;
1637 }
1638
1639 // this may overflow and/or the result may not fit in the
1640 // target type.
1641 // might need checked conversion (rep!=Rep)
1642 s = detail::duration_cast<seconds>(std::chrono::duration<rep, Period>(val));
1643 }
1644
1645 // returns true if nan or inf, writes to out.
1646 auto handle_nan_inf() -> bool {
1647 if (isfinite(val)) return false;
1648 if (isnan(val)) {
1649 write_nan();
1650 return true;
1651 }
1652 // must be +-inf
1653 if (val > 0)
1654 std::copy_n("inf", 3, out);
1655 else
1656 std::copy_n("-inf", 4, out);
1657 return true;
1658 }
1659
1660 auto days() const -> Rep { return static_cast<Rep>(s.count() / 86400); }
1661 auto hour() const -> Rep {
1662 return static_cast<Rep>(mod((s.count() / 3600), 24));
1663 }
1664
1665 auto hour12() const -> Rep {
1666 Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
1667 return hour <= 0 ? 12 : hour;
1668 }
1669
1670 auto minute() const -> Rep {
1671 return static_cast<Rep>(mod((s.count() / 60), 60));
1672 }
1673 auto second() const -> Rep { return static_cast<Rep>(mod(s.count(), 60)); }
1674
1675 auto time() const -> std::tm {
1676 auto time = std::tm();
1677 time.tm_hour = to_nonnegative_int(hour(), 24);
1678 time.tm_min = to_nonnegative_int(minute(), 60);
1679 time.tm_sec = to_nonnegative_int(second(), 60);
1680 return time;
1681 }
1682
1683 void write_sign() {
1684 if (!negative) return;
1685 *out++ = '-';
1686 negative = false;
1687 }
1688
1689 void write(Rep value, int width, pad_type pad = pad_type::zero) {
1690 write_sign();
1691 if (isnan(value)) return write_nan();
1692 uint32_or_64_or_128_t<int> n =
1693 to_unsigned(to_nonnegative_int(value, max_value<int>()));
1694 int num_digits = detail::count_digits(n);
1695 if (width > num_digits) {
1696 out = detail::write_padding(out, pad, width - num_digits);
1697 }
1698 out = format_decimal<Char>(out, n, num_digits);
1699 }
1700
1701 void write_nan() { std::copy_n("nan", 3, out); }
1702
1703 template <typename Callback, typename... Args>
1704 void format_tm(const tm& time, Callback cb, Args... args) {
1705 if (isnan(val)) return write_nan();
1706 get_locale loc(localized, locale);
1707 auto w = tm_writer_type(loc, out, time);
1708 (w.*cb)(args...);
1709 out = w.out();
1710 }
1711
1712 void on_text(const Char* begin, const Char* end) {
1713 copy<Char>(begin, end, out);
1714 }
1715
1716 // These are not implemented because durations don't have date information.
1717 void on_abbr_weekday() {}
1718 void on_full_weekday() {}
1719 void on_dec0_weekday(numeric_system) {}
1720 void on_dec1_weekday(numeric_system) {}
1721 void on_abbr_month() {}
1722 void on_full_month() {}
1723 void on_datetime(numeric_system) {}
1724 void on_loc_date(numeric_system) {}
1725 void on_loc_time(numeric_system) {}
1726 void on_us_date() {}
1727 void on_iso_date() {}
1728 void on_utc_offset(numeric_system) {}
1729 void on_tz_name() {}
1730 void on_year(numeric_system, pad_type) {}
1731 void on_short_year(numeric_system) {}
1732 void on_offset_year() {}
1733 void on_century(numeric_system) {}
1734 void on_iso_week_based_year() {}
1735 void on_iso_week_based_short_year() {}
1736 void on_dec_month(numeric_system, pad_type) {}
1737 void on_dec0_week_of_year(numeric_system, pad_type) {}
1738 void on_dec1_week_of_year(numeric_system, pad_type) {}
1739 void on_iso_week_of_year(numeric_system, pad_type) {}
1740 void on_day_of_month(numeric_system, pad_type) {}
1741
1742 void on_day_of_year(pad_type) {
1743 if (handle_nan_inf()) return;
1744 write(days(), 0);
1745 }
1746
1747 void on_24_hour(numeric_system ns, pad_type pad) {
1748 if (handle_nan_inf()) return;
1749
1750 if (ns == numeric_system::standard) return write(hour(), 2, pad);
1751 auto time = tm();
1752 time.tm_hour = to_nonnegative_int(hour(), 24);
1753 format_tm(time, &tm_writer_type::on_24_hour, ns, pad);
1754 }
1755
1756 void on_12_hour(numeric_system ns, pad_type pad) {
1757 if (handle_nan_inf()) return;
1758
1759 if (ns == numeric_system::standard) return write(hour12(), 2, pad);
1760 auto time = tm();
1761 time.tm_hour = to_nonnegative_int(hour12(), 12);
1762 format_tm(time, &tm_writer_type::on_12_hour, ns, pad);
1763 }
1764
1765 void on_minute(numeric_system ns, pad_type pad) {
1766 if (handle_nan_inf()) return;
1767
1768 if (ns == numeric_system::standard) return write(minute(), 2, pad);
1769 auto time = tm();
1770 time.tm_min = to_nonnegative_int(minute(), 60);
1771 format_tm(time, &tm_writer_type::on_minute, ns, pad);
1772 }
1773
1774 void on_second(numeric_system ns, pad_type pad) {
1775 if (handle_nan_inf()) return;
1776
1777 if (ns == numeric_system::standard) {
1778 if (std::is_floating_point<rep>::value) {
1779 auto buf = memory_buffer();
1780 write_floating_seconds(buf, std::chrono::duration<rep, Period>(val),
1781 precision);
1782 if (negative) *out++ = '-';
1783 if (buf.size() < 2 || buf[1] == '.')
1784 out = detail::write_padding(out, pad);
1785 out = copy<Char>(buf.begin(), buf.end(), out);
1786 } else {
1787 write(second(), 2, pad);
1788 write_fractional_seconds<Char>(
1789 out, std::chrono::duration<rep, Period>(val), precision);
1790 }
1791 return;
1792 }
1793 auto time = tm();
1794 time.tm_sec = to_nonnegative_int(second(), 60);
1795 format_tm(time, &tm_writer_type::on_second, ns, pad);
1796 }
1797
1798 void on_12_hour_time() {
1799 if (handle_nan_inf()) return;
1800 format_tm(time(), &tm_writer_type::on_12_hour_time);
1801 }
1802
1803 void on_24_hour_time() {
1804 if (handle_nan_inf()) {
1805 *out++ = ':';
1806 handle_nan_inf();
1807 return;
1808 }
1809
1810 write(hour(), 2);
1811 *out++ = ':';
1812 write(minute(), 2);
1813 }
1814
1815 void on_iso_time() {
1816 on_24_hour_time();
1817 *out++ = ':';
1818 if (handle_nan_inf()) return;
1819 on_second(numeric_system::standard, pad_type::zero);
1820 }
1821
1822 void on_am_pm() {
1823 if (handle_nan_inf()) return;
1824 format_tm(time(), &tm_writer_type::on_am_pm);
1825 }
1826
1827 void on_duration_value() {
1828 if (handle_nan_inf()) return;
1829 write_sign();
1830 out = format_duration_value<Char>(out, val, precision);
1831 }
1832
1833 void on_duration_unit() { out = format_duration_unit<Char, Period>(out); }
1834 };
1835
1836 } // namespace detail
1837
1838 #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
1839 using weekday = std::chrono::weekday;
1840 using day = std::chrono::day;
1841 using month = std::chrono::month;
1842 using year = std::chrono::year;
1843 using year_month_day = std::chrono::year_month_day;
1844 #else
1845 // A fallback version of weekday.
1846 class weekday {
1847 private:
1848 unsigned char value_;
1849
1850 public:
1851 weekday() = default;
1852 constexpr explicit weekday(unsigned wd) noexcept
1853 : value_(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
1854 constexpr auto c_encoding() const noexcept -> unsigned { return value_; }
1855 };
1856
1857 class day {
1858 private:
1859 unsigned char value_;
1860
1861 public:
1862 day() = default;
1863 constexpr explicit day(unsigned d) noexcept
1864 : value_(static_cast<unsigned char>(d)) {}
1865 constexpr explicit operator unsigned() const noexcept { return value_; }
1866 };
1867
1868 class month {
1869 private:
1870 unsigned char value_;
1871
1872 public:
1873 month() = default;
1874 constexpr explicit month(unsigned m) noexcept
1875 : value_(static_cast<unsigned char>(m)) {}
1876 constexpr explicit operator unsigned() const noexcept { return value_; }
1877 };
1878
1879 class year {
1880 private:
1881 int value_;
1882
1883 public:
1884 year() = default;
1885 constexpr explicit year(int y) noexcept : value_(y) {}
1886 constexpr explicit operator int() const noexcept { return value_; }
1887 };
1888
1889 class year_month_day {
1890 private:
1891 fmt::year year_;
1892 fmt::month month_;
1893 fmt::day day_;
1894
1895 public:
1896 year_month_day() = default;
1897 constexpr year_month_day(const year& y, const month& m, const day& d) noexcept
1898 : year_(y), month_(m), day_(d) {}
1899 constexpr auto year() const noexcept -> fmt::year { return year_; }
1900 constexpr auto month() const noexcept -> fmt::month { return month_; }
1901 constexpr auto day() const noexcept -> fmt::day { return day_; }
1902 };
1903 #endif // __cpp_lib_chrono >= 201907
1904
1905 template <typename Char>
1906 struct formatter<weekday, Char> : private formatter<std::tm, Char> {
1907 private:
1908 bool use_tm_formatter_ = false;
1909
1910 public:
1911 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
1912 auto it = ctx.begin(), end = ctx.end();
1913 if (it != end && *it == 'L') {
1914 ++it;
1915 this->set_localized();
1916 }
1917 use_tm_formatter_ = it != end && *it != '}';
1918 return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
1919 }
1920
1921 template <typename FormatContext>
1922 auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {
1923 auto time = std::tm();
1924 time.tm_wday = static_cast<int>(wd.c_encoding());
1925 if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
1926 detail::get_locale loc(this->localized(), ctx.locale());
1927 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
1928 w.on_abbr_weekday();
1929 return w.out();
1930 }
1931 };
1932
1933 template <typename Char>
1934 struct formatter<day, Char> : private formatter<std::tm, Char> {
1935 private:
1936 bool use_tm_formatter_ = false;
1937
1938 public:
1939 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
1940 auto it = ctx.begin(), end = ctx.end();
1941 use_tm_formatter_ = it != end && *it != '}';
1942 return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
1943 }
1944
1945 template <typename FormatContext>
1946 auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) {
1947 auto time = std::tm();
1948 time.tm_mday = static_cast<int>(static_cast<unsigned>(d));
1949 if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
1950 detail::get_locale loc(false, ctx.locale());
1951 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
1952 w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero);
1953 return w.out();
1954 }
1955 };
1956
1957 template <typename Char>
1958 struct formatter<month, Char> : private formatter<std::tm, Char> {
1959 private:
1960 bool use_tm_formatter_ = false;
1961
1962 public:
1963 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
1964 auto it = ctx.begin(), end = ctx.end();
1965 if (it != end && *it == 'L') {
1966 ++it;
1967 this->set_localized();
1968 }
1969 use_tm_formatter_ = it != end && *it != '}';
1970 return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
1971 }
1972
1973 template <typename FormatContext>
1974 auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) {
1975 auto time = std::tm();
1976 time.tm_mon = static_cast<int>(static_cast<unsigned>(m)) - 1;
1977 if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
1978 detail::get_locale loc(this->localized(), ctx.locale());
1979 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
1980 w.on_abbr_month();
1981 return w.out();
1982 }
1983 };
1984
1985 template <typename Char>
1986 struct formatter<year, Char> : private formatter<std::tm, Char> {
1987 private:
1988 bool use_tm_formatter_ = false;
1989
1990 public:
1991 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
1992 auto it = ctx.begin(), end = ctx.end();
1993 use_tm_formatter_ = it != end && *it != '}';
1994 return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
1995 }
1996
1997 template <typename FormatContext>
1998 auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) {
1999 auto time = std::tm();
2000 time.tm_year = static_cast<int>(y) - 1900;
2001 if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
2002 detail::get_locale loc(false, ctx.locale());
2003 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
2004 w.on_year(detail::numeric_system::standard, detail::pad_type::zero);
2005 return w.out();
2006 }
2007 };
2008
2009 template <typename Char>
2010 struct formatter<year_month_day, Char> : private formatter<std::tm, Char> {
2011 private:
2012 bool use_tm_formatter_ = false;
2013
2014 public:
2015 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
2016 auto it = ctx.begin(), end = ctx.end();
2017 use_tm_formatter_ = it != end && *it != '}';
2018 return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
2019 }
2020
2021 template <typename FormatContext>
2022 auto format(year_month_day val, FormatContext& ctx) const
2023 -> decltype(ctx.out()) {
2024 auto time = std::tm();
2025 time.tm_year = static_cast<int>(val.year()) - 1900;
2026 time.tm_mon = static_cast<int>(static_cast<unsigned>(val.month())) - 1;
2027 time.tm_mday = static_cast<int>(static_cast<unsigned>(val.day()));
2028 if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
2029 detail::get_locale loc(true, ctx.locale());
2030 auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
2031 w.on_iso_date();
2032 return w.out();
2033 }
2034 };
2035
2036 template <typename Rep, typename Period, typename Char>
2037 struct formatter<std::chrono::duration<Rep, Period>, Char> {
2038 private:
2039 format_specs specs_;
2040 detail::arg_ref<Char> width_ref_;
2041 detail::arg_ref<Char> precision_ref_;
2042 basic_string_view<Char> fmt_;
2043
2044 public:
2045 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
2046 auto it = ctx.begin(), end = ctx.end();
2047 if (it == end || *it == '}') return it;
2048
2049 it = detail::parse_align(it, end, specs_);
2050 if (it == end) return it;
2051
2052 Char c = *it;
2053 if ((c >= '0' && c <= '9') || c == '{') {
2054 it = detail::parse_width(it, end, specs_, width_ref_, ctx);
2055 if (it == end) return it;
2056 }
2057
2058 auto checker = detail::chrono_format_checker();
2059 if (*it == '.') {
2060 checker.has_precision_integral = !std::is_floating_point<Rep>::value;
2061 it = detail::parse_precision(it, end, specs_, precision_ref_, ctx);
2062 }
2063 if (it != end && *it == 'L') {
2064 specs_.set_localized();
2065 ++it;
2066 }
2067 end = detail::parse_chrono_format(it, end, checker);
2068 fmt_ = {it, detail::to_unsigned(end - it)};
2069 return end;
2070 }
2071
2072 template <typename FormatContext>
2073 auto format(std::chrono::duration<Rep, Period> d, FormatContext& ctx) const
2074 -> decltype(ctx.out()) {
2075 auto specs = specs_;
2076 auto precision = specs.precision;
2077 specs.precision = -1;
2078 auto begin = fmt_.begin(), end = fmt_.end();
2079 // As a possible future optimization, we could avoid extra copying if width
2080 // is not specified.
2081 auto buf = basic_memory_buffer<Char>();
2082 auto out = basic_appender<Char>(buf);
2083 detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
2084 ctx);
2085 detail::handle_dynamic_spec(specs.dynamic_precision(), precision,
2086 precision_ref_, ctx);
2087 if (begin == end || *begin == '}') {
2088 out = detail::format_duration_value<Char>(out, d.count(), precision);
2089 detail::format_duration_unit<Char, Period>(out);
2090 } else {
2091 auto f =
2092 detail::duration_formatter<Char, Rep, Period>(out, d, ctx.locale());
2093 f.precision = precision;
2094 f.localized = specs_.localized();
2095 detail::parse_chrono_format(begin, end, f);
2096 }
2097 return detail::write(
2098 ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
2099 }
2100 };
2101
2102 template <typename Char> struct formatter<std::tm, Char> {
2103 private:
2104 format_specs specs_;
2105 detail::arg_ref<Char> width_ref_;
2106 basic_string_view<Char> fmt_ =
2107 detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>();
2108
2109 protected:
2110 auto localized() const -> bool { return specs_.localized(); }
2111 FMT_CONSTEXPR void set_localized() { specs_.set_localized(); }
2112
2113 FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx, bool has_timezone)
2114 -> const Char* {
2115 auto it = ctx.begin(), end = ctx.end();
2116 if (it == end || *it == '}') return it;
2117
2118 it = detail::parse_align(it, end, specs_);
2119 if (it == end) return it;
2120
2121 Char c = *it;
2122 if ((c >= '0' && c <= '9') || c == '{') {
2123 it = detail::parse_width(it, end, specs_, width_ref_, ctx);
2124 if (it == end) return it;
2125 }
2126
2127 if (*it == 'L') {
2128 specs_.set_localized();
2129 ++it;
2130 }
2131
2132 end = detail::parse_chrono_format(it, end,
2133 detail::tm_format_checker(has_timezone));
2134 // Replace the default format string only if the new spec is not empty.
2135 if (end != it) fmt_ = {it, detail::to_unsigned(end - it)};
2136 return end;
2137 }
2138
2139 template <typename Duration, typename FormatContext>
2140 auto do_format(const std::tm& tm, FormatContext& ctx,
2141 const Duration* subsecs) const -> decltype(ctx.out()) {
2142 auto specs = specs_;
2143 auto buf = basic_memory_buffer<Char>();
2144 auto out = basic_appender<Char>(buf);
2145 detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
2146 ctx);
2147
2148 auto loc_ref = specs.localized() ? ctx.locale() : locale_ref();
2149 detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);
2150 auto w = detail::tm_writer<basic_appender<Char>, Char, Duration>(
2151 loc, out, tm, subsecs);
2152 detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w);
2153 return detail::write(
2154 ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
2155 }
2156
2157 public:
2158 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
2159 return do_parse(ctx, detail::has_tm_gmtoff<std::tm>::value);
2160 }
2161
2162 template <typename FormatContext>
2163 auto format(const std::tm& tm, FormatContext& ctx) const
2164 -> decltype(ctx.out()) {
2165 return do_format<std::chrono::seconds>(tm, ctx, nullptr);
2166 }
2167 };
2168
2169 // DEPRECATED! Reversed order of template parameters.
2170 template <typename Char, typename Duration>
2171 struct formatter<sys_time<Duration>, Char> : private formatter<std::tm, Char> {
2172 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
2173 return this->do_parse(ctx, true);
2174 }
2175
2176 template <typename FormatContext>
2177 auto format(sys_time<Duration> val, FormatContext& ctx) const
2178 -> decltype(ctx.out()) {
2179 std::tm tm = gmtime(val);
2180 using period = typename Duration::period;
2181 if FMT_CONSTEXPR20 (period::num == 1 && period::den == 1 &&
2182 !std::is_floating_point<
2183 typename Duration::rep>::value) {
2184 detail::set_tm_zone(tm, detail::utc());
2185 return formatter<std::tm, Char>::format(tm, ctx);
2186 }
2187 Duration epoch = val.time_since_epoch();
2188 Duration subsecs = detail::duration_cast<Duration>(
2189 epoch - detail::duration_cast<std::chrono::seconds>(epoch));
2190 if (subsecs.count() < 0) {
2191 auto second = detail::duration_cast<Duration>(std::chrono::seconds(1));
2192 if (tm.tm_sec != 0) {
2193 --tm.tm_sec;
2194 } else {
2195 tm = gmtime(val - second);
2196 detail::set_tm_zone(tm, detail::utc());
2197 }
2198 subsecs += second;
2199 }
2200 return formatter<std::tm, Char>::do_format(tm, ctx, &subsecs);
2201 }
2202 };
2203
2204 template <typename Duration, typename Char>
2205 struct formatter<utc_time<Duration>, Char>
2206 : formatter<sys_time<Duration>, Char> {
2207 template <typename FormatContext>
2208 auto format(utc_time<Duration> val, FormatContext& ctx) const
2209 -> decltype(ctx.out()) {
2210 return formatter<sys_time<Duration>, Char>::format(
2211 detail::utc_clock::to_sys(val), ctx);
2212 }
2213 };
2214
2215 template <typename Duration, typename Char>
2216 struct formatter<local_time<Duration>, Char>
2217 : private formatter<std::tm, Char> {
2218 FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
2219 return this->do_parse(ctx, false);
2220 }
2221
2222 template <typename FormatContext>
2223 auto format(local_time<Duration> val, FormatContext& ctx) const
2224 -> decltype(ctx.out()) {
2225 auto time_since_epoch = val.time_since_epoch();
2226 auto seconds_since_epoch =
2227 detail::duration_cast<std::chrono::seconds>(time_since_epoch);
2228 // Use gmtime to prevent time zone conversion since local_time has an
2229 // unspecified time zone.
2230 std::tm t = gmtime(seconds_since_epoch.count());
2231 using period = typename Duration::period;
2232 if (period::num == 1 && period::den == 1 &&
2233 !std::is_floating_point<typename Duration::rep>::value) {
2234 return formatter<std::tm, Char>::format(t, ctx);
2235 }
2236 auto subsecs =
2237 detail::duration_cast<Duration>(time_since_epoch - seconds_since_epoch);
2238 return formatter<std::tm, Char>::do_format(t, ctx, &subsecs);
2239 }
2240 };
2241
2242 FMT_END_EXPORT
2243 FMT_END_NAMESPACE
2244
2245 #endif // FMT_CHRONO_H_