chrono.h 78 KB

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