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