chrono.h 79 KB

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