chrono.h 78 KB

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