libstdc++
chrono_io.h
Go to the documentation of this file.
1// <chrono> Formatting -*- C++ -*-
2
3// Copyright The GNU Toolchain Authors.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/bits/chrono_io.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{chrono}
28 */
29
30#ifndef _GLIBCXX_CHRONO_IO_H
31#define _GLIBCXX_CHRONO_IO_H 1
32
33#pragma GCC system_header
34
35#if __cplusplus >= 202002L
36
37#include <sstream> // ostringstream
38#include <iomanip> // setw, setfill
39#include <format>
40#include <charconv> // from_chars
41
43
44namespace std _GLIBCXX_VISIBILITY(default)
45{
46_GLIBCXX_BEGIN_NAMESPACE_VERSION
47
48namespace chrono
49{
50/// @addtogroup chrono
51/// @{
52
53/// @cond undocumented
54namespace __detail
55{
56 // STATICALLY-WIDEN, see C++20 [time.general]
57 // It doesn't matter for format strings (which can only be char or wchar_t)
58 // but this returns the narrow string for anything that isn't wchar_t. This
59 // is done because const char* can be inserted into any ostream type, and
60 // will be widened at runtime if necessary.
61 template<typename _CharT>
62 consteval auto
63 _Widen(const char* __narrow, const wchar_t* __wide)
64 {
65 if constexpr (is_same_v<_CharT, wchar_t>)
66 return __wide;
67 else
68 return __narrow;
69 }
70#define _GLIBCXX_WIDEN_(C, S) ::std::chrono::__detail::_Widen<C>(S, L##S)
71#define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
72
73 template<typename _Period, typename _CharT>
75 __units_suffix() noexcept
76 {
77 // The standard say these are all narrow strings, which would need to
78 // be widened at run-time when inserted into a wide stream. We use
79 // STATICALLY-WIDEN to widen at compile-time.
80#define _GLIBCXX_UNITS_SUFFIX(period, suffix) \
81 if constexpr (is_same_v<_Period, period>) \
82 return _GLIBCXX_WIDEN(suffix); \
83 else
84
90#if _GLIBCXX_USE_ALT_MICROSECONDS_SUFFIX
91 // Deciding this at compile-time is wrong, maybe use nl_langinfo(CODESET)
92 // to check runtime environment and return u8"\u00b5s", "\xb5s", or "us".
94#else
96#endif
112#undef _GLIBCXX_UNITS_SUFFIX
113 return {};
114 }
115
116 template<typename _Period, typename _CharT, typename _Out>
117 inline _Out
118 __fmt_units_suffix(_Out __out) noexcept
119 {
120 if (auto __s = __detail::__units_suffix<_Period, _CharT>(); __s.size())
121 return __format::__write(std::move(__out), __s);
122 else if constexpr (_Period::den == 1)
124 (uintmax_t)_Period::num);
125 else
126 return std::format_to(std::move(__out), _GLIBCXX_WIDEN("[{}/{}]s"),
127 (uintmax_t)_Period::num,
128 (uintmax_t)_Period::den);
129 }
130} // namespace __detail
131/// @endcond
132
133 /** Write a `chrono::duration` to an ostream.
134 *
135 * @since C++20
136 */
137 template<typename _CharT, typename _Traits,
138 typename _Rep, typename _Period>
141 const duration<_Rep, _Period>& __d)
142 {
144 using period = typename _Period::type;
146 __s.flags(__os.flags());
147 __s.imbue(__os.getloc());
148 __s.precision(__os.precision());
149 __s << __d.count();
150 __detail::__fmt_units_suffix<period, _CharT>(_Out(__s));
151 __os << std::move(__s).str();
152 return __os;
153 }
154
155/// @cond undocumented
156namespace __detail
157{
158 // An unspecified type returned by `chrono::local_time_format`.
159 template<typename _Duration>
160 struct __local_time_fmt
161 {
163 const string* _M_abbrev;
164 const seconds* _M_offset_sec;
165 };
166
167 struct __local_fmt_t;
168}
169/// @endcond
170
171 /** Return an object that asssociates timezone info with a local time.
172 *
173 * A `chrono::local_time` object has no timezone associated with it. This
174 * function creates an object that allows formatting a `local_time` as
175 * though it refers to a timezone with the given abbreviated name and
176 * offset from UTC.
177 *
178 * @since C++20
179 */
180 template<typename _Duration>
181 inline __detail::__local_time_fmt<_Duration>
183 const string* __abbrev = nullptr,
184 const seconds* __offset_sec = nullptr)
185 { return {__time, __abbrev, __offset_sec}; }
186
187 /// @}
188} // namespace chrono
189
190/// @cond undocumented
191namespace __format
192{
193 [[noreturn,__gnu__::__always_inline__]]
194 inline void
195 __no_timezone_available()
196 { __throw_format_error("format error: no timezone available for %Z or %z"); }
197
198 [[noreturn,__gnu__::__always_inline__]]
199 inline void
200 __not_valid_for_duration()
201 { __throw_format_error("format error: chrono-format-spec not valid for "
202 "chrono::duration"); }
203
204 [[noreturn,__gnu__::__always_inline__]]
205 inline void
206 __invalid_chrono_spec()
207 { __throw_format_error("format error: chrono-format-spec not valid for "
208 "argument type"); }
209
210 template<typename _CharT>
211 struct _ChronoSpec : _Spec<_CharT>
212 {
213 basic_string_view<_CharT> _M_chrono_specs;
214 };
215
216 // Represents the information provided by a chrono type.
217 // e.g. month_weekday has month and weekday but no year or time of day,
218 // hh_mm_ss has time of day but no date, sys_time is time_point+timezone.
219 enum _ChronoParts {
220 _Year = 1, _Month = 2, _Day = 4, _Weekday = 8, _TimeOfDay = 16,
221 _TimeZone = 32,
222 _Date = _Year | _Month | _Day | _Weekday,
223 _DateTime = _Date | _TimeOfDay,
224 _ZonedDateTime = _DateTime | _TimeZone,
225 _Duration = 128 // special case
226 };
227
228 constexpr _ChronoParts
229 operator|(_ChronoParts __x, _ChronoParts __y) noexcept
230 { return static_cast<_ChronoParts>((int)__x | (int)__y); }
231
232 constexpr _ChronoParts&
233 operator|=(_ChronoParts& __x, _ChronoParts __y) noexcept
234 { return __x = __x | __y; }
235
236 // TODO rename this to chrono::__formatter? or chrono::__detail::__formatter?
237 template<typename _CharT>
238 struct __formatter_chrono
239 {
240 using __string_view = basic_string_view<_CharT>;
241 using __string = basic_string<_CharT>;
242
243 template<typename _ParseContext>
244 constexpr typename _ParseContext::iterator
245 _M_parse(_ParseContext& __pc, _ChronoParts __parts)
246 {
247 auto __first = __pc.begin();
248 auto __last = __pc.end();
249
250 _ChronoSpec<_CharT> __spec{};
251
252 auto __finalize = [this, &__spec] {
253 _M_spec = __spec;
254 };
255
256 auto __finished = [&] {
257 if (__first == __last || *__first == '}')
258 {
259 __finalize();
260 return true;
261 }
262 return false;
263 };
264
265 if (__finished())
266 return __first;
267
268 __first = __spec._M_parse_fill_and_align(__first, __last);
269 if (__finished())
270 return __first;
271
272 __first = __spec._M_parse_width(__first, __last, __pc);
273 if (__finished())
274 return __first;
275
276 if (__parts & _ChronoParts::_Duration)
277 {
278 __first = __spec._M_parse_precision(__first, __last, __pc);
279 if (__finished())
280 return __first;
281 }
282
283 __first = __spec._M_parse_locale(__first, __last);
284 if (__finished())
285 return __first;
286
287 // Everything up to the end of the string or the first '}' is a
288 // chrono-specs string. Check it is valid.
289 {
290 __string_view __str(__first, __last - __first);
291 auto __end = __str.find('}');
292 if (__end != __str.npos)
293 {
294 __str.remove_suffix(__str.length() - __end);
295 __last = __first + __end;
296 }
297 if (__str.find('{') != __str.npos)
298 __throw_format_error("chrono format error: '{' in chrono-specs");
299 }
300
301 // Parse chrono-specs in [first,last), checking each conversion-spec
302 // against __parts (so fail for %Y if no year in parts).
303 // Save range in __spec._M_chrono_specs.
304
305 const auto __chrono_specs = __first++; // Skip leading '%'
306 if (*__chrono_specs != '%')
307 __throw_format_error("chrono format error: no '%' at start of "
308 "chrono-specs");
309
310 _CharT __mod{};
311 bool __conv = true;
312 int __needed = 0;
313
314 while (__first != __last)
315 {
316 enum _Mods { _Mod_none, _Mod_E, _Mod_O, _Mod_E_O };
317 _Mods __allowed_mods = _Mod_none;
318
319 _CharT __c = *__first++;
320 switch (__c)
321 {
322 case 'a':
323 case 'A':
324 __needed = _Weekday;
325 break;
326 case 'b':
327 case 'h':
328 case 'B':
329 __needed = _Month;
330 break;
331 case 'c':
332 __needed = _DateTime;
333 __allowed_mods = _Mod_E;
334 break;
335 case 'C':
336 __needed = _Year;
337 __allowed_mods = _Mod_E;
338 break;
339 case 'd':
340 case 'e':
341 __needed = _Day;
342 __allowed_mods = _Mod_O;
343 break;
344 case 'D':
345 case 'F':
346 __needed = _Date;
347 break;
348 case 'g':
349 case 'G':
350 __needed = _Date;
351 break;
352 case 'H':
353 case 'I':
354 __needed = _TimeOfDay;
355 __allowed_mods = _Mod_O;
356 break;
357 case 'j':
358 if (!(__parts & _Duration))
359 __needed = _Date;
360 break;
361 case 'm':
362 __needed = _Month;
363 __allowed_mods = _Mod_O;
364 break;
365 case 'M':
366 __needed = _TimeOfDay;
367 __allowed_mods = _Mod_O;
368 break;
369 case 'p':
370 case 'r':
371 case 'R':
372 case 'T':
373 __needed = _TimeOfDay;
374 break;
375 case 'q':
376 case 'Q':
377 __needed = _Duration;
378 break;
379 case 'S':
380 __needed = _TimeOfDay;
381 __allowed_mods = _Mod_O;
382 break;
383 case 'u':
384 case 'w':
385 __needed = _Weekday;
386 __allowed_mods = _Mod_O;
387 break;
388 case 'U':
389 case 'V':
390 case 'W':
391 __needed = _Date;
392 __allowed_mods = _Mod_O;
393 break;
394 case 'x':
395 __needed = _Date;
396 __allowed_mods = _Mod_E;
397 break;
398 case 'X':
399 __needed = _TimeOfDay;
400 __allowed_mods = _Mod_E;
401 break;
402 case 'y':
403 __needed = _Year;
404 __allowed_mods = _Mod_E_O;
405 break;
406 case 'Y':
407 __needed = _Year;
408 __allowed_mods = _Mod_E;
409 break;
410 case 'z':
411 __needed = _TimeZone;
412 __allowed_mods = _Mod_E_O;
413 break;
414 case 'Z':
415 __needed = _TimeZone;
416 break;
417 case 'n':
418 case 't':
419 case '%':
420 break;
421 case 'O':
422 case 'E':
423 if (__mod) [[unlikely]]
424 {
425 __allowed_mods = _Mod_none;
426 break;
427 }
428 __mod = __c;
429 continue;
430 default:
431 __throw_format_error("chrono format error: invalid "
432 " specifier in chrono-specs");
433 }
434
435 if ((__mod == 'E' && !(__allowed_mods & _Mod_E))
436 || (__mod == 'O' && !(__allowed_mods & _Mod_O)))
437 __throw_format_error("chrono format error: invalid "
438 " modifier in chrono-specs");
439 __mod = _CharT();
440
441 if ((__parts & __needed) != __needed)
442 __throw_format_error("chrono format error: format argument "
443 "does not contain the information "
444 "required by the chrono-specs");
445
446 // Scan for next '%', ignoring literal-chars before it.
447 size_t __pos = __string_view(__first, __last - __first).find('%');
448 if (__pos == 0)
449 ++__first;
450 else
451 {
452 if (__pos == __string_view::npos)
453 {
454 __first = __last;
455 __conv = false;
456 }
457 else
458 __first += __pos + 1;
459 }
460 }
461
462 // Check for a '%' conversion-spec without a type.
463 if (__conv || __mod != _CharT())
464 __throw_format_error("chrono format error: unescaped '%' in "
465 "chrono-specs");
466
467 _M_spec = __spec;
468 _M_spec._M_chrono_specs
469 = __string_view(__chrono_specs, __first - __chrono_specs);
470
471 return __first;
472 }
473
474 // TODO this function template is instantiated for every different _Tp.
475 // Consider creating a polymorphic interface for calendar types so
476 // that we instantiate fewer different specializations. Similar to
477 // _Sink_iter for std::format. Replace each _S_year, _S_day etc. with
478 // member functions of that type.
479 template<typename _Tp, typename _FormatContext>
480 typename _FormatContext::iterator
481 _M_format(const _Tp& __t, _FormatContext& __fc,
482 bool __is_neg = false) const
483 {
484 auto __first = _M_spec._M_chrono_specs.begin();
485 const auto __last = _M_spec._M_chrono_specs.end();
486 if (__first == __last)
487 return _M_format_to_ostream(__t, __fc, __is_neg);
488
489 _Sink_iter<_CharT> __out;
490 __format::_Str_sink<_CharT> __sink;
491 bool __write_direct = false;
492 if constexpr (is_same_v<typename _FormatContext::iterator,
493 _Sink_iter<_CharT>>)
494 {
495 if (_M_spec._M_width_kind == __format::_WP_none)
496 {
497 __out = __fc.out();
498 __write_direct = true;
499 }
500 else
501 __out = __sink.out();
502 }
503 else
504 __out = __sink.out();
505
506 // formatter<duration> passes the correct value of __is_neg
507 // for durations but for hh_mm_ss we decide it here.
508 if constexpr (__is_specialization_of<_Tp, chrono::hh_mm_ss>)
509 __is_neg = __t.is_negative();
510
511 auto __print_sign = [&__is_neg, &__out] {
512 if constexpr (chrono::__is_duration_v<_Tp>
513 || __is_specialization_of<_Tp, chrono::hh_mm_ss>)
514 if (__is_neg)
515 {
516 *__out++ = _S_plus_minus[1];
517 __is_neg = false;
518 }
519 return std::move(__out);
520 };
521
522 // Characters to output for "%n", "%t" and "%%" specifiers.
523 constexpr const _CharT* __literals = _GLIBCXX_WIDEN("\n\t%");
524
525 ++__first; // Skip leading '%' at start of chrono-specs.
526
527 _CharT __mod{};
528 do
529 {
530 _CharT __c = *__first++;
531 switch (__c)
532 {
533 case 'a':
534 case 'A':
535 __out = _M_a_A(__t, std::move(__out), __fc, __c == 'A');
536 break;
537 case 'b':
538 case 'h':
539 case 'B':
540 __out = _M_b_B(__t, std::move(__out), __fc, __c == 'B');
541 break;
542 case 'c':
543 __out = _M_c(__t, std::move(__out), __fc, __mod == 'E');
544 break;
545 case 'C':
546 case 'y':
547 case 'Y':
548 __out = _M_C_y_Y(__t, std::move(__out), __fc, __c, __mod);
549 break;
550 case 'd':
551 case 'e':
552 __out = _M_d_e(__t, std::move(__out), __fc, __c, __mod == 'O');
553 break;
554 case 'D':
555 __out = _M_D(__t, std::move(__out), __fc);
556 break;
557 case 'F':
558 __out = _M_F(__t, std::move(__out), __fc);
559 break;
560 case 'g':
561 case 'G':
562 __out = _M_g_G(__t, std::move(__out), __fc, __c == 'G');
563 break;
564 case 'H':
565 case 'I':
566 __out = _M_H_I(__t, __print_sign(), __fc, __c, __mod == 'O');
567 break;
568 case 'j':
569 __out = _M_j(__t, __print_sign(), __fc);
570 break;
571 case 'm':
572 __out = _M_m(__t, std::move(__out), __fc, __mod == 'O');
573 break;
574 case 'M':
575 __out = _M_M(__t, __print_sign(), __fc, __mod == 'O');
576 break;
577 case 'p':
578 __out = _M_p(__t, std::move(__out), __fc);
579 break;
580 case 'q':
581 __out = _M_q(__t, std::move(__out), __fc);
582 break;
583 case 'Q':
584 // %Q The duration's numeric value.
585 if constexpr (chrono::__is_duration_v<_Tp>)
586 __out = std::format_to(__print_sign(), _S_empty_spec,
587 __t.count());
588 else
589 __throw_format_error("chrono format error: argument is "
590 "not a duration");
591 break;
592 case 'r':
593 __out = _M_r(__t, __print_sign(), __fc);
594 break;
595 case 'R':
596 case 'T':
597 __out = _M_R_T(__t, __print_sign(), __fc, __c == 'T');
598 break;
599 case 'S':
600 __out = _M_S(__t, __print_sign(), __fc, __mod == 'O');
601 break;
602 case 'u':
603 case 'w':
604 __out = _M_u_w(__t, std::move(__out), __fc, __c, __mod == 'O');
605 break;
606 case 'U':
607 case 'V':
608 case 'W':
609 __out = _M_U_V_W(__t, std::move(__out), __fc, __c,
610 __mod == 'O');
611 break;
612 case 'x':
613 __out = _M_x(__t, std::move(__out), __fc, __mod == 'E');
614 break;
615 case 'X':
616 __out = _M_X(__t, __print_sign(), __fc, __mod == 'E');
617 break;
618 case 'z':
619 __out = _M_z(__t, std::move(__out), __fc, (bool)__mod);
620 break;
621 case 'Z':
622 __out = _M_Z(__t, std::move(__out), __fc);
623 break;
624 case 'n':
625 *__out++ = __literals[0];
626 break;
627 case 't':
628 *__out++ = __literals[1];
629 break;
630 case '%':
631 *__out++ = __literals[2];
632 break;
633 case 'O':
634 case 'E':
635 __mod = __c;
636 continue;
637 case '}':
638 __first = __last;
639 break;
640 }
641 __mod = _CharT();
642 // Scan for next '%' and write out everything before it.
643 __string_view __str(__first, __last - __first);
644 size_t __pos = __str.find('%');
645 if (__pos == 0)
646 ++__first;
647 else
648 {
649 if (__pos == __str.npos)
650 __first = __last;
651 else
652 {
653 __str.remove_suffix(__str.length() - __pos);
654 __first += __pos + 1;
655 }
656 __out = __format::__write(std::move(__out), __str);
657 }
658 }
659 while (__first != __last);
660
661 if constexpr (is_same_v<typename _FormatContext::iterator,
662 _Sink_iter<_CharT>>)
663 if (__write_direct)
664 return __out;
665
666 auto __str = std::move(__sink).get();
667 return __format::__write_padded_as_spec(__str, __str.size(),
668 __fc, _M_spec);
669 }
670
671 _ChronoSpec<_CharT> _M_spec;
672
673 private:
674 // Return the formatting locale.
675 template<typename _FormatContext>
677 _M_locale(_FormatContext& __fc) const
678 {
679 if (!_M_spec._M_localized)
680 return std::locale::classic();
681 else
682 return __fc.locale();
683 }
684
685 // Format for empty chrono-specs, e.g. "{}" (C++20 [time.format] p6).
686 // TODO: consider moving body of every operator<< into this function
687 // and use std::format("{}", t) to implement those operators. That
688 // would avoid std::format("{}", t) calling operator<< which calls
689 // std::format again.
690 template<typename _Tp, typename _FormatContext>
691 typename _FormatContext::iterator
692 _M_format_to_ostream(const _Tp& __t, _FormatContext& __fc,
693 bool __is_neg) const
694 {
695 using ::std::chrono::__detail::__utc_leap_second;
696 using ::std::chrono::__detail::__local_time_fmt;
697
698 if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
699 return _M_format_to_ostream(__t._M_time, __fc, false);
700 else
701 {
702 basic_ostringstream<_CharT> __os;
703 __os.imbue(_M_locale(__fc));
704
705 if constexpr (__is_specialization_of<_Tp, __utc_leap_second>)
706 __os << __t._M_date << ' ' << __t._M_time;
707 else if constexpr (chrono::__is_time_point_v<_Tp>)
708 {
709 // Need to be careful here because not all specializations
710 // of chrono::sys_time can be written to an ostream.
711 // For the specializations of time_point that can be
712 // formatted with an empty chrono-specs, either it's a
713 // sys_time with period greater or equal to days:
714 if constexpr (is_convertible_v<_Tp, chrono::sys_days>)
715 __os << _S_date(__t);
716 else // Or it's formatted as "{:L%F %T}":
717 {
718 auto __days = chrono::floor<chrono::days>(__t);
719 __os << chrono::year_month_day(__days) << ' '
720 << chrono::hh_mm_ss(__t - __days);
721 }
722 }
723 else
724 {
725 if constexpr (chrono::__is_duration_v<_Tp>)
726 if (__is_neg) [[unlikely]]
727 __os << _S_plus_minus[1];
728 __os << __t;
729 }
730
731 auto __str = std::move(__os).str();
732 return __format::__write_padded_as_spec(__str, __str.size(),
733 __fc, _M_spec);
734 }
735 }
736
737 static constexpr const _CharT* _S_chars
738 = _GLIBCXX_WIDEN("0123456789+-:/ {}");
739 static constexpr const _CharT* _S_plus_minus = _S_chars + 10;
740 static constexpr _CharT _S_colon = _S_chars[12];
741 static constexpr _CharT _S_slash = _S_chars[13];
742 static constexpr _CharT _S_space = _S_chars[14];
743 static constexpr const _CharT* _S_empty_spec = _S_chars + 15;
744
745 template<typename _Tp, typename _FormatContext>
746 typename _FormatContext::iterator
747 _M_a_A(const _Tp& __t, typename _FormatContext::iterator __out,
748 _FormatContext& __ctx, bool __full) const
749 {
750 // %a Locale's abbreviated weekday name.
751 // %A Locale's full weekday name.
752 chrono::weekday __wd = _S_weekday(__t);
753 if (!__wd.ok())
754 __throw_format_error("format error: invalid weekday");
755
756 locale __loc = _M_locale(__ctx);
757 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
758 const _CharT* __days[7];
759 if (__full)
760 __tp._M_days(__days);
761 else
762 __tp._M_days_abbreviated(__days);
763 __string_view __str(__days[__wd.c_encoding()]);
764 return __format::__write(std::move(__out), __str);
765 }
766
767 template<typename _Tp, typename _FormatContext>
768 typename _FormatContext::iterator
769 _M_b_B(const _Tp& __t, typename _FormatContext::iterator __out,
770 _FormatContext& __ctx, bool __full) const
771 {
772 // %b Locale's abbreviated month name.
773 // %B Locale's full month name.
774 chrono::month __m = _S_month(__t);
775 if (!__m.ok())
776 __throw_format_error("format error: invalid month");
777 locale __loc = _M_locale(__ctx);
778 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
779 const _CharT* __months[12];
780 if (__full)
781 __tp._M_months(__months);
782 else
783 __tp._M_months_abbreviated(__months);
784 __string_view __str(__months[(unsigned)__m - 1]);
785 return __format::__write(std::move(__out), __str);
786 }
787
788 template<typename _Tp, typename _FormatContext>
789 typename _FormatContext::iterator
790 _M_c(const _Tp& __tt, typename _FormatContext::iterator __out,
791 _FormatContext& __ctx, bool __mod = false) const
792 {
793 // %c Locale's date and time representation.
794 // %Ec Locale's alternate date and time representation.
795
796 auto __t = _S_floor_seconds(__tt);
797 locale __loc = _M_locale(__ctx);
798 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
799 const _CharT* __formats[2];
800 __tp._M_date_time_formats(__formats);
801 const _CharT* __rep = __formats[__mod];
802 if (!*__rep)
803 __rep = _GLIBCXX_WIDEN("%a %b %e %H:%M:%S %Y");
804 basic_string<_CharT> __fmt(_S_empty_spec);
805 __fmt.insert(1u, 1u, _S_colon);
806 __fmt.insert(2u, __rep);
807 return std::vformat_to(std::move(__out), __loc, __fmt,
809 }
810
811 template<typename _Tp, typename _FormatContext>
812 typename _FormatContext::iterator
813 _M_C_y_Y(const _Tp& __t, typename _FormatContext::iterator __out,
814 _FormatContext& __ctx, _CharT __conv, _CharT __mod = 0) const
815 {
816 // %C Year divided by 100 using floored division.
817 // %EC Locale's alternative preresentation of the century (era name).
818 // %y Last two decimal digits of the year.
819 // %Oy Locale's alternative representation.
820 // %Ey Locale's alternative representation of offset from %EC.
821 // %Y Year as a decimal number.
822 // %EY Locale's alternative full year representation.
823
824 chrono::year __y = _S_year(__t);
825
826 if (__mod) [[unlikely]]
827 {
828 struct tm __tm{};
829 __tm.tm_year = (int)__y - 1900;
830 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
831 __conv, __mod);
832 }
833
834 basic_string<_CharT> __s;
835 int __yi = (int)__y;
836 const bool __is_neg = __yi < 0;
837 __yi = __builtin_abs(__yi);
838
839 if (__conv == 'Y' || __conv == 'C')
840 {
841 int __ci = __yi / 100;
842 if (__is_neg) [[unlikely]]
843 {
844 __s.assign(1, _S_plus_minus[1]);
845 // For floored division -123//100 is -2 and -100//100 is -1
846 if (__conv == 'C' && (__ci * 100) != __yi)
847 ++__ci;
848 }
849 if (__ci >= 100) [[unlikely]]
850 {
851 __s += std::format(_S_empty_spec, __ci / 100);
852 __ci %= 100;
853 }
854 __s += _S_two_digits(__ci);
855 }
856
857 if (__conv == 'Y' || __conv == 'y')
858 __s += _S_two_digits(__yi % 100);
859
860 return __format::__write(std::move(__out), __string_view(__s));
861 }
862
863 template<typename _Tp, typename _FormatContext>
864 typename _FormatContext::iterator
865 _M_D(const _Tp& __t, typename _FormatContext::iterator __out,
866 _FormatContext&) const
867 {
868 auto __ymd = _S_date(__t);
869 basic_string<_CharT> __s;
870#if ! _GLIBCXX_USE_CXX11_ABI
871 __s.reserve(8);
872#endif
873 __s = _S_two_digits((unsigned)__ymd.month());
874 __s += _S_slash;
875 __s += _S_two_digits((unsigned)__ymd.day());
876 __s += _S_slash;
877 __s += _S_two_digits(__builtin_abs((int)__ymd.year()) % 100);
878 return __format::__write(std::move(__out), __string_view(__s));
879 }
880
881 template<typename _Tp, typename _FormatContext>
882 typename _FormatContext::iterator
883 _M_d_e(const _Tp& __t, typename _FormatContext::iterator __out,
884 _FormatContext& __ctx, _CharT __conv, bool __mod = false) const
885 {
886 // %d The day of month as a decimal number.
887 // %Od Locale's alternative representation.
888 // %e Day of month as decimal number, padded with space.
889 // %Oe Locale's alternative digits.
890
891 chrono::day __d = _S_day(__t);
892 unsigned __i = (unsigned)__d;
893
894 if (__mod) [[unlikely]]
895 {
896 struct tm __tm{};
897 __tm.tm_mday = __i;
898 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
899 (char)__conv, 'O');
900 }
901
902 auto __sv = _S_two_digits(__i);
903 _CharT __buf[2];
904 if (__conv == _CharT('e') && __i < 10)
905 {
906 __buf[0] = _S_space;
907 __buf[1] = __sv[1];
908 __sv = {__buf, 2};
909 }
910 return __format::__write(std::move(__out), __sv);
911 }
912
913 template<typename _Tp, typename _FormatContext>
914 typename _FormatContext::iterator
915 _M_F(const _Tp& __t, typename _FormatContext::iterator __out,
916 _FormatContext&) const
917 {
918 auto __ymd = _S_date(__t);
919 auto __s = std::format(_GLIBCXX_WIDEN("{:04d}- - "),
920 (int)__ymd.year());
921 auto __sv = _S_two_digits((unsigned)__ymd.month());
922 __s[__s.size() - 5] = __sv[0];
923 __s[__s.size() - 4] = __sv[1];
924 __sv = _S_two_digits((unsigned)__ymd.day());
925 __s[__s.size() - 2] = __sv[0];
926 __s[__s.size() - 1] = __sv[1];
927 __sv = __s;
928 return __format::__write(std::move(__out), __sv);
929 }
930
931 template<typename _Tp, typename _FormatContext>
932 typename _FormatContext::iterator
933 _M_g_G(const _Tp& __t, typename _FormatContext::iterator __out,
934 _FormatContext& __ctx, bool __full) const
935 {
936 // %g last two decimal digits of the ISO week-based year.
937 // %G ISO week-based year.
938 using namespace chrono;
939 auto __d = _S_days(__t);
940 // Move to nearest Thursday:
941 __d -= (weekday(__d) - Monday) - days(3);
942 // ISO week-based year is the year that contains that Thursday:
943 year __y = year_month_day(__d).year();
944 return _M_C_y_Y(__y, std::move(__out), __ctx, "yY"[__full]);
945 }
946
947 template<typename _Tp, typename _FormatContext>
948 typename _FormatContext::iterator
949 _M_H_I(const _Tp& __t, typename _FormatContext::iterator __out,
950 _FormatContext& __ctx, _CharT __conv, bool __mod = false) const
951 {
952 // %H The hour (24-hour clock) as a decimal number.
953 // %OH Locale's alternative representation.
954 // %I The hour (12-hour clock) as a decimal number.
955 // %OI Locale's alternative representation.
956
957 const auto __hms = _S_hms(__t);
958 int __i = __hms.hours().count();
959
960 if (__mod) [[unlikely]]
961 {
962 struct tm __tm{};
963 __tm.tm_hour = __i;
964 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
965 (char)__conv, 'O');
966 }
967
968 if (__conv == _CharT('I'))
969 {
970 if (__i == 0)
971 __i = 12;
972 else if (__i > 12)
973 __i -= 12;
974 }
975 return __format::__write(std::move(__out), _S_two_digits(__i));
976 }
977
978 template<typename _Tp, typename _FormatContext>
979 typename _FormatContext::iterator
980 _M_j(const _Tp& __t, typename _FormatContext::iterator __out,
981 _FormatContext&) const
982 {
983 if constexpr (chrono::__is_duration_v<_Tp>)
984 {
985 // Decimal number of days, without padding.
986 unsigned __d = chrono::duration_cast<chrono::days>(__t).count();
987 return std::format_to(std::move(__out), _S_empty_spec, __d);
988 }
989 else
990 {
991 // Day of the year as a decimal number, padding with zero.
992 using namespace chrono;
993 auto __day = _S_days(__t);
994 auto __ymd = _S_date(__t);
995 days __d;
996 // See "Calculating Ordinal Dates" at
997 // https://github.com/HowardHinnant/date/wiki/Examples-and-Recipes
998 if constexpr (is_same_v<typename decltype(__day)::clock, local_t>)
999 __d = __day - local_days(__ymd.year()/January/0);
1000 else
1001 __d = __day - sys_days(__ymd.year()/January/0);
1002 return std::format_to(std::move(__out), _GLIBCXX_WIDEN("{:03d}"),
1003 __d.count());
1004 }
1005 }
1006
1007 template<typename _Tp, typename _FormatContext>
1008 typename _FormatContext::iterator
1009 _M_m(const _Tp& __t, typename _FormatContext::iterator __out,
1010 _FormatContext& __ctx, bool __mod) const
1011 {
1012 // %m month as a decimal number.
1013 // %Om Locale's alternative representation.
1014
1015 auto __m = _S_month(__t);
1016 auto __i = (unsigned)__m;
1017
1018 if (__mod) [[unlikely]] // %Om
1019 {
1020 struct tm __tm{};
1021 __tm.tm_mon = __i - 1;
1022 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
1023 'm', 'O');
1024 }
1025
1026 return __format::__write(std::move(__out), _S_two_digits(__i));
1027 }
1028
1029 template<typename _Tp, typename _FormatContext>
1030 typename _FormatContext::iterator
1031 _M_M(const _Tp& __t, typename _FormatContext::iterator __out,
1032 _FormatContext& __ctx, bool __mod) const
1033 {
1034 // %M The minute as a decimal number.
1035 // %OM Locale's alternative representation.
1036
1037 auto __m = _S_hms(__t).minutes();
1038 auto __i = __m.count();
1039
1040 if (__mod) [[unlikely]] // %OM
1041 {
1042 struct tm __tm{};
1043 __tm.tm_min = __i;
1044 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
1045 'M', 'O');
1046 }
1047
1048 return __format::__write(std::move(__out), _S_two_digits(__i));
1049 }
1050
1051 template<typename _Tp, typename _FormatContext>
1052 typename _FormatContext::iterator
1053 _M_p(const _Tp& __t, typename _FormatContext::iterator __out,
1054 _FormatContext& __ctx) const
1055 {
1056 // %p The locale's equivalent of the AM/PM designations.
1057 auto __hms = _S_hms(__t);
1058 locale __loc = _M_locale(__ctx);
1059 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
1060 const _CharT* __ampm[2];
1061 __tp._M_am_pm(__ampm);
1062 return std::format_to(std::move(__out), _S_empty_spec,
1063 __ampm[__hms.hours().count() >= 12]);
1064 }
1065
1066 template<typename _Tp, typename _FormatContext>
1067 typename _FormatContext::iterator
1068 _M_q(const _Tp&, typename _FormatContext::iterator __out,
1069 _FormatContext&) const
1070 {
1071 // %q The duration's unit suffix
1072 if constexpr (!chrono::__is_duration_v<_Tp>)
1073 __throw_format_error("format error: argument is not a duration");
1074 else
1075 {
1076 namespace __d = chrono::__detail;
1077 using period = typename _Tp::period;
1078 return __d::__fmt_units_suffix<period, _CharT>(std::move(__out));
1079 }
1080 }
1081
1082 // %Q handled in _M_format
1083
1084 template<typename _Tp, typename _FormatContext>
1085 typename _FormatContext::iterator
1086 _M_r(const _Tp& __tt, typename _FormatContext::iterator __out,
1087 _FormatContext& __ctx) const
1088 {
1089 // %r locale's 12-hour clock time.
1090 auto __t = _S_floor_seconds(__tt);
1091 locale __loc = _M_locale(__ctx);
1092 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
1093 const _CharT* __ampm_fmt;
1094 __tp._M_am_pm_format(&__ampm_fmt);
1095 basic_string<_CharT> __fmt(_S_empty_spec);
1096 __fmt.insert(1u, 1u, _S_colon);
1097 __fmt.insert(2u, __ampm_fmt);
1098 return std::vformat_to(std::move(__out), __fmt,
1100 }
1101
1102 template<typename _Tp, typename _FormatContext>
1103 typename _FormatContext::iterator
1104 _M_R_T(const _Tp& __t, typename _FormatContext::iterator __out,
1105 _FormatContext& __ctx, bool __secs) const
1106 {
1107 // %R Equivalent to %H:%M
1108 // %T Equivalent to %H:%M:%S
1109 auto __hms = _S_hms(__t);
1110
1111 auto __s = std::format(_GLIBCXX_WIDEN("{:02d}:00"),
1112 __hms.hours().count());
1113 auto __sv = _S_two_digits(__hms.minutes().count());
1114 __s[__s.size() - 2] = __sv[0];
1115 __s[__s.size() - 1] = __sv[1];
1116 __sv = __s;
1117 __out = __format::__write(std::move(__out), __sv);
1118 if (__secs)
1119 {
1120 *__out++ = _S_colon;
1121 __out = _M_S(__hms, std::move(__out), __ctx);
1122 }
1123 return __out;
1124 }
1125
1126 template<typename _Tp, typename _FormatContext>
1127 typename _FormatContext::iterator
1128 _M_S(const _Tp& __t, typename _FormatContext::iterator __out,
1129 _FormatContext& __ctx, bool __mod = false) const
1130 {
1131 // %S Seconds as a decimal number.
1132 // %OS The locale's alternative representation.
1133 auto __hms = _S_hms(__t);
1134
1135 if (__mod) [[unlikely]] // %OS
1136 {
1137 struct tm __tm{};
1138 __tm.tm_sec = (int)__hms.seconds().count();
1139 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
1140 'S', 'O');
1141 }
1142
1143 if constexpr (__hms.fractional_width == 0)
1144 __out = __format::__write(std::move(__out),
1145 _S_two_digits(__hms.seconds().count()));
1146 else
1147 {
1148 locale __loc = _M_locale(__ctx);
1149 auto __s = __hms.seconds();
1150 auto __ss = __hms.subseconds();
1151 using rep = typename decltype(__ss)::rep;
1152 if constexpr (is_floating_point_v<rep>)
1153 {
1154 chrono::duration<rep> __fs = __s + __ss;
1155 __out = std::format_to(std::move(__out), __loc,
1156 _GLIBCXX_WIDEN("{:#0{}.{}Lf}"),
1157 __fs.count(),
1158 3 + __hms.fractional_width,
1159 __hms.fractional_width);
1160 }
1161 else
1162 {
1163 const auto& __np
1164 = use_facet<numpunct<_CharT>>(__loc);
1165 __out = __format::__write(std::move(__out),
1166 _S_two_digits(__s.count()));
1167 *__out++ = __np.decimal_point();
1168 if constexpr (is_integral_v<rep>)
1169 __out = std::format_to(std::move(__out),
1170 _GLIBCXX_WIDEN("{:0{}}"),
1171 __ss.count(),
1172 __hms.fractional_width);
1173 else
1174 {
1175 auto __str = std::format(_S_empty_spec, __ss.count());
1176 __out = std::format_to(_GLIBCXX_WIDEN("{:0>{}s}"),
1177 __str,
1178 __hms.fractional_width);
1179 }
1180 }
1181 }
1182 return __out;
1183 }
1184
1185 // %t handled in _M_format
1186
1187 template<typename _Tp, typename _FormatContext>
1188 typename _FormatContext::iterator
1189 _M_u_w(const _Tp& __t, typename _FormatContext::iterator __out,
1190 _FormatContext& __ctx, _CharT __conv, bool __mod = false) const
1191 {
1192 // %u ISO weekday as a decimal number (1-7), where Monday is 1.
1193 // %Ou Locale's alternative numeric rep.
1194 // %w Weekday as a decimal number (0-6), where Sunday is 0.
1195 // %Ow Locale's alternative numeric rep.
1196
1197 chrono::weekday __wd = _S_weekday(__t);
1198
1199 if (__mod) [[unlikely]]
1200 {
1201 struct tm __tm{};
1202 __tm.tm_wday = __wd.c_encoding();
1203 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
1204 (char)__conv, 'O');
1205 }
1206
1207 unsigned __wdi = __conv == 'u' ? __wd.iso_encoding()
1208 : __wd.c_encoding();
1209 const _CharT __d = _S_digit(__wdi);
1210 return __format::__write(std::move(__out), __string_view(&__d, 1));
1211 }
1212
1213 template<typename _Tp, typename _FormatContext>
1214 typename _FormatContext::iterator
1215 _M_U_V_W(const _Tp& __t, typename _FormatContext::iterator __out,
1216 _FormatContext& __ctx, _CharT __conv, bool __mod = false) const
1217 {
1218 // %U Week number of the year as a decimal number, from first Sunday.
1219 // %OU Locale's alternative numeric rep.
1220 // %V ISO week-based week number as a decimal number.
1221 // %OV Locale's alternative numeric rep.
1222 // %W Week number of the year as a decimal number, from first Monday.
1223 // %OW Locale's alternative numeric rep.
1224 using namespace chrono;
1225 auto __d = _S_days(__t);
1226 using _TDays = decltype(__d); // Either sys_days or local_days.
1227
1228 if (__mod) [[unlikely]]
1229 {
1230 const year_month_day __ymd(__d);
1231 const year __y = __ymd.year();
1232 struct tm __tm{};
1233 __tm.tm_year = (int)__y - 1900;
1234 __tm.tm_yday = (__d - _TDays(__y/January/1)).count();
1235 __tm.tm_wday = weekday(__d).c_encoding();
1236 return _M_locale_fmt(std::move(__out), _M_locale(__ctx), __tm,
1237 (char)__conv, 'O');
1238 }
1239
1240 _TDays __first; // First day of week 1.
1241 if (__conv == 'V') // W01 begins on Monday before first Thursday.
1242 {
1243 // Move to nearest Thursday:
1244 __d -= (weekday(__d) - Monday) - days(3);
1245 // ISO week of __t is number of weeks since January 1 of the
1246 // same year as that nearest Thursday.
1247 __first = _TDays(year_month_day(__d).year()/January/1);
1248 }
1249 else
1250 {
1251 year __y;
1252 if constexpr (requires { __t.year(); })
1253 __y = __t.year();
1254 else
1255 __y = year_month_day(__d).year();
1256 const weekday __weekstart = __conv == 'U' ? Sunday : Monday;
1257 __first = _TDays(__y/January/__weekstart[1]);
1258 }
1259 auto __weeks = chrono::floor<weeks>(__d - __first);
1260 __string_view __sv = _S_two_digits(__weeks.count() + 1);
1261 return __format::__write(std::move(__out), __sv);
1262 }
1263
1264 template<typename _Tp, typename _FormatContext>
1265 typename _FormatContext::iterator
1266 _M_x(const _Tp& __t, typename _FormatContext::iterator __out,
1267 _FormatContext& __ctx, bool __mod = false) const
1268 {
1269 // %x Locale's date rep
1270 // %Ex Locale's alternative date representation.
1271 locale __loc = _M_locale(__ctx);
1272 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
1273 const _CharT* __date_reps[2];
1274 __tp._M_date_formats(__date_reps);
1275 const _CharT* __rep = __date_reps[__mod];
1276 if (!*__rep)
1277 return _M_D(__t, std::move(__out), __ctx);
1278
1279 basic_string<_CharT> __fmt(_S_empty_spec);
1280 __fmt.insert(1u, 1u, _S_colon);
1281 __fmt.insert(2u, __rep);
1282 return std::vformat_to(std::move(__out), __fmt,
1284 }
1285
1286 template<typename _Tp, typename _FormatContext>
1287 typename _FormatContext::iterator
1288 _M_X(const _Tp& __tt, typename _FormatContext::iterator __out,
1289 _FormatContext& __ctx, bool __mod = false) const
1290 {
1291 // %X Locale's time rep
1292 // %EX Locale's alternative time representation.
1293 auto __t = _S_floor_seconds(__tt);
1294 locale __loc = _M_locale(__ctx);
1295 const auto& __tp = use_facet<__timepunct<_CharT>>(__loc);
1296 const _CharT* __time_reps[2];
1297 __tp._M_time_formats(__time_reps);
1298 const _CharT* __rep = __time_reps[__mod];
1299 if (!*__rep)
1300 return _M_R_T(__t, std::move(__out), __ctx, true);
1301
1302 basic_string<_CharT> __fmt(_S_empty_spec);
1303 __fmt.insert(1u, 1u, _S_colon);
1304 __fmt.insert(2u, __rep);
1305 return std::vformat_to(std::move(__out), __fmt,
1307 }
1308
1309 template<typename _Tp, typename _FormatContext>
1310 typename _FormatContext::iterator
1311 _M_z(const _Tp& __t, typename _FormatContext::iterator __out,
1312 _FormatContext&, bool __mod = false) const
1313 {
1314 using ::std::chrono::__detail::__utc_leap_second;
1315 using ::std::chrono::__detail::__local_time_fmt;
1316
1317 auto __utc = __mod ? __string_view(_GLIBCXX_WIDEN("+00:00"), 6)
1318 : __string_view(_GLIBCXX_WIDEN("+0000"), 5);
1319
1320 if constexpr (chrono::__is_time_point_v<_Tp>)
1321 {
1322 if constexpr (is_same_v<typename _Tp::clock,
1323 chrono::system_clock>)
1324 return __format::__write(std::move(__out), __utc);
1325 }
1326 else if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
1327 {
1328 if (__t._M_offset_sec)
1329 {
1330 auto __sv = __utc;
1331 basic_string<_CharT> __s;
1332 if (*__t._M_offset_sec != 0s)
1333 {
1334 chrono:: hh_mm_ss __hms(*__t._M_offset_sec);
1335 __s = _S_plus_minus[__hms.is_negative()];
1336 __s += _S_two_digits(__hms.hours().count());
1337 if (__mod)
1338 __s += _S_colon;
1339 __s += _S_two_digits(__hms.minutes().count());
1340 __sv = __s;
1341 }
1342 return __format::__write(std::move(__out), __sv);
1343 }
1344 }
1345 else if constexpr (__is_specialization_of<_Tp, __utc_leap_second>)
1346 return __format::__write(std::move(__out), __utc);
1347
1348 __no_timezone_available();
1349 }
1350
1351 template<typename _Tp, typename _FormatContext>
1352 typename _FormatContext::iterator
1353 _M_Z(const _Tp& __t, typename _FormatContext::iterator __out,
1354 _FormatContext& __ctx) const
1355 {
1356 using ::std::chrono::__detail::__utc_leap_second;
1357 using ::std::chrono::__detail::__local_time_fmt;
1358
1359 __string_view __utc(_GLIBCXX_WIDEN("UTC"), 3);
1360 if constexpr (chrono::__is_time_point_v<_Tp>)
1361 {
1362 if constexpr (is_same_v<typename _Tp::clock,
1363 chrono::system_clock>)
1364 return __format::__write(std::move(__out), __utc);
1365 }
1366 else if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
1367 {
1368 if (__t._M_abbrev)
1369 {
1370 string_view __sv = *__t._M_abbrev;
1371 if constexpr (is_same_v<_CharT, char>)
1372 return __format::__write(std::move(__out), __sv);
1373 else
1374 {
1375 // TODO use resize_and_overwrite
1376 basic_string<_CharT> __ws(__sv.size(), _CharT());
1377 auto& __ct = use_facet<ctype<_CharT>>(_M_locale(__ctx));
1378 __ct.widen(__sv.begin(), __sv.end(), __ws.data());
1379 __string_view __wsv = __ws;
1380 return __format::__write(std::move(__out), __wsv);
1381 }
1382 }
1383 }
1384 else if constexpr (__is_specialization_of<_Tp, __utc_leap_second>)
1385 return __format::__write(std::move(__out), __utc);
1386
1387 __no_timezone_available();
1388 }
1389
1390 // %% handled in _M_format
1391
1392 // A single digit character in the range '0'..'9'.
1393 static _CharT
1394 _S_digit(int __n) noexcept
1395 {
1396 // Extra 9s avoid past-the-end read on bad input.
1397 return _GLIBCXX_WIDEN("0123456789999999")[__n & 0xf];
1398 }
1399
1400 // A string view of two digit characters, "00".."99".
1401 static basic_string_view<_CharT>
1402 _S_two_digits(int __n) noexcept
1403 {
1404 return {
1405 _GLIBCXX_WIDEN("0001020304050607080910111213141516171819"
1406 "2021222324252627282930313233343536373839"
1407 "4041424344454647484950515253545556575859"
1408 "6061626364656667686970717273747576777879"
1409 "8081828384858687888990919293949596979899"
1410 "9999999999999999999999999999999999999999"
1411 "9999999999999999") + 2 * (__n & 0x7f),
1412 2
1413 };
1414 }
1415
1416 // Accessors for the components of chrono types:
1417
1418 // Returns a hh_mm_ss.
1419 template<typename _Tp>
1420 static decltype(auto)
1421 _S_hms(const _Tp& __t)
1422 {
1423 using ::std::chrono::__detail::__utc_leap_second;
1424 using ::std::chrono::__detail::__local_time_fmt;
1425
1426 if constexpr (__is_specialization_of<_Tp, chrono::hh_mm_ss>)
1427 return __t;
1428 else if constexpr (__is_specialization_of<_Tp, __utc_leap_second>)
1429 return __t._M_time;
1430 else if constexpr (chrono::__is_duration_v<_Tp>)
1431 return chrono::hh_mm_ss<_Tp>(__t);
1432 else if constexpr (chrono::__is_time_point_v<_Tp>)
1433 return chrono::hh_mm_ss(__t - chrono::floor<chrono::days>(__t));
1434 else if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
1435 return _S_hms(__t._M_time);
1436 else
1437 {
1438 __invalid_chrono_spec();
1439 return chrono::hh_mm_ss<chrono::seconds>();
1440 }
1441 }
1442
1443 // Returns a sys_days or local_days.
1444 template<typename _Tp>
1445 static auto
1446 _S_days(const _Tp& __t)
1447 {
1448 using namespace chrono;
1449 using ::std::chrono::__detail::__utc_leap_second;
1450 using ::std::chrono::__detail::__local_time_fmt;
1451
1452 if constexpr (__is_time_point_v<_Tp>)
1453 return chrono::floor<days>(__t);
1454 else if constexpr (__is_specialization_of<_Tp, __utc_leap_second>)
1455 return __t._M_date;
1456 else if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
1457 return chrono::floor<days>(__t._M_time);
1458 else if constexpr (is_same_v<_Tp, year_month_day>
1459 || is_same_v<_Tp, year_month_day_last>
1460 || is_same_v<_Tp, year_month_weekday>
1461 || is_same_v<_Tp, year_month_weekday_last>)
1462 return sys_days(__t);
1463 else
1464 {
1465 if constexpr (__is_duration_v<_Tp>)
1466 __not_valid_for_duration();
1467 else
1468 __invalid_chrono_spec();
1469 return chrono::sys_days();
1470 }
1471 }
1472
1473 // Returns a year_month_day.
1474 template<typename _Tp>
1475 static chrono::year_month_day
1476 _S_date(const _Tp& __t)
1477 {
1478 if constexpr (is_same_v<_Tp, chrono::year_month_day>)
1479 return __t;
1480 else
1481 return chrono::year_month_day(_S_days(__t));
1482 }
1483
1484 template<typename _Tp>
1485 static chrono::day
1486 _S_day(const _Tp& __t)
1487 {
1488 using namespace chrono;
1489
1490 if constexpr (is_same_v<_Tp, day>)
1491 return __t;
1492 else if constexpr (requires { __t.day(); })
1493 return __t.day();
1494 else
1495 return _S_date(__t).day();
1496 }
1497
1498 template<typename _Tp>
1499 static chrono::month
1500 _S_month(const _Tp& __t)
1501 {
1502 using namespace chrono;
1503
1504 if constexpr (is_same_v<_Tp, month>)
1505 return __t;
1506 else if constexpr (requires { __t.month(); })
1507 return __t.month();
1508 else
1509 return _S_date(__t).month();
1510 }
1511
1512 template<typename _Tp>
1513 static chrono::year
1514 _S_year(const _Tp& __t)
1515 {
1516 using namespace chrono;
1517
1518 if constexpr (is_same_v<_Tp, year>)
1519 return __t;
1520 else if constexpr (requires { __t.year(); })
1521 return __t.year();
1522 else
1523 return _S_date(__t).year();
1524 }
1525
1526 template<typename _Tp>
1527 static chrono::weekday
1528 _S_weekday(const _Tp& __t)
1529 {
1530 using namespace ::std::chrono;
1531 using ::std::chrono::__detail::__local_time_fmt;
1532
1533 if constexpr (is_same_v<_Tp, weekday>)
1534 return __t;
1535 else if constexpr (requires { __t.weekday(); })
1536 return __t.weekday();
1537 else if constexpr (is_same_v<_Tp, month_weekday>)
1538 return __t.weekday_indexed().weekday();
1539 else if constexpr (is_same_v<_Tp, month_weekday_last>)
1540 return __t.weekday_last().weekday();
1541 else
1542 return weekday(_S_days(__t));
1543 }
1544
1545 // Remove subsecond precision from a time_point.
1546 template<typename _Tp>
1547 static auto
1548 _S_floor_seconds(const _Tp& __t)
1549 {
1550 using chrono::__detail::__local_time_fmt;
1551 if constexpr (chrono::__is_time_point_v<_Tp>
1552 || chrono::__is_duration_v<_Tp>)
1553 {
1554 if constexpr (_Tp::period::den != 1)
1555 return chrono::floor<chrono::seconds>(__t);
1556 else
1557 return __t;
1558 }
1559 else if constexpr (__is_specialization_of<_Tp, chrono::hh_mm_ss>)
1560 {
1561 if constexpr (_Tp::fractional_width != 0)
1562 return chrono::floor<chrono::seconds>(__t.to_duration());
1563 else
1564 return __t;
1565 }
1566 else if constexpr (__is_specialization_of<_Tp, __local_time_fmt>)
1567 return _S_floor_seconds(__t._M_time);
1568 else
1569 return __t;
1570 }
1571
1572 // Use the formatting locale's std::time_put facet to produce
1573 // a locale-specific representation.
1574 template<typename _Iter>
1575 _Iter
1576 _M_locale_fmt(_Iter __out, const locale& __loc, const struct tm& __tm,
1577 char __fmt, char __mod) const
1578 {
1579 basic_ostringstream<_CharT> __os;
1580 const auto& __tp = use_facet<time_put<_CharT>>(__loc);
1581 __tp.put(__os, __os, _S_space, &__tm, __fmt, __mod);
1582 if (__os)
1583 __out = __format::__write(std::move(__out), __os.view());
1584 return __out;
1585 }
1586 };
1587
1588} // namespace __format
1589/// @endcond
1590
1591 template<typename _Rep, typename _Period, typename _CharT>
1592 struct formatter<chrono::duration<_Rep, _Period>, _CharT>
1593 {
1594 constexpr typename basic_format_parse_context<_CharT>::iterator
1595 parse(basic_format_parse_context<_CharT>& __pc)
1596 {
1597 using namespace __format;
1598 auto __it = _M_f._M_parse(__pc, _Duration|_TimeOfDay);
1599 if constexpr (!is_floating_point_v<_Rep>)
1600 if (_M_f._M_spec._M_prec_kind != __format::_WP_none)
1601 __throw_format_error("format error: invalid precision for duration");
1602 return __it;
1603 }
1604
1605 template<typename _Out>
1606 typename basic_format_context<_Out, _CharT>::iterator
1607 format(const chrono::duration<_Rep, _Period>& __d,
1608 basic_format_context<_Out, _CharT>& __fc) const
1609 {
1610 if constexpr (numeric_limits<_Rep>::is_signed)
1611 if (__d < __d.zero()) [[unlikely]]
1612 {
1613 if constexpr (is_integral_v<_Rep>)
1614 {
1615 // -d is undefined for the most negative integer.
1616 // Convert duration to corresponding unsigned rep.
1617 using _URep = make_unsigned_t<_Rep>;
1618 auto __ucnt = -static_cast<_URep>(__d.count());
1619 auto __ud = chrono::duration<_URep, _Period>(__ucnt);
1620 return _M_f._M_format(__ud, __fc, true);
1621 }
1622 else
1623 return _M_f._M_format(-__d, __fc, true);
1624 }
1625 return _M_f._M_format(__d, __fc, false);
1626 }
1627
1628 private:
1629 __format::__formatter_chrono<_CharT> _M_f;
1630 };
1631
1632 template<typename _CharT>
1633 struct formatter<chrono::day, _CharT>
1634 {
1635 template<typename _ParseContext>
1636 constexpr typename _ParseContext::iterator
1637 parse(_ParseContext& __pc)
1638 { return _M_f._M_parse(__pc, __format::_Day); }
1639
1640 template<typename _FormatContext>
1641 typename _FormatContext::iterator
1642 format(const chrono::day& __t, _FormatContext& __fc) const
1643 { return _M_f._M_format(__t, __fc); }
1644
1645 private:
1646 __format::__formatter_chrono<_CharT> _M_f;
1647 };
1648
1649 template<typename _CharT>
1650 struct formatter<chrono::month, _CharT>
1651 {
1652 template<typename _ParseContext>
1653 constexpr typename _ParseContext::iterator
1654 parse(_ParseContext& __pc)
1655 { return _M_f._M_parse(__pc, __format::_Month); }
1656
1657 template<typename _FormatContext>
1658 typename _FormatContext::iterator
1659 format(const chrono::month& __t, _FormatContext& __fc) const
1660 { return _M_f._M_format(__t, __fc); }
1661
1662 private:
1663 __format::__formatter_chrono<_CharT> _M_f;
1664 };
1665
1666 template<typename _CharT>
1667 struct formatter<chrono::year, _CharT>
1668 {
1669 template<typename _ParseContext>
1670 constexpr typename _ParseContext::iterator
1671 parse(_ParseContext& __pc)
1672 { return _M_f._M_parse(__pc, __format::_Year); }
1673
1674 template<typename _FormatContext>
1675 typename _FormatContext::iterator
1676 format(const chrono::year& __t, _FormatContext& __fc) const
1677 { return _M_f._M_format(__t, __fc); }
1678
1679 private:
1680 __format::__formatter_chrono<_CharT> _M_f;
1681 };
1682
1683 template<typename _CharT>
1684 struct formatter<chrono::weekday, _CharT>
1685 {
1686 template<typename _ParseContext>
1687 constexpr typename _ParseContext::iterator
1688 parse(_ParseContext& __pc)
1689 { return _M_f._M_parse(__pc, __format::_Weekday); }
1690
1691 template<typename _FormatContext>
1692 typename _FormatContext::iterator
1693 format(const chrono::weekday& __t, _FormatContext& __fc) const
1694 { return _M_f._M_format(__t, __fc); }
1695
1696 private:
1697 __format::__formatter_chrono<_CharT> _M_f;
1698 };
1699
1700 template<typename _CharT>
1701 struct formatter<chrono::weekday_indexed, _CharT>
1702 {
1703 template<typename _ParseContext>
1704 constexpr typename _ParseContext::iterator
1705 parse(_ParseContext& __pc)
1706 { return _M_f._M_parse(__pc, __format::_Weekday); }
1707
1708 template<typename _FormatContext>
1709 typename _FormatContext::iterator
1710 format(const chrono::weekday_indexed& __t, _FormatContext& __fc) const
1711 { return _M_f._M_format(__t, __fc); }
1712
1713 private:
1714 __format::__formatter_chrono<_CharT> _M_f;
1715 };
1716
1717 template<typename _CharT>
1718 struct formatter<chrono::weekday_last, _CharT>
1719 {
1720 template<typename _ParseContext>
1721 constexpr typename _ParseContext::iterator
1722 parse(_ParseContext& __pc)
1723 { return _M_f._M_parse(__pc, __format::_Weekday); }
1724
1725 template<typename _FormatContext>
1726 typename _FormatContext::iterator
1727 format(const chrono::weekday_last& __t, _FormatContext& __fc) const
1728 { return _M_f._M_format(__t, __fc); }
1729
1730 private:
1731 __format::__formatter_chrono<_CharT> _M_f;
1732 };
1733
1734 template<typename _CharT>
1735 struct formatter<chrono::month_day, _CharT>
1736 {
1737 template<typename _ParseContext>
1738 constexpr typename _ParseContext::iterator
1739 parse(_ParseContext& __pc)
1740 { return _M_f._M_parse(__pc, __format::_Month|__format::_Day); }
1741
1742 template<typename _FormatContext>
1743 typename _FormatContext::iterator
1744 format(const chrono::month_day& __t, _FormatContext& __fc) const
1745 { return _M_f._M_format(__t, __fc); }
1746
1747 private:
1748 __format::__formatter_chrono<_CharT> _M_f;
1749 };
1750
1751 template<typename _CharT>
1752 struct formatter<chrono::month_day_last, _CharT>
1753 {
1754 template<typename _ParseContext>
1755 constexpr typename _ParseContext::iterator
1756 parse(_ParseContext& __pc)
1757 { return _M_f._M_parse(__pc, __format::_Month|__format::_Day); }
1758
1759 template<typename _FormatContext>
1760 typename _FormatContext::iterator
1761 format(const chrono::month_day_last& __t, _FormatContext& __fc) const
1762 { return _M_f._M_format(__t, __fc); }
1763
1764 private:
1765 __format::__formatter_chrono<_CharT> _M_f;
1766 };
1767
1768 template<typename _CharT>
1769 struct formatter<chrono::month_weekday, _CharT>
1770 {
1771 template<typename _ParseContext>
1772 constexpr typename _ParseContext::iterator
1773 parse(_ParseContext& __pc)
1774 { return _M_f._M_parse(__pc, __format::_Month|__format::_Weekday); }
1775
1776 template<typename _FormatContext>
1777 typename _FormatContext::iterator
1778 format(const chrono::month_weekday& __t, _FormatContext& __fc) const
1779 { return _M_f._M_format(__t, __fc); }
1780
1781 private:
1782 __format::__formatter_chrono<_CharT> _M_f;
1783 };
1784
1785 template<typename _CharT>
1786 struct formatter<chrono::month_weekday_last, _CharT>
1787 {
1788 template<typename _ParseContext>
1789 constexpr typename _ParseContext::iterator
1790 parse(_ParseContext& __pc)
1791 { return _M_f._M_parse(__pc, __format::_Month|__format::_Weekday); }
1792
1793 template<typename _FormatContext>
1794 typename _FormatContext::iterator
1795 format(const chrono::month_weekday_last& __t,
1796 _FormatContext& __fc) const
1797 { return _M_f._M_format(__t, __fc); }
1798
1799 private:
1800 __format::__formatter_chrono<_CharT> _M_f;
1801 };
1802
1803 template<typename _CharT>
1804 struct formatter<chrono::year_month, _CharT>
1805 {
1806 template<typename _ParseContext>
1807 constexpr typename _ParseContext::iterator
1808 parse(_ParseContext& __pc)
1809 { return _M_f._M_parse(__pc, __format::_Year|__format::_Month); }
1810
1811 template<typename _FormatContext>
1812 typename _FormatContext::iterator
1813 format(const chrono::year_month& __t, _FormatContext& __fc) const
1814 { return _M_f._M_format(__t, __fc); }
1815
1816 private:
1817 __format::__formatter_chrono<_CharT> _M_f;
1818 };
1819
1820 template<typename _CharT>
1821 struct formatter<chrono::year_month_day, _CharT>
1822 {
1823 template<typename _ParseContext>
1824 constexpr typename _ParseContext::iterator
1825 parse(_ParseContext& __pc)
1826 { return _M_f._M_parse(__pc, __format::_Date); }
1827
1828 template<typename _FormatContext>
1829 typename _FormatContext::iterator
1830 format(const chrono::year_month_day& __t, _FormatContext& __fc) const
1831 { return _M_f._M_format(__t, __fc); }
1832
1833 private:
1834 __format::__formatter_chrono<_CharT> _M_f;
1835 };
1836
1837 template<typename _CharT>
1838 struct formatter<chrono::year_month_day_last, _CharT>
1839 {
1840 template<typename _ParseContext>
1841 constexpr typename _ParseContext::iterator
1842 parse(_ParseContext& __pc)
1843 { return _M_f._M_parse(__pc, __format::_Date); }
1844
1845 template<typename _FormatContext>
1846 typename _FormatContext::iterator
1847 format(const chrono::year_month_day_last& __t,
1848 _FormatContext& __fc) const
1849 { return _M_f._M_format(__t, __fc); }
1850
1851 private:
1852 __format::__formatter_chrono<_CharT> _M_f;
1853 };
1854
1855 template<typename _CharT>
1856 struct formatter<chrono::year_month_weekday, _CharT>
1857 {
1858 template<typename _ParseContext>
1859 constexpr typename _ParseContext::iterator
1860 parse(_ParseContext& __pc)
1861 { return _M_f._M_parse(__pc, __format::_Date); }
1862
1863 template<typename _FormatContext>
1864 typename _FormatContext::iterator
1865 format(const chrono::year_month_weekday& __t,
1866 _FormatContext& __fc) const
1867 { return _M_f._M_format(__t, __fc); }
1868
1869 private:
1870 __format::__formatter_chrono<_CharT> _M_f;
1871 };
1872
1873 template<typename _CharT>
1874 struct formatter<chrono::year_month_weekday_last, _CharT>
1875 {
1876 template<typename _ParseContext>
1877 constexpr typename _ParseContext::iterator
1878 parse(_ParseContext& __pc)
1879 { return _M_f._M_parse(__pc, __format::_Date); }
1880
1881 template<typename _FormatContext>
1882 typename _FormatContext::iterator
1883 format(const chrono::year_month_weekday_last& __t,
1884 _FormatContext& __fc) const
1885 { return _M_f._M_format(__t, __fc); }
1886
1887 private:
1888 __format::__formatter_chrono<_CharT> _M_f;
1889 };
1890
1891 template<typename _Rep, typename _Period, typename _CharT>
1892 struct formatter<chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>, _CharT>
1893 {
1894 template<typename _ParseContext>
1895 constexpr typename _ParseContext::iterator
1896 parse(_ParseContext& __pc)
1897 { return _M_f._M_parse(__pc, __format::_TimeOfDay); }
1898
1899 template<typename _FormatContext>
1900 typename _FormatContext::iterator
1901 format(const chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>& __t,
1902 _FormatContext& __fc) const
1903 { return _M_f._M_format(__t, __fc); }
1904
1905 private:
1906 __format::__formatter_chrono<_CharT> _M_f;
1907 };
1908
1909#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
1910 template<typename _CharT>
1911 struct formatter<chrono::sys_info, _CharT>
1912 {
1913 template<typename _ParseContext>
1914 constexpr typename _ParseContext::iterator
1915 parse(_ParseContext& __pc)
1916 { return _M_f._M_parse(__pc, __format::_ChronoParts{}); }
1917
1918 template<typename _FormatContext>
1919 typename _FormatContext::iterator
1920 format(const chrono::sys_info& __i, _FormatContext& __fc) const
1921 { return _M_f._M_format(__i, __fc); }
1922
1923 private:
1924 __format::__formatter_chrono<_CharT> _M_f;
1925 };
1926
1927 template<typename _CharT>
1928 struct formatter<chrono::local_info, _CharT>
1929 {
1930 template<typename _ParseContext>
1931 constexpr typename _ParseContext::iterator
1932 parse(_ParseContext& __pc)
1933 { return _M_f._M_parse(__pc, __format::_ChronoParts{}); }
1934
1935 template<typename _FormatContext>
1936 typename _FormatContext::iterator
1937 format(const chrono::local_info& __i, _FormatContext& __fc) const
1938 { return _M_f._M_format(__i, __fc); }
1939
1940 private:
1941 __format::__formatter_chrono<_CharT> _M_f;
1942 };
1943#endif
1944
1945 template<typename _Duration, typename _CharT>
1946 struct formatter<chrono::sys_time<_Duration>, _CharT>
1947 {
1948 template<typename _ParseContext>
1949 constexpr typename _ParseContext::iterator
1950 parse(_ParseContext& __pc)
1951 {
1952 auto __next = _M_f._M_parse(__pc, __format::_ZonedDateTime);
1953 if constexpr (!__stream_insertable)
1954 if (_M_f._M_spec._M_chrono_specs.empty())
1955 __format::__invalid_chrono_spec(); // chrono-specs can't be empty
1956 return __next;
1957 }
1958
1959 template<typename _FormatContext>
1960 typename _FormatContext::iterator
1961 format(const chrono::sys_time<_Duration>& __t,
1962 _FormatContext& __fc) const
1963 { return _M_f._M_format(__t, __fc); }
1964
1965 private:
1966 static constexpr bool __stream_insertable
1967 = requires (basic_ostream<_CharT>& __os,
1968 chrono::sys_time<_Duration> __t) { __os << __t; };
1969
1970 __format::__formatter_chrono<_CharT> _M_f;
1971 };
1972
1973 template<typename _Duration, typename _CharT>
1974 struct formatter<chrono::utc_time<_Duration>, _CharT>
1975 : __format::__formatter_chrono<_CharT>
1976 {
1977 template<typename _ParseContext>
1978 constexpr typename _ParseContext::iterator
1979 parse(_ParseContext& __pc)
1980 { return _M_f._M_parse(__pc, __format::_ZonedDateTime); }
1981
1982 template<typename _FormatContext>
1983 typename _FormatContext::iterator
1984 format(const chrono::utc_time<_Duration>& __t,
1985 _FormatContext& __fc) const
1986 {
1987 // Adjust by removing leap seconds to get equivalent sys_time.
1988 // We can't just use clock_cast because we want to know if the time
1989 // falls within a leap second insertion, and format seconds as "60".
1990 using chrono::__detail::__utc_leap_second;
1991 using chrono::seconds;
1992 using chrono::sys_time;
1993 using _CDur = common_type_t<_Duration, seconds>;
1994 const auto __li = chrono::get_leap_second_info(__t);
1995 sys_time<_CDur> __s{__t.time_since_epoch() - __li.elapsed};
1996 if (!__li.is_leap_second) [[likely]]
1997 return _M_f._M_format(__s, __fc);
1998 else
1999 return _M_f._M_format(__utc_leap_second(__s), __fc);
2000 }
2001
2002 private:
2003 friend formatter<chrono::__detail::__utc_leap_second<_Duration>, _CharT>;
2004
2005 __format::__formatter_chrono<_CharT> _M_f;
2006 };
2007
2008 template<typename _Duration, typename _CharT>
2009 struct formatter<chrono::tai_time<_Duration>, _CharT>
2010 : __format::__formatter_chrono<_CharT>
2011 {
2012 template<typename _ParseContext>
2013 constexpr typename _ParseContext::iterator
2014 parse(_ParseContext& __pc)
2015 { return _M_f._M_parse(__pc, __format::_ZonedDateTime); }
2016
2017 template<typename _FormatContext>
2018 typename _FormatContext::iterator
2019 format(const chrono::tai_time<_Duration>& __t,
2020 _FormatContext& __fc) const
2021 {
2022 // Convert to __local_time_fmt with abbrev "TAI" and offset 0s.
2023
2024 // Offset is 1970y/January/1 - 1958y/January/1
2025 constexpr chrono::days __tai_offset = chrono::days(4383);
2026 using _CDur = common_type_t<_Duration, chrono::days>;
2027 chrono::local_time<_CDur> __lt(__t.time_since_epoch() - __tai_offset);
2028 const string __abbrev("TAI", 3);
2029 const chrono::seconds __off = 0s;
2030 const auto __lf = chrono::local_time_format(__lt, &__abbrev, &__off);
2031 return _M_f._M_format(__lf, __fc);
2032 }
2033
2034 private:
2035 __format::__formatter_chrono<_CharT> _M_f;
2036 };
2037
2038 template<typename _Duration, typename _CharT>
2039 struct formatter<chrono::gps_time<_Duration>, _CharT>
2040 : __format::__formatter_chrono<_CharT>
2041 {
2042 template<typename _ParseContext>
2043 constexpr typename _ParseContext::iterator
2044 parse(_ParseContext& __pc)
2045 { return _M_f._M_parse(__pc, __format::_ZonedDateTime); }
2046
2047 template<typename _FormatContext>
2048 typename _FormatContext::iterator
2049 format(const chrono::gps_time<_Duration>& __t,
2050 _FormatContext& __fc) const
2051 {
2052 // Convert to __local_time_fmt with abbrev "GPS" and offset 0s.
2053
2054 // Offset is 1980y/January/Sunday[1] - 1970y/January/1
2055 constexpr chrono::days __gps_offset = chrono::days(3657);
2056 using _CDur = common_type_t<_Duration, chrono::days>;
2057 chrono::local_time<_CDur> __lt(__t.time_since_epoch() + __gps_offset);
2058 const string __abbrev("GPS", 3);
2059 const chrono::seconds __off = 0s;
2060 const auto __lf = chrono::local_time_format(__lt, &__abbrev, &__off);
2061 return _M_f._M_format(__lf, __fc);
2062 }
2063
2064 private:
2065 __format::__formatter_chrono<_CharT> _M_f;
2066 };
2067
2068 template<typename _Duration, typename _CharT>
2069 struct formatter<chrono::file_time<_Duration>, _CharT>
2070 {
2071 template<typename _ParseContext>
2072 constexpr typename _ParseContext::iterator
2073 parse(_ParseContext& __pc)
2074 { return _M_f._M_parse(__pc, __format::_ZonedDateTime); }
2075
2076 template<typename _FormatContext>
2077 typename _FormatContext::iterator
2078 format(const chrono::file_time<_Duration>& __t,
2079 _FormatContext& __ctx) const
2080 {
2081 using namespace chrono;
2082 return _M_f._M_format(chrono::clock_cast<system_clock>(__t), __ctx);
2083 }
2084
2085 private:
2086 __format::__formatter_chrono<_CharT> _M_f;
2087 };
2088
2089 template<typename _Duration, typename _CharT>
2090 struct formatter<chrono::local_time<_Duration>, _CharT>
2091 {
2092 template<typename _ParseContext>
2093 constexpr typename _ParseContext::iterator
2094 parse(_ParseContext& __pc)
2095 { return _M_f._M_parse(__pc, __format::_DateTime); }
2096
2097 template<typename _FormatContext>
2098 typename _FormatContext::iterator
2099 format(const chrono::local_time<_Duration>& __t,
2100 _FormatContext& __ctx) const
2101 { return _M_f._M_format(__t, __ctx); }
2102
2103 private:
2104 __format::__formatter_chrono<_CharT> _M_f;
2105 };
2106
2107 template<typename _Duration, typename _CharT>
2108 struct formatter<chrono::__detail::__local_time_fmt<_Duration>, _CharT>
2109 {
2110 template<typename _ParseContext>
2111 constexpr typename _ParseContext::iterator
2112 parse(_ParseContext& __pc)
2113 { return _M_f._M_parse(__pc, __format::_ZonedDateTime); }
2114
2115 template<typename _FormatContext>
2116 typename _FormatContext::iterator
2117 format(const chrono::__detail::__local_time_fmt<_Duration>& __t,
2118 _FormatContext& __ctx) const
2119 { return _M_f._M_format(__t, __ctx); }
2120
2121 private:
2122 __format::__formatter_chrono<_CharT> _M_f;
2123 };
2124
2125#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
2126 template<typename _Duration, typename _TimeZonePtr, typename _CharT>
2127 struct formatter<chrono::zoned_time<_Duration, _TimeZonePtr>, _CharT>
2128 : formatter<chrono::__detail::__local_time_fmt<_Duration>, _CharT>
2129 {
2130 template<typename _FormatContext>
2131 typename _FormatContext::iterator
2132 format(const chrono::zoned_time<_Duration, _TimeZonePtr>& __tp,
2133 _FormatContext& __ctx) const
2134 {
2135 using chrono::__detail::__local_time_fmt;
2136 using _Base = formatter<__local_time_fmt<_Duration>, _CharT>;
2137 const chrono::sys_info __info = __tp.get_info();
2138 const auto __lf = chrono::local_time_format(__tp.get_local_time(),
2139 &__info.abbrev,
2140 &__info.offset);
2141 return _Base::format(__lf, __ctx);
2142 }
2143 };
2144#endif
2145
2146 // Partial specialization needed for %c formatting of __utc_leap_second.
2147 template<typename _Duration, typename _CharT>
2148 struct formatter<chrono::__detail::__utc_leap_second<_Duration>, _CharT>
2149 : formatter<chrono::utc_time<_Duration>, _CharT>
2150 {
2151 template<typename _FormatContext>
2152 typename _FormatContext::iterator
2153 format(const chrono::__detail::__utc_leap_second<_Duration>& __t,
2154 _FormatContext& __fc) const
2155 { return this->_M_f._M_format(__t, __fc); }
2156 };
2157
2158namespace chrono
2159{
2160/// @addtogroup chrono
2161/// @{
2162
2163/// @cond undocumented
2164namespace __detail
2165{
2166 template<typename _Duration = seconds>
2167 struct _Parser
2168 {
2169 static_assert(is_same_v<common_type_t<_Duration, seconds>, _Duration>);
2170
2171 explicit
2172 _Parser(__format::_ChronoParts __need) : _M_need(__need) { }
2173
2174 _Parser(_Parser&&) = delete;
2175 void operator=(_Parser&&) = delete;
2176
2177 _Duration _M_time{}; // since midnight
2178 sys_days _M_sys_days{};
2179 year_month_day _M_ymd{};
2180 weekday _M_wd{};
2181 __format::_ChronoParts _M_need;
2182 unsigned _M_is_leap_second : 1 {};
2183 unsigned _M_reserved : 15 {};
2184
2185 template<typename _CharT, typename _Traits, typename _Alloc>
2186 basic_istream<_CharT, _Traits>&
2187 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2188 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2189 minutes* __offset = nullptr);
2190
2191 private:
2192 // Read an unsigned integer from the stream and return it.
2193 // Extract no more than __n digits. Set failbit if an integer isn't read.
2194 template<typename _CharT, typename _Traits>
2195 static int_least32_t
2196 _S_read_unsigned(basic_istream<_CharT, _Traits>& __is,
2197 ios_base::iostate& __err, int __n)
2198 {
2199 int_least32_t __val = _S_try_read_digit(__is, __err);
2200 if (__val == -1) [[unlikely]]
2201 __err |= ios_base::failbit;
2202 else
2203 {
2204 int __n1 = (std::min)(__n, 9);
2205 // Cannot overflow __val unless we read more than 9 digits
2206 for (int __i = 1; __i < __n1; ++__i)
2207 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
2208 {
2209 __val *= 10;
2210 __val += __dig;
2211 }
2212
2213 while (__n1++ < __n) [[unlikely]]
2214 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
2215 {
2216 if (__builtin_mul_overflow(__val, 10, &__val)
2217 || __builtin_add_overflow(__val, __dig, &__val))
2218 {
2219 __err |= ios_base::failbit;
2220 return -1;
2221 }
2222 }
2223 }
2224 return __val;
2225 }
2226
2227 // Read an unsigned integer from the stream and return it.
2228 // Extract no more than __n digits. Set failbit if an integer isn't read.
2229 template<typename _CharT, typename _Traits>
2230 static int_least32_t
2231 _S_read_signed(basic_istream<_CharT, _Traits>& __is,
2232 ios_base::iostate& __err, int __n)
2233 {
2234 auto __sign = __is.peek();
2235 if (__sign == '-' || __sign == '+')
2236 (void) __is.get();
2237 int_least32_t __val = _S_read_unsigned(__is, __err, __n);
2238 if (__err & ios_base::failbit)
2239 {
2240 if (__sign == '-') [[unlikely]]
2241 __val *= -1;
2242 }
2243 return __val;
2244 }
2245
2246 // Read a digit from the stream and return it, or return -1.
2247 // If no digit is read eofbit will be set (but not failbit).
2248 template<typename _CharT, typename _Traits>
2249 static int_least32_t
2250 _S_try_read_digit(basic_istream<_CharT, _Traits>& __is,
2251 ios_base::iostate& __err)
2252 {
2253 int_least32_t __val = -1;
2254 auto __i = __is.peek();
2255 if (!_Traits::eq_int_type(__i, _Traits::eof())) [[likely]]
2256 {
2257 _CharT __c = _Traits::to_char_type(__i);
2258 if (_CharT('0') <= __c && __c <= _CharT('9')) [[likely]]
2259 {
2260 (void) __is.get();
2261 __val = __c - _CharT('0');
2262 }
2263 }
2264 else
2265 __err |= ios_base::eofbit;
2266 return __val;
2267 }
2268
2269 // Read the specified character and return true.
2270 // If the character is not found, set failbit and return false.
2271 template<typename _CharT, typename _Traits>
2272 static bool
2273 _S_read_chr(basic_istream<_CharT, _Traits>& __is,
2274 ios_base::iostate& __err, _CharT __c)
2275 {
2276 auto __i = __is.peek();
2277 if (_Traits::eq_int_type(__i, _Traits::eof()))
2278 __err |= ios_base::eofbit;
2279 else if (_Traits::to_char_type(__i) == __c) [[likely]]
2280 {
2281 (void) __is.get();
2282 return true;
2283 }
2284 __err |= ios_base::failbit;
2285 return false;
2286 }
2287 };
2288
2289 template<typename _Duration>
2290 using _Parser_t = _Parser<common_type_t<_Duration, seconds>>;
2291
2292} // namespace __detail
2293/// @endcond
2294
2295 template<typename _CharT, typename _Traits, typename _Rep, typename _Period,
2296 typename _Alloc = allocator<_CharT>>
2297 inline basic_istream<_CharT, _Traits>&
2298 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2299 duration<_Rep, _Period>& __d,
2300 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2301 minutes* __offset = nullptr)
2302 {
2303 auto __need = __format::_ChronoParts::_TimeOfDay;
2304 __detail::_Parser_t<duration<_Rep, _Period>> __p(__need);
2305 if (__p(__is, __fmt, __abbrev, __offset))
2306 __d = chrono::duration_cast<duration<_Rep, _Period>>(__p._M_time);
2307 return __is;
2308 }
2309
2310 template<typename _CharT, typename _Traits>
2311 inline basic_ostream<_CharT, _Traits>&
2312 operator<<(basic_ostream<_CharT, _Traits>& __os, const day& __d)
2313 {
2314 using _Ctx = __format::__format_context<_CharT>;
2315 using _Str = basic_string_view<_CharT>;
2316 _Str __s = _GLIBCXX_WIDEN("{:02d} is not a valid day");
2317 if (__d.ok())
2318 __s = __s.substr(0, 6);
2319 auto __u = (unsigned)__d;
2320 __os << std::vformat(__s, make_format_args<_Ctx>(__u));
2321 return __os;
2322 }
2323
2324 template<typename _CharT, typename _Traits,
2325 typename _Alloc = allocator<_CharT>>
2326 inline basic_istream<_CharT, _Traits>&
2327 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2328 day& __d,
2329 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2330 minutes* __offset = nullptr)
2331 {
2332 __detail::_Parser<> __p(__format::_ChronoParts::_Day);
2333 if (__p(__is, __fmt, __abbrev, __offset))
2334 __d = __p._M_ymd.day();
2335 return __is;
2336 }
2337
2338 template<typename _CharT, typename _Traits>
2339 inline basic_ostream<_CharT, _Traits>&
2340 operator<<(basic_ostream<_CharT, _Traits>& __os, const month& __m)
2341 {
2342 using _Ctx = __format::__format_context<_CharT>;
2343 using _Str = basic_string_view<_CharT>;
2344 _Str __s = _GLIBCXX_WIDEN("{:L%b}{} is not a valid month");
2345 if (__m.ok())
2346 __os << std::vformat(__os.getloc(), __s.substr(0, 6),
2347 make_format_args<_Ctx>(__m));
2348 else
2349 {
2350 auto __u = (unsigned)__m;
2351 __os << std::vformat(__s.substr(6), make_format_args<_Ctx>(__u));
2352 }
2353 return __os;
2354 }
2355
2356 template<typename _CharT, typename _Traits,
2357 typename _Alloc = allocator<_CharT>>
2358 inline basic_istream<_CharT, _Traits>&
2359 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2360 month& __m,
2361 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2362 minutes* __offset = nullptr)
2363 {
2364 __detail::_Parser<> __p(__format::_ChronoParts::_Month);
2365 if (__p(__is, __fmt, __abbrev, __offset))
2366 __m = __p._M_ymd.month();
2367 return __is;
2368 }
2369
2370 template<typename _CharT, typename _Traits>
2371 inline basic_ostream<_CharT, _Traits>&
2372 operator<<(basic_ostream<_CharT, _Traits>& __os, const year& __y)
2373 {
2374 using _Ctx = __format::__format_context<_CharT>;
2375 using _Str = basic_string_view<_CharT>;
2376 _Str __s = _GLIBCXX_WIDEN("-{:04d} is not a valid year");
2377 if (__y.ok())
2378 __s = __s.substr(0, 7);
2379 int __i = (int)__y;
2380 if (__i >= 0) [[likely]]
2381 __s.remove_prefix(1);
2382 else
2383 __i = -__i;
2384 __os << std::vformat(__s, make_format_args<_Ctx>(__i));
2385 return __os;
2386 }
2387
2388 template<typename _CharT, typename _Traits,
2389 typename _Alloc = allocator<_CharT>>
2390 inline basic_istream<_CharT, _Traits>&
2391 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2392 year& __y,
2393 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2394 minutes* __offset = nullptr)
2395 {
2396 __detail::_Parser<> __p(__format::_ChronoParts::_Year);
2397 if (__p(__is, __fmt, __abbrev, __offset))
2398 __y = __p._M_ymd.year();
2399 return __is;
2400 }
2401
2402 template<typename _CharT, typename _Traits>
2403 inline basic_ostream<_CharT, _Traits>&
2404 operator<<(basic_ostream<_CharT, _Traits>& __os, const weekday& __wd)
2405 {
2406 using _Ctx = __format::__format_context<_CharT>;
2407 using _Str = basic_string_view<_CharT>;
2408 _Str __s = _GLIBCXX_WIDEN("{:L%a}{} is not a valid weekday");
2409 if (__wd.ok())
2410 __os << std::vformat(__os.getloc(), __s.substr(0, 6),
2411 make_format_args<_Ctx>(__wd));
2412 else
2413 {
2414 auto __c = __wd.c_encoding();
2415 __os << std::vformat(__s.substr(6), make_format_args<_Ctx>(__c));
2416 }
2417 return __os;
2418 }
2419
2420 template<typename _CharT, typename _Traits,
2421 typename _Alloc = allocator<_CharT>>
2422 inline basic_istream<_CharT, _Traits>&
2423 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2424 weekday& __wd,
2425 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2426 minutes* __offset = nullptr)
2427 {
2428 __detail::_Parser<> __p(__format::_ChronoParts::_Weekday);
2429 if (__p(__is, __fmt, __abbrev, __offset))
2430 __wd = __p._M_wd;
2431 return __is;
2432 }
2433
2434 template<typename _CharT, typename _Traits>
2435 inline basic_ostream<_CharT, _Traits>&
2436 operator<<(basic_ostream<_CharT, _Traits>& __os,
2437 const weekday_indexed& __wdi)
2438 {
2439 // The standard says to format wdi.weekday() and wdi.index() using
2440 // either "{:L}[{}]" or "{:L}[{} is not a valid index]". The {:L} spec
2441 // means to format the weekday using ostringstream, so just do that.
2442 basic_stringstream<_CharT> __os2;
2443 __os2.imbue(__os.getloc());
2444 __os2 << __wdi.weekday();
2445 const auto __i = __wdi.index();
2446 basic_string_view<_CharT> __s
2447 = _GLIBCXX_WIDEN("[ is not a valid index]");
2448 __os2 << __s[0];
2449 __os2 << std::format(_GLIBCXX_WIDEN("{}"), __i);
2450 if (__i >= 1 && __i <= 5)
2451 __os2 << __s.back();
2452 else
2453 __os2 << __s.substr(1);
2454 __os << __os2.view();
2455 return __os;
2456 }
2457
2458 template<typename _CharT, typename _Traits>
2459 inline basic_ostream<_CharT, _Traits>&
2460 operator<<(basic_ostream<_CharT, _Traits>& __os,
2461 const weekday_last& __wdl)
2462 {
2463 // As above, just write straight to a stringstream, as if by "{:L}[last]"
2464 basic_stringstream<_CharT> __os2;
2465 __os2.imbue(__os.getloc());
2466 __os2 << __wdl.weekday() << _GLIBCXX_WIDEN("[last]");
2467 __os << __os2.view();
2468 return __os;
2469 }
2470
2471 template<typename _CharT, typename _Traits>
2472 inline basic_ostream<_CharT, _Traits>&
2473 operator<<(basic_ostream<_CharT, _Traits>& __os, const month_day& __md)
2474 {
2475 // As above, just write straight to a stringstream, as if by "{:L}/{}"
2476 basic_stringstream<_CharT> __os2;
2477 __os2.imbue(__os.getloc());
2478 __os2 << __md.month();
2479 if constexpr (is_same_v<_CharT, char>)
2480 __os2 << '/';
2481 else
2482 __os2 << L'/';
2483 __os2 << __md.day();
2484 __os << __os2.view();
2485 return __os;
2486 }
2487
2488 template<typename _CharT, typename _Traits,
2489 typename _Alloc = allocator<_CharT>>
2490 inline basic_istream<_CharT, _Traits>&
2491 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2492 month_day& __md,
2493 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2494 minutes* __offset = nullptr)
2495 {
2496 using __format::_ChronoParts;
2497 auto __need = _ChronoParts::_Month | _ChronoParts::_Day;
2498 __detail::_Parser<> __p(__need);
2499 if (__p(__is, __fmt, __abbrev, __offset))
2500 __md = month_day(__p._M_ymd.month(), __p._M_ymd.day());
2501 return __is;
2502 }
2503
2504 template<typename _CharT, typename _Traits>
2505 inline basic_ostream<_CharT, _Traits>&
2506 operator<<(basic_ostream<_CharT, _Traits>& __os,
2507 const month_day_last& __mdl)
2508 {
2509 // As above, just write straight to a stringstream, as if by "{:L}/last"
2510 basic_stringstream<_CharT> __os2;
2511 __os2.imbue(__os.getloc());
2512 __os2 << __mdl.month() << _GLIBCXX_WIDEN("/last");
2513 __os << __os2.view();
2514 return __os;
2515 }
2516
2517 template<typename _CharT, typename _Traits>
2518 inline basic_ostream<_CharT, _Traits>&
2519 operator<<(basic_ostream<_CharT, _Traits>& __os,
2520 const month_weekday& __mwd)
2521 {
2522 // As above, just write straight to a stringstream, as if by "{:L}/{:L}"
2523 basic_stringstream<_CharT> __os2;
2524 __os2.imbue(__os.getloc());
2525 __os2 << __mwd.month();
2526 if constexpr (is_same_v<_CharT, char>)
2527 __os2 << '/';
2528 else
2529 __os2 << L'/';
2530 __os2 << __mwd.weekday_indexed();
2531 __os << __os2.view();
2532 return __os;
2533 }
2534
2535 template<typename _CharT, typename _Traits>
2536 inline basic_ostream<_CharT, _Traits>&
2537 operator<<(basic_ostream<_CharT, _Traits>& __os,
2538 const month_weekday_last& __mwdl)
2539 {
2540 // As above, just write straight to a stringstream, as if by "{:L}/{:L}"
2541 basic_stringstream<_CharT> __os2;
2542 __os2.imbue(__os.getloc());
2543 __os2 << __mwdl.month();
2544 if constexpr (is_same_v<_CharT, char>)
2545 __os2 << '/';
2546 else
2547 __os2 << L'/';
2548 __os2 << __mwdl.weekday_last();
2549 __os << __os2.view();
2550 return __os;
2551 }
2552
2553 template<typename _CharT, typename _Traits>
2554 inline basic_ostream<_CharT, _Traits>&
2555 operator<<(basic_ostream<_CharT, _Traits>& __os, const year_month& __ym)
2556 {
2557 // As above, just write straight to a stringstream, as if by "{}/{:L}"
2558 basic_stringstream<_CharT> __os2;
2559 __os2.imbue(__os.getloc());
2560 __os2 << __ym.year();
2561 if constexpr (is_same_v<_CharT, char>)
2562 __os2 << '/';
2563 else
2564 __os2 << L'/';
2565 __os2 << __ym.month();
2566 __os << __os2.view();
2567 return __os;
2568 }
2569
2570 template<typename _CharT, typename _Traits,
2571 typename _Alloc = allocator<_CharT>>
2572 inline basic_istream<_CharT, _Traits>&
2573 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2574 year_month& __ym,
2575 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2576 minutes* __offset = nullptr)
2577 {
2578 using __format::_ChronoParts;
2579 auto __need = _ChronoParts::_Year | _ChronoParts::_Month;
2580 __detail::_Parser<> __p(__need);
2581 if (__p(__is, __fmt, __abbrev, __offset))
2582 __ym = year_month(__p._M_ymd.year(), __p._M_ymd.month());
2583 return __is;
2584 }
2585
2586 template<typename _CharT, typename _Traits>
2587 inline basic_ostream<_CharT, _Traits>&
2588 operator<<(basic_ostream<_CharT, _Traits>& __os,
2589 const year_month_day& __ymd)
2590 {
2591 using _Ctx = __format::__format_context<_CharT>;
2592 using _Str = basic_string_view<_CharT>;
2593 _Str __s = _GLIBCXX_WIDEN("{:%F} is not a valid date");
2594 __os << std::vformat(__ymd.ok() ? __s.substr(0, 5) : __s,
2595 make_format_args<_Ctx>(__ymd));
2596 return __os;
2597 }
2598
2599 template<typename _CharT, typename _Traits,
2600 typename _Alloc = allocator<_CharT>>
2601 inline basic_istream<_CharT, _Traits>&
2602 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2603 year_month_day& __ymd,
2605 minutes* __offset = nullptr)
2606 {
2607 using __format::_ChronoParts;
2608 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2609 | _ChronoParts::_Day;
2610 __detail::_Parser<> __p(__need);
2611 if (__p(__is, __fmt, __abbrev, __offset))
2612 __ymd = __p._M_ymd;
2613 return __is;
2614 }
2615
2616 template<typename _CharT, typename _Traits>
2619 const year_month_day_last& __ymdl)
2620 {
2621 // As above, just write straight to a stringstream, as if by "{}/{:L}"
2623 __os2.imbue(__os.getloc());
2624 __os2 << __ymdl.year();
2625 if constexpr (is_same_v<_CharT, char>)
2626 __os2 << '/';
2627 else
2628 __os2 << L'/';
2629 __os2 << __ymdl.month_day_last();
2630 __os << __os2.view();
2631 return __os;
2632 }
2633
2634 template<typename _CharT, typename _Traits>
2635 inline basic_ostream<_CharT, _Traits>&
2636 operator<<(basic_ostream<_CharT, _Traits>& __os,
2637 const year_month_weekday& __ymwd)
2638 {
2639 // As above, just write straight to a stringstream, as if by
2640 // "{}/{:L}/{:L}"
2641 basic_stringstream<_CharT> __os2;
2642 __os2.imbue(__os.getloc());
2643 _CharT __slash;
2644 if constexpr (is_same_v<_CharT, char>)
2645 __slash = '/';
2646 else
2647 __slash = L'/';
2648 __os2 << __ymwd.year() << __slash << __ymwd.month() << __slash
2649 << __ymwd.weekday_indexed();
2650 __os << __os2.view();
2651 return __os;
2652 }
2653
2654 template<typename _CharT, typename _Traits>
2655 inline basic_ostream<_CharT, _Traits>&
2656 operator<<(basic_ostream<_CharT, _Traits>& __os,
2657 const year_month_weekday_last& __ymwdl)
2658 {
2659 // As above, just write straight to a stringstream, as if by
2660 // "{}/{:L}/{:L}"
2661 basic_stringstream<_CharT> __os2;
2662 __os2.imbue(__os.getloc());
2663 _CharT __slash;
2664 if constexpr (is_same_v<_CharT, char>)
2665 __slash = '/';
2666 else
2667 __slash = L'/';
2668 __os2 << __ymwdl.year() << __slash << __ymwdl.month() << __slash
2669 << __ymwdl.weekday_last();
2670 __os << __os2.view();
2671 return __os;
2672 }
2673
2674 template<typename _CharT, typename _Traits, typename _Duration>
2675 inline basic_ostream<_CharT, _Traits>&
2676 operator<<(basic_ostream<_CharT, _Traits>& __os,
2677 const hh_mm_ss<_Duration>& __hms)
2678 {
2679 return __os << format(__os.getloc(), _GLIBCXX_WIDEN("{:L%T}"), __hms);
2680 }
2681
2682#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
2683 /// Writes a sys_info object to an ostream in an unspecified format.
2684 template<typename _CharT, typename _Traits>
2685 basic_ostream<_CharT, _Traits>&
2686 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_info& __i)
2687 {
2688 __os << '[' << __i.begin << ',' << __i.end
2689 << ',' << hh_mm_ss(__i.offset) << ',' << __i.save
2690 << ',' << __i.abbrev << ']';
2691 return __os;
2692 }
2693
2694 /// Writes a local_info object to an ostream in an unspecified format.
2695 template<typename _CharT, typename _Traits>
2696 basic_ostream<_CharT, _Traits>&
2697 operator<<(basic_ostream<_CharT, _Traits>& __os, const local_info& __li)
2698 {
2699 __os << '[';
2700 if (__li.result == local_info::unique)
2701 __os << __li.first;
2702 else
2703 {
2704 if (__li.result == local_info::nonexistent)
2705 __os << "nonexistent";
2706 else
2707 __os << "ambiguous";
2708 __os << " local time between " << __li.first;
2709 __os << " and " << __li.second;
2710 }
2711 __os << ']';
2712 return __os;
2713 }
2714
2715 template<typename _CharT, typename _Traits, typename _Duration,
2716 typename _TimeZonePtr>
2717 inline basic_ostream<_CharT, _Traits>&
2718 operator<<(basic_ostream<_CharT, _Traits>& __os,
2719 const zoned_time<_Duration, _TimeZonePtr>& __t)
2720 {
2721 __os << format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T %Z}"), __t);
2722 return __os;
2723 }
2724#endif
2725
2726 template<typename _CharT, typename _Traits, typename _Duration>
2727 requires (!treat_as_floating_point_v<typename _Duration::rep>)
2728 && ratio_less_v<typename _Duration::period, days::period>
2729 inline basic_ostream<_CharT, _Traits>&
2730 operator<<(basic_ostream<_CharT, _Traits>& __os,
2731 const sys_time<_Duration>& __tp)
2732 {
2733 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __tp);
2734 return __os;
2735 }
2736
2737 template<typename _CharT, typename _Traits>
2738 inline basic_ostream<_CharT, _Traits>&
2739 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_days& __dp)
2740 {
2741 __os << year_month_day{__dp};
2742 return __os;
2743 }
2744
2745 template<typename _CharT, typename _Traits, typename _Duration,
2746 typename _Alloc = allocator<_CharT>>
2747 basic_istream<_CharT, _Traits>&
2748 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2749 sys_time<_Duration>& __tp,
2750 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2751 minutes* __offset = nullptr)
2752 {
2753 minutes __off{};
2754 if (!__offset)
2755 __offset = &__off;
2756 using __format::_ChronoParts;
2757 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2758 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
2759 __detail::_Parser_t<_Duration> __p(__need);
2760 if (__p(__is, __fmt, __abbrev, __offset))
2761 {
2762 if (__p._M_is_leap_second)
2763 __is.setstate(ios_base::failbit);
2764 else
2765 {
2766 auto __st = __p._M_sys_days + __p._M_time - *__offset;
2767 __tp = chrono::time_point_cast<_Duration>(__st);
2768 }
2769 }
2770 return __is;
2771 }
2772
2773 template<typename _CharT, typename _Traits, typename _Duration>
2774 inline basic_ostream<_CharT, _Traits>&
2775 operator<<(basic_ostream<_CharT, _Traits>& __os,
2776 const utc_time<_Duration>& __t)
2777 {
2778 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
2779 return __os;
2780 }
2781
2782 template<typename _CharT, typename _Traits, typename _Duration,
2783 typename _Alloc = allocator<_CharT>>
2784 inline basic_istream<_CharT, _Traits>&
2785 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2786 utc_time<_Duration>& __tp,
2787 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2788 minutes* __offset = nullptr)
2789 {
2790 minutes __off{};
2791 if (!__offset)
2792 __offset = &__off;
2793 using __format::_ChronoParts;
2794 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2795 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
2796 __detail::_Parser_t<_Duration> __p(__need);
2797 if (__p(__is, __fmt, __abbrev, __offset))
2798 {
2799 // Converting to utc_time before adding _M_time is necessary for
2800 // "23:59:60" to correctly produce a time within a leap second.
2801 auto __ut = utc_clock::from_sys(__p._M_sys_days) + __p._M_time
2802 - *__offset;
2803 __tp = chrono::time_point_cast<_Duration>(__ut);
2804 }
2805 return __is;
2806 }
2807
2808 template<typename _CharT, typename _Traits, typename _Duration>
2809 inline basic_ostream<_CharT, _Traits>&
2810 operator<<(basic_ostream<_CharT, _Traits>& __os,
2811 const tai_time<_Duration>& __t)
2812 {
2813 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
2814 return __os;
2815 }
2816
2817 template<typename _CharT, typename _Traits, typename _Duration,
2818 typename _Alloc = allocator<_CharT>>
2819 inline basic_istream<_CharT, _Traits>&
2820 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2821 tai_time<_Duration>& __tp,
2822 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2823 minutes* __offset = nullptr)
2824 {
2825 minutes __off{};
2826 if (!__offset)
2827 __offset = &__off;
2828 using __format::_ChronoParts;
2829 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2830 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
2831 __detail::_Parser_t<_Duration> __p(__need);
2832 if (__p(__is, __fmt, __abbrev, __offset))
2833 {
2834 if (__p._M_is_leap_second)
2835 __is.setstate(ios_base::failbit);
2836 else
2837 {
2838 auto __st = __p._M_sys_days + __p._M_time - *__offset;
2839 auto __tt = tai_clock::from_utc(utc_clock::from_sys(__st));
2840 __tp = chrono::time_point_cast<_Duration>(__tt);
2841 }
2842 }
2843 return __is;
2844 }
2845
2846 template<typename _CharT, typename _Traits, typename _Duration>
2847 inline basic_ostream<_CharT, _Traits>&
2848 operator<<(basic_ostream<_CharT, _Traits>& __os,
2849 const gps_time<_Duration>& __t)
2850 {
2851 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
2852 return __os;
2853 }
2854
2855 template<typename _CharT, typename _Traits, typename _Duration,
2856 typename _Alloc = allocator<_CharT>>
2857 inline basic_istream<_CharT, _Traits>&
2858 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2859 gps_time<_Duration>& __tp,
2860 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2861 minutes* __offset = nullptr)
2862 {
2863 minutes __off{};
2864 if (!__offset)
2865 __offset = &__off;
2866 using __format::_ChronoParts;
2867 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2868 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
2869 __detail::_Parser_t<_Duration> __p(__need);
2870 if (__p(__is, __fmt, __abbrev, __offset))
2871 {
2872 if (__p._M_is_leap_second)
2873 __is.setstate(ios_base::failbit);
2874 else
2875 {
2876 auto __st = __p._M_sys_days + __p._M_time - *__offset;
2877 auto __tt = gps_clock::from_utc(utc_clock::from_sys(__st));
2878 __tp = chrono::time_point_cast<_Duration>(__tt);
2879 }
2880 }
2881 return __is;
2882 }
2883
2884 template<typename _CharT, typename _Traits, typename _Duration>
2885 inline basic_ostream<_CharT, _Traits>&
2886 operator<<(basic_ostream<_CharT, _Traits>& __os,
2887 const file_time<_Duration>& __t)
2888 {
2889 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
2890 return __os;
2891 }
2892
2893 template<typename _CharT, typename _Traits, typename _Duration,
2894 typename _Alloc = allocator<_CharT>>
2895 inline basic_istream<_CharT, _Traits>&
2896 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2897 file_time<_Duration>& __tp,
2898 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2899 minutes* __offset = nullptr)
2900 {
2901 sys_time<_Duration> __st;
2902 if (chrono::from_stream(__is, __fmt, __st, __abbrev, __offset))
2903 __tp = chrono::time_point_cast<_Duration>(file_clock::from_sys(__st));
2904 return __is;
2905 }
2906
2907 template<typename _CharT, typename _Traits, typename _Duration>
2908 inline basic_ostream<_CharT, _Traits>&
2909 operator<<(basic_ostream<_CharT, _Traits>& __os,
2910 const local_time<_Duration>& __lt)
2911 {
2912 __os << sys_time<_Duration>{__lt.time_since_epoch()};
2913 return __os;
2914 }
2915
2916 template<typename _CharT, typename _Traits, typename _Duration,
2917 typename _Alloc = allocator<_CharT>>
2918 basic_istream<_CharT, _Traits>&
2919 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
2920 local_time<_Duration>& __tp,
2921 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2922 minutes* __offset = nullptr)
2923 {
2924 using __format::_ChronoParts;
2925 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
2926 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
2927 __detail::_Parser_t<_Duration> __p(__need);
2928 if (__p(__is, __fmt, __abbrev, __offset))
2929 {
2930 days __d = __p._M_sys_days.time_since_epoch();
2931 auto __t = local_days(__d) + __p._M_time; // ignore offset
2932 __tp = chrono::time_point_cast<_Duration>(__t);
2933 }
2934 return __is;
2935 }
2936
2937 // [time.parse] parsing
2938
2939namespace __detail
2940{
2941 template<typename _Parsable, typename _CharT,
2942 typename _Traits = std::char_traits<_CharT>,
2943 typename... _OptArgs>
2944 concept __parsable = requires (basic_istream<_CharT, _Traits>& __is,
2945 const _CharT* __fmt, _Parsable& __tp,
2946 _OptArgs*... __args)
2947 { from_stream(__is, __fmt, __tp, __args...); };
2948
2949 template<typename _Parsable, typename _CharT,
2950 typename _Traits = char_traits<_CharT>,
2951 typename _Alloc = allocator<_CharT>>
2952 struct _Parse
2953 {
2954 private:
2955 using __string_type = basic_string<_CharT, _Traits, _Alloc>;
2956
2957 public:
2958 _Parse(const _CharT* __fmt, _Parsable& __tp,
2959 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
2960 minutes* __offset = nullptr)
2961 : _M_fmt(__fmt), _M_tp(std::__addressof(__tp)),
2962 _M_abbrev(__abbrev), _M_offset(__offset)
2963 { }
2964
2965 _Parse(_Parse&&) = delete;
2966 _Parse& operator=(_Parse&&) = delete;
2967
2968 private:
2969 using __stream_type = basic_istream<_CharT, _Traits>;
2970
2971 const _CharT* const _M_fmt;
2972 _Parsable* const _M_tp;
2973 __string_type* const _M_abbrev;
2974 minutes* const _M_offset;
2975
2976 friend __stream_type&
2977 operator>>(__stream_type& __is, _Parse&& __p)
2978 {
2979 if (__p._M_offset)
2980 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev,
2981 __p._M_offset);
2982 else if (__p._M_abbrev)
2983 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev);
2984 else
2985 from_stream(__is, __p._M_fmt, *__p._M_tp);
2986 return __is;
2987 }
2988
2989 friend void operator>>(__stream_type&, _Parse&) = delete;
2990 friend void operator>>(__stream_type&, const _Parse&) = delete;
2991 };
2992} // namespace __detail
2993
2994 template<typename _CharT, __detail::__parsable<_CharT> _Parsable>
2995 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
2996 inline auto
2997 parse(const _CharT* __fmt, _Parsable& __tp)
2998 { return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp); }
2999
3000 template<typename _CharT, typename _Traits, typename _Alloc,
3001 __detail::__parsable<_CharT, _Traits> _Parsable>
3002 [[nodiscard]]
3003 inline auto
3004 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp)
3005 {
3006 return __detail::_Parse<_Parsable, _CharT, _Traits>(__fmt.c_str(), __tp);
3007 }
3008
3009 template<typename _CharT, typename _Traits, typename _Alloc,
3010 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
3011 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
3012 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
3013 inline auto
3014 parse(const _CharT* __fmt, _Parsable& __tp,
3015 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
3016 {
3017 auto __pa = std::__addressof(__abbrev);
3018 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
3019 __pa);
3020 }
3021
3022 template<typename _CharT, typename _Traits, typename _Alloc,
3023 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
3024 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
3025 [[nodiscard]]
3026 inline auto
3027 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
3028 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
3029 {
3030 auto __pa = std::__addressof(__abbrev);
3031 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
3032 __tp, __pa);
3033 }
3034
3035 template<typename _CharT, typename _Traits = char_traits<_CharT>,
3036 typename _StrT = basic_string<_CharT, _Traits>,
3037 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
3038 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
3039 inline auto
3040 parse(const _CharT* __fmt, _Parsable& __tp, minutes& __offset)
3041 {
3042 return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp, nullptr,
3043 &__offset);
3044 }
3045
3046 template<typename _CharT, typename _Traits, typename _Alloc,
3047 typename _StrT = basic_string<_CharT, _Traits>,
3048 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
3049 [[nodiscard]]
3050 inline auto
3051 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
3052 minutes& __offset)
3053 {
3054 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
3055 __tp, nullptr,
3056 &__offset);
3057 }
3058
3059 template<typename _CharT, typename _Traits, typename _Alloc,
3060 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
3061 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
3062 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
3063 inline auto
3064 parse(const _CharT* __fmt, _Parsable& __tp,
3065 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
3066 {
3067 auto __pa = std::__addressof(__abbrev);
3068 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
3069 __pa,
3070 &__offset);
3071 }
3072
3073 template<typename _CharT, typename _Traits, typename _Alloc,
3074 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
3075 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
3076 [[nodiscard]]
3077 inline auto
3078 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
3079 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
3080 {
3081 auto __pa = std::__addressof(__abbrev);
3082 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
3083 __tp, __pa,
3084 &__offset);
3085 }
3086
3087 /// @cond undocumented
3088 template<typename _Duration>
3089 template<typename _CharT, typename _Traits, typename _Alloc>
3090 basic_istream<_CharT, _Traits>&
3091 __detail::_Parser<_Duration>::
3092 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3093 basic_string<_CharT, _Traits, _Alloc>* __abbrev,
3094 minutes* __offset)
3095 {
3096 using sentry = typename basic_istream<_CharT, _Traits>::sentry;
3098 if (sentry __cerb(__is, true); __cerb)
3099 {
3100 locale __loc = __is.getloc();
3101 auto& __tmget = std::use_facet<std::time_get<_CharT>>(__loc);
3102 auto& __tmpunct = std::use_facet<std::__timepunct<_CharT>>(__loc);
3103
3104 // RAII type to save and restore stream state.
3105 struct _Stream_state
3106 {
3107 explicit
3108 _Stream_state(basic_istream<_CharT, _Traits>& __i)
3109 : _M_is(__i),
3110 _M_flags(__i.flags(ios_base::skipws | ios_base::dec)),
3111 _M_w(__i.width(0))
3112 { }
3113
3114 ~_Stream_state()
3115 {
3116 _M_is.flags(_M_flags);
3117 _M_is.width(_M_w);
3118 }
3119
3120 _Stream_state(_Stream_state&&) = delete;
3121
3122 basic_istream<_CharT, _Traits>& _M_is;
3123 ios_base::fmtflags _M_flags;
3124 streamsize _M_w;
3125 };
3126
3127 auto __is_failed = [](ios_base::iostate __e) {
3128 return static_cast<bool>(__e & ios_base::failbit);
3129 };
3130
3131 // Read an unsigned integer from the stream and return it.
3132 // Extract no more than __n digits. Set __err on error.
3133 auto __read_unsigned = [&] (int __n) {
3134 return _S_read_unsigned(__is, __err, __n);
3135 };
3136
3137 // Read a signed integer from the stream and return it.
3138 // Extract no more than __n digits. Set __err on error.
3139 auto __read_signed = [&] (int __n) {
3140 return _S_read_signed(__is, __err, __n);
3141 };
3142
3143 // Read an expected character from the stream.
3144 auto __read_chr = [&__is, &__err] (_CharT __c) {
3145 return _S_read_chr(__is, __err, __c);
3146 };
3147
3148 using __format::_ChronoParts;
3149 _ChronoParts __parts{};
3150
3151 const year __bad_y = --year::min(); // SHRT_MIN
3152 const month __bad_mon(255);
3153 const day __bad_day(255);
3154 const weekday __bad_wday(255);
3155 const hours __bad_h(-1);
3156 const minutes __bad_min(-9999);
3157 const seconds __bad_sec(-1);
3158
3159 year __y = __bad_y, __yy = __bad_y; // %Y, %yy
3160 year __iso_y = __bad_y, __iso_yy = __bad_y; // %G, %g
3161 month __m = __bad_mon; // %m
3162 day __d = __bad_day; // %d
3163 weekday __wday = __bad_wday; // %a %A %u %w
3164 hours __h = __bad_h, __h12 = __bad_h; // %H, %I
3165 minutes __min = __bad_min; // %M
3166 _Duration __s = __bad_sec; // %S
3167 int __ampm = 0; // %p
3168 int __iso_wk = -1, __sunday_wk = -1, __monday_wk = -1; // %V, %U, %W
3169 int __century = -1; // %C
3170 int __dayofyear = -1; // %j (for non-duration)
3171
3172 minutes __tz_offset = __bad_min;
3173 basic_string<_CharT, _Traits> __tz_abbr;
3174
3175 if ((_M_need & _ChronoParts::_TimeOfDay)
3176 && (_M_need & _ChronoParts::_Year))
3177 {
3178 // For time_points assume "00:00:00" is implicitly present,
3179 // so we don't fail to parse if it's not (PR libstdc++/114240).
3180 // We will still fail to parse if there's no year+month+day.
3181 __h = hours(0);
3182 __parts = _ChronoParts::_TimeOfDay;
3183 }
3184
3185 // bool __is_neg = false; // TODO: how is this handled for parsing?
3186
3187 _CharT __mod{}; // One of 'E' or 'O' or nul.
3188 unsigned __num = 0; // Non-zero for N modifier.
3189 bool __is_flag = false; // True if we're processing a % flag.
3190
3191 constexpr bool __is_floating
3192 = treat_as_floating_point_v<typename _Duration::rep>;
3193
3194 // If an out-of-range value is extracted (e.g. 61min for %M),
3195 // do not set failbit immediately because we might not need it
3196 // (e.g. parsing chrono::year doesn't care about invalid %M values).
3197 // Instead set the variable back to its initial 'bad' state,
3198 // and also set related variables corresponding to the same field
3199 // (e.g. a bad %M value for __min should also reset __h and __s).
3200 // If a valid value is needed later the bad value will cause failure.
3201
3202 // For some fields we don't know the correct range when parsing and
3203 // we have to be liberal in what we accept, e.g. we allow 366 for
3204 // day-of-year because that's valid in leap years, and we allow 31
3205 // for day-of-month. If those values are needed to determine the
3206 // result then we can do a correct range check at the end when we
3207 // know the how many days the relevant year or month actually has.
3208
3209 while (*__fmt)
3210 {
3211 _CharT __c = *__fmt++;
3212 if (!__is_flag)
3213 {
3214 if (__c == '%')
3215 __is_flag = true; // This is the start of a flag.
3216 else if (std::isspace(__c, __loc))
3217 std::ws(__is); // Match zero or more whitespace characters.
3218 else if (!__read_chr(__c)) [[unlikely]]
3219 break; // Failed to match the expected character.
3220
3221 continue; // Process next character in the format string.
3222 }
3223
3224 // Now processing a flag.
3225 switch (__c)
3226 {
3227 case 'a': // Locale's weekday name
3228 case 'A': // (full or abbreviated, matched case-insensitively).
3229 if (__mod || __num) [[unlikely]]
3230 __err = ios_base::failbit;
3231 else
3232 {
3233 struct tm __tm{};
3234 __tmget.get(__is, {}, __is, __err, &__tm,
3235 __fmt - 2, __fmt);
3236 if (!__is_failed(__err))
3237 __wday = weekday(__tm.tm_wday);
3238 }
3239 __parts |= _ChronoParts::_Weekday;
3240 break;
3241
3242 case 'b': // Locale's month name
3243 case 'h': // (full or abbreviated, matched case-insensitively).
3244 case 'B':
3245 if (__mod || __num) [[unlikely]]
3246 __err = ios_base::failbit;
3247 else
3248 {
3249 // strptime behaves differently for %b and %B,
3250 // but chrono::parse says they're equivalent.
3251 // Luckily libstdc++ std::time_get works as needed.
3252 struct tm __tm{};
3253 __tmget.get(__is, {}, __is, __err, &__tm,
3254 __fmt - 2, __fmt);
3255 if (!__is_failed(__err))
3256 __m = month(__tm.tm_mon + 1);
3257 }
3258 __parts |= _ChronoParts::_Month;
3259 break;
3260
3261 case 'c': // Locale's date and time representation.
3262 if (__mod == 'O' || __num) [[unlikely]]
3263 __err |= ios_base::failbit;
3264 else
3265 {
3266 struct tm __tm{};
3267 __tmget.get(__is, {}, __is, __err, &__tm,
3268 __fmt - 2 - (__mod == 'E'), __fmt);
3269 if (!__is_failed(__err))
3270 {
3271 __y = year(__tm.tm_year + 1900);
3272 __m = month(__tm.tm_mon + 1);
3273 __d = day(__tm.tm_mday);
3274 __h = hours(__tm.tm_hour);
3275 __min = minutes(__tm.tm_min);
3276 __s = seconds(__tm.tm_sec);
3277 }
3278 }
3279 __parts |= _ChronoParts::_DateTime;
3280 break;
3281
3282 case 'C': // Century
3283 if (!__mod) [[likely]]
3284 {
3285 auto __v = __read_signed(__num ? __num : 2);
3286 if (!__is_failed(__err))
3287 {
3288 int __cmin = (int)year::min() / 100;
3289 int __cmax = (int)year::max() / 100;
3290 if (__cmin <= __v && __v <= __cmax)
3291 __century = __v * 100;
3292 else
3293 __century = -2; // This prevents guessing century.
3294 }
3295 }
3296 else if (__mod == 'E')
3297 {
3298 struct tm __tm{};
3299 __tmget.get(__is, {}, __is, __err, &__tm,
3300 __fmt - 3, __fmt);
3301 if (!__is_failed(__err))
3302 __century = __tm.tm_year;
3303 }
3304 else [[unlikely]]
3305 __err |= ios_base::failbit;
3306 // N.B. don't set this here: __parts |= _ChronoParts::_Year;
3307 break;
3308
3309 case 'd': // Day of month (1-31)
3310 case 'e':
3311 if (!__mod) [[likely]]
3312 {
3313 auto __v = __read_unsigned(__num ? __num : 2);
3314 if (!__is_failed(__err))
3315 __d = day(__v);
3316 }
3317 else if (__mod == 'O')
3318 {
3319 struct tm __tm{};
3320 __tmget.get(__is, {}, __is, __err, &__tm,
3321 __fmt - 3, __fmt);
3322 if (!__is_failed(__err))
3323 __d = day(__tm.tm_mday);
3324 }
3325 else [[unlikely]]
3326 __err |= ios_base::failbit;
3327 __parts |= _ChronoParts::_Day;
3328 break;
3329
3330 case 'D': // %m/%d/%y
3331 if (__mod || __num) [[unlikely]]
3332 __err |= ios_base::failbit;
3333 else
3334 {
3335 auto __month = __read_unsigned(2); // %m
3336 __read_chr('/');
3337 auto __day = __read_unsigned(2); // %d
3338 __read_chr('/');
3339 auto __year = __read_unsigned(2); // %y
3340 if (__is_failed(__err))
3341 break;
3342 __y = year(__year + 1900 + 100 * int(__year < 69));
3343 __m = month(__month);
3344 __d = day(__day);
3345 if (!year_month_day(__y, __m, __d).ok())
3346 {
3347 __y = __yy = __iso_y = __iso_yy = __bad_y;
3348 __m = __bad_mon;
3349 __d = __bad_day;
3350 break;
3351 }
3352 }
3353 __parts |= _ChronoParts::_Date;
3354 break;
3355
3356 case 'F': // %Y-%m-%d - any N modifier only applies to %Y.
3357 if (__mod) [[unlikely]]
3358 __err |= ios_base::failbit;
3359 else
3360 {
3361 auto __year = __read_signed(__num ? __num : 4); // %Y
3362 __read_chr('-');
3363 auto __month = __read_unsigned(2); // %m
3364 __read_chr('-');
3365 auto __day = __read_unsigned(2); // %d
3366 if (__is_failed(__err))
3367 break;
3368 __y = year(__year);
3369 __m = month(__month);
3370 __d = day(__day);
3371 if (!year_month_day(__y, __m, __d).ok())
3372 {
3373 __y = __yy = __iso_y = __iso_yy = __bad_y;
3374 __m = __bad_mon;
3375 __d = __bad_day;
3376 break;
3377 }
3378 }
3379 __parts |= _ChronoParts::_Date;
3380 break;
3381
3382 case 'g': // Last two digits of ISO week-based year.
3383 if (__mod) [[unlikely]]
3384 __err |= ios_base::failbit;
3385 else
3386 {
3387 auto __val = __read_unsigned(__num ? __num : 2);
3388 if (__val >= 0 && __val <= 99)
3389 {
3390 __iso_yy = year(__val);
3391 if (__century == -1) // No %C has been parsed yet.
3392 __century = 2000;
3393 }
3394 else
3395 __iso_yy = __iso_y = __y = __yy = __bad_y;
3396 }
3397 __parts |= _ChronoParts::_Year;
3398 break;
3399
3400 case 'G': // ISO week-based year.
3401 if (__mod) [[unlikely]]
3402 __err |= ios_base::failbit;
3403 else
3404 __iso_y = year(__read_unsigned(__num ? __num : 4));
3405 __parts |= _ChronoParts::_Year;
3406 break;
3407
3408 case 'H': // 24-hour (00-23)
3409 case 'I': // 12-hour (1-12)
3410 if (__mod == 'E') [[unlikely]]
3411 __err |= ios_base::failbit;
3412 else if (__mod == 'O')
3413 {
3414#if 0
3415 struct tm __tm{};
3416 __tm.tm_ampm = 1;
3417 __tmget.get(__is, {}, __is, __err, &__tm,
3418 __fmt - 3, __fmt);
3419 if (!__is_failed(__err))
3420 {
3421 if (__c == 'I')
3422 {
3423 __h12 = hours(__tm.tm_hour);
3424 __h = __bad_h;
3425 }
3426 else
3427 __h = hours(__tm.tm_hour);
3428 }
3429#else
3430 // XXX %OI seems to be unimplementable.
3431 __err |= ios_base::failbit;
3432#endif
3433 }
3434 else
3435 {
3436 auto __val = __read_unsigned(__num ? __num : 2);
3437 if (__c == 'I' && __val >= 1 && __val <= 12)
3438 {
3439 __h12 = hours(__val);
3440 __h = __bad_h;
3441 }
3442 else if (__c == 'H' && __val >= 0 && __val <= 23)
3443 {
3444 __h = hours(__val);
3445 __h12 = __bad_h;
3446 }
3447 else
3448 {
3449 if (_M_need & _ChronoParts::_TimeOfDay)
3450 __err |= ios_base::failbit;
3451 break;
3452 }
3453 }
3454 __parts |= _ChronoParts::_TimeOfDay;
3455 break;
3456
3457 case 'j': // For duration, count of days, otherwise day of year
3458 if (__mod) [[unlikely]]
3459 __err |= ios_base::failbit;
3460 else if (_M_need == _ChronoParts::_TimeOfDay) // duration
3461 {
3462 auto __val = __read_signed(__num ? __num : 3);
3463 if (!__is_failed(__err))
3464 {
3465 __h = days(__val); // __h will get added to _M_time
3466 __parts |= _ChronoParts::_TimeOfDay;
3467 }
3468 }
3469 else
3470 {
3471 __dayofyear = __read_unsigned(__num ? __num : 3);
3472 // N.B. do not alter __parts here, done after loop.
3473 // No need for range checking here either.
3474 }
3475 break;
3476
3477 case 'm': // Month (1-12)
3478 if (__mod == 'E') [[unlikely]]
3479 __err |= ios_base::failbit;
3480 else if (__mod == 'O')
3481 {
3482 struct tm __tm{};
3483 __tmget.get(__is, {}, __is, __err, &__tm,
3484 __fmt - 2, __fmt);
3485 if (!__is_failed(__err))
3486 __m = month(__tm.tm_mon + 1);
3487 }
3488 else
3489 {
3490 auto __val = __read_unsigned(__num ? __num : 2);
3491 if (__val >= 1 && __val <= 12)
3492 __m = month(__val);
3493 else
3494 __m = __bad_mon;
3495 }
3496 __parts |= _ChronoParts::_Month;
3497 break;
3498
3499 case 'M': // Minutes
3500 if (__mod == 'E') [[unlikely]]
3501 __err |= ios_base::failbit;
3502 else if (__mod == 'O')
3503 {
3504 struct tm __tm{};
3505 __tmget.get(__is, {}, __is, __err, &__tm,
3506 __fmt - 2, __fmt);
3507 if (!__is_failed(__err))
3508 __min = minutes(__tm.tm_min);
3509 }
3510 else
3511 {
3512 auto __val = __read_unsigned(__num ? __num : 2);
3513 if (0 <= __val && __val < 60)
3514 __min = minutes(__val);
3515 else
3516 {
3517 if (_M_need & _ChronoParts::_TimeOfDay)
3518 __err |= ios_base::failbit;
3519 break;
3520 }
3521 }
3522 __parts |= _ChronoParts::_TimeOfDay;
3523 break;
3524
3525 case 'p': // Locale's AM/PM designation for 12-hour clock.
3526 if (__mod || __num)
3527 __err |= ios_base::failbit;
3528 else
3529 {
3530 // Can't use std::time_get here as it can't parse %p
3531 // in isolation without %I. This might be faster anyway.
3532 const _CharT* __ampms[2];
3533 __tmpunct._M_am_pm(__ampms);
3534 int __n = 0, __which = 3;
3535 while (__which != 0)
3536 {
3537 auto __i = __is.peek();
3538 if (_Traits::eq_int_type(__i, _Traits::eof()))
3539 {
3541 break;
3542 }
3543 __i = std::toupper(_Traits::to_char_type(__i), __loc);
3544 if (__which & 1)
3545 {
3546 if (__i != std::toupper(__ampms[0][__n], __loc))
3547 __which ^= 1;
3548 else if (__ampms[0][__n + 1] == _CharT())
3549 {
3550 __which = 1;
3551 (void) __is.get();
3552 break;
3553 }
3554 }
3555 if (__which & 2)
3556 {
3557 if (__i != std::toupper(__ampms[1][__n], __loc))
3558 __which ^= 2;
3559 else if (__ampms[1][__n + 1] == _CharT())
3560 {
3561 __which = 2;
3562 (void) __is.get();
3563 break;
3564 }
3565 }
3566 if (__which)
3567 (void) __is.get();
3568 ++__n;
3569 }
3570 if (__which == 0 || __which == 3)
3571 __err |= ios_base::failbit;
3572 else
3573 __ampm = __which;
3574 }
3575 break;
3576
3577 case 'r': // Locale's 12-hour time.
3578 if (__mod || __num)
3579 __err |= ios_base::failbit;
3580 else
3581 {
3582 struct tm __tm{};
3583 __tmget.get(__is, {}, __is, __err, &__tm,
3584 __fmt - 2, __fmt);
3585 if (!__is_failed(__err))
3586 {
3587 __h = hours(__tm.tm_hour);
3588 __min = minutes(__tm.tm_min);
3589 __s = seconds(__tm.tm_sec);
3590 }
3591 }
3592 __parts |= _ChronoParts::_TimeOfDay;
3593 break;
3594
3595 case 'R': // %H:%M
3596 case 'T': // %H:%M:%S
3597 if (__mod || __num) [[unlikely]]
3598 {
3599 __err |= ios_base::failbit;
3600 break;
3601 }
3602 else
3603 {
3604 auto __val = __read_unsigned(2);
3605 if (__val == -1 || __val > 23) [[unlikely]]
3606 {
3607 if (_M_need & _ChronoParts::_TimeOfDay)
3608 __err |= ios_base::failbit;
3609 break;
3610 }
3611 if (!__read_chr(':')) [[unlikely]]
3612 break;
3613 __h = hours(__val);
3614
3615 __val = __read_unsigned(2);
3616 if (__val == -1 || __val > 60) [[unlikely]]
3617 {
3618 if (_M_need & _ChronoParts::_TimeOfDay)
3619 __err |= ios_base::failbit;
3620 break;
3621 }
3622 __min = minutes(__val);
3623
3624 if (__c == 'R')
3625 {
3626 __parts |= _ChronoParts::_TimeOfDay;
3627 break;
3628 }
3629 else if (!__read_chr(':')) [[unlikely]]
3630 break;
3631 }
3632 [[fallthrough]];
3633
3634 case 'S': // Seconds
3635 if (__mod == 'E') [[unlikely]]
3636 __err |= ios_base::failbit;
3637 else if (__mod == 'O')
3638 {
3639 struct tm __tm{};
3640 __tmget.get(__is, {}, __is, __err, &__tm,
3641 __fmt - 3, __fmt);
3642 if (!__is_failed(__err))
3643 __s = seconds(__tm.tm_sec);
3644 }
3645 else if constexpr (_Duration::period::den == 1
3646 && !__is_floating)
3647 {
3648 auto __val = __read_unsigned(__num ? __num : 2);
3649 if (0 <= __val && __val <= 59) [[likely]]
3650 __s = seconds(__val);
3651 else
3652 {
3653 if (_M_need & _ChronoParts::_TimeOfDay)
3654 __err |= ios_base::failbit;
3655 break;
3656 }
3657 }
3658 else // Read fractional seconds
3659 {
3660 basic_stringstream<_CharT> __buf;
3661 auto __digit = _S_try_read_digit(__is, __err);
3662 if (__digit != -1)
3663 {
3664 __buf.put(_CharT('0') + __digit);
3665 __digit = _S_try_read_digit(__is, __err);
3666 if (__digit != -1)
3667 __buf.put(_CharT('0') + __digit);
3668 }
3669
3670 auto __i = __is.peek();
3671 if (_Traits::eq_int_type(__i, _Traits::eof()))
3672 __err |= ios_base::eofbit;
3673 else
3674 {
3675 _CharT __dp = '.';
3676 if (__loc != locale::classic())
3677 {
3678 auto& __np = use_facet<numpunct<_CharT>>(__loc);
3679 __dp = __np.decimal_point();
3680 }
3681 _CharT __c = _Traits::to_char_type(__i);
3682 if (__c == __dp)
3683 {
3684 (void) __is.get();
3685 __buf.put('.');
3686 int __prec
3687 = hh_mm_ss<_Duration>::fractional_width;
3688 do
3689 {
3690 __digit = _S_try_read_digit(__is, __err);
3691 if (__digit != -1)
3692 __buf.put(_CharT('0') + __digit);
3693 else
3694 break;
3695 }
3696 while (--__prec);
3697 }
3698 }
3699
3700 if (!__is_failed(__err)) [[likely]]
3701 {
3702 long double __val{};
3703#if __cpp_lib_to_chars
3704 string __str = std::move(__buf).str();
3705 auto __first = __str.data();
3706 auto __last = __first + __str.size();
3707 using enum chars_format;
3708 auto [ptr, ec] = std::from_chars(__first, __last,
3709 __val, fixed);
3710 if ((bool)ec || ptr != __last) [[unlikely]]
3711 __err |= ios_base::failbit;
3712 else
3713#else
3714 if (__buf >> __val)
3715#endif
3716 {
3717 duration<long double> __fs(__val);
3718 if constexpr (__is_floating)
3719 __s = __fs;
3720 else
3721 __s = chrono::round<_Duration>(__fs);
3722 }
3723 }
3724 }
3725 __parts |= _ChronoParts::_TimeOfDay;
3726 break;
3727
3728 case 'u': // ISO weekday (1-7)
3729 case 'w': // Weekday (0-6)
3730 if (__mod == 'E') [[unlikely]]
3731 __err |= ios_base::failbit;
3732 else if (__mod == 'O')
3733 {
3734 if (__c == 'w')
3735 {
3736 struct tm __tm{};
3737 __tmget.get(__is, {}, __is, __err, &__tm,
3738 __fmt - 3, __fmt);
3739 if (!__is_failed(__err))
3740 __wday = weekday(__tm.tm_wday);
3741 }
3742 else
3743 __err |= ios_base::failbit;
3744 }
3745 else
3746 {
3747 const int __lo = __c == 'u' ? 1 : 0;
3748 const int __hi = __lo + 6;
3749 auto __val = __read_unsigned(__num ? __num : 1);
3750 if (__lo <= __val && __val <= __hi)
3751 __wday = weekday(__val);
3752 else
3753 {
3754 __wday = __bad_wday;
3755 break;
3756 }
3757 }
3758 __parts |= _ChronoParts::_Weekday;
3759 break;
3760
3761 case 'U': // Week number of the year (from first Sunday).
3762 case 'V': // ISO week-based week number.
3763 case 'W': // Week number of the year (from first Monday).
3764 if (__mod == 'E') [[unlikely]]
3765 __err |= ios_base::failbit;
3766 else if (__mod == 'O')
3767 {
3768 if (__c == 'V') [[unlikely]]
3769 __err |= ios_base::failbit;
3770 else
3771 {
3772 // TODO nl_langinfo_l(ALT_DIGITS) ?
3773 // Not implementable using std::time_get.
3774 }
3775 }
3776 else
3777 {
3778 const int __lo = __c == 'V' ? 1 : 0;
3779 const int __hi = 53;
3780 auto __val = __read_unsigned(__num ? __num : 2);
3781 if (__lo <= __val && __val <= __hi)
3782 {
3783 switch (__c)
3784 {
3785 case 'U':
3786 __sunday_wk = __val;
3787 break;
3788 case 'V':
3789 __iso_wk = __val;
3790 break;
3791 case 'W':
3792 __monday_wk = __val;
3793 break;
3794 }
3795 }
3796 else
3797 __iso_wk = __sunday_wk = __monday_wk = -1;
3798 }
3799 // N.B. do not alter __parts here, done after loop.
3800 break;
3801
3802 case 'x': // Locale's date representation.
3803 if (__mod == 'O' || __num) [[unlikely]]
3804 __err |= ios_base::failbit;
3805 else
3806 {
3807 struct tm __tm{};
3808 __tmget.get(__is, {}, __is, __err, &__tm,
3809 __fmt - 2 - (__mod == 'E'), __fmt);
3810 if (!__is_failed(__err))
3811 {
3812 __y = year(__tm.tm_year + 1900);
3813 __m = month(__tm.tm_mon + 1);
3814 __d = day(__tm.tm_mday);
3815 }
3816 }
3817 __parts |= _ChronoParts::_Date;
3818 break;
3819
3820 case 'X': // Locale's time representation.
3821 if (__mod == 'O' || __num) [[unlikely]]
3822 __err |= ios_base::failbit;
3823 else
3824 {
3825 struct tm __tm{};
3826 __tmget.get(__is, {}, __is, __err, &__tm,
3827 __fmt - 2 - (__mod == 'E'), __fmt);
3828 if (!__is_failed(__err))
3829 {
3830 __h = hours(__tm.tm_hour);
3831 __min = minutes(__tm.tm_min);
3832 __s = seconds(__tm.tm_sec);
3833 }
3834 }
3835 __parts |= _ChronoParts::_TimeOfDay;
3836 break;
3837
3838 case 'y': // Last two digits of year.
3839 if (__mod) [[unlikely]]
3840 {
3841 struct tm __tm{};
3842 __tmget.get(__is, {}, __is, __err, &__tm,
3843 __fmt - 3, __fmt);
3844 if (!__is_failed(__err))
3845 {
3846 int __cent = __tm.tm_year < 2000 ? 1900 : 2000;
3847 __yy = year(__tm.tm_year - __cent);
3848 if (__century == -1) // No %C has been parsed yet.
3849 __century = __cent;
3850 }
3851 }
3852 else
3853 {
3854 auto __val = __read_unsigned(__num ? __num : 2);
3855 if (__val >= 0 && __val <= 99)
3856 {
3857 __yy = year(__val);
3858 if (__century == -1) // No %C has been parsed yet.
3859 __century = __val < 69 ? 2000 : 1900;
3860 }
3861 else
3862 __y = __yy = __iso_yy = __iso_y = __bad_y;
3863 }
3864 __parts |= _ChronoParts::_Year;
3865 break;
3866
3867 case 'Y': // Year
3868 if (__mod == 'O') [[unlikely]]
3869 __err |= ios_base::failbit;
3870 else if (__mod == 'E')
3871 {
3872 struct tm __tm{};
3873 __tmget.get(__is, {}, __is, __err, &__tm,
3874 __fmt - 3, __fmt);
3875 if (!__is_failed(__err))
3876 __y = year(__tm.tm_year);
3877 }
3878 else
3879 {
3880 auto __val = __read_unsigned(__num ? __num : 4);
3881 if (!__is_failed(__err))
3882 __y = year(__val);
3883 }
3884 __parts |= _ChronoParts::_Year;
3885 break;
3886
3887 case 'z':
3888 if (__num) [[unlikely]]
3889 __err |= ios_base::failbit;
3890 else
3891 {
3892 // For %Ez and %Oz read [+|-][h]h[:mm].
3893 // For %z read [+|-]hh[mm].
3894
3895 auto __i = __is.peek();
3896 if (_Traits::eq_int_type(__i, _Traits::eof()))
3897 {
3899 break;
3900 }
3901 _CharT __ic = _Traits::to_char_type(__i);
3902 const bool __neg = __ic == _CharT('-');
3903 if (__ic == _CharT('-') || __ic == _CharT('+'))
3904 (void) __is.get();
3905
3906 int_least32_t __hh;
3907 if (__mod)
3908 {
3909 // Read h[h]
3910 __hh = __read_unsigned(2);
3911 }
3912 else
3913 {
3914 // Read hh
3915 __hh = 10 * _S_try_read_digit(__is, __err);
3916 __hh += _S_try_read_digit(__is, __err);
3917 }
3918
3919 if (__is_failed(__err))
3920 break;
3921
3922 __i = __is.peek();
3923 if (_Traits::eq_int_type(__i, _Traits::eof()))
3924 {
3925 __err |= ios_base::eofbit;
3926 __tz_offset = minutes(__hh * (__neg ? -60 : 60));
3927 break;
3928 }
3929 __ic = _Traits::to_char_type(__i);
3930
3931 bool __read_mm = false;
3932 if (__mod)
3933 {
3934 if (__ic == _GLIBCXX_WIDEN(":")[0])
3935 {
3936 // Read [:mm] part.
3937 (void) __is.get();
3938 __read_mm = true;
3939 }
3940 }
3941 else if (_CharT('0') <= __ic && __ic <= _CharT('9'))
3942 {
3943 // Read [mm] part.
3944 __read_mm = true;
3945 }
3946
3947 int_least32_t __mm = 0;
3948 if (__read_mm)
3949 {
3950 __mm = 10 * _S_try_read_digit(__is, __err);
3951 __mm += _S_try_read_digit(__is, __err);
3952 }
3953
3954 if (!__is_failed(__err))
3955 {
3956 auto __z = __hh * 60 + __mm;
3957 __tz_offset = minutes(__neg ? -__z : __z);
3958 }
3959 }
3960 break;
3961
3962 case 'Z':
3963 if (__mod || __num) [[unlikely]]
3964 __err |= ios_base::failbit;
3965 else
3966 {
3967 basic_string_view<_CharT> __x = _GLIBCXX_WIDEN("_/-+");
3968 __tz_abbr.clear();
3969 while (true)
3970 {
3971 auto __i = __is.peek();
3972 if (!_Traits::eq_int_type(__i, _Traits::eof()))
3973 {
3974 _CharT __a = _Traits::to_char_type(__i);
3975 if (std::isalnum(__a, __loc)
3976 || __x.find(__a) != __x.npos)
3977 {
3978 __tz_abbr.push_back(__a);
3979 (void) __is.get();
3980 continue;
3981 }
3982 }
3983 else
3984 __err |= ios_base::eofbit;
3985 break;
3986 }
3987 if (__tz_abbr.empty())
3988 __err |= ios_base::failbit;
3989 }
3990 break;
3991
3992 case 'n': // Exactly one whitespace character.
3993 if (__mod || __num) [[unlikely]]
3994 __err |= ios_base::failbit;
3995 else
3996 {
3997 _CharT __i = __is.peek();
3998 if (_Traits::eq_int_type(__i, _Traits::eof()))
4000 else if (std::isspace(_Traits::to_char_type(__i), __loc))
4001 (void) __is.get();
4002 else
4003 __err |= ios_base::failbit;
4004 }
4005 break;
4006
4007 case 't': // Zero or one whitespace characters.
4008 if (__mod || __num) [[unlikely]]
4009 __err |= ios_base::failbit;
4010 else
4011 {
4012 _CharT __i = __is.peek();
4013 if (_Traits::eq_int_type(__i, _Traits::eof()))
4014 __err |= ios_base::eofbit;
4015 else if (std::isspace(_Traits::to_char_type(__i), __loc))
4016 (void) __is.get();
4017 }
4018 break;
4019
4020 case '%': // A % character.
4021 if (__mod || __num) [[unlikely]]
4022 __err |= ios_base::failbit;
4023 else
4024 __read_chr('%');
4025 break;
4026
4027 case 'O': // Modifiers
4028 case 'E':
4029 if (__mod || __num) [[unlikely]]
4030 {
4031 __err |= ios_base::failbit;
4032 break;
4033 }
4034 __mod = __c;
4035 continue;
4036
4037 default:
4038 if (_CharT('1') <= __c && __c <= _CharT('9'))
4039 {
4040 if (!__mod) [[likely]]
4041 {
4042 // %Nx - extract positive decimal integer N
4043 auto __end = __fmt + _Traits::length(__fmt);
4044 auto [__v, __ptr]
4045 = __format::__parse_integer(__fmt - 1, __end);
4046 if (__ptr) [[likely]]
4047 {
4048 __num = __v;
4049 __fmt = __ptr;
4050 continue;
4051 }
4052 }
4053 }
4054 __err |= ios_base::failbit;
4055 }
4056
4057 if (__is_failed(__err)) [[unlikely]]
4058 break;
4059
4060 __is_flag = false;
4061 __num = 0;
4062 __mod = _CharT();
4063 }
4064
4065 if (__century >= 0)
4066 {
4067 if (__yy != __bad_y && __y == __bad_y)
4068 __y = years(__century) + __yy; // Use %y instead of %Y
4069 if (__iso_yy != __bad_y && __iso_y == __bad_y)
4070 __iso_y = years(__century) + __iso_yy; // Use %g instead of %G
4071 }
4072
4073 bool __can_use_doy = false;
4074 bool __can_use_iso_wk = false;
4075 bool __can_use_sun_wk = false;
4076 bool __can_use_mon_wk = false;
4077
4078 // A year + day-of-year can be converted to a full date.
4079 if (__y != __bad_y && __dayofyear >= 0)
4080 {
4081 __can_use_doy = true;
4082 __parts |= _ChronoParts::_Date;
4083 }
4084 else if (__y != __bad_y && __wday != __bad_wday && __sunday_wk >= 0)
4085 {
4086 __can_use_sun_wk = true;
4087 __parts |= _ChronoParts::_Date;
4088 }
4089 else if (__y != __bad_y && __wday != __bad_wday && __monday_wk >= 0)
4090 {
4091 __can_use_mon_wk = true;
4092 __parts |= _ChronoParts::_Date;
4093 }
4094 else if (__iso_y != __bad_y && __wday != __bad_wday && __iso_wk > 0)
4095 {
4096 // An ISO week date can be converted to a full date.
4097 __can_use_iso_wk = true;
4098 __parts |= _ChronoParts::_Date;
4099 }
4100
4101 if (__is_failed(__err)) [[unlikely]]
4102 ; // Don't bother doing any more work.
4103 else if (__is_flag) [[unlikely]] // incomplete format flag
4104 __err |= ios_base::failbit;
4105 else if ((_M_need & __parts) == _M_need) [[likely]]
4106 {
4107 // We try to avoid calculating _M_sys_days and _M_ymd unless
4108 // necessary, because converting sys_days to year_month_day
4109 // (or vice versa) requires non-trivial calculations.
4110 // If we have y/m/d values then use them to populate _M_ymd
4111 // and only convert it to _M_sys_days if the caller needs that.
4112 // But if we don't have y/m/d and need to calculate the date
4113 // from the day-of-year or a week+weekday then we set _M_sys_days
4114 // and only convert it to _M_ymd if the caller needs that.
4115
4116 // We do more error checking here, but only for the fields that
4117 // we actually need to use. For example, we will not diagnose
4118 // an invalid dayofyear==366 for non-leap years unless actually
4119 // using __dayofyear. This should mean we never produce invalid
4120 // results, but it means not all invalid inputs are diagnosed,
4121 // e.g. "2023-01-01 366" >> "%F %j" ignores the invalid 366.
4122 // We also do not diagnose inconsistent values for the same
4123 // field, e.g. "2021 2022 2023" >> "%C%y %Y %Y" just uses 2023.
4124
4125 // Whether the caller wants _M_wd.
4126 // The _Weekday bit is only set for chrono::weekday.
4127 const bool __need_wday = _M_need & _ChronoParts::_Weekday;
4128
4129 // Whether the caller wants _M_sys_days and _M_time.
4130 // Only true for durations and time_points.
4131 const bool __need_time = _M_need & _ChronoParts::_TimeOfDay;
4132
4133 if (__need_wday && __wday != __bad_wday)
4134 _M_wd = __wday; // Caller only wants a weekday and we have one.
4135 else if (_M_need & _ChronoParts::_Date) // subsumes __need_wday
4136 {
4137 // Whether the caller wants _M_ymd.
4138 // True for chrono::year etc., false for time_points.
4139 const bool __need_ymd = !__need_wday && !__need_time;
4140
4141 if ((_M_need & _ChronoParts::_Year && __y == __bad_y)
4142 || (_M_need & _ChronoParts::_Month && __m == __bad_mon)
4143 || (_M_need & _ChronoParts::_Day && __d == __bad_day))
4144 {
4145 // Missing at least one of y/m/d so calculate sys_days
4146 // from the other data we have available.
4147
4148 if (__can_use_doy)
4149 {
4150 if ((0 < __dayofyear && __dayofyear <= 365)
4151 || (__dayofyear == 366 && __y.is_leap()))
4152 [[likely]]
4153 {
4154 _M_sys_days = sys_days(__y/January/1)
4155 + days(__dayofyear - 1);
4156 if (__need_ymd)
4157 _M_ymd = year_month_day(_M_sys_days);
4158 }
4159 else
4160 __err |= ios_base::failbit;
4161 }
4162 else if (__can_use_iso_wk)
4163 {
4164 // Calculate y/m/d from ISO week date.
4165
4166 if (__iso_wk == 53)
4167 {
4168 // A year has 53 weeks iff Jan 1st is a Thursday
4169 // or Jan 1 is a Wednesday and it's a leap year.
4170 const sys_days __jan4(__iso_y/January/4);
4171 weekday __wd1(__jan4 - days(3));
4172 if (__wd1 != Thursday)
4173 if (__wd1 != Wednesday || !__iso_y.is_leap())
4174 __err |= ios_base::failbit;
4175 }
4176
4177 if (!__is_failed(__err)) [[likely]]
4178 {
4179 // First Thursday is always in week one:
4180 sys_days __w(Thursday[1]/January/__iso_y);
4181 // First day of week-based year:
4182 __w -= Thursday - Monday;
4183 __w += days(weeks(__iso_wk - 1));
4184 __w += __wday - Monday;
4185 _M_sys_days = __w;
4186
4187 if (__need_ymd)
4188 _M_ymd = year_month_day(_M_sys_days);
4189 }
4190 }
4191 else if (__can_use_sun_wk)
4192 {
4193 // Calculate y/m/d from week number + weekday.
4194 sys_days __wk1(__y/January/Sunday[1]);
4195 _M_sys_days = __wk1 + weeks(__sunday_wk - 1)
4196 + days(__wday.c_encoding());
4197 _M_ymd = year_month_day(_M_sys_days);
4198 if (_M_ymd.year() != __y) [[unlikely]]
4199 __err |= ios_base::failbit;
4200 }
4201 else if (__can_use_mon_wk)
4202 {
4203 // Calculate y/m/d from week number + weekday.
4204 sys_days __wk1(__y/January/Monday[1]);
4205 _M_sys_days = __wk1 + weeks(__monday_wk - 1)
4206 + days(__wday.c_encoding() - 1);
4207 _M_ymd = year_month_day(_M_sys_days);
4208 if (_M_ymd.year() != __y) [[unlikely]]
4209 __err |= ios_base::failbit;
4210 }
4211 else // Should not be able to get here.
4212 __err |= ios_base::failbit;
4213 }
4214 else
4215 {
4216 // We know that all fields the caller needs are present,
4217 // but check that their values are in range.
4218 // Make unwanted fields valid so that _M_ymd.ok() is true.
4219
4220 if (_M_need & _ChronoParts::_Year)
4221 {
4222 if (!__y.ok()) [[unlikely]]
4223 __err |= ios_base::failbit;
4224 }
4225 else if (__y == __bad_y)
4226 __y = 1972y; // Leap year so that Feb 29 is valid.
4227
4228 if (_M_need & _ChronoParts::_Month)
4229 {
4230 if (!__m.ok()) [[unlikely]]
4231 __err |= ios_base::failbit;
4232 }
4233 else if (__m == __bad_mon)
4234 __m = January;
4235
4236 if (_M_need & _ChronoParts::_Day)
4237 {
4238 if (__d < day(1) || __d > (__y/__m/last).day())
4239 __err |= ios_base::failbit;
4240 }
4241 else if (__d == __bad_day)
4242 __d = 1d;
4243
4244 if (year_month_day __ymd(__y, __m, __d); __ymd.ok())
4245 {
4246 _M_ymd = __ymd;
4247 if (__need_wday || __need_time)
4248 _M_sys_days = sys_days(_M_ymd);
4249 }
4250 else [[unlikely]]
4251 __err |= ios_base::failbit;
4252 }
4253
4254 if (__need_wday)
4255 _M_wd = weekday(_M_sys_days);
4256 }
4257
4258 // Need to set _M_time for both durations and time_points.
4259 if (__need_time)
4260 {
4261 if (__h == __bad_h && __h12 != __bad_h)
4262 {
4263 if (__ampm == 1)
4264 __h = __h12 == hours(12) ? hours(0) : __h12;
4265 else if (__ampm == 2)
4266 __h = __h12 == hours(12) ? __h12 : __h12 + hours(12);
4267 else [[unlikely]]
4268 __err |= ios_base::failbit;
4269 }
4270
4271 auto __t = _M_time.zero();
4272 bool __ok = false;
4273
4274 if (__h != __bad_h)
4275 {
4276 __ok = true;
4277 __t += __h;
4278 }
4279
4280 if (__min != __bad_min)
4281 {
4282 __ok = true;
4283 __t += __min;
4284 }
4285
4286 if (__s != __bad_sec)
4287 {
4288 __ok = true;
4289 __t += __s;
4290 _M_is_leap_second = __s >= seconds(60);
4291 }
4292
4293 if (__ok)
4294 _M_time = __t;
4295 else
4296 __err |= ios_base::failbit;
4297 }
4298
4299 if (!__is_failed(__err)) [[likely]]
4300 {
4301 if (__offset && __tz_offset != __bad_min)
4302 *__offset = __tz_offset;
4303 if (__abbrev && !__tz_abbr.empty())
4304 *__abbrev = std::move(__tz_abbr);
4305 }
4306 }
4307 else
4308 __err |= ios_base::failbit;
4309 }
4310 if (__err)
4311 __is.setstate(__err);
4312 return __is;
4313 }
4314 /// @endcond
4315#undef _GLIBCXX_WIDEN
4316
4317 /// @} group chrono
4318} // namespace chrono
4319
4320_GLIBCXX_END_NAMESPACE_VERSION
4321} // namespace std
4322
4323#endif // C++20
4324
4325#endif //_GLIBCXX_CHRONO_IO_H
__detail::__local_time_fmt< _Duration > local_time_format(local_time< _Duration > __time, const string *__abbrev=nullptr, const seconds *__offset_sec=nullptr)
Definition chrono_io.h:182
duration< int64_t > seconds
seconds
Definition chrono.h:897
duration< int64_t, ratio< 604800 > > weeks
weeks
Definition chrono.h:910
duration< int64_t, ratio< 3600 > > hours
hours
Definition chrono.h:903
duration< int64_t, ratio< 86400 > > days
days
Definition chrono.h:907
basic_ostream< _CharT, _Traits > & operator<<(std::basic_ostream< _CharT, _Traits > &__os, const duration< _Rep, _Period > &__d)
Definition chrono_io.h:140
duration< int64_t, ratio< 60 > > minutes
minutes
Definition chrono.h:900
duration< int64_t, ratio< 31556952 > > years
years
Definition chrono.h:913
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:127
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition move.h:51
constexpr const _Tp & min(const _Tp &, const _Tp &)
This does what you think it does.
ISO C++ entities toplevel namespace is std.
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:68
chars_format
floating-point format for primitive numerical conversion
Definition charconv:621
bool isspace(_CharT __c, const locale &__loc)
Convenience interface to ctype.is(ctype_base::space, __c).
_CharT toupper(_CharT __c, const locale &__loc)
Convenience interface to ctype.toupper(__c).
bool isalnum(_CharT __c, const locale &__loc)
Convenience interface to ctype.is(ctype_base::alnum, __c).
ios_base & dec(ios_base &__base)
Calls base.setf(ios_base::dec, ios_base::basefield).
Definition ios_base.h:1079
ios_base & skipws(ios_base &__base)
Calls base.setf(ios_base::skipws).
Definition ios_base.h:1005
std::basic_istream< _CharT, _Traits > & operator>>(std::basic_istream< _CharT, _Traits > &__is, bitset< _Nb > &__x)
Global I/O operators for bitsets.
Definition bitset:1597
constexpr bitset< _Nb > operator|(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1567
basic_istream< _CharT, _Traits > & ws(basic_istream< _CharT, _Traits > &__is)
Quick and easy way to eat whitespace.
Definition istream.tcc:1070
constexpr from_chars_result from_chars(const char *__first, const char *__last, _Tp &__value, int __base=10)
std::from_chars for integral types.
Definition charconv:552
ISO C++ 2011 namespace for date and time utilities.
static constexpr bool is_signed
Definition limits:223
iterator begin()
Definition cow_string.h:797
_Ios_Iostate iostate
This is a bitmask type.
Definition ios_base.h:442
static const iostate eofbit
Indicates that an input operation reached the end of an input sequence.
Definition ios_base.h:449
static const iostate goodbit
Indicates all is well.
Definition ios_base.h:457
static const iostate failbit
Indicates that an input operation failed to read the expected characters, or that an output operation...
Definition ios_base.h:454
Container class for localization functionality.
static const locale & classic()
Return reference to the C locale.