Coverage Report

Created: 2026-05-14 06:08

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