spdlog
Loading...
Searching...
No Matches
bundled/chrono.h
Go to the documentation of this file.
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
8#ifndef FMT_CHRONO_H_
9#define FMT_CHRONO_H_
10
11#include <algorithm>
12#include <chrono>
13#include <ctime>
14#include <locale>
15#include <sstream>
16
17#include "format.h"
18
20
21// Enable safe chrono durations, unless explicitly disabled.
22#ifndef FMT_SAFE_DURATION_CAST
23# define FMT_SAFE_DURATION_CAST 1
24#endif
25#if FMT_SAFE_DURATION_CAST
26
27// For conversion between std::chrono::durations without undefined
28// behaviour or erroneous results.
29// This is a stripped down version of duration_cast, for inclusion in fmt.
30// See https://github.com/pauldreik/safe_duration_cast
31//
32// Copyright Paul Dreik 2019
33namespace safe_duration_cast {
34
35template <typename To, typename From,
39FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
40 ec = 0;
43 static_assert(F::is_integer, "From must be integral");
44 static_assert(T::is_integer, "To must be integral");
45
46 // A and B are both signed, or both unsigned.
47 if (F::digits <= T::digits) {
48 // From fits in To without any problem.
49 } else {
50 // From does not always fit in To, resort to a dynamic check.
51 if (from < (T::min)() || from > (T::max)()) {
52 // outside range.
53 ec = 1;
54 return {};
55 }
56 }
57 return static_cast<To>(from);
58}
59
60/**
61 * converts From to To, without loss. If the dynamic value of from
62 * can't be converted to To without loss, ec is set.
63 */
64template <typename To, typename From,
68FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
69 ec = 0;
72 static_assert(F::is_integer, "From must be integral");
73 static_assert(T::is_integer, "To must be integral");
74
75 if (detail::const_check(F::is_signed && !T::is_signed)) {
76 // From may be negative, not allowed!
77 if (fmt::detail::is_negative(from)) {
78 ec = 1;
79 return {};
80 }
81 // From is positive. Can it always fit in To?
82 if (F::digits > T::digits &&
83 from > static_cast<From>(detail::max_value<To>())) {
84 ec = 1;
85 return {};
86 }
87 }
88
89 if (!F::is_signed && T::is_signed && F::digits >= T::digits &&
90 from > static_cast<From>(detail::max_value<To>())) {
91 ec = 1;
92 return {};
93 }
94 return static_cast<To>(from); // Lossless conversion.
95}
96
97template <typename To, typename From,
99FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
100 ec = 0;
101 return from;
102} // function
103
104// clang-format off
105/**
106 * converts From to To if possible, otherwise ec is set.
107 *
108 * input | output
109 * ---------------------------------|---------------
110 * NaN | NaN
111 * Inf | Inf
112 * normal, fits in output | converted (possibly lossy)
113 * normal, does not fit in output | ec is set
114 * subnormal | best effort
115 * -Inf | -Inf
116 */
117// clang-format on
118template <typename To, typename From,
120FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
121 ec = 0;
123 static_assert(std::is_floating_point<From>::value, "From must be floating");
124 static_assert(std::is_floating_point<To>::value, "To must be floating");
125
126 // catch the only happy case
127 if (std::isfinite(from)) {
128 if (from >= T::lowest() && from <= (T::max)()) {
129 return static_cast<To>(from);
130 }
131 // not within range.
132 ec = 1;
133 return {};
134 }
135
136 // nan and inf will be preserved
137 return static_cast<To>(from);
138} // function
139
140template <typename To, typename From,
142FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
143 ec = 0;
144 static_assert(std::is_floating_point<From>::value, "From must be floating");
145 return from;
146}
147
148/**
149 * safe duration cast between integral durations
150 */
151template <typename To, typename FromRep, typename FromPeriod,
154To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
155 int& ec) {
157 ec = 0;
158 // the basic idea is that we need to convert from count() in the from type
159 // to count() in the To type, by multiplying it with this:
160 struct Factor
161 : std::ratio_divide<typename From::period, typename To::period> {};
162
163 static_assert(Factor::num > 0, "num must be positive");
164 static_assert(Factor::den > 0, "den must be positive");
165
166 // the conversion is like this: multiply from.count() with Factor::num
167 // /Factor::den and convert it to To::rep, all this without
168 // overflow/underflow. let's start by finding a suitable type that can hold
169 // both To, From and Factor::num
170 using IntermediateRep =
171 typename std::common_type<typename From::rep, typename To::rep,
172 decltype(Factor::num)>::type;
173
174 // safe conversion to IntermediateRep
175 IntermediateRep count =
176 lossless_integral_conversion<IntermediateRep>(from.count(), ec);
177 if (ec) return {};
178 // multiply with Factor::num without overflow or underflow
179 if (detail::const_check(Factor::num != 1)) {
180 const auto max1 = detail::max_value<IntermediateRep>() / Factor::num;
181 if (count > max1) {
182 ec = 1;
183 return {};
184 }
185 const auto min1 =
187 if (count < min1) {
188 ec = 1;
189 return {};
190 }
191 count *= Factor::num;
192 }
193
194 if (detail::const_check(Factor::den != 1)) count /= Factor::den;
195 auto tocount = lossless_integral_conversion<typename To::rep>(count, ec);
196 return ec ? To() : To(tocount);
197}
198
199/**
200 * safe duration_cast between floating point durations
201 */
202template <typename To, typename FromRep, typename FromPeriod,
205To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
206 int& ec) {
208 ec = 0;
209 if (std::isnan(from.count())) {
210 // nan in, gives nan out. easy.
212 }
213 // maybe we should also check if from is denormal, and decide what to do about
214 // it.
215
216 // +-inf should be preserved.
217 if (std::isinf(from.count())) {
218 return To{from.count()};
219 }
220
221 // the basic idea is that we need to convert from count() in the from type
222 // to count() in the To type, by multiplying it with this:
223 struct Factor
224 : std::ratio_divide<typename From::period, typename To::period> {};
225
226 static_assert(Factor::num > 0, "num must be positive");
227 static_assert(Factor::den > 0, "den must be positive");
228
229 // the conversion is like this: multiply from.count() with Factor::num
230 // /Factor::den and convert it to To::rep, all this without
231 // overflow/underflow. let's start by finding a suitable type that can hold
232 // both To, From and Factor::num
233 using IntermediateRep =
234 typename std::common_type<typename From::rep, typename To::rep,
235 decltype(Factor::num)>::type;
236
237 // force conversion of From::rep -> IntermediateRep to be safe,
238 // even if it will never happen be narrowing in this context.
239 IntermediateRep count =
240 safe_float_conversion<IntermediateRep>(from.count(), ec);
241 if (ec) {
242 return {};
243 }
244
245 // multiply with Factor::num without overflow or underflow
246 if (Factor::num != 1) {
247 constexpr auto max1 = detail::max_value<IntermediateRep>() /
248 static_cast<IntermediateRep>(Factor::num);
249 if (count > max1) {
250 ec = 1;
251 return {};
252 }
253 constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
254 static_cast<IntermediateRep>(Factor::num);
255 if (count < min1) {
256 ec = 1;
257 return {};
258 }
259 count *= static_cast<IntermediateRep>(Factor::num);
260 }
261
262 // this can't go wrong, right? den>0 is checked earlier.
263 if (Factor::den != 1) {
265 count /= static_cast<common_t>(Factor::den);
266 }
267
268 // convert to the to type, safely
269 using ToRep = typename To::rep;
270
271 const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
272 if (ec) {
273 return {};
274 }
275 return To{tocount};
276}
277} // namespace safe_duration_cast
278#endif
279
280// Prevents expansion of a preceding token as a function-style macro.
281// Usage: f FMT_NOMACRO()
282#define FMT_NOMACRO
283
284namespace detail {
285template <typename T = void> struct null {};
286inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
287inline null<> localtime_s(...) { return null<>(); }
288inline null<> gmtime_r(...) { return null<>(); }
289inline null<> gmtime_s(...) { return null<>(); }
290
291inline auto do_write(const std::tm& time, const std::locale& loc, char format,
292 char modifier) -> std::string {
293 auto&& os = std::ostringstream();
294 os.imbue(loc);
295 using iterator = std::ostreambuf_iterator<char>;
296 const auto& facet = std::use_facet<std::time_put<char, iterator>>(loc);
297 auto end = facet.put(os, os, ' ', &time, format, modifier);
298 if (end.failed()) FMT_THROW(format_error("failed to format time"));
299 auto str = os.str();
300 if (!detail::is_utf8() || loc == std::locale::classic()) return str;
301 // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
302 // gcc-4.
303#if FMT_MSC_VER != 0 || \
304 (defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI))
305 // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
306 // and newer.
307 using code_unit = wchar_t;
308#else
309 using code_unit = char32_t;
310#endif
312 auto mb = std::mbstate_t();
313 const char* from_next = nullptr;
314 code_unit* to_next = nullptr;
315 constexpr size_t buf_size = 32;
316 code_unit buf[buf_size] = {};
317 auto result = f.in(mb, str.data(), str.data() + str.size(), from_next, buf,
318 buf + buf_size, to_next);
319 if (result != std::codecvt_base::ok)
320 FMT_THROW(format_error("failed to format time"));
321 str.clear();
322 for (code_unit* p = buf; p != to_next; ++p) {
323 uint32_t c = static_cast<uint32_t>(*p);
324 if (sizeof(code_unit) == 2 && c >= 0xd800 && c <= 0xdfff) {
325 // surrogate pair
326 ++p;
327 if (p == to_next || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) {
328 FMT_THROW(format_error("failed to format time"));
329 }
330 c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;
331 }
332 if (c < 0x80) {
333 str.push_back(static_cast<char>(c));
334 } else if (c < 0x800) {
335 str.push_back(static_cast<char>(0xc0 | (c >> 6)));
336 str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
337 } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {
338 str.push_back(static_cast<char>(0xe0 | (c >> 12)));
339 str.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
340 str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
341 } else if (c >= 0x10000 && c <= 0x10ffff) {
342 str.push_back(static_cast<char>(0xf0 | (c >> 18)));
343 str.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));
344 str.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
345 str.push_back(static_cast<char>(0x80 | (c & 0x3f)));
346 } else {
347 FMT_THROW(format_error("failed to format time"));
348 }
349 }
350 return str;
351}
352
353template <typename OutputIt>
354auto write(OutputIt out, const std::tm& time, const std::locale& loc,
355 char format, char modifier = 0) -> OutputIt {
356 auto str = do_write(time, loc, format, modifier);
357 return std::copy(str.begin(), str.end(), out);
358}
359} // namespace detail
360
362
363/**
364 Converts given time since epoch as ``std::time_t`` value into calendar time,
365 expressed in local time. Unlike ``std::localtime``, this function is
366 thread-safe on most platforms.
367 */
369 struct dispatcher {
370 std::time_t time_;
371 std::tm tm_;
372
373 dispatcher(std::time_t t) : time_(t) {}
374
375 bool run() {
376 using namespace fmt::detail;
377 return handle(localtime_r(&time_, &tm_));
378 }
379
380 bool handle(std::tm* tm) { return tm != nullptr; }
381
382 bool handle(detail::null<>) {
383 using namespace fmt::detail;
384 return fallback(localtime_s(&tm_, &time_));
385 }
386
387 bool fallback(int res) { return res == 0; }
388
389#if !FMT_MSC_VER
390 bool fallback(detail::null<>) {
391 using namespace fmt::detail;
392 std::tm* tm = std::localtime(&time_);
393 if (tm) tm_ = *tm;
394 return tm != nullptr;
395 }
396#endif
397 };
398 dispatcher lt(time);
399 // Too big time values may be unsupported.
400 if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
401 return lt.tm_;
402}
403
408
409/**
410 Converts given time since epoch as ``std::time_t`` value into calendar time,
411 expressed in Coordinated Universal Time (UTC). Unlike ``std::gmtime``, this
412 function is thread-safe on most platforms.
413 */
415 struct dispatcher {
416 std::time_t time_;
417 std::tm tm_;
418
419 dispatcher(std::time_t t) : time_(t) {}
420
421 bool run() {
422 using namespace fmt::detail;
423 return handle(gmtime_r(&time_, &tm_));
424 }
425
426 bool handle(std::tm* tm) { return tm != nullptr; }
427
428 bool handle(detail::null<>) {
429 using namespace fmt::detail;
430 return fallback(gmtime_s(&tm_, &time_));
431 }
432
433 bool fallback(int res) { return res == 0; }
434
435#if !FMT_MSC_VER
436 bool fallback(detail::null<>) {
437 std::tm* tm = std::gmtime(&time_);
438 if (tm) tm_ = *tm;
439 return tm != nullptr;
440 }
441#endif
442 };
443 dispatcher gt(time);
444 // Too big time values may be unsupported.
445 if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
446 return gt.tm_;
447}
448
453
455
456inline size_t strftime(char* str, size_t count, const char* format,
457 const std::tm* time) {
458 // Assign to a pointer to suppress GCCs -Wformat-nonliteral
459 // First assign the nullptr to suppress -Wsuggest-attribute=format
460 std::size_t (*strftime)(char*, std::size_t, const char*, const std::tm*) =
461 nullptr;
463 return strftime(str, count, format, time);
464}
465
466inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format,
467 const std::tm* time) {
468 // See above
469 std::size_t (*wcsftime)(wchar_t*, std::size_t, const wchar_t*,
470 const std::tm*) = nullptr;
471 wcsftime = std::wcsftime;
472 return wcsftime(str, count, format, time);
473}
474
476
477template <typename Char, typename Duration>
478struct formatter<std::chrono::time_point<std::chrono::system_clock, Duration>,
479 Char> : formatter<std::tm, Char> {
481 this->specs = {default_specs, sizeof(default_specs) / sizeof(Char)};
482 }
483
484 template <typename ParseContext>
485 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
486 auto it = ctx.begin();
487 if (it != ctx.end() && *it == ':') ++it;
488 auto end = it;
489 while (end != ctx.end() && *end != '}') ++end;
490 if (end != it) this->specs = {it, detail::to_unsigned(end - it)};
491 return end;
492 }
493
494 template <typename FormatContext>
496 FormatContext& ctx) -> decltype(ctx.out()) {
497 std::tm time = localtime(val);
498 return formatter<std::tm, Char>::format(time, ctx);
499 }
500
501 static constexpr Char default_specs[] = {'%', 'Y', '-', '%', 'm', '-',
502 '%', 'd', ' ', '%', 'H', ':',
503 '%', 'M', ':', '%', 'S'};
504};
505
506template <typename Char, typename Duration>
507constexpr Char
509 Char>::default_specs[];
510
511template <typename Char> struct formatter<std::tm, Char> {
512 template <typename ParseContext>
513 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
514 auto it = ctx.begin();
515 if (it != ctx.end() && *it == ':') ++it;
516 auto end = it;
517 while (end != ctx.end() && *end != '}') ++end;
518 specs = {it, detail::to_unsigned(end - it)};
519 return end;
520 }
521
522 template <typename FormatContext>
523 auto format(const std::tm& tm, FormatContext& ctx) const
524 -> decltype(ctx.out()) {
526 tm_format.append(specs.begin(), specs.end());
527 // By appending an extra space we can distinguish an empty result that
528 // indicates insufficient buffer size from a guaranteed non-empty result
529 // https://github.com/fmtlib/fmt/issues/2238
530 tm_format.push_back(' ');
531 tm_format.push_back('\0');
533 size_t start = buf.size();
534 for (;;) {
535 size_t size = buf.capacity() - start;
536 size_t count = detail::strftime(&buf[start], size, &tm_format[0], &tm);
537 if (count != 0) {
538 buf.resize(start + count);
539 break;
540 }
541 const size_t MIN_GROWTH = 10;
542 buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH));
543 }
544 // Remove the extra space.
545 return std::copy(buf.begin(), buf.end() - 1, ctx.out());
546 }
547
549};
550
552
553template <typename Period> FMT_CONSTEXPR inline const char* get_units() {
562 if (std::is_same<Period, std::ratio<1>>::value) return "s";
571 if (std::is_same<Period, std::ratio<60>>::value) return "m";
572 if (std::is_same<Period, std::ratio<3600>>::value) return "h";
573 return nullptr;
574}
575
576enum class numeric_system {
577 standard,
578 // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
580};
581
582// Parses a put_time-like format string and invokes handler actions.
583template <typename Char, typename Handler>
584FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
585 const Char* end,
586 Handler&& handler) {
587 auto ptr = begin;
588 while (ptr != end) {
589 auto c = *ptr;
590 if (c == '}') break;
591 if (c != '%') {
592 ++ptr;
593 continue;
594 }
595 if (begin != ptr) handler.on_text(begin, ptr);
596 ++ptr; // consume '%'
597 if (ptr == end) FMT_THROW(format_error("invalid format"));
598 c = *ptr++;
599 switch (c) {
600 case '%':
601 handler.on_text(ptr - 1, ptr);
602 break;
603 case 'n': {
604 const Char newline[] = {'\n'};
605 handler.on_text(newline, newline + 1);
606 break;
607 }
608 case 't': {
609 const Char tab[] = {'\t'};
610 handler.on_text(tab, tab + 1);
611 break;
612 }
613 // Day of the week:
614 case 'a':
615 handler.on_abbr_weekday();
616 break;
617 case 'A':
618 handler.on_full_weekday();
619 break;
620 case 'w':
621 handler.on_dec0_weekday(numeric_system::standard);
622 break;
623 case 'u':
624 handler.on_dec1_weekday(numeric_system::standard);
625 break;
626 // Month:
627 case 'b':
628 handler.on_abbr_month();
629 break;
630 case 'B':
631 handler.on_full_month();
632 break;
633 // Hour, minute, second:
634 case 'H':
635 handler.on_24_hour(numeric_system::standard);
636 break;
637 case 'I':
638 handler.on_12_hour(numeric_system::standard);
639 break;
640 case 'M':
641 handler.on_minute(numeric_system::standard);
642 break;
643 case 'S':
644 handler.on_second(numeric_system::standard);
645 break;
646 // Other:
647 case 'c':
648 handler.on_datetime(numeric_system::standard);
649 break;
650 case 'x':
651 handler.on_loc_date(numeric_system::standard);
652 break;
653 case 'X':
654 handler.on_loc_time(numeric_system::standard);
655 break;
656 case 'D':
657 handler.on_us_date();
658 break;
659 case 'F':
660 handler.on_iso_date();
661 break;
662 case 'r':
663 handler.on_12_hour_time();
664 break;
665 case 'R':
666 handler.on_24_hour_time();
667 break;
668 case 'T':
669 handler.on_iso_time();
670 break;
671 case 'p':
672 handler.on_am_pm();
673 break;
674 case 'Q':
675 handler.on_duration_value();
676 break;
677 case 'q':
678 handler.on_duration_unit();
679 break;
680 case 'z':
681 handler.on_utc_offset();
682 break;
683 case 'Z':
684 handler.on_tz_name();
685 break;
686 // Alternative representation:
687 case 'E': {
688 if (ptr == end) FMT_THROW(format_error("invalid format"));
689 c = *ptr++;
690 switch (c) {
691 case 'c':
692 handler.on_datetime(numeric_system::alternative);
693 break;
694 case 'x':
695 handler.on_loc_date(numeric_system::alternative);
696 break;
697 case 'X':
698 handler.on_loc_time(numeric_system::alternative);
699 break;
700 default:
701 FMT_THROW(format_error("invalid format"));
702 }
703 break;
704 }
705 case 'O':
706 if (ptr == end) FMT_THROW(format_error("invalid format"));
707 c = *ptr++;
708 switch (c) {
709 case 'w':
710 handler.on_dec0_weekday(numeric_system::alternative);
711 break;
712 case 'u':
713 handler.on_dec1_weekday(numeric_system::alternative);
714 break;
715 case 'H':
716 handler.on_24_hour(numeric_system::alternative);
717 break;
718 case 'I':
719 handler.on_12_hour(numeric_system::alternative);
720 break;
721 case 'M':
722 handler.on_minute(numeric_system::alternative);
723 break;
724 case 'S':
725 handler.on_second(numeric_system::alternative);
726 break;
727 default:
728 FMT_THROW(format_error("invalid format"));
729 }
730 break;
731 default:
732 FMT_THROW(format_error("invalid format"));
733 }
734 begin = ptr;
735 }
736 if (begin != ptr) handler.on_text(begin, ptr);
737 return ptr;
738}
739
740template <typename Derived> struct null_chrono_spec_handler {
742 static_cast<Derived*>(this)->unsupported();
743 }
767};
768
785
786template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
787inline bool isnan(T) {
788 return false;
789}
790template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
791inline bool isnan(T value) {
792 return std::isnan(value);
793}
794
795template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
796inline bool isfinite(T) {
797 return true;
798}
799template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
800inline bool isfinite(T value) {
801 return std::isfinite(value);
802}
803
804// Converts value to int and checks that it's in the range [0, upper).
805template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
806inline int to_nonnegative_int(T value, int upper) {
807 FMT_ASSERT(value >= 0 && to_unsigned(value) <= to_unsigned(upper),
808 "invalid value");
809 (void)upper;
810 return static_cast<int>(value);
811}
812template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
813inline int to_nonnegative_int(T value, int upper) {
815 std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)),
816 "invalid value");
817 (void)upper;
818 return static_cast<int>(value);
819}
820
821template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
822inline T mod(T x, int y) {
823 return x % static_cast<T>(y);
824}
825template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
826inline T mod(T x, int y) {
827 return std::fmod(x, static_cast<T>(y));
828}
829
830// If T is an integral type, maps T to its unsigned counterpart, otherwise
831// leaves it unchanged (unlike std::make_unsigned).
832template <typename T, bool INTEGRAL = std::is_integral<T>::value>
834 using type = T;
835};
836
837template <typename T> struct make_unsigned_or_unchanged<T, true> {
839};
840
841#if FMT_SAFE_DURATION_CAST
842// throwing version of safe_duration_cast
843template <typename To, typename FromRep, typename FromPeriod>
844To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) {
845 int ec;
846 To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
847 if (ec) FMT_THROW(format_error("cannot format duration"));
848 return to;
849}
850#endif
851
852template <typename Rep, typename Period,
856 // this may overflow and/or the result may not fit in the
857 // target type.
858#if FMT_SAFE_DURATION_CAST
859 using CommonSecondsType =
860 typename std::common_type<decltype(d), std::chrono::seconds>::type;
861 const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d);
862 const auto d_as_whole_seconds =
863 fmt_safe_duration_cast<std::chrono::seconds>(d_as_common);
864 // this conversion should be nonproblematic
865 const auto diff = d_as_common - d_as_whole_seconds;
866 const auto ms =
867 fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
868 return ms;
869#else
870 auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
871 return std::chrono::duration_cast<std::chrono::milliseconds>(d - s);
872#endif
873}
874
875template <typename Rep, typename Period,
879 using common_type = typename std::common_type<Rep, std::intmax_t>::type;
880 auto ms = mod(d.count() * static_cast<common_type>(Period::num) /
881 static_cast<common_type>(Period::den) * 1000,
882 1000);
883 return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms));
884}
885
886template <typename Char, typename Rep, typename OutputIt,
888OutputIt format_duration_value(OutputIt out, Rep val, int) {
889 return write<Char>(out, val);
890}
891
892template <typename Char, typename Rep, typename OutputIt,
894OutputIt format_duration_value(OutputIt out, Rep val, int precision) {
895 auto specs = basic_format_specs<Char>();
896 specs.precision = precision;
897 specs.type = precision > 0 ? 'f' : 'g';
898 return write<Char>(out, val, specs);
899}
900
901template <typename Char, typename OutputIt>
902OutputIt copy_unit(string_view unit, OutputIt out, Char) {
903 return std::copy(unit.begin(), unit.end(), out);
904}
905
906template <typename OutputIt>
907OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) {
908 // This works when wchar_t is UTF-32 because units only contain characters
909 // that have the same representation in UTF-16 and UTF-32.
910 utf8_to_utf16 u(unit);
911 return std::copy(u.c_str(), u.c_str() + u.size(), out);
912}
913
914template <typename Char, typename Period, typename OutputIt>
915OutputIt format_duration_unit(OutputIt out) {
916 if (const char* unit = get_units<Period>())
917 return copy_unit(string_view(unit), out, Char());
918 *out++ = '[';
919 out = write<Char>(out, Period::num);
920 if (const_check(Period::den != 1)) {
921 *out++ = '/';
922 out = write<Char>(out, Period::den);
923 }
924 *out++ = ']';
925 *out++ = 's';
926 return out;
927}
928
929template <typename FormatContext, typename OutputIt, typename Rep,
930 typename Period>
932 FormatContext& context;
933 OutputIt out;
935 bool localized = false;
936 // rep is unsigned to avoid overflow.
937 using rep =
938 conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
939 unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
945
946 using char_type = typename FormatContext::char_type;
947
948 explicit chrono_formatter(FormatContext& ctx, OutputIt o,
950 : context(ctx),
951 out(o),
952 val(static_cast<rep>(d.count())),
953 negative(false) {
954 if (d.count() < 0) {
955 val = 0 - val;
956 negative = true;
957 }
958
959 // this may overflow and/or the result may not fit in the
960 // target type.
961#if FMT_SAFE_DURATION_CAST
962 // might need checked conversion (rep!=Rep)
964 s = fmt_safe_duration_cast<seconds>(tmpval);
965#else
966 s = std::chrono::duration_cast<seconds>(
968#endif
969 }
970
971 // returns true if nan or inf, writes to out.
973 if (isfinite(val)) {
974 return false;
975 }
976 if (isnan(val)) {
977 write_nan();
978 return true;
979 }
980 // must be +-inf
981 if (val > 0) {
982 write_pinf();
983 } else {
984 write_ninf();
985 }
986 return true;
987 }
988
989 Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); }
990
991 Rep hour12() const {
992 Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
993 return hour <= 0 ? 12 : hour;
994 }
995
996 Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); }
997 Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); }
998
999 std::tm time() const {
1000 auto time = std::tm();
1001 time.tm_hour = to_nonnegative_int(hour(), 24);
1002 time.tm_min = to_nonnegative_int(minute(), 60);
1003 time.tm_sec = to_nonnegative_int(second(), 60);
1004 return time;
1005 }
1006
1007 void write_sign() {
1008 if (negative) {
1009 *out++ = '-';
1010 negative = false;
1011 }
1012 }
1013
1014 void write(Rep value, int width) {
1015 write_sign();
1016 if (isnan(value)) return write_nan();
1018 to_unsigned(to_nonnegative_int(value, max_value<int>()));
1019 int num_digits = detail::count_digits(n);
1020 if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
1021 out = format_decimal<char_type>(out, n, num_digits).end;
1022 }
1023
1024 void write_nan() { std::copy_n("nan", 3, out); }
1025 void write_pinf() { std::copy_n("inf", 3, out); }
1026 void write_ninf() { std::copy_n("-inf", 4, out); }
1027
1028 void format_localized(const tm& time, char format, char modifier = 0) {
1029 if (isnan(val)) return write_nan();
1030 const auto& loc = localized ? context.locale().template get<std::locale>()
1032 out = detail::write(out, time, loc, format, modifier);
1033 }
1034
1035 void on_text(const char_type* begin, const char_type* end) {
1036 std::copy(begin, end, out);
1037 }
1038
1039 // These are not implemented because durations don't have date information.
1049 void on_us_date() {}
1050 void on_iso_date() {}
1052 void on_tz_name() {}
1053
1055 if (handle_nan_inf()) return;
1056
1057 if (ns == numeric_system::standard) return write(hour(), 2);
1058 auto time = tm();
1059 time.tm_hour = to_nonnegative_int(hour(), 24);
1060 format_localized(time, 'H', 'O');
1061 }
1062
1064 if (handle_nan_inf()) return;
1065
1066 if (ns == numeric_system::standard) return write(hour12(), 2);
1067 auto time = tm();
1068 time.tm_hour = to_nonnegative_int(hour12(), 12);
1069 format_localized(time, 'I', 'O');
1070 }
1071
1073 if (handle_nan_inf()) return;
1074
1075 if (ns == numeric_system::standard) return write(minute(), 2);
1076 auto time = tm();
1077 time.tm_min = to_nonnegative_int(minute(), 60);
1078 format_localized(time, 'M', 'O');
1079 }
1080
1082 if (handle_nan_inf()) return;
1083
1084 if (ns == numeric_system::standard) {
1085 write(second(), 2);
1086#if FMT_SAFE_DURATION_CAST
1087 // convert rep->Rep
1088 using duration_rep = std::chrono::duration<rep, Period>;
1089 using duration_Rep = std::chrono::duration<Rep, Period>;
1090 auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val});
1091#else
1093#endif
1094 auto ms = get_milliseconds(tmpval);
1095 if (ms != std::chrono::milliseconds(0)) {
1096 *out++ = '.';
1097 write(ms.count(), 3);
1098 }
1099 return;
1100 }
1101 auto time = tm();
1102 time.tm_sec = to_nonnegative_int(second(), 60);
1103 format_localized(time, 'S', 'O');
1104 }
1105
1107 if (handle_nan_inf()) return;
1108 format_localized(time(), 'r');
1109 }
1110
1112 if (handle_nan_inf()) {
1113 *out++ = ':';
1115 return;
1116 }
1117
1118 write(hour(), 2);
1119 *out++ = ':';
1120 write(minute(), 2);
1121 }
1122
1125 *out++ = ':';
1126 if (handle_nan_inf()) return;
1127 write(second(), 2);
1128 }
1129
1130 void on_am_pm() {
1131 if (handle_nan_inf()) return;
1132 format_localized(time(), 'p');
1133 }
1134
1136 if (handle_nan_inf()) return;
1137 write_sign();
1138 out = format_duration_value<char_type>(out, val, precision);
1139 }
1140
1142 out = format_duration_unit<char_type, Period>(out);
1143 }
1144};
1145
1147
1148#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
1149using weekday = std::chrono::weekday;
1150#else
1151// A fallback version of weekday.
1152class weekday {
1153 private:
1154 unsigned char value;
1155
1156 public:
1157 weekday() = default;
1158 explicit constexpr weekday(unsigned wd) noexcept
1159 : value(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
1160 constexpr unsigned c_encoding() const noexcept { return value; }
1161};
1162#endif
1163
1164// A rudimentary weekday formatter.
1165template <> struct formatter<weekday> {
1166 private:
1167 bool localized = false;
1168
1169 public:
1170 FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
1171 auto begin = ctx.begin(), end = ctx.end();
1172 if (begin != end && *begin == 'L') {
1173 ++begin;
1174 localized = true;
1175 }
1176 return begin;
1177 }
1178
1179 auto format(weekday wd, format_context& ctx) -> decltype(ctx.out()) {
1180 auto time = std::tm();
1181 time.tm_wday = static_cast<int>(wd.c_encoding());
1182 const auto& loc = localized ? ctx.locale().template get<std::locale>()
1184 return detail::write(ctx.out(), time, loc, 'a');
1185 }
1186};
1187
1188template <typename Rep, typename Period, typename Char>
1189struct formatter<std::chrono::duration<Rep, Period>, Char> {
1190 private:
1192 int precision = -1;
1193 using arg_ref_type = detail::arg_ref<Char>;
1196 bool localized = false;
1199
1200 struct spec_handler {
1204
1205 template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
1206 context.check_arg_id(arg_id);
1207 return arg_ref_type(arg_id);
1208 }
1209
1211 context.check_arg_id(arg_id);
1212 return arg_ref_type(arg_id);
1213 }
1214
1216 return arg_ref_type(context.next_arg_id());
1217 }
1218
1219 void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
1221 f.specs.fill = fill;
1222 }
1223 FMT_CONSTEXPR void on_align(align_t align) { f.specs.align = align; }
1224 FMT_CONSTEXPR void on_width(int width) { f.specs.width = width; }
1225 FMT_CONSTEXPR void on_precision(int _precision) {
1226 f.precision = _precision;
1227 }
1229
1230 template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
1231 f.width_ref = make_arg_ref(arg_id);
1232 }
1233
1234 template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
1235 f.precision_ref = make_arg_ref(arg_id);
1236 }
1237 };
1238
1240 struct parse_range {
1243 };
1244
1246 auto begin = ctx.begin(), end = ctx.end();
1247 if (begin == end || *begin == '}') return {begin, begin};
1248 spec_handler handler{*this, ctx, format_str};
1249 begin = detail::parse_align(begin, end, handler);
1250 if (begin == end) return {begin, begin};
1251 begin = detail::parse_width(begin, end, handler);
1252 if (begin == end) return {begin, begin};
1253 if (*begin == '.') {
1255 begin = detail::parse_precision(begin, end, handler);
1256 else
1257 handler.on_error("precision not allowed for this argument type");
1258 }
1259 if (begin != end && *begin == 'L') {
1260 ++begin;
1261 localized = true;
1262 }
1263 end = parse_chrono_format(begin, end, detail::chrono_format_checker());
1264 return {begin, end};
1265 }
1266
1267 public:
1269 -> decltype(ctx.begin()) {
1270 auto range = do_parse(ctx);
1271 format_str = basic_string_view<Char>(
1272 &*range.begin, detail::to_unsigned(range.end - range.begin));
1273 return range.end;
1274 }
1275
1276 template <typename FormatContext>
1277 auto format(const duration& d, FormatContext& ctx) const
1278 -> decltype(ctx.out()) {
1279 auto specs_copy = specs;
1280 auto precision_copy = precision;
1281 auto begin = format_str.begin(), end = format_str.end();
1282 // As a possible future optimization, we could avoid extra copying if width
1283 // is not specified.
1285 auto out = std::back_inserter(buf);
1286 detail::handle_dynamic_spec<detail::width_checker>(specs_copy.width,
1287 width_ref, ctx);
1288 detail::handle_dynamic_spec<detail::precision_checker>(precision_copy,
1289 precision_ref, ctx);
1290 if (begin == end || *begin == '}') {
1291 out = detail::format_duration_value<Char>(out, d.count(), precision_copy);
1292 detail::format_duration_unit<Char, Period>(out);
1293 } else {
1294 detail::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
1295 ctx, out, d);
1296 f.precision = precision_copy;
1297 f.localized = localized;
1298 detail::parse_chrono_format(begin, end, f);
1299 }
1300 return detail::write(
1301 ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs_copy);
1302 }
1303};
1304
1307
1308#endif // FMT_CHRONO_H_
T back_inserter(T... args)
#define FMT_NOMACRO
FMT_CONSTEXPR const Char * parse_chrono_format(const Char *begin, const Char *end, Handler &&handler)
numeric_system
OutputIt copy_unit(string_view unit, OutputIt out, Char)
OutputIt format_duration_value(OutputIt out, Rep val, int)
FMT_MODULE_EXPORT_BEGIN std::tm localtime(std::time_t time)
bool isnan(T)
std::chrono::duration< Rep, std::milli > get_milliseconds(std::chrono::duration< Rep, Period > d)
OutputIt format_duration_unit(OutputIt out)
std::tm gmtime(std::time_t time)
bool isfinite(T)
int to_nonnegative_int(T value, int upper)
T mod(T x, int y)
FMT_BEGIN_DETAIL_NAMESPACE size_t strftime(char *str, size_t count, const char *format, const std::tm *time)
FMT_BEGIN_DETAIL_NAMESPACE FMT_CONSTEXPR const char * get_units()
constexpr auto end() const FMT_NOEXCEPT -> iterator
Definition core.h:645
FMT_CONSTEXPR void check_arg_id(int)
Definition core.h:670
typename basic_string_view< Char >::iterator iterator
Definition core.h:627
FMT_CONSTEXPR auto next_arg_id() -> int
Definition core.h:658
constexpr auto begin() const FMT_NOEXCEPT -> iterator
Definition core.h:638
void reserve(size_t new_capacity)
Definition format.h:701
void append(const ContiguousRange &range)
Definition format.h:706
void resize(size_t count)
Definition format.h:698
constexpr auto end() const -> iterator
Definition core.h:487
constexpr auto begin() const -> iterator
Definition core.h:486
T classic(T... args)
auto size() const -> size_t
Definition format.h:1147
auto c_str() const -> const wchar_t *
Definition format.h:1148
Definition core.h:1120
unsigned char value
constexpr weekday(unsigned wd) noexcept
weekday()=default
constexpr unsigned c_encoding() const noexcept
std::basic_string< Char > format(const text_style &ts, const S &format_str, const Args &... args)
Definition color.h:583
T copy(T... args)
T copy_n(T... args)
#define FMT_ASSERT(condition, message)
Definition core.h:372
#define FMT_END_DETAIL_NAMESPACE
Definition core.h:245
#define FMT_MODULE_EXPORT_BEGIN
Definition core.h:242
constexpr auto count() -> size_t
Definition core.h:1039
#define FMT_CONSTEXPR
Definition core.h:99
type
Definition core.h:1048
#define FMT_BEGIN_NAMESPACE
Definition core.h:235
#define FMT_BEGIN_DETAIL_NAMESPACE
Definition core.h:244
constexpr auto const_check(T value) -> T
Definition core.h:361
#define FMT_ENABLE_IF(...)
Definition core.h:347
FMT_CONSTEXPR auto to_unsigned(Int value) -> typename std::make_unsigned< Int >::type
Definition core.h:412
#define FMT_NORETURN
Definition core.h:166
typename std::conditional< B, T, F >::type conditional_t
Definition core.h:323
T
Definition core.h:320
#define FMT_END_NAMESPACE
Definition core.h:230
#define FMT_MODULE_EXPORT_END
Definition core.h:243
T fill_n(T... args)
T fmod(T... args)
template FMT_API std::locale detail::locale_ref::get< std::locale >() const
conditional_t< num_bits< T >()<=32 &&!FMT_REDUCE_INT_INSTANTIATIONS, uint32_t, conditional_t< num_bits< T >()<=64, uint64_t, uint128_t > > uint32_or_64_or_128_t
Definition format.h:847
FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n, const fill_t< Char > &fill) -> OutputIt
Definition format.h:1264
#define FMT_THROW(x)
Definition format.h:96
auto ptr(T p) -> const void *
Definition format.h:2451
T gmtime(T... args)
T isfinite(T... args)
T isinf(T... args)
T isnan(T... args)
T localtime(T... args)
T lowest(T... args)
T make_shared(T... args)
Definition core.h:1858
type
Definition core.h:1859
Definition args.h:19
null gmtime_s(...)
null gmtime_r(...)
auto write(OutputIt out, const std::tm &time, const std::locale &loc, char format, char modifier=0) -> OutputIt
null localtime_s(...)
auto do_write(const std::tm &time, const std::locale &loc, char format, char modifier) -> std::string
T quiet_NaN(T... args)
T strftime(T... args)
FMT_CONSTEXPR void on_duration_unit()
FMT_CONSTEXPR void on_am_pm()
FMT_CONSTEXPR void on_24_hour_time()
FMT_CONSTEXPR void on_iso_time()
FMT_CONSTEXPR void on_duration_value()
FMT_CONSTEXPR void on_minute(numeric_system)
FMT_NORETURN void unsupported()
FMT_CONSTEXPR void on_12_hour(numeric_system)
FMT_CONSTEXPR void on_24_hour(numeric_system)
FMT_CONSTEXPR void on_second(numeric_system)
FMT_CONSTEXPR void on_12_hour_time()
FMT_CONSTEXPR void on_text(const Char *, const Char *)
void on_datetime(numeric_system)
typename FormatContext::char_type char_type
void on_minute(numeric_system ns)
void on_second(numeric_system ns)
void on_text(const char_type *begin, const char_type *end)
void on_dec0_weekday(numeric_system)
void on_loc_date(numeric_system)
void on_12_hour(numeric_system ns)
void format_localized(const tm &time, char format, char modifier=0)
void write(Rep value, int width)
FormatContext & context
chrono_formatter(FormatContext &ctx, OutputIt o, std::chrono::duration< Rep, Period > d)
std::tm time() const
void on_loc_time(numeric_system)
void on_24_hour(numeric_system ns)
conditional_t< std::is_integral< Rep >::value &&sizeof(Rep)< sizeof(int), unsigned, typename make_unsigned_or_unchanged< Rep >::type > rep
void on_dec1_weekday(numeric_system)
FMT_CONSTEXPR void on_fill(basic_string_view< Char > fill)
FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view< Char > arg_id)
FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context< Char > &ctx)
typename basic_format_parse_context< Char >::iterator iterator
FMT_CONSTEXPR auto parse(basic_format_parse_context< Char > &ctx) -> decltype(ctx.begin())
auto format(const duration &d, FormatContext &ctx) const -> decltype(ctx.out())
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin())
auto format(std::chrono::time_point< std::chrono::system_clock > val, FormatContext &ctx) -> decltype(ctx.out())
auto format(const std::tm &tm, FormatContext &ctx) const -> decltype(ctx.out())
basic_string_view< Char > specs
FMT_CONSTEXPR auto parse(ParseContext &ctx) -> decltype(ctx.begin())
auto format(weekday wd, format_context &ctx) -> decltype(ctx.out())
FMT_CONSTEXPR auto parse(format_parse_context &ctx) -> decltype(ctx.begin())
typename std::make_unsigned< T >::type type
FMT_CONSTEXPR void on_datetime(numeric_system)
FMT_CONSTEXPR void on_full_month()
FMT_CONSTEXPR void on_second(numeric_system)
FMT_CONSTEXPR void on_abbr_month()
FMT_CONSTEXPR void on_us_date()
FMT_CONSTEXPR void on_am_pm()
FMT_CONSTEXPR void on_dec0_weekday(numeric_system)
FMT_CONSTEXPR void on_abbr_weekday()
FMT_CONSTEXPR void on_utc_offset()
FMT_CONSTEXPR void on_iso_date()
FMT_CONSTEXPR void on_duration_unit()
FMT_CONSTEXPR void on_24_hour(numeric_system)
FMT_CONSTEXPR void on_12_hour(numeric_system)
FMT_CONSTEXPR void on_full_weekday()
FMT_CONSTEXPR void unsupported()
FMT_CONSTEXPR void on_duration_value()
FMT_CONSTEXPR void on_12_hour_time()
FMT_CONSTEXPR void on_loc_date(numeric_system)
FMT_CONSTEXPR void on_iso_time()
FMT_CONSTEXPR void on_dec1_weekday(numeric_system)
FMT_CONSTEXPR void on_24_hour_time()
FMT_CONSTEXPR void on_loc_time(numeric_system)
FMT_CONSTEXPR void on_minute(numeric_system)
FMT_CONSTEXPR void on_tz_name()
T wcsftime(T... args)