Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-09 08:31:53

0001 // Formatting library for C++ - chrono support
0002 //
0003 // Copyright (c) 2012 - present, Victor Zverovich
0004 // All rights reserved.
0005 //
0006 // For the license information refer to format.h.
0007 
0008 #ifndef FMT_CHRONO_H_
0009 #define FMT_CHRONO_H_
0010 
0011 #include <algorithm>
0012 #include <chrono>
0013 #include <cmath>    // std::isfinite
0014 #include <cstring>  // std::memcpy
0015 #include <ctime>
0016 #include <iterator>
0017 #include <locale>
0018 #include <ostream>
0019 #include <type_traits>
0020 
0021 #include "ostream.h"  // formatbuf
0022 
0023 FMT_BEGIN_NAMESPACE
0024 
0025 // Check if std::chrono::local_t is available.
0026 #ifndef FMT_USE_LOCAL_TIME
0027 #  ifdef __cpp_lib_chrono
0028 #    define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L)
0029 #  else
0030 #    define FMT_USE_LOCAL_TIME 0
0031 #  endif
0032 #endif
0033 
0034 // Check if std::chrono::utc_timestamp is available.
0035 #ifndef FMT_USE_UTC_TIME
0036 #  ifdef __cpp_lib_chrono
0037 #    define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)
0038 #  else
0039 #    define FMT_USE_UTC_TIME 0
0040 #  endif
0041 #endif
0042 
0043 // Enable tzset.
0044 #ifndef FMT_USE_TZSET
0045 // UWP doesn't provide _tzset.
0046 #  if FMT_HAS_INCLUDE("winapifamily.h")
0047 #    include <winapifamily.h>
0048 #  endif
0049 #  if defined(_WIN32) && (!defined(WINAPI_FAMILY) || \
0050                           (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
0051 #    define FMT_USE_TZSET 1
0052 #  else
0053 #    define FMT_USE_TZSET 0
0054 #  endif
0055 #endif
0056 
0057 // Enable safe chrono durations, unless explicitly disabled.
0058 #ifndef FMT_SAFE_DURATION_CAST
0059 #  define FMT_SAFE_DURATION_CAST 1
0060 #endif
0061 #if FMT_SAFE_DURATION_CAST
0062 
0063 // For conversion between std::chrono::durations without undefined
0064 // behaviour or erroneous results.
0065 // This is a stripped down version of duration_cast, for inclusion in fmt.
0066 // See https://github.com/pauldreik/safe_duration_cast
0067 //
0068 // Copyright Paul Dreik 2019
0069 namespace safe_duration_cast {
0070 
0071 template <typename To, typename From,
0072           FMT_ENABLE_IF(!std::is_same<From, To>::value &&
0073                         std::numeric_limits<From>::is_signed ==
0074                             std::numeric_limits<To>::is_signed)>
0075 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
0076     -> To {
0077   ec = 0;
0078   using F = std::numeric_limits<From>;
0079   using T = std::numeric_limits<To>;
0080   static_assert(F::is_integer, "From must be integral");
0081   static_assert(T::is_integer, "To must be integral");
0082 
0083   // A and B are both signed, or both unsigned.
0084   if (detail::const_check(F::digits <= T::digits)) {
0085     // From fits in To without any problem.
0086   } else {
0087     // From does not always fit in To, resort to a dynamic check.
0088     if (from < (T::min)() || from > (T::max)()) {
0089       // outside range.
0090       ec = 1;
0091       return {};
0092     }
0093   }
0094   return static_cast<To>(from);
0095 }
0096 
0097 /**
0098  * converts From to To, without loss. If the dynamic value of from
0099  * can't be converted to To without loss, ec is set.
0100  */
0101 template <typename To, typename From,
0102           FMT_ENABLE_IF(!std::is_same<From, To>::value &&
0103                         std::numeric_limits<From>::is_signed !=
0104                             std::numeric_limits<To>::is_signed)>
0105 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
0106     -> To {
0107   ec = 0;
0108   using F = std::numeric_limits<From>;
0109   using T = std::numeric_limits<To>;
0110   static_assert(F::is_integer, "From must be integral");
0111   static_assert(T::is_integer, "To must be integral");
0112 
0113   if (detail::const_check(F::is_signed && !T::is_signed)) {
0114     // From may be negative, not allowed!
0115     if (fmt::detail::is_negative(from)) {
0116       ec = 1;
0117       return {};
0118     }
0119     // From is positive. Can it always fit in To?
0120     if (detail::const_check(F::digits > T::digits) &&
0121         from > static_cast<From>(detail::max_value<To>())) {
0122       ec = 1;
0123       return {};
0124     }
0125   }
0126 
0127   if (detail::const_check(!F::is_signed && T::is_signed &&
0128                           F::digits >= T::digits) &&
0129       from > static_cast<From>(detail::max_value<To>())) {
0130     ec = 1;
0131     return {};
0132   }
0133   return static_cast<To>(from);  // Lossless conversion.
0134 }
0135 
0136 template <typename To, typename From,
0137           FMT_ENABLE_IF(std::is_same<From, To>::value)>
0138 FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
0139     -> To {
0140   ec = 0;
0141   return from;
0142 }  // function
0143 
0144 // clang-format off
0145 /**
0146  * converts From to To if possible, otherwise ec is set.
0147  *
0148  * input                            |    output
0149  * ---------------------------------|---------------
0150  * NaN                              | NaN
0151  * Inf                              | Inf
0152  * normal, fits in output           | converted (possibly lossy)
0153  * normal, does not fit in output   | ec is set
0154  * subnormal                        | best effort
0155  * -Inf                             | -Inf
0156  */
0157 // clang-format on
0158 template <typename To, typename From,
0159           FMT_ENABLE_IF(!std::is_same<From, To>::value)>
0160 FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
0161   ec = 0;
0162   using T = std::numeric_limits<To>;
0163   static_assert(std::is_floating_point<From>::value, "From must be floating");
0164   static_assert(std::is_floating_point<To>::value, "To must be floating");
0165 
0166   // catch the only happy case
0167   if (std::isfinite(from)) {
0168     if (from >= T::lowest() && from <= (T::max)()) {
0169       return static_cast<To>(from);
0170     }
0171     // not within range.
0172     ec = 1;
0173     return {};
0174   }
0175 
0176   // nan and inf will be preserved
0177   return static_cast<To>(from);
0178 }  // function
0179 
0180 template <typename To, typename From,
0181           FMT_ENABLE_IF(std::is_same<From, To>::value)>
0182 FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
0183   ec = 0;
0184   static_assert(std::is_floating_point<From>::value, "From must be floating");
0185   return from;
0186 }
0187 
0188 /**
0189  * safe duration cast between integral durations
0190  */
0191 template <typename To, typename FromRep, typename FromPeriod,
0192           FMT_ENABLE_IF(std::is_integral<FromRep>::value),
0193           FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
0194 auto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
0195                         int& ec) -> To {
0196   using From = std::chrono::duration<FromRep, FromPeriod>;
0197   ec = 0;
0198   // the basic idea is that we need to convert from count() in the from type
0199   // to count() in the To type, by multiplying it with this:
0200   struct Factor
0201       : std::ratio_divide<typename From::period, typename To::period> {};
0202 
0203   static_assert(Factor::num > 0, "num must be positive");
0204   static_assert(Factor::den > 0, "den must be positive");
0205 
0206   // the conversion is like this: multiply from.count() with Factor::num
0207   // /Factor::den and convert it to To::rep, all this without
0208   // overflow/underflow. let's start by finding a suitable type that can hold
0209   // both To, From and Factor::num
0210   using IntermediateRep =
0211       typename std::common_type<typename From::rep, typename To::rep,
0212                                 decltype(Factor::num)>::type;
0213 
0214   // safe conversion to IntermediateRep
0215   IntermediateRep count =
0216       lossless_integral_conversion<IntermediateRep>(from.count(), ec);
0217   if (ec) return {};
0218   // multiply with Factor::num without overflow or underflow
0219   if (detail::const_check(Factor::num != 1)) {
0220     const auto max1 = detail::max_value<IntermediateRep>() / Factor::num;
0221     if (count > max1) {
0222       ec = 1;
0223       return {};
0224     }
0225     const auto min1 =
0226         (std::numeric_limits<IntermediateRep>::min)() / Factor::num;
0227     if (detail::const_check(!std::is_unsigned<IntermediateRep>::value) &&
0228         count < min1) {
0229       ec = 1;
0230       return {};
0231     }
0232     count *= Factor::num;
0233   }
0234 
0235   if (detail::const_check(Factor::den != 1)) count /= Factor::den;
0236   auto tocount = lossless_integral_conversion<typename To::rep>(count, ec);
0237   return ec ? To() : To(tocount);
0238 }
0239 
0240 /**
0241  * safe duration_cast between floating point durations
0242  */
0243 template <typename To, typename FromRep, typename FromPeriod,
0244           FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
0245           FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
0246 auto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
0247                         int& ec) -> To {
0248   using From = std::chrono::duration<FromRep, FromPeriod>;
0249   ec = 0;
0250   if (std::isnan(from.count())) {
0251     // nan in, gives nan out. easy.
0252     return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
0253   }
0254   // maybe we should also check if from is denormal, and decide what to do about
0255   // it.
0256 
0257   // +-inf should be preserved.
0258   if (std::isinf(from.count())) {
0259     return To{from.count()};
0260   }
0261 
0262   // the basic idea is that we need to convert from count() in the from type
0263   // to count() in the To type, by multiplying it with this:
0264   struct Factor
0265       : std::ratio_divide<typename From::period, typename To::period> {};
0266 
0267   static_assert(Factor::num > 0, "num must be positive");
0268   static_assert(Factor::den > 0, "den must be positive");
0269 
0270   // the conversion is like this: multiply from.count() with Factor::num
0271   // /Factor::den and convert it to To::rep, all this without
0272   // overflow/underflow. let's start by finding a suitable type that can hold
0273   // both To, From and Factor::num
0274   using IntermediateRep =
0275       typename std::common_type<typename From::rep, typename To::rep,
0276                                 decltype(Factor::num)>::type;
0277 
0278   // force conversion of From::rep -> IntermediateRep to be safe,
0279   // even if it will never happen be narrowing in this context.
0280   IntermediateRep count =
0281       safe_float_conversion<IntermediateRep>(from.count(), ec);
0282   if (ec) {
0283     return {};
0284   }
0285 
0286   // multiply with Factor::num without overflow or underflow
0287   if (detail::const_check(Factor::num != 1)) {
0288     constexpr auto max1 = detail::max_value<IntermediateRep>() /
0289                           static_cast<IntermediateRep>(Factor::num);
0290     if (count > max1) {
0291       ec = 1;
0292       return {};
0293     }
0294     constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
0295                           static_cast<IntermediateRep>(Factor::num);
0296     if (count < min1) {
0297       ec = 1;
0298       return {};
0299     }
0300     count *= static_cast<IntermediateRep>(Factor::num);
0301   }
0302 
0303   // this can't go wrong, right? den>0 is checked earlier.
0304   if (detail::const_check(Factor::den != 1)) {
0305     using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
0306     count /= static_cast<common_t>(Factor::den);
0307   }
0308 
0309   // convert to the to type, safely
0310   using ToRep = typename To::rep;
0311 
0312   const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
0313   if (ec) {
0314     return {};
0315   }
0316   return To{tocount};
0317 }
0318 }  // namespace safe_duration_cast
0319 #endif
0320 
0321 // Prevents expansion of a preceding token as a function-style macro.
0322 // Usage: f FMT_NOMACRO()
0323 #define FMT_NOMACRO
0324 
0325 namespace detail {
0326 template <typename T = void> struct null {};
0327 inline auto localtime_r FMT_NOMACRO(...) -> null<> { return null<>(); }
0328 inline auto localtime_s(...) -> null<> { return null<>(); }
0329 inline auto gmtime_r(...) -> null<> { return null<>(); }
0330 inline auto gmtime_s(...) -> null<> { return null<>(); }
0331 
0332 inline auto get_classic_locale() -> const std::locale& {
0333   static const auto& locale = std::locale::classic();
0334   return locale;
0335 }
0336 
0337 template <typename CodeUnit> struct codecvt_result {
0338   static constexpr const size_t max_size = 32;
0339   CodeUnit buf[max_size];
0340   CodeUnit* end;
0341 };
0342 
0343 template <typename CodeUnit>
0344 void write_codecvt(codecvt_result<CodeUnit>& out, string_view in_buf,
0345                    const std::locale& loc) {
0346 #if FMT_CLANG_VERSION
0347 #  pragma clang diagnostic push
0348 #  pragma clang diagnostic ignored "-Wdeprecated"
0349   auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
0350 #  pragma clang diagnostic pop
0351 #else
0352   auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
0353 #endif
0354   auto mb = std::mbstate_t();
0355   const char* from_next = nullptr;
0356   auto result = f.in(mb, in_buf.begin(), in_buf.end(), from_next,
0357                      std::begin(out.buf), std::end(out.buf), out.end);
0358   if (result != std::codecvt_base::ok)
0359     FMT_THROW(format_error("failed to format time"));
0360 }
0361 
0362 template <typename OutputIt>
0363 auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)
0364     -> OutputIt {
0365   if (detail::is_utf8() && loc != get_classic_locale()) {
0366     // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
0367     // gcc-4.
0368 #if FMT_MSC_VERSION != 0 || \
0369     (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI))
0370     // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
0371     // and newer.
0372     using code_unit = wchar_t;
0373 #else
0374     using code_unit = char32_t;
0375 #endif
0376 
0377     using unit_t = codecvt_result<code_unit>;
0378     unit_t unit;
0379     write_codecvt(unit, in, loc);
0380     // In UTF-8 is used one to four one-byte code units.
0381     auto u =
0382         to_utf8<code_unit, basic_memory_buffer<char, unit_t::max_size * 4>>();
0383     if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)}))
0384       FMT_THROW(format_error("failed to format time"));
0385     return copy_str<char>(u.c_str(), u.c_str() + u.size(), out);
0386   }
0387   return copy_str<char>(in.data(), in.data() + in.size(), out);
0388 }
0389 
0390 template <typename Char, typename OutputIt,
0391           FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
0392 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
0393     -> OutputIt {
0394   codecvt_result<Char> unit;
0395   write_codecvt(unit, sv, loc);
0396   return copy_str<Char>(unit.buf, unit.end, out);
0397 }
0398 
0399 template <typename Char, typename OutputIt,
0400           FMT_ENABLE_IF(std::is_same<Char, char>::value)>
0401 auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
0402     -> OutputIt {
0403   return write_encoded_tm_str(out, sv, loc);
0404 }
0405 
0406 template <typename Char>
0407 inline void do_write(buffer<Char>& buf, const std::tm& time,
0408                      const std::locale& loc, char format, char modifier) {
0409   auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
0410   auto&& os = std::basic_ostream<Char>(&format_buf);
0411   os.imbue(loc);
0412   const auto& facet = std::use_facet<std::time_put<Char>>(loc);
0413   auto end = facet.put(os, os, Char(' '), &time, format, modifier);
0414   if (end.failed()) FMT_THROW(format_error("failed to format time"));
0415 }
0416 
0417 template <typename Char, typename OutputIt,
0418           FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
0419 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
0420            char format, char modifier = 0) -> OutputIt {
0421   auto&& buf = get_buffer<Char>(out);
0422   do_write<Char>(buf, time, loc, format, modifier);
0423   return get_iterator(buf, out);
0424 }
0425 
0426 template <typename Char, typename OutputIt,
0427           FMT_ENABLE_IF(std::is_same<Char, char>::value)>
0428 auto write(OutputIt out, const std::tm& time, const std::locale& loc,
0429            char format, char modifier = 0) -> OutputIt {
0430   auto&& buf = basic_memory_buffer<Char>();
0431   do_write<char>(buf, time, loc, format, modifier);
0432   return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);
0433 }
0434 
0435 template <typename Rep1, typename Rep2>
0436 struct is_same_arithmetic_type
0437     : public std::integral_constant<bool,
0438                                     (std::is_integral<Rep1>::value &&
0439                                      std::is_integral<Rep2>::value) ||
0440                                         (std::is_floating_point<Rep1>::value &&
0441                                          std::is_floating_point<Rep2>::value)> {
0442 };
0443 
0444 template <
0445     typename To, typename FromRep, typename FromPeriod,
0446     FMT_ENABLE_IF(is_same_arithmetic_type<FromRep, typename To::rep>::value)>
0447 auto fmt_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
0448 #if FMT_SAFE_DURATION_CAST
0449   // Throwing version of safe_duration_cast is only available for
0450   // integer to integer or float to float casts.
0451   int ec;
0452   To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
0453   if (ec) FMT_THROW(format_error("cannot format duration"));
0454   return to;
0455 #else
0456   // Standard duration cast, may overflow.
0457   return std::chrono::duration_cast<To>(from);
0458 #endif
0459 }
0460 
0461 template <
0462     typename To, typename FromRep, typename FromPeriod,
0463     FMT_ENABLE_IF(!is_same_arithmetic_type<FromRep, typename To::rep>::value)>
0464 auto fmt_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
0465   // Mixed integer <-> float cast is not supported by safe_duration_cast.
0466   return std::chrono::duration_cast<To>(from);
0467 }
0468 
0469 template <typename Duration>
0470 auto to_time_t(
0471     std::chrono::time_point<std::chrono::system_clock, Duration> time_point)
0472     -> std::time_t {
0473   // Cannot use std::chrono::system_clock::to_time_t since this would first
0474   // require a cast to std::chrono::system_clock::time_point, which could
0475   // overflow.
0476   return fmt_duration_cast<std::chrono::duration<std::time_t>>(
0477              time_point.time_since_epoch())
0478       .count();
0479 }
0480 }  // namespace detail
0481 
0482 FMT_BEGIN_EXPORT
0483 
0484 /**
0485   Converts given time since epoch as ``std::time_t`` value into calendar time,
0486   expressed in local time. Unlike ``std::localtime``, this function is
0487   thread-safe on most platforms.
0488  */
0489 inline auto localtime(std::time_t time) -> std::tm {
0490   struct dispatcher {
0491     std::time_t time_;
0492     std::tm tm_;
0493 
0494     dispatcher(std::time_t t) : time_(t) {}
0495 
0496     auto run() -> bool {
0497       using namespace fmt::detail;
0498       return handle(localtime_r(&time_, &tm_));
0499     }
0500 
0501     auto handle(std::tm* tm) -> bool { return tm != nullptr; }
0502 
0503     auto handle(detail::null<>) -> bool {
0504       using namespace fmt::detail;
0505       return fallback(localtime_s(&tm_, &time_));
0506     }
0507 
0508     auto fallback(int res) -> bool { return res == 0; }
0509 
0510 #if !FMT_MSC_VERSION
0511     auto fallback(detail::null<>) -> bool {
0512       using namespace fmt::detail;
0513       std::tm* tm = std::localtime(&time_);
0514       if (tm) tm_ = *tm;
0515       return tm != nullptr;
0516     }
0517 #endif
0518   };
0519   dispatcher lt(time);
0520   // Too big time values may be unsupported.
0521   if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
0522   return lt.tm_;
0523 }
0524 
0525 #if FMT_USE_LOCAL_TIME
0526 template <typename Duration>
0527 inline auto localtime(std::chrono::local_time<Duration> time) -> std::tm {
0528   return localtime(
0529       detail::to_time_t(std::chrono::current_zone()->to_sys(time)));
0530 }
0531 #endif
0532 
0533 /**
0534   Converts given time since epoch as ``std::time_t`` value into calendar time,
0535   expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this
0536   function is thread-safe on most platforms.
0537  */
0538 inline auto gmtime(std::time_t time) -> std::tm {
0539   struct dispatcher {
0540     std::time_t time_;
0541     std::tm tm_;
0542 
0543     dispatcher(std::time_t t) : time_(t) {}
0544 
0545     auto run() -> bool {
0546       using namespace fmt::detail;
0547       return handle(gmtime_r(&time_, &tm_));
0548     }
0549 
0550     auto handle(std::tm* tm) -> bool { return tm != nullptr; }
0551 
0552     auto handle(detail::null<>) -> bool {
0553       using namespace fmt::detail;
0554       return fallback(gmtime_s(&tm_, &time_));
0555     }
0556 
0557     auto fallback(int res) -> bool { return res == 0; }
0558 
0559 #if !FMT_MSC_VERSION
0560     auto fallback(detail::null<>) -> bool {
0561       std::tm* tm = std::gmtime(&time_);
0562       if (tm) tm_ = *tm;
0563       return tm != nullptr;
0564     }
0565 #endif
0566   };
0567   auto gt = dispatcher(time);
0568   // Too big time values may be unsupported.
0569   if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
0570   return gt.tm_;
0571 }
0572 
0573 template <typename Duration>
0574 inline auto gmtime(
0575     std::chrono::time_point<std::chrono::system_clock, Duration> time_point)
0576     -> std::tm {
0577   return gmtime(detail::to_time_t(time_point));
0578 }
0579 
0580 namespace detail {
0581 
0582 // Writes two-digit numbers a, b and c separated by sep to buf.
0583 // The method by Pavel Novikov based on
0584 // https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.
0585 inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
0586                                    unsigned c, char sep) {
0587   unsigned long long digits =
0588       a | (b << 24) | (static_cast<unsigned long long>(c) << 48);
0589   // Convert each value to BCD.
0590   // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.
0591   // The difference is
0592   //   y - x = a * 6
0593   // a can be found from x:
0594   //   a = floor(x / 10)
0595   // then
0596   //   y = x + a * 6 = x + floor(x / 10) * 6
0597   // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).
0598   digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;
0599   // Put low nibbles to high bytes and high nibbles to low bytes.
0600   digits = ((digits & 0x00f00000f00000f0) >> 4) |
0601            ((digits & 0x000f00000f00000f) << 8);
0602   auto usep = static_cast<unsigned long long>(sep);
0603   // Add ASCII '0' to each digit byte and insert separators.
0604   digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
0605 
0606   constexpr const size_t len = 8;
0607   if (const_check(is_big_endian())) {
0608     char tmp[len];
0609     std::memcpy(tmp, &digits, len);
0610     std::reverse_copy(tmp, tmp + len, buf);
0611   } else {
0612     std::memcpy(buf, &digits, len);
0613   }
0614 }
0615 
0616 template <typename Period>
0617 FMT_CONSTEXPR inline auto get_units() -> const char* {
0618   if (std::is_same<Period, std::atto>::value) return "as";
0619   if (std::is_same<Period, std::femto>::value) return "fs";
0620   if (std::is_same<Period, std::pico>::value) return "ps";
0621   if (std::is_same<Period, std::nano>::value) return "ns";
0622   if (std::is_same<Period, std::micro>::value) return "µs";
0623   if (std::is_same<Period, std::milli>::value) return "ms";
0624   if (std::is_same<Period, std::centi>::value) return "cs";
0625   if (std::is_same<Period, std::deci>::value) return "ds";
0626   if (std::is_same<Period, std::ratio<1>>::value) return "s";
0627   if (std::is_same<Period, std::deca>::value) return "das";
0628   if (std::is_same<Period, std::hecto>::value) return "hs";
0629   if (std::is_same<Period, std::kilo>::value) return "ks";
0630   if (std::is_same<Period, std::mega>::value) return "Ms";
0631   if (std::is_same<Period, std::giga>::value) return "Gs";
0632   if (std::is_same<Period, std::tera>::value) return "Ts";
0633   if (std::is_same<Period, std::peta>::value) return "Ps";
0634   if (std::is_same<Period, std::exa>::value) return "Es";
0635   if (std::is_same<Period, std::ratio<60>>::value) return "min";
0636   if (std::is_same<Period, std::ratio<3600>>::value) return "h";
0637   if (std::is_same<Period, std::ratio<86400>>::value) return "d";
0638   return nullptr;
0639 }
0640 
0641 enum class numeric_system {
0642   standard,
0643   // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
0644   alternative
0645 };
0646 
0647 // Glibc extensions for formatting numeric values.
0648 enum class pad_type {
0649   unspecified,
0650   // Do not pad a numeric result string.
0651   none,
0652   // Pad a numeric result string with zeros even if the conversion specifier
0653   // character uses space-padding by default.
0654   zero,
0655   // Pad a numeric result string with spaces.
0656   space,
0657 };
0658 
0659 template <typename OutputIt>
0660 auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt {
0661   if (pad == pad_type::none) return out;
0662   return std::fill_n(out, width, pad == pad_type::space ? ' ' : '0');
0663 }
0664 
0665 template <typename OutputIt>
0666 auto write_padding(OutputIt out, pad_type pad) -> OutputIt {
0667   if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0';
0668   return out;
0669 }
0670 
0671 // Parses a put_time-like format string and invokes handler actions.
0672 template <typename Char, typename Handler>
0673 FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end,
0674                                        Handler&& handler) -> const Char* {
0675   if (begin == end || *begin == '}') return begin;
0676   if (*begin != '%') FMT_THROW(format_error("invalid format"));
0677   auto ptr = begin;
0678   pad_type pad = pad_type::unspecified;
0679   while (ptr != end) {
0680     auto c = *ptr;
0681     if (c == '}') break;
0682     if (c != '%') {
0683       ++ptr;
0684       continue;
0685     }
0686     if (begin != ptr) handler.on_text(begin, ptr);
0687     ++ptr;  // consume '%'
0688     if (ptr == end) FMT_THROW(format_error("invalid format"));
0689     c = *ptr;
0690     switch (c) {
0691     case '_':
0692       pad = pad_type::space;
0693       ++ptr;
0694       break;
0695     case '-':
0696       pad = pad_type::none;
0697       ++ptr;
0698       break;
0699     case '0':
0700       pad = pad_type::zero;
0701       ++ptr;
0702       break;
0703     }
0704     if (ptr == end) FMT_THROW(format_error("invalid format"));
0705     c = *ptr++;
0706     switch (c) {
0707     case '%':
0708       handler.on_text(ptr - 1, ptr);
0709       break;
0710     case 'n': {
0711       const Char newline[] = {'\n'};
0712       handler.on_text(newline, newline + 1);
0713       break;
0714     }
0715     case 't': {
0716       const Char tab[] = {'\t'};
0717       handler.on_text(tab, tab + 1);
0718       break;
0719     }
0720     // Year:
0721     case 'Y':
0722       handler.on_year(numeric_system::standard);
0723       break;
0724     case 'y':
0725       handler.on_short_year(numeric_system::standard);
0726       break;
0727     case 'C':
0728       handler.on_century(numeric_system::standard);
0729       break;
0730     case 'G':
0731       handler.on_iso_week_based_year();
0732       break;
0733     case 'g':
0734       handler.on_iso_week_based_short_year();
0735       break;
0736     // Day of the week:
0737     case 'a':
0738       handler.on_abbr_weekday();
0739       break;
0740     case 'A':
0741       handler.on_full_weekday();
0742       break;
0743     case 'w':
0744       handler.on_dec0_weekday(numeric_system::standard);
0745       break;
0746     case 'u':
0747       handler.on_dec1_weekday(numeric_system::standard);
0748       break;
0749     // Month:
0750     case 'b':
0751     case 'h':
0752       handler.on_abbr_month();
0753       break;
0754     case 'B':
0755       handler.on_full_month();
0756       break;
0757     case 'm':
0758       handler.on_dec_month(numeric_system::standard);
0759       break;
0760     // Day of the year/month:
0761     case 'U':
0762       handler.on_dec0_week_of_year(numeric_system::standard);
0763       break;
0764     case 'W':
0765       handler.on_dec1_week_of_year(numeric_system::standard);
0766       break;
0767     case 'V':
0768       handler.on_iso_week_of_year(numeric_system::standard);
0769       break;
0770     case 'j':
0771       handler.on_day_of_year();
0772       break;
0773     case 'd':
0774       handler.on_day_of_month(numeric_system::standard);
0775       break;
0776     case 'e':
0777       handler.on_day_of_month_space(numeric_system::standard);
0778       break;
0779     // Hour, minute, second:
0780     case 'H':
0781       handler.on_24_hour(numeric_system::standard, pad);
0782       break;
0783     case 'I':
0784       handler.on_12_hour(numeric_system::standard, pad);
0785       break;
0786     case 'M':
0787       handler.on_minute(numeric_system::standard, pad);
0788       break;
0789     case 'S':
0790       handler.on_second(numeric_system::standard, pad);
0791       break;
0792     // Other:
0793     case 'c':
0794       handler.on_datetime(numeric_system::standard);
0795       break;
0796     case 'x':
0797       handler.on_loc_date(numeric_system::standard);
0798       break;
0799     case 'X':
0800       handler.on_loc_time(numeric_system::standard);
0801       break;
0802     case 'D':
0803       handler.on_us_date();
0804       break;
0805     case 'F':
0806       handler.on_iso_date();
0807       break;
0808     case 'r':
0809       handler.on_12_hour_time();
0810       break;
0811     case 'R':
0812       handler.on_24_hour_time();
0813       break;
0814     case 'T':
0815       handler.on_iso_time();
0816       break;
0817     case 'p':
0818       handler.on_am_pm();
0819       break;
0820     case 'Q':
0821       handler.on_duration_value();
0822       break;
0823     case 'q':
0824       handler.on_duration_unit();
0825       break;
0826     case 'z':
0827       handler.on_utc_offset(numeric_system::standard);
0828       break;
0829     case 'Z':
0830       handler.on_tz_name();
0831       break;
0832     // Alternative representation:
0833     case 'E': {
0834       if (ptr == end) FMT_THROW(format_error("invalid format"));
0835       c = *ptr++;
0836       switch (c) {
0837       case 'Y':
0838         handler.on_year(numeric_system::alternative);
0839         break;
0840       case 'y':
0841         handler.on_offset_year();
0842         break;
0843       case 'C':
0844         handler.on_century(numeric_system::alternative);
0845         break;
0846       case 'c':
0847         handler.on_datetime(numeric_system::alternative);
0848         break;
0849       case 'x':
0850         handler.on_loc_date(numeric_system::alternative);
0851         break;
0852       case 'X':
0853         handler.on_loc_time(numeric_system::alternative);
0854         break;
0855       case 'z':
0856         handler.on_utc_offset(numeric_system::alternative);
0857         break;
0858       default:
0859         FMT_THROW(format_error("invalid format"));
0860       }
0861       break;
0862     }
0863     case 'O':
0864       if (ptr == end) FMT_THROW(format_error("invalid format"));
0865       c = *ptr++;
0866       switch (c) {
0867       case 'y':
0868         handler.on_short_year(numeric_system::alternative);
0869         break;
0870       case 'm':
0871         handler.on_dec_month(numeric_system::alternative);
0872         break;
0873       case 'U':
0874         handler.on_dec0_week_of_year(numeric_system::alternative);
0875         break;
0876       case 'W':
0877         handler.on_dec1_week_of_year(numeric_system::alternative);
0878         break;
0879       case 'V':
0880         handler.on_iso_week_of_year(numeric_system::alternative);
0881         break;
0882       case 'd':
0883         handler.on_day_of_month(numeric_system::alternative);
0884         break;
0885       case 'e':
0886         handler.on_day_of_month_space(numeric_system::alternative);
0887         break;
0888       case 'w':
0889         handler.on_dec0_weekday(numeric_system::alternative);
0890         break;
0891       case 'u':
0892         handler.on_dec1_weekday(numeric_system::alternative);
0893         break;
0894       case 'H':
0895         handler.on_24_hour(numeric_system::alternative, pad);
0896         break;
0897       case 'I':
0898         handler.on_12_hour(numeric_system::alternative, pad);
0899         break;
0900       case 'M':
0901         handler.on_minute(numeric_system::alternative, pad);
0902         break;
0903       case 'S':
0904         handler.on_second(numeric_system::alternative, pad);
0905         break;
0906       case 'z':
0907         handler.on_utc_offset(numeric_system::alternative);
0908         break;
0909       default:
0910         FMT_THROW(format_error("invalid format"));
0911       }
0912       break;
0913     default:
0914       FMT_THROW(format_error("invalid format"));
0915     }
0916     begin = ptr;
0917   }
0918   if (begin != ptr) handler.on_text(begin, ptr);
0919   return ptr;
0920 }
0921 
0922 template <typename Derived> struct null_chrono_spec_handler {
0923   FMT_CONSTEXPR void unsupported() {
0924     static_cast<Derived*>(this)->unsupported();
0925   }
0926   FMT_CONSTEXPR void on_year(numeric_system) { unsupported(); }
0927   FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }
0928   FMT_CONSTEXPR void on_offset_year() { unsupported(); }
0929   FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }
0930   FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }
0931   FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }
0932   FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }
0933   FMT_CONSTEXPR void on_full_weekday() { unsupported(); }
0934   FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }
0935   FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }
0936   FMT_CONSTEXPR void on_abbr_month() { unsupported(); }
0937   FMT_CONSTEXPR void on_full_month() { unsupported(); }
0938   FMT_CONSTEXPR void on_dec_month(numeric_system) { unsupported(); }
0939   FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) { unsupported(); }
0940   FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) { unsupported(); }
0941   FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) { unsupported(); }
0942   FMT_CONSTEXPR void on_day_of_year() { unsupported(); }
0943   FMT_CONSTEXPR void on_day_of_month(numeric_system) { unsupported(); }
0944   FMT_CONSTEXPR void on_day_of_month_space(numeric_system) { unsupported(); }
0945   FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }
0946   FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }
0947   FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }
0948   FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }
0949   FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }
0950   FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }
0951   FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }
0952   FMT_CONSTEXPR void on_us_date() { unsupported(); }
0953   FMT_CONSTEXPR void on_iso_date() { unsupported(); }
0954   FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }
0955   FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }
0956   FMT_CONSTEXPR void on_iso_time() { unsupported(); }
0957   FMT_CONSTEXPR void on_am_pm() { unsupported(); }
0958   FMT_CONSTEXPR void on_duration_value() { unsupported(); }
0959   FMT_CONSTEXPR void on_duration_unit() { unsupported(); }
0960   FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); }
0961   FMT_CONSTEXPR void on_tz_name() { unsupported(); }
0962 };
0963 
0964 struct tm_format_checker : null_chrono_spec_handler<tm_format_checker> {
0965   FMT_NORETURN void unsupported() { FMT_THROW(format_error("no format")); }
0966 
0967   template <typename Char>
0968   FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
0969   FMT_CONSTEXPR void on_year(numeric_system) {}
0970   FMT_CONSTEXPR void on_short_year(numeric_system) {}
0971   FMT_CONSTEXPR void on_offset_year() {}
0972   FMT_CONSTEXPR void on_century(numeric_system) {}
0973   FMT_CONSTEXPR void on_iso_week_based_year() {}
0974   FMT_CONSTEXPR void on_iso_week_based_short_year() {}
0975   FMT_CONSTEXPR void on_abbr_weekday() {}
0976   FMT_CONSTEXPR void on_full_weekday() {}
0977   FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}
0978   FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}
0979   FMT_CONSTEXPR void on_abbr_month() {}
0980   FMT_CONSTEXPR void on_full_month() {}
0981   FMT_CONSTEXPR void on_dec_month(numeric_system) {}
0982   FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system) {}
0983   FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system) {}
0984   FMT_CONSTEXPR void on_iso_week_of_year(numeric_system) {}
0985   FMT_CONSTEXPR void on_day_of_year() {}
0986   FMT_CONSTEXPR void on_day_of_month(numeric_system) {}
0987   FMT_CONSTEXPR void on_day_of_month_space(numeric_system) {}
0988   FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
0989   FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
0990   FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
0991   FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
0992   FMT_CONSTEXPR void on_datetime(numeric_system) {}
0993   FMT_CONSTEXPR void on_loc_date(numeric_system) {}
0994   FMT_CONSTEXPR void on_loc_time(numeric_system) {}
0995   FMT_CONSTEXPR void on_us_date() {}
0996   FMT_CONSTEXPR void on_iso_date() {}
0997   FMT_CONSTEXPR void on_12_hour_time() {}
0998   FMT_CONSTEXPR void on_24_hour_time() {}
0999   FMT_CONSTEXPR void on_iso_time() {}
1000   FMT_CONSTEXPR void on_am_pm() {}
1001   FMT_CONSTEXPR void on_utc_offset(numeric_system) {}
1002   FMT_CONSTEXPR void on_tz_name() {}
1003 };
1004 
1005 inline auto tm_wday_full_name(int wday) -> const char* {
1006   static constexpr const char* full_name_list[] = {
1007       "Sunday",   "Monday", "Tuesday", "Wednesday",
1008       "Thursday", "Friday", "Saturday"};
1009   return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?";
1010 }
1011 inline auto tm_wday_short_name(int wday) -> const char* {
1012   static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed",
1013                                                     "Thu", "Fri", "Sat"};
1014   return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???";
1015 }
1016 
1017 inline auto tm_mon_full_name(int mon) -> const char* {
1018   static constexpr const char* full_name_list[] = {
1019       "January", "February", "March",     "April",   "May",      "June",
1020       "July",    "August",   "September", "October", "November", "December"};
1021   return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?";
1022 }
1023 inline auto tm_mon_short_name(int mon) -> const char* {
1024   static constexpr const char* short_name_list[] = {
1025       "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1026       "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1027   };
1028   return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???";
1029 }
1030 
1031 template <typename T, typename = void>
1032 struct has_member_data_tm_gmtoff : std::false_type {};
1033 template <typename T>
1034 struct has_member_data_tm_gmtoff<T, void_t<decltype(T::tm_gmtoff)>>
1035     : std::true_type {};
1036 
1037 template <typename T, typename = void>
1038 struct has_member_data_tm_zone : std::false_type {};
1039 template <typename T>
1040 struct has_member_data_tm_zone<T, void_t<decltype(T::tm_zone)>>
1041     : std::true_type {};
1042 
1043 #if FMT_USE_TZSET
1044 inline void tzset_once() {
1045   static bool init = []() -> bool {
1046     _tzset();
1047     return true;
1048   }();
1049   ignore_unused(init);
1050 }
1051 #endif
1052 
1053 // Converts value to Int and checks that it's in the range [0, upper).
1054 template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
1055 inline auto to_nonnegative_int(T value, Int upper) -> Int {
1056   if (!std::is_unsigned<Int>::value &&
1057       (value < 0 || to_unsigned(value) > to_unsigned(upper))) {
1058     FMT_THROW(fmt::format_error("chrono value is out of range"));
1059   }
1060   return static_cast<Int>(value);
1061 }
1062 template <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>
1063 inline auto to_nonnegative_int(T value, Int upper) -> Int {
1064   if (value < 0 || value > static_cast<T>(upper))
1065     FMT_THROW(format_error("invalid value"));
1066   return static_cast<Int>(value);
1067 }
1068 
1069 constexpr auto pow10(std::uint32_t n) -> long long {
1070   return n == 0 ? 1 : 10 * pow10(n - 1);
1071 }
1072 
1073 // Counts the number of fractional digits in the range [0, 18] according to the
1074 // C++20 spec. If more than 18 fractional digits are required then returns 6 for
1075 // microseconds precision.
1076 template <long long Num, long long Den, int N = 0,
1077           bool Enabled = (N < 19) && (Num <= max_value<long long>() / 10)>
1078 struct count_fractional_digits {
1079   static constexpr int value =
1080       Num % Den == 0 ? N : count_fractional_digits<Num * 10, Den, N + 1>::value;
1081 };
1082 
1083 // Base case that doesn't instantiate any more templates
1084 // in order to avoid overflow.
1085 template <long long Num, long long Den, int N>
1086 struct count_fractional_digits<Num, Den, N, false> {
1087   static constexpr int value = (Num % Den == 0) ? N : 6;
1088 };
1089 
1090 // Format subseconds which are given as an integer type with an appropriate
1091 // number of digits.
1092 template <typename Char, typename OutputIt, typename Duration>
1093 void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {
1094   constexpr auto num_fractional_digits =
1095       count_fractional_digits<Duration::period::num,
1096                               Duration::period::den>::value;
1097 
1098   using subsecond_precision = std::chrono::duration<
1099       typename std::common_type<typename Duration::rep,
1100                                 std::chrono::seconds::rep>::type,
1101       std::ratio<1, detail::pow10(num_fractional_digits)>>;
1102 
1103   const auto fractional = d - fmt_duration_cast<std::chrono::seconds>(d);
1104   const auto subseconds =
1105       std::chrono::treat_as_floating_point<
1106           typename subsecond_precision::rep>::value
1107           ? fractional.count()
1108           : fmt_duration_cast<subsecond_precision>(fractional).count();
1109   auto n = static_cast<uint32_or_64_or_128_t<long long>>(subseconds);
1110   const int num_digits = detail::count_digits(n);
1111 
1112   int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits);
1113   if (precision < 0) {
1114     FMT_ASSERT(!std::is_floating_point<typename Duration::rep>::value, "");
1115     if (std::ratio_less<typename subsecond_precision::period,
1116                         std::chrono::seconds::period>::value) {
1117       *out++ = '.';
1118       out = std::fill_n(out, leading_zeroes, '0');
1119       out = format_decimal<Char>(out, n, num_digits).end;
1120     }
1121   } else {
1122     *out++ = '.';
1123     leading_zeroes = (std::min)(leading_zeroes, precision);
1124     out = std::fill_n(out, leading_zeroes, '0');
1125     int remaining = precision - leading_zeroes;
1126     if (remaining != 0 && remaining < num_digits) {
1127       n /= to_unsigned(detail::pow10(to_unsigned(num_digits - remaining)));
1128       out = format_decimal<Char>(out, n, remaining).end;
1129       return;
1130     }
1131     out = format_decimal<Char>(out, n, num_digits).end;
1132     remaining -= num_digits;
1133     out = std::fill_n(out, remaining, '0');
1134   }
1135 }
1136 
1137 // Format subseconds which are given as a floating point type with an
1138 // appropriate number of digits. We cannot pass the Duration here, as we
1139 // explicitly need to pass the Rep value in the chrono_formatter.
1140 template <typename Duration>
1141 void write_floating_seconds(memory_buffer& buf, Duration duration,
1142                             int num_fractional_digits = -1) {
1143   using rep = typename Duration::rep;
1144   FMT_ASSERT(std::is_floating_point<rep>::value, "");
1145 
1146   auto val = duration.count();
1147 
1148   if (num_fractional_digits < 0) {
1149     // For `std::round` with fallback to `round`:
1150     // On some toolchains `std::round` is not available (e.g. GCC 6).
1151     using namespace std;
1152     num_fractional_digits =
1153         count_fractional_digits<Duration::period::num,
1154                                 Duration::period::den>::value;
1155     if (num_fractional_digits < 6 && static_cast<rep>(round(val)) != val)
1156       num_fractional_digits = 6;
1157   }
1158 
1159   fmt::format_to(std::back_inserter(buf), FMT_STRING("{:.{}f}"),
1160                  std::fmod(val * static_cast<rep>(Duration::period::num) /
1161                                static_cast<rep>(Duration::period::den),
1162                            static_cast<rep>(60)),
1163                  num_fractional_digits);
1164 }
1165 
1166 template <typename OutputIt, typename Char,
1167           typename Duration = std::chrono::seconds>
1168 class tm_writer {
1169  private:
1170   static constexpr int days_per_week = 7;
1171 
1172   const std::locale& loc_;
1173   const bool is_classic_;
1174   OutputIt out_;
1175   const Duration* subsecs_;
1176   const std::tm& tm_;
1177 
1178   auto tm_sec() const noexcept -> int {
1179     FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, "");
1180     return tm_.tm_sec;
1181   }
1182   auto tm_min() const noexcept -> int {
1183     FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, "");
1184     return tm_.tm_min;
1185   }
1186   auto tm_hour() const noexcept -> int {
1187     FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, "");
1188     return tm_.tm_hour;
1189   }
1190   auto tm_mday() const noexcept -> int {
1191     FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, "");
1192     return tm_.tm_mday;
1193   }
1194   auto tm_mon() const noexcept -> int {
1195     FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, "");
1196     return tm_.tm_mon;
1197   }
1198   auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }
1199   auto tm_wday() const noexcept -> int {
1200     FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, "");
1201     return tm_.tm_wday;
1202   }
1203   auto tm_yday() const noexcept -> int {
1204     FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, "");
1205     return tm_.tm_yday;
1206   }
1207 
1208   auto tm_hour12() const noexcept -> int {
1209     const auto h = tm_hour();
1210     const auto z = h < 12 ? h : h - 12;
1211     return z == 0 ? 12 : z;
1212   }
1213 
1214   // POSIX and the C Standard are unclear or inconsistent about what %C and %y
1215   // do if the year is negative or exceeds 9999. Use the convention that %C
1216   // concatenated with %y yields the same output as %Y, and that %Y contains at
1217   // least 4 characters, with more only if necessary.
1218   auto split_year_lower(long long year) const noexcept -> int {
1219     auto l = year % 100;
1220     if (l < 0) l = -l;  // l in [0, 99]
1221     return static_cast<int>(l);
1222   }
1223 
1224   // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date.
1225   auto iso_year_weeks(long long curr_year) const noexcept -> int {
1226     const auto prev_year = curr_year - 1;
1227     const auto curr_p =
1228         (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %
1229         days_per_week;
1230     const auto prev_p =
1231         (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %
1232         days_per_week;
1233     return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);
1234   }
1235   auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {
1236     return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /
1237            days_per_week;
1238   }
1239   auto tm_iso_week_year() const noexcept -> long long {
1240     const auto year = tm_year();
1241     const auto w = iso_week_num(tm_yday(), tm_wday());
1242     if (w < 1) return year - 1;
1243     if (w > iso_year_weeks(year)) return year + 1;
1244     return year;
1245   }
1246   auto tm_iso_week_of_year() const noexcept -> int {
1247     const auto year = tm_year();
1248     const auto w = iso_week_num(tm_yday(), tm_wday());
1249     if (w < 1) return iso_year_weeks(year - 1);
1250     if (w > iso_year_weeks(year)) return 1;
1251     return w;
1252   }
1253 
1254   void write1(int value) {
1255     *out_++ = static_cast<char>('0' + to_unsigned(value) % 10);
1256   }
1257   void write2(int value) {
1258     const char* d = digits2(to_unsigned(value) % 100);
1259     *out_++ = *d++;
1260     *out_++ = *d;
1261   }
1262   void write2(int value, pad_type pad) {
1263     unsigned int v = to_unsigned(value) % 100;
1264     if (v >= 10) {
1265       const char* d = digits2(v);
1266       *out_++ = *d++;
1267       *out_++ = *d;
1268     } else {
1269       out_ = detail::write_padding(out_, pad);
1270       *out_++ = static_cast<char>('0' + v);
1271     }
1272   }
1273 
1274   void write_year_extended(long long year) {
1275     // At least 4 characters.
1276     int width = 4;
1277     if (year < 0) {
1278       *out_++ = '-';
1279       year = 0 - year;
1280       --width;
1281     }
1282     uint32_or_64_or_128_t<long long> n = to_unsigned(year);
1283     const int num_digits = count_digits(n);
1284     if (width > num_digits) out_ = std::fill_n(out_, width - num_digits, '0');
1285     out_ = format_decimal<Char>(out_, n, num_digits).end;
1286   }
1287   void write_year(long long year) {
1288     if (year >= 0 && year < 10000) {
1289       write2(static_cast<int>(year / 100));
1290       write2(static_cast<int>(year % 100));
1291     } else {
1292       write_year_extended(year);
1293     }
1294   }
1295 
1296   void write_utc_offset(long offset, numeric_system ns) {
1297     if (offset < 0) {
1298       *out_++ = '-';
1299       offset = -offset;
1300     } else {
1301       *out_++ = '+';
1302     }
1303     offset /= 60;
1304     write2(static_cast<int>(offset / 60));
1305     if (ns != numeric_system::standard) *out_++ = ':';
1306     write2(static_cast<int>(offset % 60));
1307   }
1308   template <typename T, FMT_ENABLE_IF(has_member_data_tm_gmtoff<T>::value)>
1309   void format_utc_offset_impl(const T& tm, numeric_system ns) {
1310     write_utc_offset(tm.tm_gmtoff, ns);
1311   }
1312   template <typename T, FMT_ENABLE_IF(!has_member_data_tm_gmtoff<T>::value)>
1313   void format_utc_offset_impl(const T& tm, numeric_system ns) {
1314 #if defined(_WIN32) && defined(_UCRT)
1315 #  if FMT_USE_TZSET
1316     tzset_once();
1317 #  endif
1318     long offset = 0;
1319     _get_timezone(&offset);
1320     if (tm.tm_isdst) {
1321       long dstbias = 0;
1322       _get_dstbias(&dstbias);
1323       offset += dstbias;
1324     }
1325     write_utc_offset(-offset, ns);
1326 #else
1327     if (ns == numeric_system::standard) return format_localized('z');
1328 
1329     // Extract timezone offset from timezone conversion functions.
1330     std::tm gtm = tm;
1331     std::time_t gt = std::mktime(&gtm);
1332     std::tm ltm = gmtime(gt);
1333     std::time_t lt = std::mktime(&ltm);
1334     long offset = gt - lt;
1335     write_utc_offset(offset, ns);
1336 #endif
1337   }
1338 
1339   template <typename T, FMT_ENABLE_IF(has_member_data_tm_zone<T>::value)>
1340   void format_tz_name_impl(const T& tm) {
1341     if (is_classic_)
1342       out_ = write_tm_str<Char>(out_, tm.tm_zone, loc_);
1343     else
1344       format_localized('Z');
1345   }
1346   template <typename T, FMT_ENABLE_IF(!has_member_data_tm_zone<T>::value)>
1347   void format_tz_name_impl(const T&) {
1348     format_localized('Z');
1349   }
1350 
1351   void format_localized(char format, char modifier = 0) {
1352     out_ = write<Char>(out_, tm_, loc_, format, modifier);
1353   }
1354 
1355  public:
1356   tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm,
1357             const Duration* subsecs = nullptr)
1358       : loc_(loc),
1359         is_classic_(loc_ == get_classic_locale()),
1360         out_(out),
1361         subsecs_(subsecs),
1362         tm_(tm) {}
1363 
1364   auto out() const -> OutputIt { return out_; }
1365 
1366   FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
1367     out_ = copy_str<Char>(begin, end, out_);
1368   }
1369 
1370   void on_abbr_weekday() {
1371     if (is_classic_)
1372       out_ = write(out_, tm_wday_short_name(tm_wday()));
1373     else
1374       format_localized('a');
1375   }
1376   void on_full_weekday() {
1377     if (is_classic_)
1378       out_ = write(out_, tm_wday_full_name(tm_wday()));
1379     else
1380       format_localized('A');
1381   }
1382   void on_dec0_weekday(numeric_system ns) {
1383     if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());
1384     format_localized('w', 'O');
1385   }
1386   void on_dec1_weekday(numeric_system ns) {
1387     if (is_classic_ || ns == numeric_system::standard) {
1388       auto wday = tm_wday();
1389       write1(wday == 0 ? days_per_week : wday);
1390     } else {
1391       format_localized('u', 'O');
1392     }
1393   }
1394 
1395   void on_abbr_month() {
1396     if (is_classic_)
1397       out_ = write(out_, tm_mon_short_name(tm_mon()));
1398     else
1399       format_localized('b');
1400   }
1401   void on_full_month() {
1402     if (is_classic_)
1403       out_ = write(out_, tm_mon_full_name(tm_mon()));
1404     else
1405       format_localized('B');
1406   }
1407 
1408   void on_datetime(numeric_system ns) {
1409     if (is_classic_) {
1410       on_abbr_weekday();
1411       *out_++ = ' ';
1412       on_abbr_month();
1413       *out_++ = ' ';
1414       on_day_of_month_space(numeric_system::standard);
1415       *out_++ = ' ';
1416       on_iso_time();
1417       *out_++ = ' ';
1418       on_year(numeric_system::standard);
1419     } else {
1420       format_localized('c', ns == numeric_system::standard ? '\0' : 'E');
1421     }
1422   }
1423   void on_loc_date(numeric_system ns) {
1424     if (is_classic_)
1425       on_us_date();
1426     else
1427       format_localized('x', ns == numeric_system::standard ? '\0' : 'E');
1428   }
1429   void on_loc_time(numeric_system ns) {
1430     if (is_classic_)
1431       on_iso_time();
1432     else
1433       format_localized('X', ns == numeric_system::standard ? '\0' : 'E');
1434   }
1435   void on_us_date() {
1436     char buf[8];
1437     write_digit2_separated(buf, to_unsigned(tm_mon() + 1),
1438                            to_unsigned(tm_mday()),
1439                            to_unsigned(split_year_lower(tm_year())), '/');
1440     out_ = copy_str<Char>(std::begin(buf), std::end(buf), out_);
1441   }
1442   void on_iso_date() {
1443     auto year = tm_year();
1444     char buf[10];
1445     size_t offset = 0;
1446     if (year >= 0 && year < 10000) {
1447       copy2(buf, digits2(static_cast<size_t>(year / 100)));
1448     } else {
1449       offset = 4;
1450       write_year_extended(year);
1451       year = 0;
1452     }
1453     write_digit2_separated(buf + 2, static_cast<unsigned>(year % 100),
1454                            to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),
1455                            '-');
1456     out_ = copy_str<Char>(std::begin(buf) + offset, std::end(buf), out_);
1457   }
1458 
1459   void on_utc_offset(numeric_system ns) { format_utc_offset_impl(tm_, ns); }
1460   void on_tz_name() { format_tz_name_impl(tm_); }
1461 
1462   void on_year(numeric_system ns) {
1463     if (is_classic_ || ns == numeric_system::standard)
1464       return write_year(tm_year());
1465     format_localized('Y', 'E');
1466   }
1467   void on_short_year(numeric_system ns) {
1468     if (is_classic_ || ns == numeric_system::standard)
1469       return write2(split_year_lower(tm_year()));
1470     format_localized('y', 'O');
1471   }
1472   void on_offset_year() {
1473     if (is_classic_) return write2(split_year_lower(tm_year()));
1474     format_localized('y', 'E');
1475   }
1476 
1477   void on_century(numeric_system ns) {
1478     if (is_classic_ || ns == numeric_system::standard) {
1479       auto year = tm_year();
1480       auto upper = year / 100;
1481       if (year >= -99 && year < 0) {
1482         // Zero upper on negative year.
1483         *out_++ = '-';
1484         *out_++ = '0';
1485       } else if (upper >= 0 && upper < 100) {
1486         write2(static_cast<int>(upper));
1487       } else {
1488         out_ = write<Char>(out_, upper);
1489       }
1490     } else {
1491       format_localized('C', 'E');
1492     }
1493   }
1494 
1495   void on_dec_month(numeric_system ns) {
1496     if (is_classic_ || ns == numeric_system::standard)
1497       return write2(tm_mon() + 1);
1498     format_localized('m', 'O');
1499   }
1500 
1501   void on_dec0_week_of_year(numeric_system ns) {
1502     if (is_classic_ || ns == numeric_system::standard)
1503       return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week);
1504     format_localized('U', 'O');
1505   }
1506   void on_dec1_week_of_year(numeric_system ns) {
1507     if (is_classic_ || ns == numeric_system::standard) {
1508       auto wday = tm_wday();
1509       write2((tm_yday() + days_per_week -
1510               (wday == 0 ? (days_per_week - 1) : (wday - 1))) /
1511              days_per_week);
1512     } else {
1513       format_localized('W', 'O');
1514     }
1515   }
1516   void on_iso_week_of_year(numeric_system ns) {
1517     if (is_classic_ || ns == numeric_system::standard)
1518       return write2(tm_iso_week_of_year());
1519     format_localized('V', 'O');
1520   }
1521 
1522   void on_iso_week_based_year() { write_year(tm_iso_week_year()); }
1523   void on_iso_week_based_short_year() {
1524     write2(split_year_lower(tm_iso_week_year()));
1525   }
1526 
1527   void on_day_of_year() {
1528     auto yday = tm_yday() + 1;
1529     write1(yday / 100);
1530     write2(yday % 100);
1531   }
1532   void on_day_of_month(numeric_system ns) {
1533     if (is_classic_ || ns == numeric_system::standard) return write2(tm_mday());
1534     format_localized('d', 'O');
1535   }
1536   void on_day_of_month_space(numeric_system ns) {
1537     if (is_classic_ || ns == numeric_system::standard) {
1538       auto mday = to_unsigned(tm_mday()) % 100;
1539       const char* d2 = digits2(mday);
1540       *out_++ = mday < 10 ? ' ' : d2[0];
1541       *out_++ = d2[1];
1542     } else {
1543       format_localized('e', 'O');
1544     }
1545   }
1546 
1547   void on_24_hour(numeric_system ns, pad_type pad) {
1548     if (is_classic_ || ns == numeric_system::standard)
1549       return write2(tm_hour(), pad);
1550     format_localized('H', 'O');
1551   }
1552   void on_12_hour(numeric_system ns, pad_type pad) {
1553     if (is_classic_ || ns == numeric_system::standard)
1554       return write2(tm_hour12(), pad);
1555     format_localized('I', 'O');
1556   }
1557   void on_minute(numeric_system ns, pad_type pad) {
1558     if (is_classic_ || ns == numeric_system::standard)
1559       return write2(tm_min(), pad);
1560     format_localized('M', 'O');
1561   }
1562 
1563   void on_second(numeric_system ns, pad_type pad) {
1564     if (is_classic_ || ns == numeric_system::standard) {
1565       write2(tm_sec(), pad);
1566       if (subsecs_) {
1567         if (std::is_floating_point<typename Duration::rep>::value) {
1568           auto buf = memory_buffer();
1569           write_floating_seconds(buf, *subsecs_);
1570           if (buf.size() > 1) {
1571             // Remove the leading "0", write something like ".123".
1572             out_ = std::copy(buf.begin() + 1, buf.end(), out_);
1573           }
1574         } else {
1575           write_fractional_seconds<Char>(out_, *subsecs_);
1576         }
1577       }
1578     } else {
1579       // Currently no formatting of subseconds when a locale is set.
1580       format_localized('S', 'O');
1581     }
1582   }
1583 
1584   void on_12_hour_time() {
1585     if (is_classic_) {
1586       char buf[8];
1587       write_digit2_separated(buf, to_unsigned(tm_hour12()),
1588                              to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');
1589       out_ = copy_str<Char>(std::begin(buf), std::end(buf), out_);
1590       *out_++ = ' ';
1591       on_am_pm();
1592     } else {
1593       format_localized('r');
1594     }
1595   }
1596   void on_24_hour_time() {
1597     write2(tm_hour());
1598     *out_++ = ':';
1599     write2(tm_min());
1600   }
1601   void on_iso_time() {
1602     on_24_hour_time();
1603     *out_++ = ':';
1604     on_second(numeric_system::standard, pad_type::unspecified);
1605   }
1606 
1607   void on_am_pm() {
1608     if (is_classic_) {
1609       *out_++ = tm_hour() < 12 ? 'A' : 'P';
1610       *out_++ = 'M';
1611     } else {
1612       format_localized('p');
1613     }
1614   }
1615 
1616   // These apply to chrono durations but not tm.
1617   void on_duration_value() {}
1618   void on_duration_unit() {}
1619 };
1620 
1621 struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
1622   bool has_precision_integral = false;
1623 
1624   FMT_NORETURN void unsupported() { FMT_THROW(format_error("no date")); }
1625 
1626   template <typename Char>
1627   FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
1628   FMT_CONSTEXPR void on_day_of_year() {}
1629   FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
1630   FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
1631   FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
1632   FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
1633   FMT_CONSTEXPR void on_12_hour_time() {}
1634   FMT_CONSTEXPR void on_24_hour_time() {}
1635   FMT_CONSTEXPR void on_iso_time() {}
1636   FMT_CONSTEXPR void on_am_pm() {}
1637   FMT_CONSTEXPR void on_duration_value() const {
1638     if (has_precision_integral) {
1639       FMT_THROW(format_error("precision not allowed for this argument type"));
1640     }
1641   }
1642   FMT_CONSTEXPR void on_duration_unit() {}
1643 };
1644 
1645 template <typename T,
1646           FMT_ENABLE_IF(std::is_integral<T>::value&& has_isfinite<T>::value)>
1647 inline auto isfinite(T) -> bool {
1648   return true;
1649 }
1650 
1651 template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
1652 inline auto mod(T x, int y) -> T {
1653   return x % static_cast<T>(y);
1654 }
1655 template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
1656 inline auto mod(T x, int y) -> T {
1657   return std::fmod(x, static_cast<T>(y));
1658 }
1659 
1660 // If T is an integral type, maps T to its unsigned counterpart, otherwise
1661 // leaves it unchanged (unlike std::make_unsigned).
1662 template <typename T, bool INTEGRAL = std::is_integral<T>::value>
1663 struct make_unsigned_or_unchanged {
1664   using type = T;
1665 };
1666 
1667 template <typename T> struct make_unsigned_or_unchanged<T, true> {
1668   using type = typename std::make_unsigned<T>::type;
1669 };
1670 
1671 template <typename Rep, typename Period,
1672           FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1673 inline auto get_milliseconds(std::chrono::duration<Rep, Period> d)
1674     -> std::chrono::duration<Rep, std::milli> {
1675   // this may overflow and/or the result may not fit in the
1676   // target type.
1677 #if FMT_SAFE_DURATION_CAST
1678   using CommonSecondsType =
1679       typename std::common_type<decltype(d), std::chrono::seconds>::type;
1680   const auto d_as_common = fmt_duration_cast<CommonSecondsType>(d);
1681   const auto d_as_whole_seconds =
1682       fmt_duration_cast<std::chrono::seconds>(d_as_common);
1683   // this conversion should be nonproblematic
1684   const auto diff = d_as_common - d_as_whole_seconds;
1685   const auto ms =
1686       fmt_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
1687   return ms;
1688 #else
1689   auto s = fmt_duration_cast<std::chrono::seconds>(d);
1690   return fmt_duration_cast<std::chrono::milliseconds>(d - s);
1691 #endif
1692 }
1693 
1694 template <typename Char, typename Rep, typename OutputIt,
1695           FMT_ENABLE_IF(std::is_integral<Rep>::value)>
1696 auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt {
1697   return write<Char>(out, val);
1698 }
1699 
1700 template <typename Char, typename Rep, typename OutputIt,
1701           FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
1702 auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt {
1703   auto specs = format_specs<Char>();
1704   specs.precision = precision;
1705   specs.type = precision >= 0 ? presentation_type::fixed_lower
1706                               : presentation_type::general_lower;
1707   return write<Char>(out, val, specs);
1708 }
1709 
1710 template <typename Char, typename OutputIt>
1711 auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt {
1712   return std::copy(unit.begin(), unit.end(), out);
1713 }
1714 
1715 template <typename OutputIt>
1716 auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt {
1717   // This works when wchar_t is UTF-32 because units only contain characters
1718   // that have the same representation in UTF-16 and UTF-32.
1719   utf8_to_utf16 u(unit);
1720   return std::copy(u.c_str(), u.c_str() + u.size(), out);
1721 }
1722 
1723 template <typename Char, typename Period, typename OutputIt>
1724 auto format_duration_unit(OutputIt out) -> OutputIt {
1725   if (const char* unit = get_units<Period>())
1726     return copy_unit(string_view(unit), out, Char());
1727   *out++ = '[';
1728   out = write<Char>(out, Period::num);
1729   if (const_check(Period::den != 1)) {
1730     *out++ = '/';
1731     out = write<Char>(out, Period::den);
1732   }
1733   *out++ = ']';
1734   *out++ = 's';
1735   return out;
1736 }
1737 
1738 class get_locale {
1739  private:
1740   union {
1741     std::locale locale_;
1742   };
1743   bool has_locale_ = false;
1744 
1745  public:
1746   get_locale(bool localized, locale_ref loc) : has_locale_(localized) {
1747     if (localized)
1748       ::new (&locale_) std::locale(loc.template get<std::locale>());
1749   }
1750   ~get_locale() {
1751     if (has_locale_) locale_.~locale();
1752   }
1753   operator const std::locale&() const {
1754     return has_locale_ ? locale_ : get_classic_locale();
1755   }
1756 };
1757 
1758 template <typename FormatContext, typename OutputIt, typename Rep,
1759           typename Period>
1760 struct chrono_formatter {
1761   FormatContext& context;
1762   OutputIt out;
1763   int precision;
1764   bool localized = false;
1765   // rep is unsigned to avoid overflow.
1766   using rep =
1767       conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
1768                     unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
1769   rep val;
1770   using seconds = std::chrono::duration<rep>;
1771   seconds s;
1772   using milliseconds = std::chrono::duration<rep, std::milli>;
1773   bool negative;
1774 
1775   using char_type = typename FormatContext::char_type;
1776   using tm_writer_type = tm_writer<OutputIt, char_type>;
1777 
1778   chrono_formatter(FormatContext& ctx, OutputIt o,
1779                    std::chrono::duration<Rep, Period> d)
1780       : context(ctx),
1781         out(o),
1782         val(static_cast<rep>(d.count())),
1783         negative(false) {
1784     if (d.count() < 0) {
1785       val = 0 - val;
1786       negative = true;
1787     }
1788 
1789     // this may overflow and/or the result may not fit in the
1790     // target type.
1791     // might need checked conversion (rep!=Rep)
1792     s = fmt_duration_cast<seconds>(std::chrono::duration<rep, Period>(val));
1793   }
1794 
1795   // returns true if nan or inf, writes to out.
1796   auto handle_nan_inf() -> bool {
1797     if (isfinite(val)) {
1798       return false;
1799     }
1800     if (isnan(val)) {
1801       write_nan();
1802       return true;
1803     }
1804     // must be +-inf
1805     if (val > 0) {
1806       write_pinf();
1807     } else {
1808       write_ninf();
1809     }
1810     return true;
1811   }
1812 
1813   auto days() const -> Rep { return static_cast<Rep>(s.count() / 86400); }
1814   auto hour() const -> Rep {
1815     return static_cast<Rep>(mod((s.count() / 3600), 24));
1816   }
1817 
1818   auto hour12() const -> Rep {
1819     Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
1820     return hour <= 0 ? 12 : hour;
1821   }
1822 
1823   auto minute() const -> Rep {
1824     return static_cast<Rep>(mod((s.count() / 60), 60));
1825   }
1826   auto second() const -> Rep { return static_cast<Rep>(mod(s.count(), 60)); }
1827 
1828   auto time() const -> std::tm {
1829     auto time = std::tm();
1830     time.tm_hour = to_nonnegative_int(hour(), 24);
1831     time.tm_min = to_nonnegative_int(minute(), 60);
1832     time.tm_sec = to_nonnegative_int(second(), 60);
1833     return time;
1834   }
1835 
1836   void write_sign() {
1837     if (negative) {
1838       *out++ = '-';
1839       negative = false;
1840     }
1841   }
1842 
1843   void write(Rep value, int width, pad_type pad = pad_type::unspecified) {
1844     write_sign();
1845     if (isnan(value)) return write_nan();
1846     uint32_or_64_or_128_t<int> n =
1847         to_unsigned(to_nonnegative_int(value, max_value<int>()));
1848     int num_digits = detail::count_digits(n);
1849     if (width > num_digits) {
1850       out = detail::write_padding(out, pad, width - num_digits);
1851     }
1852     out = format_decimal<char_type>(out, n, num_digits).end;
1853   }
1854 
1855   void write_nan() { std::copy_n("nan", 3, out); }
1856   void write_pinf() { std::copy_n("inf", 3, out); }
1857   void write_ninf() { std::copy_n("-inf", 4, out); }
1858 
1859   template <typename Callback, typename... Args>
1860   void format_tm(const tm& time, Callback cb, Args... args) {
1861     if (isnan(val)) return write_nan();
1862     get_locale loc(localized, context.locale());
1863     auto w = tm_writer_type(loc, out, time);
1864     (w.*cb)(args...);
1865     out = w.out();
1866   }
1867 
1868   void on_text(const char_type* begin, const char_type* end) {
1869     std::copy(begin, end, out);
1870   }
1871 
1872   // These are not implemented because durations don't have date information.
1873   void on_abbr_weekday() {}
1874   void on_full_weekday() {}
1875   void on_dec0_weekday(numeric_system) {}
1876   void on_dec1_weekday(numeric_system) {}
1877   void on_abbr_month() {}
1878   void on_full_month() {}
1879   void on_datetime(numeric_system) {}
1880   void on_loc_date(numeric_system) {}
1881   void on_loc_time(numeric_system) {}
1882   void on_us_date() {}
1883   void on_iso_date() {}
1884   void on_utc_offset(numeric_system) {}
1885   void on_tz_name() {}
1886   void on_year(numeric_system) {}
1887   void on_short_year(numeric_system) {}
1888   void on_offset_year() {}
1889   void on_century(numeric_system) {}
1890   void on_iso_week_based_year() {}
1891   void on_iso_week_based_short_year() {}
1892   void on_dec_month(numeric_system) {}
1893   void on_dec0_week_of_year(numeric_system) {}
1894   void on_dec1_week_of_year(numeric_system) {}
1895   void on_iso_week_of_year(numeric_system) {}
1896   void on_day_of_month(numeric_system) {}
1897   void on_day_of_month_space(numeric_system) {}
1898 
1899   void on_day_of_year() {
1900     if (handle_nan_inf()) return;
1901     write(days(), 0);
1902   }
1903 
1904   void on_24_hour(numeric_system ns, pad_type pad) {
1905     if (handle_nan_inf()) return;
1906 
1907     if (ns == numeric_system::standard) return write(hour(), 2, pad);
1908     auto time = tm();
1909     time.tm_hour = to_nonnegative_int(hour(), 24);
1910     format_tm(time, &tm_writer_type::on_24_hour, ns, pad);
1911   }
1912 
1913   void on_12_hour(numeric_system ns, pad_type pad) {
1914     if (handle_nan_inf()) return;
1915 
1916     if (ns == numeric_system::standard) return write(hour12(), 2, pad);
1917     auto time = tm();
1918     time.tm_hour = to_nonnegative_int(hour12(), 12);
1919     format_tm(time, &tm_writer_type::on_12_hour, ns, pad);
1920   }
1921 
1922   void on_minute(numeric_system ns, pad_type pad) {
1923     if (handle_nan_inf()) return;
1924 
1925     if (ns == numeric_system::standard) return write(minute(), 2, pad);
1926     auto time = tm();
1927     time.tm_min = to_nonnegative_int(minute(), 60);
1928     format_tm(time, &tm_writer_type::on_minute, ns, pad);
1929   }
1930 
1931   void on_second(numeric_system ns, pad_type pad) {
1932     if (handle_nan_inf()) return;
1933 
1934     if (ns == numeric_system::standard) {
1935       if (std::is_floating_point<rep>::value) {
1936         auto buf = memory_buffer();
1937         write_floating_seconds(buf, std::chrono::duration<rep, Period>(val),
1938                                precision);
1939         if (negative) *out++ = '-';
1940         if (buf.size() < 2 || buf[1] == '.') {
1941           out = detail::write_padding(out, pad);
1942         }
1943         out = std::copy(buf.begin(), buf.end(), out);
1944       } else {
1945         write(second(), 2, pad);
1946         write_fractional_seconds<char_type>(
1947             out, std::chrono::duration<rep, Period>(val), precision);
1948       }
1949       return;
1950     }
1951     auto time = tm();
1952     time.tm_sec = to_nonnegative_int(second(), 60);
1953     format_tm(time, &tm_writer_type::on_second, ns, pad);
1954   }
1955 
1956   void on_12_hour_time() {
1957     if (handle_nan_inf()) return;
1958     format_tm(time(), &tm_writer_type::on_12_hour_time);
1959   }
1960 
1961   void on_24_hour_time() {
1962     if (handle_nan_inf()) {
1963       *out++ = ':';
1964       handle_nan_inf();
1965       return;
1966     }
1967 
1968     write(hour(), 2);
1969     *out++ = ':';
1970     write(minute(), 2);
1971   }
1972 
1973   void on_iso_time() {
1974     on_24_hour_time();
1975     *out++ = ':';
1976     if (handle_nan_inf()) return;
1977     on_second(numeric_system::standard, pad_type::unspecified);
1978   }
1979 
1980   void on_am_pm() {
1981     if (handle_nan_inf()) return;
1982     format_tm(time(), &tm_writer_type::on_am_pm);
1983   }
1984 
1985   void on_duration_value() {
1986     if (handle_nan_inf()) return;
1987     write_sign();
1988     out = format_duration_value<char_type>(out, val, precision);
1989   }
1990 
1991   void on_duration_unit() {
1992     out = format_duration_unit<char_type, Period>(out);
1993   }
1994 };
1995 
1996 }  // namespace detail
1997 
1998 #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
1999 using weekday = std::chrono::weekday;
2000 #else
2001 // A fallback version of weekday.
2002 class weekday {
2003  private:
2004   unsigned char value;
2005 
2006  public:
2007   weekday() = default;
2008   explicit constexpr weekday(unsigned wd) noexcept
2009       : value(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
2010   constexpr auto c_encoding() const noexcept -> unsigned { return value; }
2011 };
2012 
2013 class year_month_day {};
2014 #endif
2015 
2016 // A rudimentary weekday formatter.
2017 template <typename Char> struct formatter<weekday, Char> {
2018  private:
2019   bool localized = false;
2020 
2021  public:
2022   FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
2023       -> decltype(ctx.begin()) {
2024     auto begin = ctx.begin(), end = ctx.end();
2025     if (begin != end && *begin == 'L') {
2026       ++begin;
2027       localized = true;
2028     }
2029     return begin;
2030   }
2031 
2032   template <typename FormatContext>
2033   auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {
2034     auto time = std::tm();
2035     time.tm_wday = static_cast<int>(wd.c_encoding());
2036     detail::get_locale loc(localized, ctx.locale());
2037     auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
2038     w.on_abbr_weekday();
2039     return w.out();
2040   }
2041 };
2042 
2043 template <typename Rep, typename Period, typename Char>
2044 struct formatter<std::chrono::duration<Rep, Period>, Char> {
2045  private:
2046   format_specs<Char> specs_;
2047   detail::arg_ref<Char> width_ref_;
2048   detail::arg_ref<Char> precision_ref_;
2049   bool localized_ = false;
2050   basic_string_view<Char> format_str_;
2051 
2052  public:
2053   FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
2054       -> decltype(ctx.begin()) {
2055     auto it = ctx.begin(), end = ctx.end();
2056     if (it == end || *it == '}') return it;
2057 
2058     it = detail::parse_align(it, end, specs_);
2059     if (it == end) return it;
2060 
2061     it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx);
2062     if (it == end) return it;
2063 
2064     auto checker = detail::chrono_format_checker();
2065     if (*it == '.') {
2066       checker.has_precision_integral = !std::is_floating_point<Rep>::value;
2067       it = detail::parse_precision(it, end, specs_.precision, precision_ref_,
2068                                    ctx);
2069     }
2070     if (it != end && *it == 'L') {
2071       localized_ = true;
2072       ++it;
2073     }
2074     end = detail::parse_chrono_format(it, end, checker);
2075     format_str_ = {it, detail::to_unsigned(end - it)};
2076     return end;
2077   }
2078 
2079   template <typename FormatContext>
2080   auto format(std::chrono::duration<Rep, Period> d, FormatContext& ctx) const
2081       -> decltype(ctx.out()) {
2082     auto specs = specs_;
2083     auto precision = specs.precision;
2084     specs.precision = -1;
2085     auto begin = format_str_.begin(), end = format_str_.end();
2086     // As a possible future optimization, we could avoid extra copying if width
2087     // is not specified.
2088     auto buf = basic_memory_buffer<Char>();
2089     auto out = std::back_inserter(buf);
2090     detail::handle_dynamic_spec<detail::width_checker>(specs.width, width_ref_,
2091                                                        ctx);
2092     detail::handle_dynamic_spec<detail::precision_checker>(precision,
2093                                                            precision_ref_, ctx);
2094     if (begin == end || *begin == '}') {
2095       out = detail::format_duration_value<Char>(out, d.count(), precision);
2096       detail::format_duration_unit<Char, Period>(out);
2097     } else {
2098       using chrono_formatter =
2099           detail::chrono_formatter<FormatContext, decltype(out), Rep, Period>;
2100       auto f = chrono_formatter(ctx, out, d);
2101       f.precision = precision;
2102       f.localized = localized_;
2103       detail::parse_chrono_format(begin, end, f);
2104     }
2105     return detail::write(
2106         ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
2107   }
2108 };
2109 
2110 template <typename Char, typename Duration>
2111 struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
2112                  Char> : formatter<std::tm, Char> {
2113   FMT_CONSTEXPR formatter() {
2114     this->format_str_ = detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>{};
2115   }
2116 
2117   template <typename FormatContext>
2118   auto format(std::chrono::time_point<std::chrono::system_clock, Duration> val,
2119               FormatContext& ctx) const -> decltype(ctx.out()) {
2120     using period = typename Duration::period;
2121     if (detail::const_check(
2122             period::num != 1 || period::den != 1 ||
2123             std::is_floating_point<typename Duration::rep>::value)) {
2124       const auto epoch = val.time_since_epoch();
2125       auto subsecs = detail::fmt_duration_cast<Duration>(
2126           epoch - detail::fmt_duration_cast<std::chrono::seconds>(epoch));
2127 
2128       if (subsecs.count() < 0) {
2129         auto second =
2130             detail::fmt_duration_cast<Duration>(std::chrono::seconds(1));
2131         if (epoch.count() < ((Duration::min)() + second).count())
2132           FMT_THROW(format_error("duration is too small"));
2133         subsecs += second;
2134         val -= second;
2135       }
2136 
2137       return formatter<std::tm, Char>::do_format(gmtime(val), ctx, &subsecs);
2138     }
2139 
2140     return formatter<std::tm, Char>::format(gmtime(val), ctx);
2141   }
2142 };
2143 
2144 #if FMT_USE_LOCAL_TIME
2145 template <typename Char, typename Duration>
2146 struct formatter<std::chrono::local_time<Duration>, Char>
2147     : formatter<std::tm, Char> {
2148   FMT_CONSTEXPR formatter() {
2149     this->format_str_ = detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>{};
2150   }
2151 
2152   template <typename FormatContext>
2153   auto format(std::chrono::local_time<Duration> val, FormatContext& ctx) const
2154       -> decltype(ctx.out()) {
2155     using period = typename Duration::period;
2156     if (period::num != 1 || period::den != 1 ||
2157         std::is_floating_point<typename Duration::rep>::value) {
2158       const auto epoch = val.time_since_epoch();
2159       const auto subsecs = detail::fmt_duration_cast<Duration>(
2160           epoch - detail::fmt_duration_cast<std::chrono::seconds>(epoch));
2161 
2162       return formatter<std::tm, Char>::do_format(localtime(val), ctx, &subsecs);
2163     }
2164 
2165     return formatter<std::tm, Char>::format(localtime(val), ctx);
2166   }
2167 };
2168 #endif
2169 
2170 #if FMT_USE_UTC_TIME
2171 template <typename Char, typename Duration>
2172 struct formatter<std::chrono::time_point<std::chrono::utc_clock, Duration>,
2173                  Char>
2174     : formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
2175                 Char> {
2176   template <typename FormatContext>
2177   auto format(std::chrono::time_point<std::chrono::utc_clock, Duration> val,
2178               FormatContext& ctx) const -> decltype(ctx.out()) {
2179     return formatter<
2180         std::chrono::time_point<std::chrono::system_clock, Duration>,
2181         Char>::format(std::chrono::utc_clock::to_sys(val), ctx);
2182   }
2183 };
2184 #endif
2185 
2186 template <typename Char> struct formatter<std::tm, Char> {
2187  private:
2188   format_specs<Char> specs_;
2189   detail::arg_ref<Char> width_ref_;
2190 
2191  protected:
2192   basic_string_view<Char> format_str_;
2193 
2194   template <typename FormatContext, typename Duration>
2195   auto do_format(const std::tm& tm, FormatContext& ctx,
2196                  const Duration* subsecs) const -> decltype(ctx.out()) {
2197     auto specs = specs_;
2198     auto buf = basic_memory_buffer<Char>();
2199     auto out = std::back_inserter(buf);
2200     detail::handle_dynamic_spec<detail::width_checker>(specs.width, width_ref_,
2201                                                        ctx);
2202 
2203     auto loc_ref = ctx.locale();
2204     detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);
2205     auto w =
2206         detail::tm_writer<decltype(out), Char, Duration>(loc, out, tm, subsecs);
2207     detail::parse_chrono_format(format_str_.begin(), format_str_.end(), w);
2208     return detail::write(
2209         ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
2210   }
2211 
2212  public:
2213   FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
2214       -> decltype(ctx.begin()) {
2215     auto it = ctx.begin(), end = ctx.end();
2216     if (it == end || *it == '}') return it;
2217 
2218     it = detail::parse_align(it, end, specs_);
2219     if (it == end) return it;
2220 
2221     it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx);
2222     if (it == end) return it;
2223 
2224     end = detail::parse_chrono_format(it, end, detail::tm_format_checker());
2225     // Replace the default format_str only if the new spec is not empty.
2226     if (end != it) format_str_ = {it, detail::to_unsigned(end - it)};
2227     return end;
2228   }
2229 
2230   template <typename FormatContext>
2231   auto format(const std::tm& tm, FormatContext& ctx) const
2232       -> decltype(ctx.out()) {
2233     return do_format<FormatContext, std::chrono::seconds>(tm, ctx, nullptr);
2234   }
2235 };
2236 
2237 FMT_END_EXPORT
2238 FMT_END_NAMESPACE
2239 
2240 #endif  // FMT_CHRONO_H_