chrono.h 76 KB

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