chrono.h 72 KB

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