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