You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

chrono.h 79 kB

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