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#ifdef _GLIBCXX_SYSHDR
34#pragma GCC system_header
35#endif
36
37#if __cplusplus >= 202002L
38
39#include <sstream> // ostringstream
40#include <format>
41#include <charconv> // from_chars
42#include <stdexcept> // __sso_string
43
45#include <bits/unique_ptr.h>
46
47namespace std _GLIBCXX_VISIBILITY(default)
48{
49_GLIBCXX_BEGIN_NAMESPACE_VERSION
50
51namespace chrono
52{
53/// @addtogroup chrono
54/// @{
55
56/// @cond undocumented
57namespace __detail
58{
59#define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
60#define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
61
62 template<typename _Period, typename _CharT>
64 __units_suffix() noexcept
65 {
66 // The standard say these are all narrow strings, which would need to
67 // be widened at run-time when inserted into a wide stream. We use
68 // STATICALLY-WIDEN to widen at compile-time.
69#define _GLIBCXX_UNITS_SUFFIX(period, suffix) \
70 if constexpr (is_same_v<_Period, period>) \
71 return _GLIBCXX_WIDEN(suffix); \
72 else
73
74 _GLIBCXX_UNITS_SUFFIX(atto, "as")
75 _GLIBCXX_UNITS_SUFFIX(femto, "fs")
76 _GLIBCXX_UNITS_SUFFIX(pico, "ps")
77 _GLIBCXX_UNITS_SUFFIX(nano, "ns")
78 _GLIBCXX_UNITS_SUFFIX(milli, "ms")
79#if _GLIBCXX_USE_ALT_MICROSECONDS_SUFFIX
80 // Deciding this at compile-time is wrong, maybe use nl_langinfo(CODESET)
81 // to check runtime environment and return u8"\u00b5s", "\xb5s", or "us".
82 _GLIBCXX_UNITS_SUFFIX(micro, "\u00b5s")
83#else
84 _GLIBCXX_UNITS_SUFFIX(micro, "us")
85#endif
86 _GLIBCXX_UNITS_SUFFIX(centi, "cs")
87 _GLIBCXX_UNITS_SUFFIX(deci, "ds")
88 _GLIBCXX_UNITS_SUFFIX(ratio<1>, "s")
89 _GLIBCXX_UNITS_SUFFIX(deca, "das")
90 _GLIBCXX_UNITS_SUFFIX(hecto, "hs")
91 _GLIBCXX_UNITS_SUFFIX(kilo, "ks")
92 _GLIBCXX_UNITS_SUFFIX(mega, "Ms")
93 _GLIBCXX_UNITS_SUFFIX(giga, "Gs")
94 _GLIBCXX_UNITS_SUFFIX(tera, "Ts")
95 _GLIBCXX_UNITS_SUFFIX(tera, "Ts")
96 _GLIBCXX_UNITS_SUFFIX(peta, "Ps")
97 _GLIBCXX_UNITS_SUFFIX(exa, "Es")
98 _GLIBCXX_UNITS_SUFFIX(ratio<60>, "min")
99 _GLIBCXX_UNITS_SUFFIX(ratio<3600>, "h")
100 _GLIBCXX_UNITS_SUFFIX(ratio<86400>, "d")
101#undef _GLIBCXX_UNITS_SUFFIX
102 return {};
103 }
104
105 template<typename _Period, typename _CharT, typename _Out>
106 inline _Out
107 __fmt_units_suffix(_Out __out) noexcept
108 {
109 if (auto __s = __detail::__units_suffix<_Period, _CharT>(); __s.size())
110 return __format::__write(std::move(__out), __s);
111 else if constexpr (_Period::den == 1)
112 return std::format_to(std::move(__out), _GLIBCXX_WIDEN("[{}]s"),
113 (uintmax_t)_Period::num);
114 else
115 return std::format_to(std::move(__out), _GLIBCXX_WIDEN("[{}/{}]s"),
116 (uintmax_t)_Period::num,
117 (uintmax_t)_Period::den);
118 }
119} // namespace __detail
120/// @endcond
121
122 /** Write a `chrono::duration` to an ostream.
123 *
124 * @since C++20
125 */
126 template<typename _CharT, typename _Traits,
127 typename _Rep, typename _Period>
130 const duration<_Rep, _Period>& __d)
131 {
133 using period = typename _Period::type;
135 __s.flags(__os.flags());
136 __s.imbue(__os.getloc());
137 __s.precision(__os.precision());
138 // _GLIBCXX_RESOLVE_LIB_DEFECTS
139 // 4118. How should duration formatters format custom rep types?
140 __s << +__d.count();
141 __detail::__fmt_units_suffix<period, _CharT>(_Out(__s));
142 __os << std::move(__s).str();
143 return __os;
144 }
145
146/// @cond undocumented
147namespace __detail
148{
149 // An unspecified type returned by `chrono::local_time_format`.
150 // This is called `local-time-format-t` in the standard.
151 template<typename _Duration>
152 struct __local_time_fmt
153 {
154 local_time<_Duration> _M_time;
155 const string* _M_abbrev;
156 const seconds* _M_offset_sec;
157 };
158
159 // _GLIBCXX_RESOLVE_LIB_DEFECTS
160 // 4124. Cannot format zoned_time with resolution coarser than seconds
161 template<typename _Duration>
162 using __local_time_fmt_for
163 = __local_time_fmt<common_type_t<_Duration, seconds>>;
164}
165/// @endcond
166
167 /** Return an object that asssociates timezone info with a local time.
168 *
169 * A `chrono::local_time` object has no timezone associated with it. This
170 * function creates an object that allows formatting a `local_time` as
171 * though it refers to a timezone with the given abbreviated name and
172 * offset from UTC.
173 *
174 * @since C++20
175 */
176 template<typename _Duration>
177 inline __detail::__local_time_fmt<_Duration>
178 local_time_format(local_time<_Duration> __time,
179 const string* __abbrev = nullptr,
180 const seconds* __offset_sec = nullptr)
181 { return {__time, __abbrev, __offset_sec}; }
182
183 /// @}
184} // namespace chrono
185
186/// @cond undocumented
187namespace __format
188{
189 [[noreturn,__gnu__::__always_inline__]]
190 inline void
191 __not_valid_for_duration()
192 { __throw_format_error("format error: chrono-format-spec not valid for "
193 "chrono::duration"); }
194
195 [[noreturn,__gnu__::__always_inline__]]
196 inline void
197 __invalid_chrono_spec()
198 { __throw_format_error("format error: chrono-format-spec not valid for "
199 "argument type"); }
200
201 // Represents the information provided by a chrono type.
202 // e.g. month_weekday has month and weekday but no year or time of day,
203 // hh_mm_ss has time of day but no date, sys_time is time_point+timezone.
204 enum class _ChronoParts : unsigned short {
205 _None = 0, _TotalSeconds = 1u, _Subseconds = 1u << 2,
206
207 // time since epoch
208 _EpochUnits = 1u << 3, _UnitSuffix = 1u << 4,
209 _EpochSeconds = _EpochUnits | _TotalSeconds,
210
211 // local (wall) time
212 _LocalDays = 1u << 5,
213 _LocalSeconds = _LocalDays | _TotalSeconds,
214
215 _Year = 1u << 6, _Month = 1u << 7, _Day = 1u << 8,
216 _Weekday = 1u << 9, _WeekdayIndex = 1u << 10, _DayOfYear = 1u << 11,
217 _IndexedWeekday = _Weekday | _WeekdayIndex,
218 _YearMonthDay = _Year | _Month | _Day,
219 _Date = _LocalDays | _YearMonthDay | _IndexedWeekday | _DayOfYear,
220
221 _HoursMinutesSeconds = 1u << 12,
222 _TimeOfDay = _HoursMinutesSeconds | _Subseconds,
223 _Time = _TimeOfDay | _TotalSeconds,
224 _EpochTime = _Time | _EpochUnits | _UnitSuffix,
225 _DateTime = _Date | _Time,
226
227 _ZoneAbbrev = 1u << 13, _ZoneOffset = 1u << 14,
228 _TimeZone = _ZoneAbbrev | _ZoneOffset,
229 _ZonedDateTime = _DateTime | _TimeZone,
230 };
231
232 [[__gnu__::__always_inline__]]
233 constexpr _ChronoParts
234 operator&(_ChronoParts __x, _ChronoParts __y) noexcept
235 { return static_cast<_ChronoParts>((unsigned)__x & (unsigned)__y); }
236
237 [[__gnu__::__always_inline__]]
238 constexpr _ChronoParts&
239 operator&=(_ChronoParts& __x, _ChronoParts __y) noexcept
240 { return __x = __x & __y; }
241
242 [[__gnu__::__always_inline__]]
243 constexpr _ChronoParts
244 operator|(_ChronoParts __x, _ChronoParts __y) noexcept
245 { return static_cast<_ChronoParts>((unsigned short)__x | (unsigned short)__y); }
246
247 [[__gnu__::__always_inline__]]
248 constexpr _ChronoParts&
249 operator|=(_ChronoParts& __x, _ChronoParts __y) noexcept
250 { return __x = __x | __y; }
251
252 // returns copy of x with all bits from y unset.
253 [[__gnu__::__always_inline__]]
254 constexpr _ChronoParts
255 operator-(_ChronoParts __x, _ChronoParts __y) noexcept
256 { return static_cast<_ChronoParts>((unsigned short)__x & ~(unsigned short)__y); }
257
258 // unsets all bits of x that are set in y
259 [[__gnu__::__always_inline__]]
260 constexpr _ChronoParts&
261 operator-=(_ChronoParts& __x, _ChronoParts __y) noexcept
262 { return __x = __x - __y; }
263
264 [[__gnu__::__always_inline__]]
265 constexpr bool
266 operator==(_ChronoParts __x, decltype(nullptr)) noexcept
267 { return (unsigned short)__x == 0; }
268
269 template<typename _CharT>
270 struct _ChronoSpec : _Spec<_CharT>
271 {
272 // When _M_prec_kind is _WP_none, the _M_prec contains the default
273 // value of fraction digits to be used for time '%S'.
274
275 // Placed in tail-padding of __format::_Spec<C>.
276 // This indicates that a locale-dependent conversion specifier such as
277 // %a is used in the chrono-specs. This is not the same as the
278 // _Spec<C>::_M_localized member which indicates that "L" was present
279 // in the format-spec, e.g. "{:L%a}" is localized and locale-specific,
280 // but "{:L}" is only localized and "{:%a}" is only locale-specific.
281 unsigned _M_locale_specific : 1;
282 // Indicates if parts that are checked for ok come directly from the
283 // input, instead of being computed.
284 unsigned _M_needs_ok_check : 1;
285 // Indicates that duration should be treated as floating point.
286 unsigned _M_floating_point_rep : 1;
287 // Indicate that duration uses user-defined representation.
288 unsigned _M_custom_rep : 1;
289 unsigned _M_unused : 4;
290
291 // Chrono parts required by format specs
292 _ChronoParts _M_needed;
293 basic_string_view<_CharT> _M_chrono_specs;
294
295 [[__gnu__::__always_inline__]]
296 constexpr bool
297 _M_needs(_ChronoParts __parts) const
298 { return (_M_needed & __parts) != 0; }
299 };
300
301 template<typename _CharT>
302 struct _ChronoFormats
303 {
304 using _String_view = basic_string_view<_CharT>;
305
306 static consteval
307 _String_view
308 _S_ftz() noexcept
309 { return _GLIBCXX_WIDEN("%F %T %Z"); }
310
311 static consteval
312 _String_view
313 _S_ft() noexcept
314 { return _S_ftz().substr(0, 5); }
315
316 static consteval
317 _String_view
318 _S_f() noexcept
319 { return _S_ftz().substr(0, 2); }
320
321 static consteval
322 _String_view
323 _S_t() noexcept
324 { return _S_ftz().substr(3, 2); }
325
326 static consteval
327 _String_view
328 _S_ymd() noexcept
329 { return _GLIBCXX_WIDEN("%Y/%b/%d"); }
330
331 static consteval
332 _String_view
333 _S_ym() noexcept
334 { return _S_ymd().substr(0, 5); }
335
336 static consteval
337 _String_view
338 _S_md() noexcept
339 { return _S_ymd().substr(3); }
340
341 static consteval
342 _String_view
343 _S_y() noexcept
344 { return _S_ymd().substr(0, 2); }
345
346 static consteval
347 _String_view
348 _S_m() noexcept
349 { return _S_ymd().substr(3, 2); }
350
351 static consteval
352 _String_view
353 _S_d() noexcept
354 { return _S_ymd().substr(6, 2); }
355
356 static consteval
357 _String_view
358 _S_ymwi() noexcept
359 // %\0 is extension for handling weekday index
360 { return _String_view(_GLIBCXX_WIDEN("%Y/%b/%a[%\0]"), 12); }
361
362 static consteval
363 _String_view
364 _S_mwi() noexcept
365 { return _S_ymwi().substr(3); }
366
367 static consteval
368 _String_view
369 _S_wi() noexcept
370 { return _S_ymwi().substr(6); }
371
372 static consteval
373 _String_view
374 _S_w() noexcept
375 { return _S_ymwi().substr(6, 2); }
376
377 static consteval
378 _String_view
379 _S_ymwl() noexcept
380 { return _GLIBCXX_WIDEN("%Y/%b/%a[last]"); }
381
382 static consteval
383 _String_view
384 _S_mwl() noexcept
385 { return _S_ymwl().substr(3); }
386
387 static consteval
388 _String_view
389 _S_wl() noexcept
390 { return _S_ymwl().substr(6); }
391
392 static consteval
393 _String_view
394 _S_yml() noexcept
395 { return _GLIBCXX_WIDEN("%Y/%b/last"); }
396
397 static consteval
398 _String_view
399 _S_ml() noexcept
400 { return _S_yml().substr(3); }
401 };
402
403 template<typename _CharT>
404 struct _ChronoData
405 {
406 static constexpr unsigned _S_max_prec = 18;
407 using _Attoseconds = chrono::duration<__UINT_LEAST64_TYPE__, atto>;
408
409 using _FormatContext
410 = basic_format_context<_Sink_iter<_CharT>, _CharT>;
411 using _FormatArgs = basic_format_args<_FormatContext>;
412 static inline auto _S_args = std::make_format_args<_FormatContext>();
413
414 _ChronoData() = default;
415 _ChronoData(_ChronoData&&) = delete;
416
417 // time since epoch
418 chrono::seconds _M_eseconds;
419 // n.b. due offset being seconds or coarser, local and epoch subseconds
420 // has the same value
421 _Attoseconds _M_subseconds;
422 // _M_ereps.get(0) stores duration units
423 // _M_ereps.get(1) stores subseconds units
424 // _M_ereps.get(2) stores precision
425 _FormatArgs _M_ereps = _S_args;
426 basic_string_view<_CharT> _M_unit_suffix;
427
428 // local (wall) time
429 chrono::local_seconds _M_lseconds;
430 chrono::local_days _M_ldays;
431
432 chrono::year _M_year;
433 chrono::month _M_month;
434 chrono::day _M_day;
435 chrono::weekday _M_weekday;
436 unsigned char _M_weekday_index;
437 chrono::days _M_day_of_year;
438
439 bool _M_is_neg;
440 chrono::hours _M_hours;
441 chrono::minutes _M_minutes;
442 chrono::seconds _M_seconds;
443
444 chrono::seconds _M_zone_offset;
445 basic_string_view<_CharT> _M_zone_abbrev;
446 const char* _M_zone_cstr = "";
447
448 template<typename _YearMonth>
449 [[__gnu__::__always_inline__]]
450 _ChronoParts
451 _M_fill_year_month(const _YearMonth& __ym, _ChronoParts __parts)
452 {
453 _M_year = __ym.year();
454 __parts -= _ChronoParts::_Year;
455 _M_month = __ym.month();
456 __parts -= _ChronoParts::_Month;
457 return __parts;
458 }
459
460 [[__gnu__::__always_inline__]]
461 _ChronoParts
462 _M_fill_day(chrono::day __d, _ChronoParts __parts)
463 {
464 _M_day = __d;
465 __parts -= _ChronoParts::_Day;
466 _M_weekday_index = ((unsigned)__d + 6u) % 7u;
467 __parts -= _ChronoParts::_WeekdayIndex;
468 return __parts;
469 }
470
471 [[__gnu__::__always_inline__]]
472 _ChronoParts
473 _M_fill_weekday(chrono::weekday_indexed __wi, _ChronoParts __parts)
474 {
475 _M_weekday = __wi.weekday();
476 __parts -= _ChronoParts::_Weekday;
477 _M_weekday_index = __wi.index();
478 __parts -= _ChronoParts::_WeekdayIndex;
479 return __parts;
480 }
481
482 [[__gnu__::__always_inline__]]
483 _ChronoParts
484 _M_fill_aux(chrono::local_days __ld, _ChronoParts __parts)
485 {
486 using namespace chrono;
487 if ((__parts & _ChronoParts::_Weekday) != 0)
488 _M_weekday = weekday(__ld);
489 __parts -= _ChronoParts::_Weekday;
490 if ((__parts & _ChronoParts::_DayOfYear) != 0)
491 // See "Calculating Ordinal Dates" at
492 // https://github.com/HowardHinnant/date/wiki/Examples-and-Recipes
493 _M_day_of_year = __ld - local_days(_M_year/January/0);
494 __parts -= _ChronoParts::_DayOfYear;
495 return __parts;
496 }
497
498 [[__gnu__::__always_inline__]]
499 _ChronoParts
500 _M_fill_ldays(chrono::local_days __ld, _ChronoParts __parts)
501 {
502 _M_ldays = __ld;
503 __parts -= _ChronoParts::_LocalDays;
504 return _M_fill_aux(__ld, __parts);
505 }
506
507 void
508 _M_fill_time(chrono::seconds __d)
509 {
510 chrono::hh_mm_ss<chrono::seconds> __hms(__d);
511 _M_hours = __hms.hours();
512 _M_minutes = __hms.minutes();
513 _M_seconds = __hms.seconds();
514 }
515
516 void
517 _M_fill_date_time(chrono::local_seconds __ls, _ChronoParts __parts)
518 {
519 _M_ldays = chrono::floor<chrono::days>(__ls);
520 __parts -= _ChronoParts::_LocalDays;
521 if ((__parts & _ChronoParts::_HoursMinutesSeconds) != 0)
522 _M_fill_time(_M_lseconds - _M_ldays);
523
524 if ((__parts & _ChronoParts::_Date) != 0)
525 {
526 const chrono::year_month_day __ymd(_M_ldays);
527 _M_fill_year_month(__ymd, __parts);
528 _M_fill_day(__ymd.day(), __parts);
529 _M_fill_aux(_M_ldays, __parts);
530 }
531 }
532
533 void
534 _M_fill_zone(const char* __abbrev, const wchar_t* __wabbrev)
535 {
536 if constexpr (is_same_v<_CharT, char>)
537 _M_zone_abbrev = __abbrev;
538 else
539 _M_zone_abbrev = __wabbrev;
540 _M_zone_cstr = __abbrev;
541 }
542
543 [[__gnu__::__always_inline__]]
544 void
545 _M_fill_utc_zone()
546 { _M_fill_zone("UTC", L"UTC"); }
547 };
548
549 // TODO rename this to chrono::__formatter? or chrono::__detail::__formatter?
550 template<typename _CharT>
551 struct __formatter_chrono
552 {
553 using __string_view = basic_string_view<_CharT>;
554 using __string = basic_string<_CharT>;
555
556 __formatter_chrono() = default;
557
558 constexpr explicit
559 __formatter_chrono(_ChronoSpec<_CharT> __spec) noexcept
560 : _M_spec(__spec)
561 { }
562
563 template<typename _ParseContext>
564 constexpr typename _ParseContext::iterator
565 _M_parse(_ParseContext& __pc, _ChronoParts __parts,
566 const _ChronoSpec<_CharT>& __def)
567 {
568 auto __first = __pc.begin();
569 auto __last = __pc.end();
570
571 _ChronoSpec<_CharT> __spec = __def;
572
573 auto __finalize = [this, &__spec, &__def] {
574 using enum _ChronoParts;
575 _ChronoParts __checked
576 = __spec._M_debug ? _YearMonthDay|_IndexedWeekday
577 : _Month|_Weekday;
578 // n.b. for calendar types __def._M_needed contains only parts
579 // copied from the input, remaining ones are computed, and thus ok
580 __spec._M_needs_ok_check
581 = __spec._M_needs(__def._M_needed & __checked);
582 _M_spec = __spec;
583 };
584
585 auto __finished = [&] {
586 if (__first == __last || *__first == '}')
587 {
588 __finalize();
589 return true;
590 }
591 return false;
592 };
593
594 if (__finished())
595 return __first;
596
597 __first = __spec._M_parse_fill_and_align(__first, __last);
598 if (__finished())
599 return __first;
600
601 __first = __spec._M_parse_width(__first, __last, __pc);
602 if (__finished())
603 return __first;
604
605 if (*__first == '.')
606 {
607 if ((__parts & _ChronoParts::_EpochUnits) == 0
608 || !__spec._M_floating_point_rep)
609 __throw_format_error("format error: invalid precision for duration");
610
611 // Precision is allowed, but value is ignored.
612 __first = _Spec<_CharT>()._M_parse_precision(__first, __last, __pc);
613 // Still inditate that there was user supplied precision.
614 __spec._M_prec_kind = _WP_value;
615 if (__finished())
616 return __first;
617 }
618
619 __spec._M_localized = false;
620 __first = __spec._M_parse_locale(__first, __last);
621 if (__finished())
622 return __first;
623
624 // Everything up to the end of the string or the first '}' is a
625 // chrono-specs string. Check it is valid.
626 {
627 __string_view __str(__first, __last - __first);
628 auto __end = __str.find('}');
629 if (__end != __str.npos)
630 {
631 __str.remove_suffix(__str.length() - __end);
632 __last = __first + __end;
633 }
634 if (__str.find('{') != __str.npos)
635 __throw_format_error("chrono format error: '{' in chrono-specs");
636 }
637
638 // Parse chrono-specs in [first,last), checking each conversion-spec
639 // against __parts (so fail for %Y if no year in parts).
640 // Save range in __spec._M_chrono_specs.
641 __spec._M_debug = false;
642 __spec._M_locale_specific = false;
643 __spec._M_needed = _ChronoParts::_None;
644 __spec._M_chrono_specs = __string_view();
645
646 const auto __chrono_specs = __first++; // Skip leading '%'
647 if (*__chrono_specs != '%')
648 __throw_format_error("chrono format error: no '%' at start of "
649 "chrono-specs");
650
651 _CharT __mod{};
652 bool __conv = true;
653 while (__first != __last)
654 {
655 enum _Mods { _Mod_none, _Mod_E, _Mod_O, _Mod_E_O };
656 _Mods __allowed_mods = _Mod_none;
657
658 _ChronoParts __needed = _ChronoParts::_None;
659 bool __locale_specific = false;
660
661 _CharT __c = *__first++;
662 switch (__c)
663 {
664 using enum _ChronoParts;
665 case 'a':
666 case 'A':
667 __needed = _Weekday;
668 __locale_specific = true;
669 break;
670 case 'b':
671 case 'h':
672 case 'B':
673 __needed = _Month;
674 __locale_specific = true;
675 break;
676 case 'c':
677 __needed = _Date|_HoursMinutesSeconds;
678 __allowed_mods = _Mod_E;
679 __locale_specific = true;
680 break;
681 case 'C':
682 __needed = _Year;
683 __allowed_mods = _Mod_E;
684 break;
685 case 'd':
686 case 'e':
687 __needed = _Day;
688 __allowed_mods = _Mod_O;
689 break;
690 case 'D':
691 case 'F':
692 __needed = _YearMonthDay;
693 break;
694 case 'g':
695 case 'G':
696 case 'V':
697 __needed = _LocalDays|_Year|_DayOfYear|_Weekday;
698 break;
699 case 'H':
700 case 'I':
701 __needed = _HoursMinutesSeconds;
702 __allowed_mods = _Mod_O;
703 break;
704 case 'j':
705 __needed = __parts & _DayOfYear;
706 // If we do not know day-of-year then we must have a duration,
707 // which is to be formatted as decimal number of days.
708 if (__needed == _None)
709 __needed = _HoursMinutesSeconds;
710 break;
711 case 'm':
712 __needed = _Month;
713 __allowed_mods = _Mod_O;
714 break;
715 case 'M':
716 __needed = _HoursMinutesSeconds;
717 __allowed_mods = _Mod_O;
718 break;
719 case 'p':
720 case 'r':
721 __locale_specific = true;
722 [[fallthrough]];
723 case 'R':
724 __needed = _HoursMinutesSeconds;
725 break;
726 case 'T':
727 __needed = _TimeOfDay;
728 break;
729 case 'q':
730 __needed = _UnitSuffix;
731 break;
732 case 'Q':
733 __needed = _EpochUnits;
734 break;
735 case 'S':
736 __needed = _TimeOfDay;
737 __allowed_mods = _Mod_O;
738 break;
739 case 'u':
740 case 'w':
741 __needed = _Weekday;
742 __allowed_mods = _Mod_O;
743 break;
744 case 'U':
745 case 'W':
746 __needed = _DayOfYear|_Weekday;
747 __allowed_mods = _Mod_O;
748 break;
749 case 'x':
750 __needed = _Date;
751 __locale_specific = true;
752 __allowed_mods = _Mod_E;
753 break;
754 case 'X':
755 __needed = _HoursMinutesSeconds;
756 __locale_specific = true;
757 __allowed_mods = _Mod_E;
758 break;
759 case 'y':
760 __needed = _Year;
761 __allowed_mods = _Mod_E_O;
762 break;
763 case 'Y':
764 __needed = _Year;
765 __allowed_mods = _Mod_E;
766 break;
767 case 'z':
768 __needed = _ZoneOffset;
769 __allowed_mods = _Mod_E_O;
770 break;
771 case 'Z':
772 __needed = _ZoneAbbrev;
773 break;
774 case 'n':
775 case 't':
776 case '%':
777 break;
778 case 'O':
779 case 'E':
780 if (__mod) [[unlikely]]
781 {
782 __allowed_mods = _Mod_none;
783 break;
784 }
785 __mod = __c;
786 continue;
787 default:
788 __throw_format_error("chrono format error: invalid "
789 " specifier in chrono-specs");
790 }
791
792 if ((__mod == 'E' && !(__allowed_mods & _Mod_E))
793 || (__mod == 'O' && !(__allowed_mods & _Mod_O)))
794 __throw_format_error("chrono format error: invalid "
795 " modifier in chrono-specs");
796 if (__mod && __c != 'z')
797 __locale_specific = true;
798 __mod = _CharT();
799
800 // localized formats do not include subseconds
801 if (__locale_specific)
802 __needed -= _ChronoParts::_Subseconds;
803
804 if ((__parts & __needed) != __needed)
805 __throw_format_error("chrono format error: format argument "
806 "does not contain the information "
807 "required by the chrono-specs");
808 __spec._M_needed |= __needed;
809 __spec._M_locale_specific |= __locale_specific;
810
811 // Scan for next '%', ignoring literal-chars before it.
812 size_t __pos = __string_view(__first, __last - __first).find('%');
813 if (__pos == 0)
814 ++__first;
815 else
816 {
817 if (__pos == __string_view::npos)
818 {
819 __first = __last;
820 __conv = false;
821 }
822 else
823 __first += __pos + 1;
824 }
825 }
826
827 // Check for a '%' conversion-spec without a type.
828 if (__conv || __mod != _CharT())
829 __throw_format_error("chrono format error: unescaped '%' in "
830 "chrono-specs");
831
832 __spec._M_chrono_specs
833 = __string_view(__chrono_specs, __first - __chrono_specs);
834
835 __finalize();
836 return __first;
837 }
838
839 // pre: !_M_spec._M_chrono_specs.empty()
840 template<typename _FormatContext>
841 typename _FormatContext::iterator
842 _M_format(const _ChronoData<_CharT>& __t, _FormatContext& __fc) const
843 {
844#if defined _GLIBCXX_USE_NL_LANGINFO_L && __CHAR_BIT__ == 8
845 // _GLIBCXX_RESOLVE_LIB_DEFECTS
846 // 3565. Handling of encodings in localized formatting
847 // of chrono types is underspecified
848 if constexpr (is_same_v<_CharT, char>)
849 if constexpr (__unicode::__literal_encoding_is_utf8())
850 if (_M_spec._M_localized && _M_spec._M_locale_specific)
851 {
852 extern locale __with_encoding_conversion(const locale&);
853
854 // Allocate and cache the necessary state to convert strings
855 // in the locale's encoding to UTF-8.
856 locale __loc = __fc.locale();
857 if (__loc != locale::classic())
858 __fc._M_loc = __with_encoding_conversion(__loc);
859 }
860#endif
861
862 const size_t __padwidth = _M_spec._M_get_width(__fc);
863 if (__padwidth == 0)
864 return _M_format_to(__t, __fc.out(), __fc);
865
866 using _Out = typename _FormatContext::iterator;
867 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth);
868 _M_format_to(__t, __sink.out(), __fc);
869 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
870 }
871
872
873 _ChronoSpec<_CharT> _M_spec;
874
875 protected:
876 static constexpr const _CharT* _S_chars
877 = _GLIBCXX_WIDEN("0123456789.Lf:/ +-{}");
878 static constexpr _CharT _S_dot = _S_chars[10];
879 static constexpr _CharT _S_colon = _S_chars[13];
880 static constexpr _CharT _S_slash = _S_chars[14];
881 static constexpr _CharT _S_space = _S_chars[15];
882 static constexpr const _CharT* _S_fp_fmt = _S_chars + 11;
883 static constexpr const _CharT* _S_plus_minus = _S_chars + 16;
884 static constexpr const _CharT* _S_minus_empty_spec = _S_chars + 17;
885 static constexpr const _CharT* _S_empty_spec = _S_chars + 18;
886
887 [[__gnu__::__always_inline__]]
888 static _Runtime_format_string<_CharT>
889 _S_empty_fs()
890 { return _Runtime_format_string<_CharT>(_S_empty_spec); }
891
892 static constexpr const _CharT* _S_weekdays[]
893 {
894 _GLIBCXX_WIDEN("Sunday"),
895 _GLIBCXX_WIDEN("Monday"),
896 _GLIBCXX_WIDEN("Tuesday"),
897 _GLIBCXX_WIDEN("Wednesday"),
898 _GLIBCXX_WIDEN("Thursday"),
899 _GLIBCXX_WIDEN("Friday"),
900 _GLIBCXX_WIDEN("Saturday"),
901 };
902
903 static constexpr const _CharT* _S_months[]
904 {
905 _GLIBCXX_WIDEN("January"),
906 _GLIBCXX_WIDEN("February"),
907 _GLIBCXX_WIDEN("March"),
908 _GLIBCXX_WIDEN("April"),
909 _GLIBCXX_WIDEN("May"),
910 _GLIBCXX_WIDEN("June"),
911 _GLIBCXX_WIDEN("July"),
912 _GLIBCXX_WIDEN("August"),
913 _GLIBCXX_WIDEN("September"),
914 _GLIBCXX_WIDEN("October"),
915 _GLIBCXX_WIDEN("November"),
916 _GLIBCXX_WIDEN("December"),
917 };
918
919 private:
920 template<typename _OutIter>
921 _OutIter
922 _M_write(_OutIter __out, const locale& __loc, __string_view __s) const
923 {
924#if defined _GLIBCXX_USE_NL_LANGINFO_L && __CHAR_BIT__ == 8
925 __sso_string __buf;
926 // _GLIBCXX_RESOLVE_LIB_DEFECTS
927 // 3565. Handling of encodings in localized formatting
928 // of chrono types is underspecified
929 if constexpr (is_same_v<_CharT, char>)
930 if constexpr (__unicode::__literal_encoding_is_utf8())
931 if (_M_spec._M_localized && _M_spec._M_locale_specific
932 && __loc != locale::classic())
933 {
934 extern string_view
935 __locale_encoding_to_utf8(const locale&, string_view, void*);
936
937 __s = __locale_encoding_to_utf8(__loc, __s, &__buf);
938 }
939#endif
940 return __format::__write(std::move(__out), __s);
941 }
942
943 [[__gnu__::__always_inline__]]
944 static bool
945 _S_localized_spec(_CharT __conv, _CharT __mod)
946 {
947 switch (__conv)
948 {
949 case 'a':
950 case 'A':
951 case 'b':
952 case 'B':
953 case 'c':
954 case 'h':
955 case 'p':
956 case 'r':
957 case 'x':
958 case 'X':
959 return true;
960 case 'z':
961 return false;
962 default:
963 return (bool)__mod;
964 };
965 }
966
967 // Use the formatting locale's std::time_put facet to produce
968 // a locale-specific representation.
969 template<typename _Iter>
970 _Iter
971 _M_locale_fmt(_Iter __out, const locale& __loc, const struct tm& __tm,
972 char __fmt, char __mod) const
973 {
974 basic_ostringstream<_CharT> __os;
975 __os.imbue(__loc);
976 const auto& __tp = use_facet<time_put<_CharT>>(__loc);
977 __tp.put(__os, __os, _S_space, &__tm, __fmt, __mod);
978 if (__os)
979 __out = _M_write(std::move(__out), __loc, __os.view());
980 return __out;
981 }
982
983 __string_view
984 _M_check_ok(const _ChronoData<_CharT>& __t, _CharT& __conv) const
985 {
986 if (!_M_spec._M_debug)
987 {
988 switch (__conv)
989 {
990 case 'a':
991 case 'A':
992 if (!__t._M_weekday.ok()) [[unlikely]]
993 __throw_format_error("format error: invalid weekday");
994 break;
995 case 'b':
996 case 'h':
997 case 'B':
998 if (!__t._M_month.ok()) [[unlikely]]
999 __throw_format_error("format error: invalid month");
1000 break;
1001 default:
1002 break;
1003 }
1004 return __string_view();
1005 }
1006
1007 switch (__conv)
1008 {
1009 // %\0 is extension for handling weekday index
1010 case '\0':
1011 if (__t._M_weekday_index < 1 || __t._M_weekday_index > 5) [[unlikely]]
1012 return _GLIBCXX_WIDEN("index");
1013 break;
1014 case 'a':
1015 case 'A':
1016 if (!__t._M_weekday.ok()) [[unlikely]]
1017 {
1018 __conv = 'w'; // print as decimal number
1019 return _GLIBCXX_WIDEN("weekday");
1020 }
1021 break;
1022 case 'b':
1023 case 'h':
1024 case 'B':
1025 if (!__t._M_month.ok()) [[unlikely]]
1026 {
1027 __conv = 'm'; // print as decimal number
1028 return _GLIBCXX_WIDEN("month");
1029 }
1030 break;
1031 case 'd':
1032 case 'e':
1033 if (!__t._M_day.ok()) [[unlikely]]
1034 return _GLIBCXX_WIDEN("day");
1035 break;
1036 case 'F':
1037 if (!(__t._M_year/__t._M_month/__t._M_day).ok()) [[unlikely]]
1038 return _GLIBCXX_WIDEN("date");
1039 break;
1040 case 'Y':
1041 if (!__t._M_year.ok()) [[unlikely]]
1042 return _GLIBCXX_WIDEN("year");
1043 break;
1044 default:
1045 break;
1046 }
1047 return __string_view();
1048 }
1049
1050 template<typename _OutIter, typename _FormatContext>
1051 _OutIter
1052 _M_format_to(const _ChronoData<_CharT>& __t, _OutIter __out,
1053 _FormatContext& __fc) const
1054 {
1055 auto __first = _M_spec._M_chrono_specs.begin();
1056 const auto __last = _M_spec._M_chrono_specs.end();
1057
1058 auto __print_sign = [__is_neg = __t._M_is_neg, &__out] () mutable {
1059 if (__is_neg)
1060 {
1061 *__out++ = _S_plus_minus[1];
1062 __is_neg = false;
1063 }
1064 return std::move(__out);
1065 };
1066
1067 struct tm __tm{};
1068 bool __use_locale_fmt = false;
1069 if (_M_spec._M_localized && _M_spec._M_locale_specific)
1070 if (__fc.locale() != locale::classic())
1071 {
1072 __use_locale_fmt = true;
1073
1074 __tm.tm_year = (int)__t._M_year - 1900;
1075 __tm.tm_yday = __t._M_day_of_year.count();
1076 __tm.tm_mon = (unsigned)__t._M_month - 1;
1077 __tm.tm_mday = (unsigned)__t._M_day;
1078 __tm.tm_wday = __t._M_weekday.c_encoding();
1079 __tm.tm_hour = __t._M_hours.count();
1080 __tm.tm_min = __t._M_minutes.count();
1081 __tm.tm_sec = __t._M_seconds.count();
1082
1083 // Some locales use %Z in their %c format but we don't want strftime
1084 // to use the system's local time zone (from /etc/localtime or $TZ)
1085 // as the output for %Z. Setting tm_isdst to -1 says there is no
1086 // time zone info available for the time in __tm.
1087 __tm.tm_isdst = -1;
1088
1089#ifdef _GLIBCXX_USE_STRUCT_TM_TM_ZONE
1090 // POSIX.1-2024 adds tm.tm_zone which will be used for %Z.
1091 // BSD has had tm_zone since 1987 but as char* so cast away const.
1092 if (__t._M_zone_cstr)
1093 __tm.tm_zone = const_cast<char*>(__t._M_zone_cstr);
1094#endif
1095 }
1096
1097 // Characters to output for "%n", "%t" and "%%" specifiers.
1098 constexpr const _CharT* __literals = _GLIBCXX_WIDEN("\n\t%");
1099
1100 ++__first; // Skip leading '%' at start of chrono-specs.
1101
1102 _CharT __mod{};
1103 do
1104 {
1105 _CharT __c = *__first++;
1106 __string_view __invalid;
1107 if (_M_spec._M_needs_ok_check)
1108 __invalid = _M_check_ok(__t, __c);
1109
1110 if (__invalid.empty() &&__use_locale_fmt
1111 && _S_localized_spec(__c, __mod)) [[unlikely]]
1112 __out = _M_locale_fmt(std::move(__out), __fc.locale(),
1113 __tm, __c, __mod);
1114 else switch (__c)
1115 {
1116 // %\0 is extension for handling weekday index
1117 case '\0':
1118 __out = _M_wi(__t._M_weekday_index, std::move(__out));
1119 break;
1120 case 'a':
1121 case 'A':
1122 __out = _M_a_A(__t._M_weekday, std::move(__out), __c == 'A');
1123 break;
1124 case 'b':
1125 case 'h':
1126 case 'B':
1127 __out = _M_b_B(__t._M_month, std::move(__out), __c == 'B');
1128 break;
1129 case 'c':
1130 __out = _M_c(__t, std::move(__out));
1131 break;
1132 case 'C':
1133 case 'y':
1134 case 'Y':
1135 __out = _M_C_y_Y(__t._M_year, std::move(__out), __c);
1136 break;
1137 case 'd':
1138 case 'e':
1139 __out = _M_d_e(__t._M_day, std::move(__out), __c);
1140 break;
1141 case 'D':
1142 case 'x':
1143 __out = _M_D_x(__t, std::move(__out));
1144 break;
1145 case 'F':
1146 __out = _M_F(__t, std::move(__out));
1147 break;
1148 case 'g':
1149 case 'G':
1150 case 'V':
1151 __out = _M_g_G_V(__t, std::move(__out), __c);
1152 break;
1153 case 'H':
1154 case 'I':
1155 __out = _M_H_I(__t._M_hours, __print_sign(), __c);
1156 break;
1157 case 'j':
1158 __out = _M_j(__t, __print_sign());
1159 break;
1160 case 'm':
1161 __out = _M_m(__t._M_month, std::move(__out));
1162 break;
1163 case 'M':
1164 __out = _M_M(__t._M_minutes, __print_sign());
1165 break;
1166 case 'p':
1167 __out = _M_p(__t._M_hours, std::move(__out));
1168 break;
1169 case 'q':
1170 __out = _M_q(__t._M_unit_suffix, std::move(__out));
1171 break;
1172 case 'Q':
1173 __out = _M_Q(__t, __print_sign(), __fc);
1174 break;
1175 case 'r':
1176 __out = _M_r(__t, __print_sign());
1177 break;
1178 case 'R':
1179 case 'X':
1180 __out = _M_R_X(__t, __print_sign(), __c != 'R');
1181 break;
1182 case 'T':
1183 __out = _M_T(__t, __print_sign(), __fc);
1184 break;
1185 case 'S':
1186 __out = _M_S(__t, __print_sign(), __fc, __mod != 'O');
1187 break;
1188 case 'u':
1189 case 'w':
1190 __out = _M_u_w(__t._M_weekday, std::move(__out), __c);
1191 break;
1192 case 'U':
1193 case 'W':
1194 __out = _M_U_W(__t, std::move(__out), __c);
1195 break;
1196 case 'z':
1197 __out = _M_z(__t._M_zone_offset, std::move(__out), (bool)__mod);
1198 break;
1199 case 'Z':
1200 __out = _M_Z(__t._M_zone_abbrev, std::move(__out));
1201 break;
1202 case 'n':
1203 *__out++ = __literals[0];
1204 break;
1205 case 't':
1206 *__out++ = __literals[1];
1207 break;
1208 case '%':
1209 *__out++ = __literals[2];
1210 break;
1211 case 'O':
1212 case 'E':
1213 __mod = __c;
1214 continue;
1215 case '}':
1216 __first = __last;
1217 break;
1218 }
1219
1220 if (!__invalid.empty())
1221 {
1222 constexpr __string_view __pref = _GLIBCXX_WIDEN(" is not a valid ");
1223 __out = __format::__write(std::move(__out), __pref);
1224 __out = __format::__write(std::move(__out), __invalid);
1225 }
1226
1227 __mod = _CharT();
1228 // Scan for next '%' and write out everything before it.
1229 __string_view __str(__first, __last - __first);
1230 size_t __pos = __str.find('%');
1231 if (__pos == 0)
1232 ++__first;
1233 else
1234 {
1235 if (__pos == __str.npos)
1236 __first = __last;
1237 else
1238 {
1239 __str.remove_suffix(__str.length() - __pos);
1240 __first += __pos + 1;
1241 }
1242 __out = __format::__write(std::move(__out), __str);
1243 }
1244 }
1245 while (__first != __last);
1246 return std::move(__out);
1247 }
1248
1249 template<typename _OutIter>
1250 _OutIter
1251 _M_wi(unsigned __wi, _OutIter __out) const
1252 {
1253 // %\0 Extension to format weekday index, used only by empty format spec
1254 _CharT __buf[3];
1255 __out = __format::__write(std::move(__out), _S_str_d1(__buf, __wi));
1256 return std::move(__out);
1257 }
1258
1259 template<typename _OutIter>
1260 _OutIter
1261 _M_a_A(chrono::weekday __wd, _OutIter __out, bool __full) const
1262 {
1263 // %a Locale's abbreviated weekday name.
1264 // %A Locale's full weekday name.
1265 __string_view __str = _S_weekdays[__wd.c_encoding()];
1266 if (!__full)
1267 __str = __str.substr(0, 3);
1268 return __format::__write(std::move(__out), __str);
1269 }
1270
1271 template<typename _OutIter>
1272 _OutIter
1273 _M_b_B(chrono::month __m, _OutIter __out, bool __full) const
1274 {
1275 // %b Locale's abbreviated month name.
1276 // %B Locale's full month name.
1277 __string_view __str = _S_months[(unsigned)__m - 1];
1278 if (!__full)
1279 __str = __str.substr(0, 3);
1280 return __format::__write(std::move(__out), __str);
1281 }
1282
1283 template<typename _OutIter>
1284 _OutIter
1285 _M_c(const _ChronoData<_CharT>& __t, _OutIter __out) const
1286 {
1287 // %c Locale's date and time representation, for C-locale: %a %b %e %T %Y
1288 // %Ec Locale's alternate date and time representation, for C-locale same as above
1289
1290 __out = _M_a_A(__t._M_weekday, std::move(__out), false);
1291 *__out = _S_space;
1292 __out = _M_b_B(__t._M_month, std::move(++__out), false);
1293 *__out = _S_space;
1294 __out = _M_d_e(__t._M_day, std::move(++__out), 'e');
1295 *__out = _S_space;
1296 __out = _M_R_X(__t, std::move(++__out), true);
1297 *__out = _S_space;
1298 return _M_C_y_Y(__t._M_year, std::move(++__out), 'Y');
1299 }
1300
1301 template<typename _OutIter>
1302 _OutIter
1303 _M_C_y_Y(chrono::year __y, _OutIter __out, _CharT __conv) const
1304 {
1305 // %C Year divided by 100 using floored division.
1306 // %EC Locale's alternative preresentation of the century (era name).
1307 // %y Last two decimal digits of the year.
1308 // %Oy Locale's alternative representation.
1309 // %Ey Locale's alternative representation of offset from %EC.
1310 // %Y Year as a decimal number.
1311 // %EY Locale's alternative full year representation.
1312
1313 int __yi = (int)__y;
1314 const bool __is_neg = __yi < 0;
1315 __yi = __builtin_abs(__yi);
1316 int __ci = __yi / 100;
1317 // For floored division -123//100 is -2 and -100//100 is -1
1318 if (__conv == 'C' && __is_neg && (__ci * 100) != __yi) [[unlikely]]
1319 ++__ci;
1320
1321 if (__conv != 'y' && __ci >= 100) [[unlikely]]
1322 {
1323 using _FmtStr = _Runtime_format_string<_CharT>;
1324 __string_view __fs = _S_minus_empty_spec + !__is_neg;
1325 __out = std::format_to(std::move(__out), _FmtStr(__fs),
1326 __conv == 'C' ? __ci : __yi);
1327 }
1328 else
1329 {
1330 _CharT __buf[5];
1331 __buf[0] = _S_plus_minus[1];
1332 __string_view __sv(__buf + 3, __buf + 3);
1333 if (__conv != 'y')
1334 {
1335 _S_fill_two_digits(__buf + 1, __ci);
1336 __sv = __string_view(__buf + !__is_neg, __buf + 3);
1337 }
1338 if (__conv != 'C')
1339 {
1340 _S_fill_two_digits(__buf + 3, __yi % 100);
1341 __sv = __string_view(__sv.data(), __buf + 5);
1342 }
1343 __out = __format::__write(std::move(__out), __sv);
1344 }
1345 return __out;
1346 }
1347
1348 template<typename _OutIter>
1349 _OutIter
1350 _M_D_x(const _ChronoData<_CharT>& __t, _OutIter __out) const
1351 {
1352 // %D Equivalent to %m/%d/%y
1353 // %x Locale's date rep, for C-locale: %m/%d/%y
1354 // %Ex Locale's alternative date representation, for C-locale same as above
1355
1356 auto __di = (unsigned)__t._M_day;
1357 auto __mi = (unsigned)__t._M_month;
1358 auto __yi = __builtin_abs((int)__t._M_year) % 100;
1359
1360 if (__mi >= 100 || __di >= 100) [[unlikely]]
1361 {
1362 using _FmtStr = _Runtime_format_string<_CharT>;
1363 __string_view __fs = _GLIBCXX_WIDEN("{:02d}/{:02d}/{:02d}");
1364 __out = std::format_to(std::move(__out), _FmtStr(__fs),
1365 __mi, __di, __yi);
1366 }
1367 else
1368 {
1369 _CharT __buf[8];
1370 __buf[2] = _S_slash;
1371 __buf[5] = _S_slash;
1372 __string_view __sv(__buf, __buf + 8);
1373
1374 _S_fill_two_digits(__buf, __mi);
1375 _S_fill_two_digits(__buf + 3, __di);
1376 _S_fill_two_digits(__buf + 6, __yi);
1377 __out = __format::__write(std::move(__out), __sv);
1378 }
1379 return std::move(__out);
1380 }
1381
1382 template<typename _OutIter>
1383 _OutIter
1384 _M_d_e(chrono::day __d, _OutIter __out, _CharT __conv) const
1385 {
1386 // %d The day of month as a decimal number.
1387 // %Od Locale's alternative representation.
1388 // %e Day of month as decimal number, padded with space.
1389 // %Oe Locale's alternative digits.
1390
1391 unsigned __i = (unsigned)__d;
1392
1393 _CharT __buf[3];
1394 auto __sv = _S_str_d2(__buf, __i);
1395 if (__conv == _CharT('e') && __i < 10)
1396 {
1397 __buf[1] = __sv[1];
1398 __buf[0] = _S_space;
1399 __sv = {__buf, 2};
1400 }
1401
1402 __out = __format::__write(std::move(__out), __sv);
1403 return std::move(__out);
1404 }
1405
1406 template<typename _OutIter>
1407 _OutIter
1408 _M_F(const _ChronoData<_CharT>& __t, _OutIter __out) const
1409 {
1410 auto __di = (unsigned)__t._M_day;
1411 auto __mi = (unsigned)__t._M_month;
1412 auto __yi = (int)__t._M_year;
1413 const bool __is_neg = __yi < 0;
1414 __yi = __builtin_abs(__yi);
1415
1416 if (__yi >= 10000 || __mi >= 100 || __di >= 100) [[unlikely]]
1417 {
1418 using _FmtStr = _Runtime_format_string<_CharT>;
1419 __string_view __fs
1420 = _GLIBCXX_WIDEN("-{:04d}-{:02d}-{:02d}") + !__is_neg;
1421 __out = std::format_to(std::move(__out), _FmtStr(__fs),
1422 __yi, __mi, __di);
1423 }
1424 else
1425 {
1426 _CharT __buf[11];
1427 __buf[0] = _S_plus_minus[1];
1428 __buf[5] = _S_plus_minus[1];
1429 __buf[8] = _S_plus_minus[1];
1430 __string_view __sv(__buf + !__is_neg, __buf + 11);
1431
1432 _S_fill_two_digits(__buf + 1, __yi / 100);
1433 _S_fill_two_digits(__buf + 3, __yi % 100);
1434 _S_fill_two_digits(__buf + 6, __mi);
1435 _S_fill_two_digits(__buf + 9, __di);
1436 __out = __format::__write(std::move(__out), __sv);
1437 }
1438
1439 return std::move(__out);
1440 }
1441
1442 template<typename _OutIter>
1443 _OutIter
1444 _M_g_G_V(const _ChronoData<_CharT>& __t, _OutIter __out,
1445 _CharT __conv) const
1446 {
1447 // %g last two decimal digits of the ISO week-based year.
1448 // %G ISO week-based year.
1449 // %V ISO week-based week number as a decimal number.
1450 // %OV Locale's alternative numeric rep.
1451
1452 // ISO week-based year of __t is the year that contains the nearest
1453 // Thursday. The ISO week of __t is the number of weeks since
1454 // January 1 of that year.
1455
1456 using namespace chrono;
1457 // Offset of the nearest Thursday:
1458 const days __offset = (__t._M_weekday - Monday) - days(3);
1459 // Nearest Thursday as local days:
1460 const local_days __ild = __t._M_ldays - __offset;
1461 // Day of year of nearest Thursday:
1462 days __idoy = __t._M_day_of_year - __offset;
1463
1464 // Year of nearest Thursday:
1465 year __iyear;
1466 if (__idoy <= days(0))
1467 __iyear = __t._M_year - years(1);
1468 else if (__idoy <= days(365))
1469 __iyear = __t._M_year;
1470 else if (__idoy == days(366) && __t._M_year.is_leap())
1471 __iyear = __t._M_year;
1472 else if (__idoy <= days(730))
1473 __iyear = __t._M_year + years(1);
1474 else [[unlikely]]
1475 __iyear = year_month_day(__ild).year();
1476
1477 if (__conv != 'V')
1478 return _M_C_y_Y(__iyear, std::move(__out), "yY"[__conv == 'G']);
1479
1480 if (__iyear != __t._M_year)
1481 __idoy = __ild - local_days(__iyear/January/0);
1482
1483 const auto __wi = chrono::floor<weeks>(__idoy - days(1)).count() + 1;
1484 return __format::__write(std::move(__out), _S_two_digits(__wi));
1485 }
1486
1487 template<typename _OutIter>
1488 _OutIter
1489 _M_H_I(chrono::hours __h, _OutIter __out, _CharT __conv) const
1490 {
1491 // %H The hour (24-hour clock) as a decimal number.
1492 // %OH Locale's alternative representation.
1493 // %I The hour (12-hour clock) as a decimal number.
1494 // %OI Locale's alternative representation.
1495
1496 int __i = __h.count();
1497
1498 if (__conv == _CharT('I'))
1499 {
1500 __i %= 12;
1501 if (__i == 0)
1502 __i = 12;
1503 }
1504 else if (__i >= 100) [[unlikely]]
1505 return std::format_to(std::move(__out), _S_empty_fs(), __i);
1506
1507 return __format::__write(std::move(__out), _S_two_digits(__i));
1508 }
1509
1510 template<typename _OutIter>
1511 _OutIter
1512 _M_j(const _ChronoData<_CharT>& __t, _OutIter __out) const
1513 {
1514 if (!_M_spec._M_needs(_ChronoParts::_DayOfYear))
1515 {
1516 // Decimal number of days, without padding.
1517 auto __d = chrono::floor<chrono::days>(__t._M_hours).count();
1518 return std::format_to(std::move(__out), _S_empty_fs(), __d);
1519 }
1520
1521 auto __d = __t._M_day_of_year.count();
1522 if (__d >= 1000) [[unlikely]]
1523 return std::format_to(std::move(__out), _S_empty_fs(), __d);
1524
1525 _CharT __buf[3];
1526 return __format::__write(std::move(__out), _S_str_d3(__buf, __d));
1527 }
1528
1529 template<typename _OutIter>
1530 _OutIter
1531 _M_m(chrono::month __m, _OutIter __out) const
1532 {
1533 // %m month as a decimal number.
1534 // %Om Locale's alternative representation.
1535 auto __i = (unsigned)__m;
1536 if (__i == 0 && _M_spec._M_debug) [[unlikely]]
1537 // 0 should not be padded to two digits
1538 return __format::__write(std::move(__out), _S_digit(0));
1539
1540 _CharT __buf[3];
1541 return __format::__write(std::move(__out), _S_str_d2(__buf, __i));
1542 }
1543
1544 template<typename _OutIter>
1545 _OutIter
1546 _M_M(chrono::minutes __m, _OutIter __out) const
1547 {
1548 // %M The minute as a decimal number.
1549 // %OM Locale's alternative representation.
1550
1551 auto __i = __m.count();
1552 return __format::__write(std::move(__out), _S_two_digits(__i));
1553 }
1554
1555 template<typename _OutIter>
1556 _OutIter
1557 _M_p(chrono::hours __h, _OutIter __out) const
1558 {
1559 // %p The locale's equivalent of the AM/PM designations.
1560
1561 _CharT __buf[2];
1562 _S_fill_ampm(__buf, __h);
1563 return __format::__write(std::move(__out), __string_view(__buf, 2));
1564 }
1565
1566 template<typename _OutIter>
1567 _OutIter
1568 _M_q(__string_view __us, _OutIter __out) const
1569 {
1570 // %q The duration's unit suffix
1571 return __format::__write(std::move(__out), __us);
1572 }
1573
1574 template<typename _OutIter, typename _FormatContext>
1575 _OutIter
1576 _M_Q(const _ChronoData<_CharT>& __t, _OutIter __out,
1577 _FormatContext&) const
1578 {
1579 // %Q The duration's numeric value.
1580 return std::vformat_to(std::move(__out), _S_empty_spec, __t._M_ereps);
1581 }
1582
1583 template<typename _OutIter>
1584 _OutIter
1585 _M_r(const _ChronoData<_CharT>& __t, _OutIter __out) const
1586 {
1587 // %r Locale's 12-hour clock time, for C-locale: %I:%M:%S %p
1588 auto __hi = __t._M_hours.count() % 12;
1589 if (__hi == 0)
1590 __hi = 12;
1591
1592 _CharT __buf[11];
1593 __buf[2] = _S_colon;
1594 __buf[5] = _S_colon;
1595 __buf[8] = _S_space;
1596 _S_fill_two_digits(__buf, __hi);
1597 _S_fill_two_digits(__buf + 3, __t._M_minutes.count());
1598 _S_fill_two_digits(__buf + 6, __t._M_seconds.count());
1599 _S_fill_ampm(__buf + 9, __t._M_hours);
1600
1601 return __format::__write(std::move(__out), __string_view(__buf, 11));
1602 }
1603
1604 template<typename _OutIter>
1605 _OutIter
1606 _M_R_X(const _ChronoData<_CharT>& __t, _OutIter __out,
1607 bool __secs) const
1608 {
1609 // %R Equivalent to %H:%M
1610 // %X Locale's time rep, for C-locale: %H:%M:%S (without subseconds)
1611 // %EX Locale's alternative time representation, for C-locale same as above
1612
1613 auto __hi = __t._M_hours.count();
1614
1615 _CharT __buf[8];
1616 __buf[2] = _S_colon;
1617 __buf[5] = _S_colon;
1618 __string_view __sv(__buf, 8);
1619
1620 if (__hi >= 100) [[unlikely]]
1621 {
1622 __out = std::format_to(std::move(__out), _S_empty_fs(), __hi);
1623 __sv.remove_prefix(2);
1624 }
1625 else
1626 _S_fill_two_digits(__buf, __hi);
1627
1628 _S_fill_two_digits(__buf + 3, __t._M_minutes.count());
1629 if (__secs)
1630 _S_fill_two_digits(__buf + 6, __t._M_seconds.count());
1631 else
1632 __sv.remove_suffix(3);
1633
1634 return __format::__write(std::move(__out), __sv);
1635 }
1636
1637 template<typename _OutIter, typename _FormatContext>
1638 _OutIter
1639 _M_S(const _ChronoData<_CharT>& __t, _OutIter __out,
1640 _FormatContext& __ctx, bool __subs = true) const
1641 {
1642 // %S Seconds as a decimal number.
1643 // %OS The locale's alternative representation.
1644 auto __s = __t._M_seconds;
1645
1646 __out = __format::__write(std::move(__out),
1647 _S_two_digits(__s.count()));
1648 if (__subs)
1649 __out = _M_subsecs(__t, std::move(__out), __ctx);
1650 return __out;
1651 }
1652
1653 template<typename _OutIter, typename _FormatContext>
1654 _OutIter
1655 _M_subsecs(const _ChronoData<_CharT>& __t, _OutIter __out,
1656 _FormatContext& __ctx) const
1657 {
1658 unsigned __prec = _M_spec._M_prec_kind != _WP_none
1659 ? _M_spec._M_get_precision(__ctx)
1660 : _M_spec._M_prec;
1661 if (__prec == 0)
1662 return __out;
1663
1664 _CharT __dot = _S_dot;
1665 if (_M_spec._M_localized) [[unlikely]]
1666 {
1667 auto __loc = __ctx.locale();
1668 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1669 __dot = __np.decimal_point();
1670 }
1671 *__out = __dot;
1672 ++__out;
1673
1674 if (_M_spec._M_floating_point_rep)
1675 {
1676 _Str_sink<_CharT> __sink;
1677 if (_M_spec._M_localized && _M_spec._M_custom_rep) [[unlikely]]
1678 std::vformat_to(__sink.out(), __ctx.locale(),
1679 _GLIBCXX_WIDEN("{1:0.{2}Lf}"), __t._M_ereps);
1680 else
1681 std::vformat_to(__sink.out(),
1682 _GLIBCXX_WIDEN("{1:0.{2}f}"), __t._M_ereps);
1683
1684 auto __sv = __sink.view();
1685 // Skip leading zero and dot
1686 __sv.remove_prefix(2);
1687 return __format::__write(std::move(__out), __sv);
1688 }
1689
1690 constexpr unsigned __max_prec = _ChronoData<_CharT>::_S_max_prec;
1691 constexpr typename _ChronoData<_CharT>::_Attoseconds::rep __pow10t[]
1692 {
1693 1u,
1694 10u, 100u, 1000u,
1695 10'000u, 100'000u, 1000'000u,
1696 10'000'000u, 100'000'000u, 1000'000'000u,
1697 10'000'000'000u, 100'000'000'000u, 1000'000'000'000u,
1698 10'000'000'000'000u, 100'000'000'000'000u, 1000'000'000'000'000u,
1699 10'000'000'000'000'000u, 100'000'000'000'000'000u, 1000'000'000'000'000'000u,
1700 };
1701
1702 auto __subs = __t._M_subseconds.count();
1703 if (__prec < __max_prec)
1704 __subs /= __pow10t[__max_prec - __prec];
1705 else if (__prec > __max_prec)
1706 __prec = __max_prec;
1707
1708 using _FmtStr = _Runtime_format_string<_CharT>;
1709 return std::format_to(__out, _FmtStr(_GLIBCXX_WIDEN("{0:0{1}}")),
1710 __subs, __prec);
1711 }
1712
1713 // %t handled in _M_format
1714
1715 template<typename _OutIter, typename _FormatContext>
1716 _OutIter
1717 _M_T(const _ChronoData<_CharT>& __t, _OutIter __out,
1718 _FormatContext& __ctx) const
1719 {
1720 // %T Equivalent to %H:%M:%S, with subseconds
1721 __out = _M_R_X(__t, std::move(__out), true);
1722 return _M_subsecs(__t, std::move(__out), __ctx);
1723 }
1724
1725 template<typename _OutIter>
1726 _OutIter
1727 _M_u_w(chrono::weekday __wd, _OutIter __out, _CharT __conv) const
1728 {
1729 // %u ISO weekday as a decimal number (1-7), where Monday is 1.
1730 // %Ou Locale's alternative numeric rep.
1731 // %w Weekday as a decimal number (0-6), where Sunday is 0.
1732 // %Ow Locale's alternative numeric rep.
1733 unsigned __wdi = __conv == 'u' ? __wd.iso_encoding()
1734 : __wd.c_encoding();
1735 _CharT __buf[3];
1736 return __format::__write(std::move(__out), _S_str_d1(__buf, __wdi));
1737 }
1738
1739 template<typename _OutIter>
1740 _OutIter
1741 _M_U_W(const _ChronoData<_CharT>& __t, _OutIter __out,
1742 _CharT __conv) const
1743 {
1744 // %U Week number of the year as a decimal number, from first Sunday.
1745 // %OU Locale's alternative numeric rep.
1746 // %W Week number of the year as a decimal number, from first Monday.
1747 // %OW Locale's alternative numeric rep.
1748
1749 using namespace chrono;
1750 const weekday __weekstart = __conv == 'U' ? Sunday : Monday;
1751 const days __offset = __t._M_weekday - __weekstart;
1752 auto __weeks = chrono::floor<weeks>(__t._M_day_of_year - __offset - days(1));
1753 return __format::__write(std::move(__out), _S_two_digits(__weeks.count() + 1));
1754 }
1755
1756 template<typename _OutIter>
1757 _OutIter
1758 _M_z(chrono::seconds __ts, _OutIter __out, bool __mod = false) const
1759 {
1760 if (__ts == 0s)
1761 {
1762 __string_view __zero
1763 = __mod ? _GLIBCXX_WIDEN("+00:00") : _GLIBCXX_WIDEN("+0000");
1764 return __format::__write(std::move(__out), __zero);
1765 }
1766
1767 chrono::hh_mm_ss<chrono::seconds> __hms(__ts);
1768 unsigned __mo = 3 + __mod;
1769
1770 _CharT __buf[6];
1771 __buf[0] = _S_plus_minus[__hms.is_negative()];
1772 __buf[3] = _S_colon;
1773 _S_fill_two_digits(__buf + 1, __hms.hours().count());
1774 _S_fill_two_digits(__buf + __mo, __hms.minutes().count());
1775
1776 __string_view __sv(__buf, __mo + 2);
1777 return __format::__write(std::move(__out), __sv);
1778 }
1779
1780 template<typename _OutIter>
1781 _OutIter
1782 _M_Z(__string_view __abbrev, _OutIter __out) const
1783 { return __format::__write(std::move(__out), __abbrev); }
1784
1785 // %% handled in _M_format
1786
1787 // A string view of single digit character, "0".."9".
1788 static basic_string_view<_CharT>
1789 _S_digit(int __n) noexcept
1790 {
1791 // Extra 9s avoid past-the-end read on bad input.
1792 return { _GLIBCXX_WIDEN("0123456789999999") + (__n & 0xf), 1 };
1793 }
1794
1795 // A string view of two digit characters, "00".."99".
1796 static basic_string_view<_CharT>
1797 _S_two_digits(int __n) noexcept
1798 {
1799 return {
1800 _GLIBCXX_WIDEN("0001020304050607080910111213141516171819"
1801 "2021222324252627282930313233343536373839"
1802 "4041424344454647484950515253545556575859"
1803 "6061626364656667686970717273747576777879"
1804 "8081828384858687888990919293949596979899"
1805 "9999999999999999999999999999999999999999"
1806 "9999999999999999") + 2 * (__n & 0x7f),
1807 2
1808 };
1809 }
1810
1811 // Fills __buf[0] and __buf[1] with 2 digit value of __n.
1812 [[__gnu__::__always_inline__]]
1813 static void
1814 _S_fill_two_digits(_CharT* __buf, unsigned __n)
1815 {
1816 auto __sv = _S_two_digits(__n);
1817 __buf[0] = __sv[0];
1818 __buf[1] = __sv[1];
1819 }
1820
1821 // Fills __buf[0] and __buf[1] with "AM", "PM" depending on __h.
1822 [[__gnu__::__always_inline__]]
1823 static void
1824 _S_fill_ampm(_CharT* __buf, chrono::hours __h)
1825 {
1826 auto __hi = __h.count();
1827 if (__hi >= 24) [[unlikely]]
1828 __hi %= 24;
1829
1830 constexpr const _CharT* __apm = _GLIBCXX_WIDEN("APM");
1831 __buf[0] = __apm[__hi >= 12];
1832 __buf[1] = __apm[2];
1833 }
1834
1835 // Returns decimal representation of __n.
1836 // Returned string_view may point to __buf.
1837 [[__gnu__::__always_inline__]]
1838 static basic_string_view<_CharT>
1839 _S_str_d1(span<_CharT, 3> __buf, unsigned __n)
1840 {
1841 if (__n < 10) [[likely]]
1842 return _S_digit(__n);
1843 return _S_str_d2(__buf, __n);
1844 }
1845
1846 // Returns decimal representation of __n, padded to 2 digits.
1847 // Returned string_view may point to __buf.
1848 [[__gnu__::__always_inline__]]
1849 static basic_string_view<_CharT>
1850 _S_str_d2(span<_CharT, 3> __buf, unsigned __n)
1851 {
1852 if (__n < 100) [[likely]]
1853 return _S_two_digits(__n);
1854 return _S_str_d3(__buf, __n);
1855 }
1856
1857 // Returns decimal representation of __n, padded to 3 digits.
1858 // Returned string_view points to __buf.
1859 [[__gnu__::__always_inline__]]
1860 static basic_string_view<_CharT>
1861 _S_str_d3(span<_CharT, 3> __buf, unsigned __n)
1862 {
1863 _S_fill_two_digits(__buf.data(), __n / 10);
1864 __buf[2] = _S_chars[__n % 10];
1865 return __string_view(__buf.data(), 3);
1866 }
1867 };
1868
1869 template<typename _CharT>
1870 struct __formatter_duration : private __formatter_chrono<_CharT>
1871 {
1872 template<typename _Rep, typename _Period>
1873 constexpr static auto
1874 _S_subseconds(const chrono::duration<_Rep, _Period>& __d)
1875 {
1876 if constexpr (chrono::treat_as_floating_point_v<_Rep>)
1877 return chrono::duration<_Rep>(__d);
1878 else if constexpr (_Period::den == 1)
1879 return chrono::seconds(0);
1880 else
1881 {
1882 using _Attoseconds = _ChronoData<_CharT>::_Attoseconds;
1883 using _CRep = common_type_t<_Rep, typename _Attoseconds::rep>;
1884 chrono::duration<_CRep, _Period> subs(__d.count());
1885 return chrono::duration_cast<_Attoseconds>(subs);
1886 }
1887 }
1888
1889 public:
1890 template<typename _Duration>
1891 static consteval
1892 _ChronoSpec<_CharT>
1893 _S_spec_for(_ChronoParts __parts)
1894 {
1895 using _Rep = typename _Duration::rep;
1896 using enum _ChronoParts;
1897
1898 _ChronoSpec<_CharT> __res{};
1899 __res._M_floating_point_rep = chrono::treat_as_floating_point_v<_Rep>;
1900 __res._M_custom_rep = !is_arithmetic_v<_Rep>;
1901 __res._M_prec = chrono::hh_mm_ss<_Duration>::fractional_width;
1902 if ((__parts & _TimeOfDay) != 0)
1903 __res._M_localized = __res._M_prec > 0 || __res._M_floating_point_rep;
1904
1905 if ((__parts & _TimeOfDay) != 0)
1906 __res._M_needed |= _TimeOfDay;
1907 if ((__parts & _Date) != 0)
1908 __res._M_needed |= _YearMonthDay;
1909 if ((__parts & _ZoneAbbrev) != 0)
1910 __res._M_needed |= _ZoneAbbrev;
1911
1912 switch (__parts)
1913 {
1914 case _ZonedDateTime:
1915 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ftz();
1916 break;
1917 case _DateTime:
1918 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ft();
1919 break;
1920 case _Date:
1921 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_f();
1922 break;
1923 case _Time:
1924 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_t();
1925 break;
1926 case _None:
1927 break;
1928 default:
1929 __builtin_unreachable();
1930 }
1931 return __res;
1932 };
1933
1934 using __formatter_chrono<_CharT>::__formatter_chrono;
1935 using __formatter_chrono<_CharT>::_M_spec;
1936
1937 template<typename _Duration, typename _ParseContext>
1938 constexpr typename _ParseContext::iterator
1939 _M_parse(_ParseContext& __pc, _ChronoParts __parts,
1940 const _ChronoSpec<_CharT>& __def = {})
1941 {
1942 using _Rep = typename _Duration::rep;
1943 using enum _ChronoParts;
1944
1945 auto __res
1946 = __formatter_chrono<_CharT>::_M_parse(__pc, __parts, __def);
1947 // n.b. durations do not contain date parts, and for time point all
1948 // date parts are computed, and they are always ok.
1949 _M_spec._M_needs_ok_check = false;
1950
1951 // check for custom floating point durations, if digits of output
1952 // will contain subseconds, then formatters must support specifying
1953 // precision.
1954 if constexpr (!is_floating_point_v<_Rep>)
1955 if constexpr (chrono::treat_as_floating_point_v<_Rep>)
1956 if (_M_spec._M_needs(_Subseconds|_EpochUnits)
1957 || _M_spec._M_prec_kind != _WP_none
1958 || _M_spec._M_prec_value > 0)
1959 {
1960 constexpr const _CharT* __fs = _GLIBCXX_WIDEN("#02.5Lf");
1961 basic_format_parse_context<_CharT> __npc(__fs);
1962 formatter<_Rep, _CharT> __fmtter;
1963 __fmtter.parse(__npc);
1964 }
1965 return __res;
1966 }
1967
1968 // Return the formatting locale.
1969 template<typename _FormatContext>
1970 std::locale
1971 _M_locale(_FormatContext& __fc) const
1972 {
1973 if (!_M_spec._M_localized)
1974 return std::locale::classic();
1975 else
1976 return __fc.locale();
1977 }
1978
1979 // Format duration for empty chrono-specs, e.g. "{}" (C++20 [time.format] p6).
1980 template<typename _Rep, typename _Period, typename _FormatContext>
1981 typename _FormatContext::iterator
1982 _M_format_to_ostream(const chrono::duration<_Rep, _Period>& __d,
1983 bool __is_neg,
1984 _FormatContext& __fc) const
1985 {
1986 basic_ostringstream<_CharT> __os;
1987 __os.imbue(this->_M_locale(__fc));
1988
1989 if (__is_neg) [[unlikely]]
1990 __os << this->_S_plus_minus[1];
1991 __os << __d;
1992
1993 auto __str = std::move(__os).str();
1994 return __format::__write_padded_as_spec(__str, __str.size(),
1995 __fc, _M_spec);
1996 }
1997
1998 template<typename _Rep1, typename _Period1,
1999 typename _Rep2, typename _Period2,
2000 typename _FormatContext>
2001 typename _FormatContext::iterator
2002 _M_format_units(_ChronoData<_CharT>& __cd,
2003 const chrono::duration<_Rep1, _Period1>& __ed,
2004 const chrono::duration<_Rep2, _Period2>& __ss,
2005 _FormatContext& __fc) const
2006 {
2007 __format::_Str_sink<_CharT> __suffix_store;
2008 constexpr auto _S_unit_suffix
2009 = chrono::__detail::__units_suffix<_Period1, _CharT>();
2010 if constexpr (!_S_unit_suffix.empty())
2011 __cd._M_unit_suffix = _S_unit_suffix;
2012 else if (_M_spec._M_needs(_ChronoParts::_UnitSuffix))
2013 {
2014 chrono::__detail::
2015 __fmt_units_suffix<_Period1, _CharT>(__suffix_store.out());
2016 __cd._M_unit_suffix = __suffix_store.view();
2017 }
2018
2019 const auto __prec = _M_spec._M_prec_kind != _WP_none
2020 ? _M_spec._M_get_precision(__fc)
2021 : _M_spec._M_prec;
2022
2023 using _ErasedContext = typename _ChronoData<_CharT>::_FormatContext;
2024 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2025 // 4118. How should duration formatters format custom rep?
2026 auto __ereps = +__ed.count();
2027 if (!_M_spec._M_needs(_ChronoParts::_Subseconds))
2028 {
2029 auto __ssreps = 0u;
2030 auto __args_store
2031 = std::make_format_args<_ErasedContext>(__ereps, __ssreps, __prec);
2032 __cd._M_ereps = __args_store;
2033 return this->_M_format(__cd, __fc);
2034 }
2035
2036 using _Attoseconds = _ChronoData<_CharT>::_Attoseconds;
2037 auto __nss = _S_subseconds(__ss);
2038 __cd._M_subseconds = chrono::duration_cast<_Attoseconds>(__nss);
2039
2040 auto __ssreps = __nss.count();
2041 auto __args_store
2042 = std::make_format_args<_ErasedContext>(__ereps, __ssreps, __prec);
2043 __cd._M_ereps = __args_store;
2044
2045 return this->_M_format(__cd, __fc);
2046 }
2047
2048 // pre: __cd._M_lseconds and __cd._M_eseconds are set.
2049 template<typename _Rep1, typename _Period1, typename _FormatContext>
2050 typename _FormatContext::iterator
2051 _M_format_time_point(_ChronoData<_CharT>& __cd,
2052 const chrono::duration<_Rep1, _Period1>& __ed,
2053 _FormatContext& __fc) const
2054 {
2055 auto __parts = _M_spec._M_needed - _ChronoParts::_TotalSeconds;
2056 if ((__parts & _ChronoParts::_DateTime) != 0)
2057 __cd._M_fill_date_time(__cd._M_lseconds, __parts);
2058 return _M_format_units(__cd, __ed, __ed - __cd._M_eseconds, __fc);
2059 }
2060 };
2061
2062#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
2063 template<typename _CharT>
2064 struct __formatter_chrono_info
2065 {
2066 constexpr typename basic_format_parse_context<_CharT>::iterator
2067 parse(basic_format_parse_context<_CharT>& __pc)
2068 { return _M_f._M_parse(__pc, _ChronoParts(), {}); }
2069
2070 template<typename _Info, typename _Out>
2071 typename basic_format_context<_Out, _CharT>::iterator
2072 format(const _Info& __i,
2073 basic_format_context<_Out, _CharT>& __fc) const
2074 {
2075 // n.b. only acceptable chrono-spec for info is one containing
2076 // only whitespaces and %%, that do not depend on formatted object.
2077 if (!_M_f._M_spec._M_chrono_specs.empty()) [[unlikely]]
2078 return _M_f._M_format(_ChronoData<_CharT>{}, __fc);
2079
2080 const size_t __padwidth = _M_f._M_spec._M_get_width(__fc);
2081 if (__padwidth == 0)
2082 return _M_format_to(__fc.out(), __i);
2083
2084 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth);
2085 _M_format_to(__sink.out(), __i);
2086 return __sink._M_finish(_M_f._M_spec._M_align, _M_f._M_spec._M_fill);
2087 }
2088
2089 private:
2090 template<typename _Out>
2091 _Out
2092 _M_format_to(_Out __out, const chrono::sys_info& __si) const
2093 {
2094 using _FmtStr = _Runtime_format_string<_CharT>;
2095 // n.b. only decimal separator is locale dependent for specifiers
2096 // used below, as sys_info uses seconds and minutes duration, the
2097 // output is locale-independent.
2098 constexpr auto* __fs
2099 = _GLIBCXX_WIDEN("[{0:%F %T},{1:%F %T},{2:%T},{3:%Q%q},{0:%Z}]");
2100 const chrono::local_seconds __lb(__si.begin.time_since_epoch());
2101 return std::format_to(std::move(__out), _FmtStr(__fs),
2102 chrono::local_time_format(__lb, &__si.abbrev),
2103 __si.end, __si.offset, __si.save);
2104 }
2105
2106 template<typename _Out>
2107 _Out
2108 _M_format_to(_Out __out, const chrono::local_info& __li) const
2109 {
2110 *__out = _Separators<_CharT>::_S_squares()[0];
2111 ++__out;
2112 if (__li.result == chrono::local_info::unique)
2113 __out = _M_format_to(std::move(__out), __li.first);
2114 else
2115 {
2116 basic_string_view<_CharT> __sv;
2117 if (__li.result == chrono::local_info::nonexistent)
2118 __sv =_GLIBCXX_WIDEN("nonexistent");
2119 else
2120 __sv = _GLIBCXX_WIDEN("ambiguous");
2121 __out = __format::__write(std::move(__out), __sv);
2122
2123 __sv = _GLIBCXX_WIDEN(" local time between ");
2124 __out = __format::__write(std::move(__out), __sv);
2125 __out = _M_format_to(std::move(__out), __li.first);
2126
2127 __sv = _GLIBCXX_WIDEN(" and ");
2128 __out = __format::__write(std::move(__out), __sv);
2129 __out = _M_format_to(std::move(__out), __li.second);
2130 }
2131 *__out = _Separators<_CharT>::_S_squares()[1];
2132 ++__out;
2133 return std::move(__out);
2134 }
2135
2136 __formatter_chrono<_CharT> _M_f;
2137 };
2138#endif
2139
2140} // namespace __format
2141/// @endcond
2142
2143 template<typename _Rep, typename _Period, typename _CharT>
2144 requires __format::__formattable_impl<_Rep, _CharT>
2145 struct formatter<chrono::duration<_Rep, _Period>, _CharT>
2146 {
2147 constexpr typename basic_format_parse_context<_CharT>::iterator
2148 parse(basic_format_parse_context<_CharT>& __pc)
2149 {
2150 using enum __format::_ChronoParts;
2151 return _M_f.template _M_parse<_Duration>(__pc, _EpochTime, __defSpec);
2152 }
2153
2154 template<typename _Out>
2155 typename basic_format_context<_Out, _CharT>::iterator
2156 format(const chrono::duration<_Rep, _Period>& __d,
2157 basic_format_context<_Out, _CharT>& __fc) const
2158 {
2159 if constexpr (numeric_limits<_Rep>::is_signed)
2160 if (__d < __d.zero()) [[unlikely]]
2161 {
2162 if constexpr (is_integral_v<_Rep>)
2163 {
2164 // -d is undefined for the most negative integer.
2165 // Convert duration to corresponding unsigned rep.
2166 using _URep = make_unsigned_t<_Rep>;
2167 auto __ucnt = -static_cast<_URep>(__d.count());
2168 auto __ud = chrono::duration<_URep, _Period>(__ucnt);
2169 return _M_format(__ud, true, __fc);
2170 }
2171 else
2172 return _M_format(-__d, true, __fc);
2173 }
2174 return _M_format(__d, false, __fc);
2175 }
2176
2177 private:
2178 using _Duration = chrono::duration<_Rep, _Period>;
2179
2180 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2181 {
2182 using enum __format::_ChronoParts;
2183 auto __res = __format::__formatter_duration<_CharT>::
2184 template _S_spec_for<_Duration>(_None);
2185 __res._M_localized = !is_integral_v<_Rep>;
2186 // n.b. for integral format output is the same as ostream output
2187 if constexpr (is_integral_v<_Rep>)
2188 {
2189 __res._M_needed = _EpochUnits|_UnitSuffix;
2190 __res._M_chrono_specs = _GLIBCXX_WIDEN("%Q%q");
2191 }
2192 return __res;
2193 }();
2194
2195 template<typename _Rep2, typename _Out>
2196 typename basic_format_context<_Out, _CharT>::iterator
2197 _M_format(const chrono::duration<_Rep2, _Period>& __d,
2198 bool __is_neg,
2199 basic_format_context<_Out, _CharT>& __fc) const
2200 {
2201 using namespace chrono;
2202 using enum __format::_ChronoParts;
2203 if constexpr (!is_integral_v<_Rep>)
2204 if (_M_f._M_spec._M_chrono_specs.empty())
2205 return _M_f._M_format_to_ostream(__d, __is_neg, __fc);
2206
2207 __format::_ChronoData<_CharT> __cd;
2208 __cd._M_is_neg = __is_neg;
2209 auto __ts = chrono::floor<chrono::seconds>(__d);
2210 __cd._M_eseconds = __ts;
2211 if (_M_f._M_spec._M_needs(_HoursMinutesSeconds))
2212 __cd._M_fill_time(__ts);
2213 return _M_f._M_format_units(__cd, __d, __d - __ts, __fc);
2214 }
2215
2216 __format::__formatter_duration<_CharT> _M_f{__defSpec};
2217 };
2218
2219 template<__format::__char _CharT>
2220 struct formatter<chrono::day, _CharT>
2221 {
2222 constexpr typename basic_format_parse_context<_CharT>::iterator
2223 parse(basic_format_parse_context<_CharT>& __pc)
2224 {
2225 using enum __format::_ChronoParts;
2226 return _M_f._M_parse(__pc, _Day|_WeekdayIndex, __defSpec);
2227 }
2228
2229 template<typename _Out>
2230 typename basic_format_context<_Out, _CharT>::iterator
2231 format(const chrono::day& __t,
2232 basic_format_context<_Out, _CharT>& __fc) const
2233 {
2234 __format::_ChronoData<_CharT> __cd{};
2235 __cd._M_fill_day(__t, __defSpec._M_needed);
2236 return _M_f._M_format(__cd, __fc);
2237 }
2238
2239 private:
2240 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2241 {
2242 using __format::_ChronoFormats;
2243 using enum __format::_ChronoParts;
2244
2245 __format::_ChronoSpec<_CharT> __res{};
2246 __res._M_debug = true;
2247 __res._M_needed = _Day;
2248 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_d();
2249 return __res;
2250 }();
2251
2252 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2253 };
2254
2255 template<__format::__char _CharT>
2256 struct formatter<chrono::month, _CharT>
2257 {
2258 constexpr typename basic_format_parse_context<_CharT>::iterator
2259 parse(basic_format_parse_context<_CharT>& __pc)
2260 {
2261 using enum __format::_ChronoParts;
2262 return _M_f._M_parse(__pc, _Month, __defSpec);
2263 }
2264
2265 template<typename _Out>
2266 typename basic_format_context<_Out, _CharT>::iterator
2267 format(const chrono::month& __t,
2268 basic_format_context<_Out, _CharT>& __fc) const
2269 {
2270 __format::_ChronoData<_CharT> __cd{};
2271 __cd._M_month = __t;
2272 return _M_f._M_format(__cd, __fc);
2273 }
2274
2275 private:
2276 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2277 {
2278 using __format::_ChronoFormats;
2279 using enum __format::_ChronoParts;
2280
2281 __format::_ChronoSpec<_CharT> __res{};
2282 __res._M_debug = true;
2283 __res._M_localized = true;
2284 __res._M_locale_specific = true;
2285 __res._M_needed = _Month;
2286 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_m();
2287 return __res;
2288 }();
2289
2290 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2291 };
2292
2293 template<__format::__char _CharT>
2294 struct formatter<chrono::year, _CharT>
2295 {
2296 constexpr typename basic_format_parse_context<_CharT>::iterator
2297 parse(basic_format_parse_context<_CharT>& __pc)
2298 {
2299 using enum __format::_ChronoParts;
2300 return _M_f._M_parse(__pc, _Year, __defSpec);
2301 }
2302
2303 template<typename _Out>
2304 typename basic_format_context<_Out, _CharT>::iterator
2305 format(const chrono::year& __t,
2306 basic_format_context<_Out, _CharT>& __fc) const
2307 {
2308 __format::_ChronoData<_CharT> __cd{};
2309 __cd._M_year = __t;
2310 return _M_f._M_format(__cd, __fc);
2311 }
2312
2313 private:
2314 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2315 {
2316 using __format::_ChronoFormats;
2317 using enum __format::_ChronoParts;
2318
2319 __format::_ChronoSpec<_CharT> __res{};
2320 __res._M_debug = true;
2321 __res._M_needed = _Year;
2322 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_y();
2323 return __res;
2324 }();
2325
2326 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2327 };
2328
2329 template<__format::__char _CharT>
2330 struct formatter<chrono::weekday, _CharT>
2331 {
2332 constexpr typename basic_format_parse_context<_CharT>::iterator
2333 parse(basic_format_parse_context<_CharT>& __pc)
2334 {
2335 using enum __format::_ChronoParts;
2336 return _M_f._M_parse(__pc, _Weekday, __defSpec);
2337 }
2338
2339 template<typename _Out>
2340 typename basic_format_context<_Out, _CharT>::iterator
2341 format(const chrono::weekday& __t,
2342 basic_format_context<_Out, _CharT>& __fc) const
2343 {
2344 __format::_ChronoData<_CharT> __cd{};
2345 __cd._M_weekday = __t;
2346 return _M_f._M_format(__cd, __fc);
2347 }
2348
2349 private:
2350 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2351 {
2352 using __format::_ChronoFormats;
2353 using enum __format::_ChronoParts;
2354
2355 __format::_ChronoSpec<_CharT> __res{};
2356 __res._M_debug = true;
2357 __res._M_localized = true;
2358 __res._M_locale_specific = true;
2359 __res._M_needed = _Weekday;
2360 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_w();
2361 return __res;
2362 }();
2363
2364 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2365 };
2366
2367 template<__format::__char _CharT>
2368 struct formatter<chrono::weekday_indexed, _CharT>
2369 {
2370 constexpr typename basic_format_parse_context<_CharT>::iterator
2371 parse(basic_format_parse_context<_CharT>& __pc)
2372 {
2373 using enum __format::_ChronoParts;
2374 return _M_f._M_parse(__pc, _IndexedWeekday, __defSpec);
2375 }
2376
2377 template<typename _Out>
2378 typename basic_format_context<_Out, _CharT>::iterator
2379 format(const chrono::weekday_indexed& __t,
2380 basic_format_context<_Out, _CharT>& __fc) const
2381 {
2382 __format::_ChronoData<_CharT> __cd{};
2383 __cd._M_fill_weekday(__t, __defSpec._M_needed);
2384 return _M_f._M_format(__cd, __fc);
2385 }
2386
2387 private:
2388 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2389 {
2390 using __format::_ChronoFormats;
2391 using enum __format::_ChronoParts;
2392
2393 __format::_ChronoSpec<_CharT> __res{};
2394 __res._M_debug = true;
2395 __res._M_localized = true;
2396 __res._M_locale_specific = true;
2397 __res._M_needed = _IndexedWeekday;
2398 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_wi();
2399 return __res;
2400 }();
2401
2402 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2403 };
2404
2405 template<__format::__char _CharT>
2406 struct formatter<chrono::weekday_last, _CharT>
2407 {
2408 constexpr typename basic_format_parse_context<_CharT>::iterator
2409 parse(basic_format_parse_context<_CharT>& __pc)
2410 {
2411 using enum __format::_ChronoParts;
2412 return _M_f._M_parse(__pc, _Weekday, __defSpec);
2413 }
2414
2415 template<typename _Out>
2416 typename basic_format_context<_Out, _CharT>::iterator
2417 format(const chrono::weekday_last& __t,
2418 basic_format_context<_Out, _CharT>& __fc) const
2419 {
2420 __format::_ChronoData<_CharT> __cd{};
2421 __cd._M_weekday = __t.weekday();
2422 return _M_f._M_format(__cd, __fc);
2423 }
2424
2425 private:
2426 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2427 {
2428 using __format::_ChronoFormats;
2429 using enum __format::_ChronoParts;
2430
2431 __format::_ChronoSpec<_CharT> __res{};
2432 __res._M_debug = true;
2433 __res._M_localized = true;
2434 __res._M_locale_specific = true;
2435 __res._M_needed = _Weekday;
2436 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_wl();
2437 return __res;
2438 }();
2439
2440 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2441 };
2442
2443 template<__format::__char _CharT>
2444 struct formatter<chrono::month_day, _CharT>
2445 {
2446 constexpr typename basic_format_parse_context<_CharT>::iterator
2447 parse(basic_format_parse_context<_CharT>& __pc)
2448 {
2449 using enum __format::_ChronoParts;
2450 return _M_f._M_parse(__pc, _Month|_Day|_WeekdayIndex, __defSpec);
2451 }
2452
2453 template<typename _Out>
2454 typename basic_format_context<_Out, _CharT>::iterator
2455 format(const chrono::month_day& __t,
2456 basic_format_context<_Out, _CharT>& __fc) const
2457 {
2458 __format::_ChronoData<_CharT> __cd{};
2459 __cd._M_month = __t.month();
2460 __cd._M_fill_day(__t.day(), __defSpec._M_needed);
2461 return _M_f._M_format(__cd, __fc);
2462 }
2463
2464 private:
2465 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2466 {
2467 using __format::_ChronoFormats;
2468 using enum __format::_ChronoParts;
2469
2470 __format::_ChronoSpec<_CharT> __res{};
2471 __res._M_debug = true;
2472 __res._M_localized = true;
2473 __res._M_locale_specific = true;
2474 __res._M_needed = _Month|_Day;
2475 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_md();
2476 return __res;
2477 }();
2478
2479 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2480 };
2481
2482 template<__format::__char _CharT>
2483 struct formatter<chrono::month_day_last, _CharT>
2484 {
2485 constexpr typename basic_format_parse_context<_CharT>::iterator
2486 parse(basic_format_parse_context<_CharT>& __pc)
2487 {
2488 using enum __format::_ChronoParts;
2489 return _M_f._M_parse(__pc, _Month, __defSpec);
2490 }
2491
2492 template<typename _Out>
2493 typename basic_format_context<_Out, _CharT>::iterator
2494 format(const chrono::month_day_last& __t,
2495 basic_format_context<_Out, _CharT>& __fc) const
2496 {
2497 __format::_ChronoData<_CharT> __cd{};
2498 __cd._M_month = __t.month();
2499 return _M_f._M_format(__cd, __fc);
2500 }
2501
2502 private:
2503 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2504 {
2505 using __format::_ChronoFormats;
2506 using enum __format::_ChronoParts;
2507
2508 __format::_ChronoSpec<_CharT> __res{};
2509 __res._M_debug = true;
2510 __res._M_localized = true;
2511 __res._M_locale_specific = true;
2512 __res._M_needed = _Month;
2513 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ml();
2514 return __res;
2515 }();
2516
2517 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2518 };
2519
2520 template<__format::__char _CharT>
2521 struct formatter<chrono::month_weekday, _CharT>
2522 {
2523 constexpr typename basic_format_parse_context<_CharT>::iterator
2524 parse(basic_format_parse_context<_CharT>& __pc)
2525 {
2526 using enum __format::_ChronoParts;
2527 return _M_f._M_parse(__pc, _Month|_IndexedWeekday, __defSpec);
2528 }
2529
2530 template<typename _Out>
2531 typename basic_format_context<_Out, _CharT>::iterator
2532 format(const chrono::month_weekday& __t,
2533 basic_format_context<_Out, _CharT>& __fc) const
2534 {
2535 __format::_ChronoData<_CharT> __cd{};
2536 __cd._M_month = __t.month();
2537 __cd._M_fill_weekday(__t.weekday_indexed(), __defSpec._M_needed);
2538 return _M_f._M_format(__cd, __fc);
2539 }
2540
2541 private:
2542 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2543 {
2544 using __format::_ChronoFormats;
2545 using enum __format::_ChronoParts;
2546
2547 __format::_ChronoSpec<_CharT> __res{};
2548 __res._M_debug = true;
2549 __res._M_localized = true;
2550 __res._M_locale_specific = true;
2551 __res._M_needed = _Month|_IndexedWeekday;
2552 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_mwi();
2553 return __res;
2554 }();
2555
2556 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2557 };
2558
2559 template<__format::__char _CharT>
2560 struct formatter<chrono::month_weekday_last, _CharT>
2561 {
2562 constexpr typename basic_format_parse_context<_CharT>::iterator
2563 parse(basic_format_parse_context<_CharT>& __pc)
2564 {
2565 using enum __format::_ChronoParts;
2566 return _M_f._M_parse(__pc, _Month|_Weekday, __defSpec);
2567 }
2568
2569 template<typename _Out>
2570 typename basic_format_context<_Out, _CharT>::iterator
2571 format(const chrono::month_weekday_last& __t,
2572 basic_format_context<_Out, _CharT>& __fc) const
2573 {
2574 __format::_ChronoData<_CharT> __cd{};
2575 __cd._M_month = __t.month();
2576 __cd._M_weekday = __t.weekday_last().weekday();
2577 return _M_f._M_format(__cd, __fc);
2578 }
2579
2580 private:
2581 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2582 {
2583 using __format::_ChronoFormats;
2584 using enum __format::_ChronoParts;
2585
2586 __format::_ChronoSpec<_CharT> __res{};
2587 __res._M_debug = true;
2588 __res._M_localized = true;
2589 __res._M_locale_specific = true;
2590 __res._M_needed = _Month|_Weekday;
2591 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_mwl();
2592 return __res;
2593 }();
2594
2595 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2596 };
2597
2598 template<__format::__char _CharT>
2599 struct formatter<chrono::year_month, _CharT>
2600 {
2601 constexpr typename basic_format_parse_context<_CharT>::iterator
2602 parse(basic_format_parse_context<_CharT>& __pc)
2603 {
2604 using enum __format::_ChronoParts;
2605 return _M_f._M_parse(__pc, _Year|_Month, __defSpec);
2606 }
2607
2608 template<typename _Out>
2609 typename basic_format_context<_Out, _CharT>::iterator
2610 format(const chrono::year_month& __t,
2611 basic_format_context<_Out, _CharT>& __fc) const
2612 {
2613 __format::_ChronoData<_CharT> __cd{};
2614 __cd._M_fill_year_month(__t, __defSpec._M_needed);
2615 return _M_f._M_format(__cd, __fc);
2616 }
2617
2618 private:
2619 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2620 {
2621 using __format::_ChronoFormats;
2622 using enum __format::_ChronoParts;
2623
2624 __format::_ChronoSpec<_CharT> __res{};
2625 __res._M_debug = true;
2626 __res._M_localized = true;
2627 __res._M_locale_specific = true;
2628 __res._M_needed = _Year|_Month;
2629 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ym();
2630 return __res;
2631 }();
2632
2633 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2634 };
2635
2636 template<__format::__char _CharT>
2637 struct formatter<chrono::year_month_day, _CharT>
2638 {
2639 constexpr typename basic_format_parse_context<_CharT>::iterator
2640 parse(basic_format_parse_context<_CharT>& __pc)
2641 {
2642 using enum __format::_ChronoParts;
2643 return _M_f._M_parse(__pc, _Date, __defSpec);
2644 }
2645
2646 template<typename _Out>
2647 typename basic_format_context<_Out, _CharT>::iterator
2648 format(const chrono::year_month_day& __t,
2649 basic_format_context<_Out, _CharT>& __fc) const
2650 {
2651 __format::_ChronoData<_CharT> __cd{};
2652 auto __parts = _M_f._M_spec._M_needed;
2653 __parts = __cd._M_fill_year_month(__t, __parts);
2654 __parts = __cd._M_fill_day(__t.day(), __parts);
2655 if (__parts == 0)
2656 return _M_f._M_format(__cd, __fc);
2657
2658 chrono::local_days __ld(__t);
2659 __cd._M_fill_ldays(__ld, __parts);
2660 return _M_f._M_format(__cd, __fc);
2661 }
2662
2663 private:
2664 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2665 {
2666 using __format::_ChronoFormats;
2667 using enum __format::_ChronoParts;
2668
2669 __format::_ChronoSpec<_CharT> __res{};
2670 __res._M_debug = true;
2671 __res._M_needed = _YearMonthDay;
2672 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_f();
2673 return __res;
2674 }();
2675
2676 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2677 };
2678
2679 template<__format::__char _CharT>
2680 struct formatter<chrono::year_month_day_last, _CharT>
2681 {
2682 constexpr typename basic_format_parse_context<_CharT>::iterator
2683 parse(basic_format_parse_context<_CharT>& __pc)
2684 {
2685 using enum __format::_ChronoParts;
2686 return _M_f._M_parse(__pc, _Date, __defSpec);
2687 }
2688
2689 template<typename _Out>
2690 typename basic_format_context<_Out, _CharT>::iterator
2691 format(const chrono::year_month_day_last& __t,
2692 basic_format_context<_Out, _CharT>& __fc) const
2693 {
2694 __format::_ChronoData<_CharT> __cd{};
2695 auto __parts = _M_f._M_spec._M_needed;
2696 __parts = __cd._M_fill_year_month(__t, __parts);
2697 if (__parts == 0)
2698 return _M_f._M_format(__cd, __fc);
2699
2700 chrono::local_days __ld(__t);
2701 __parts = __cd._M_fill_ldays(__ld, __parts);
2702 if (__parts == 0)
2703 return _M_f._M_format(__cd, __fc);
2704
2705 chrono::year_month_day __ymd(__ld);
2706 __cd._M_fill_day(__ymd.day(), __parts);
2707 return _M_f._M_format(__cd, __fc);
2708 }
2709
2710 private:
2711 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2712 {
2713 using __format::_ChronoFormats;
2714 using enum __format::_ChronoParts;
2715
2716 __format::_ChronoSpec<_CharT> __res{};
2717 __res._M_debug = true;
2718 __res._M_localized = true;
2719 __res._M_locale_specific = true;
2720 __res._M_needed = _Year|_Month;
2721 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_yml();
2722 return __res;
2723 }();
2724
2725 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2726 };
2727
2728 template<__format::__char _CharT>
2729 struct formatter<chrono::year_month_weekday, _CharT>
2730 {
2731 constexpr typename basic_format_parse_context<_CharT>::iterator
2732 parse(basic_format_parse_context<_CharT>& __pc)
2733 {
2734 using enum __format::_ChronoParts;
2735 return _M_f._M_parse(__pc, _Date, __defSpec);
2736 }
2737
2738 template<typename _Out>
2739 typename basic_format_context<_Out, _CharT>::iterator
2740 format(const chrono::year_month_weekday& __t,
2741 basic_format_context<_Out, _CharT>& __fc) const
2742 {
2743 __format::_ChronoData<_CharT> __cd{};
2744 auto __parts = _M_f._M_spec._M_needed;
2745 __parts = __cd._M_fill_year_month(__t, __parts);
2746 __parts = __cd._M_fill_weekday(__t.weekday_indexed(), __parts);
2747 if (__parts == 0)
2748 return _M_f._M_format(__cd, __fc);
2749
2750 chrono::local_days __ld(__t);
2751 __parts = __cd._M_fill_ldays(__ld, __parts);
2752 if (__parts == 0)
2753 return _M_f._M_format(__cd, __fc);
2754
2755 chrono::year_month_day __ymd(__ld);
2756 // n.b. weekday index is supplied by input, do not override it
2757 __cd._M_day = __ymd.day();
2758 return _M_f._M_format(__cd, __fc);
2759 }
2760
2761 private:
2762 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2763 {
2764 using __format::_ChronoFormats;
2765 using enum __format::_ChronoParts;
2766
2767 __format::_ChronoSpec<_CharT> __res{};
2768 __res._M_debug = true;
2769 __res._M_localized = true;
2770 __res._M_locale_specific = true;
2771 __res._M_needed = _Year|_Month|_IndexedWeekday;
2772 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ymwi();
2773 return __res;
2774 }();
2775
2776 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2777 };
2778
2779 template<__format::__char _CharT>
2780 struct formatter<chrono::year_month_weekday_last, _CharT>
2781 {
2782 constexpr typename basic_format_parse_context<_CharT>::iterator
2783 parse(basic_format_parse_context<_CharT>& __pc)
2784 {
2785 using enum __format::_ChronoParts;
2786 return _M_f._M_parse(__pc, _Date, __defSpec);
2787 }
2788
2789 template<typename _Out>
2790 typename basic_format_context<_Out, _CharT>::iterator
2791 format(const chrono::year_month_weekday_last& __t,
2792 basic_format_context<_Out, _CharT>& __fc) const
2793 {
2794 __format::_ChronoData<_CharT> __cd{};
2795 auto __parts = _M_f._M_spec._M_needed;
2796 __parts = __cd._M_fill_year_month(__t, __parts);
2797 __cd._M_weekday = __t.weekday_last().weekday();
2798 __parts -= __format::_ChronoParts::_Weekday;
2799 if (__parts == 0)
2800 return _M_f._M_format(__cd, __fc);
2801
2802 chrono::local_days __ld(__t);
2803 __parts = __cd._M_fill_ldays(__ld, __parts);
2804 if (__parts == 0)
2805 return _M_f._M_format(__cd, __fc);
2806
2807 chrono::year_month_day __ymd(__ld);
2808 __cd._M_fill_day(__ymd.day(), __parts);
2809 return _M_f._M_format(__cd, __fc);
2810 }
2811
2812 private:
2813 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2814 {
2815 using __format::_ChronoFormats;
2816 using enum __format::_ChronoParts;
2817
2818 __format::_ChronoSpec<_CharT> __res{};
2819 __res._M_debug = true;
2820 __res._M_localized = true;
2821 __res._M_locale_specific = true;
2822 __res._M_needed = _Year|_Month|_Weekday;
2823 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ymwl();
2824 return __res;
2825 }();
2826
2827 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2828 };
2829
2830 template<typename _Rep, typename _Period, __format::__char _CharT>
2831 struct formatter<chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>, _CharT>
2832 {
2833 constexpr typename basic_format_parse_context<_CharT>::iterator
2834 parse(basic_format_parse_context<_CharT>& __pc)
2835 {
2836 using enum __format::_ChronoParts;
2837 return _M_f.template _M_parse<_Precision>(__pc, _Time, __defSpec);
2838 }
2839
2840 template<typename _Out>
2841 typename basic_format_context<_Out, _CharT>::iterator
2842 format(const chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>& __t,
2843 basic_format_context<_Out, _CharT>& __fc) const
2844 {
2845 using enum __format::_ChronoParts;
2846
2847 __format::_ChronoData<_CharT> __cd;
2848 __cd._M_is_neg = __t.is_negative();
2849 __cd._M_hours = __t.hours();
2850 __cd._M_minutes = __t.minutes();
2851 __cd._M_seconds = __t.seconds();
2852
2853 _Precision __d(0);
2854 // n.b. computing total duration or total seconds may overflow,
2855 // do not compute them if not requested.
2856 if (_M_f._M_spec._M_needs(_EpochUnits))
2857 __d = __t.to_duration();
2858 if (_M_f._M_spec._M_needs(_TotalSeconds))
2859 __cd._M_eseconds
2860 = __cd._M_hours + __cd._M_minutes + __cd._M_seconds;
2861 return _M_f._M_format_units(__cd, __d, __t.subseconds(), __fc);
2862 }
2863
2864 private:
2865 using _Precision
2866 = typename chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>::precision;
2867 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
2868 __format::__formatter_duration<_CharT>::
2869 template _S_spec_for<_Precision>(__format::_ChronoParts::_Time);
2870
2871 __format::__formatter_duration<_CharT> _M_f{__defSpec};
2872 };
2873
2874#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
2875 template<__format::__char _CharT>
2876 struct formatter<chrono::sys_info, _CharT>
2877 {
2878 constexpr typename basic_format_parse_context<_CharT>::iterator
2879 parse(basic_format_parse_context<_CharT>& __pc)
2880 { return _M_f.parse(__pc); }
2881
2882 template<typename _Out>
2883 typename basic_format_context<_Out, _CharT>::iterator
2884 format(const chrono::sys_info& __i,
2885 basic_format_context<_Out, _CharT>& __fc) const
2886 { return _M_f.format(__i, __fc); }
2887
2888 private:
2889 __format::__formatter_chrono_info<_CharT> _M_f;
2890 };
2891
2892 template<__format::__char _CharT>
2893 struct formatter<chrono::local_info, _CharT>
2894 {
2895 constexpr typename basic_format_parse_context<_CharT>::iterator
2896 parse(basic_format_parse_context<_CharT>& __pc)
2897 { return _M_f.parse(__pc); }
2898
2899 template<typename _Out>
2900 typename basic_format_context<_Out, _CharT>::iterator
2901 format(const chrono::local_info& __i,
2902 basic_format_context<_Out, _CharT>& __fc) const
2903 { return _M_f.format(__i, __fc); }
2904
2905 private:
2906 __format::__formatter_chrono_info<_CharT> _M_f;
2907 };
2908#endif
2909
2910 template<typename _Duration, __format::__char _CharT>
2911 struct formatter<chrono::sys_time<_Duration>, _CharT>
2912 {
2913 constexpr typename basic_format_parse_context<_CharT>::iterator
2914 parse(basic_format_parse_context<_CharT>& __pc)
2915 {
2916 using enum __format::_ChronoParts;
2917 auto __next
2918 = _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
2919 if constexpr (!__stream_insertable)
2920 if (_M_f._M_spec._M_chrono_specs.empty())
2921 __format::__invalid_chrono_spec(); // chrono-specs can't be empty
2922 return __next;
2923 }
2924
2925 template<typename _Out>
2926 typename basic_format_context<_Out, _CharT>::iterator
2927 format(const chrono::sys_time<_Duration>& __t,
2928 basic_format_context<_Out, _CharT>& __fc) const
2929 {
2930 __format::_ChronoData<_CharT> __cd{};
2931 __cd._M_fill_utc_zone();
2932
2933 _Duration __ed = __t.time_since_epoch();
2934 __cd._M_eseconds = chrono::floor<chrono::seconds>(__ed);
2935 __cd._M_lseconds = chrono::local_seconds(__cd._M_eseconds);
2936 return _M_f._M_format_time_point(__cd, __ed, __fc);
2937 }
2938
2939 private:
2940 static constexpr bool __stream_insertable
2941 = requires (basic_ostream<_CharT>& __os,
2942 chrono::sys_time<_Duration> __t) { __os << __t; };
2943
2944 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2945 {
2946 using enum __format::_ChronoParts;
2947 __format::_ChronoParts __needed = _DateTime;
2948 if constexpr (!__stream_insertable)
2949 __needed = _None;
2950 else if constexpr (is_convertible_v<_Duration, chrono::days>)
2951 __needed = _Date;
2952 return __format::__formatter_duration<_CharT>::
2953 template _S_spec_for<_Duration>(__needed);
2954 }();
2955
2956 __format::__formatter_duration<_CharT> _M_f{__defSpec};
2957 };
2958
2959 template<typename _Duration, __format::__char _CharT>
2960 struct formatter<chrono::utc_time<_Duration>, _CharT>
2961 : __format::__formatter_chrono<_CharT>
2962 {
2963 constexpr typename basic_format_parse_context<_CharT>::iterator
2964 parse(basic_format_parse_context<_CharT>& __pc)
2965 {
2966 using enum __format::_ChronoParts;
2967 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
2968 }
2969
2970 template<typename _Out>
2971 typename basic_format_context<_Out, _CharT>::iterator
2972 format(const chrono::utc_time<_Duration>& __t,
2973 basic_format_context<_Out, _CharT>& __fc) const
2974 {
2975 using __format::_ChronoParts;
2976 using namespace chrono;
2977 __format::_ChronoData<_CharT> __cd{};
2978 __cd._M_fill_utc_zone();
2979
2980 _Duration __ed = __t.time_since_epoch();
2981 __cd._M_eseconds = chrono::floor<seconds>(__ed);
2982 // Adjust by removing leap seconds to get equivalent sys_time.
2983 // We can't just use clock_cast because we want to know if the time
2984 // falls within a leap second insertion, and format seconds as "60".
2985 const auto __li = chrono::get_leap_second_info(__t);
2986 __cd._M_lseconds = local_seconds(__cd._M_eseconds - __li.elapsed);
2987 auto __parts = _M_f._M_spec._M_needed - _ChronoParts::_TotalSeconds;
2988 if ((__parts & _ChronoParts::_DateTime) != 0)
2989 {
2990 __cd._M_fill_date_time(__cd._M_lseconds, __parts);
2991 __cd._M_seconds += seconds(__li.is_leap_second);
2992 }
2993 return _M_f._M_format_units(__cd, __ed, __ed - __cd._M_eseconds, __fc);
2994 }
2995
2996 private:
2997 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
2998 __format::__formatter_duration<_CharT>::
2999 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3000
3001 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3002 };
3003
3004 template<typename _Duration, __format::__char _CharT>
3005 struct formatter<chrono::tai_time<_Duration>, _CharT>
3006 : __format::__formatter_chrono<_CharT>
3007 {
3008 constexpr typename basic_format_parse_context<_CharT>::iterator
3009 parse(basic_format_parse_context<_CharT>& __pc)
3010 {
3011 using enum __format::_ChronoParts;
3012 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3013 }
3014
3015 template<typename _Out>
3016 typename basic_format_context<_Out, _CharT>::iterator
3017 format(const chrono::tai_time<_Duration>& __t,
3018 basic_format_context<_Out, _CharT>& __fc) const
3019 {
3020 using namespace chrono;
3021 __format::_ChronoData<_CharT> __cd{};
3022 __cd._M_fill_zone("TAI", L"TAI");
3023
3024 _Duration __ed = __t.time_since_epoch();
3025 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3026 // Offset is 1970y/January/1 - 1958y/January/1
3027 constexpr chrono::days __tai_offset = chrono::days(4383);
3028 __cd._M_lseconds = local_seconds(__cd._M_eseconds - __tai_offset);
3029 return _M_f._M_format_time_point(__cd, __ed, __fc);
3030 }
3031
3032 private:
3033 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3034 __format::__formatter_duration<_CharT>::
3035 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3036
3037 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3038 };
3039
3040 template<typename _Duration, __format::__char _CharT>
3041 struct formatter<chrono::gps_time<_Duration>, _CharT>
3042 : __format::__formatter_chrono<_CharT>
3043 {
3044 constexpr typename basic_format_parse_context<_CharT>::iterator
3045 parse(basic_format_parse_context<_CharT>& __pc)
3046 {
3047 using enum __format::_ChronoParts;
3048 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3049 }
3050
3051 template<typename _Out>
3052 typename basic_format_context<_Out, _CharT>::iterator
3053 format(const chrono::gps_time<_Duration>& __t,
3054 basic_format_context<_Out, _CharT>& __fc) const
3055 {
3056 using namespace chrono;
3057 __format::_ChronoData<_CharT> __cd{};
3058 __cd._M_fill_zone("GPS", L"GPS");
3059
3060 _Duration __ed = __t.time_since_epoch();
3061 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3062 // Offset is 1980y/January/Sunday[1] - 1970y/January/1
3063 constexpr chrono::days __gps_offset = chrono::days(3657);
3064 __cd._M_lseconds = local_seconds(__cd._M_eseconds + __gps_offset);
3065 return _M_f._M_format_time_point(__cd, __ed, __fc);
3066 }
3067
3068 private:
3069 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3070 __format::__formatter_duration<_CharT>::
3071 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3072
3073 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3074 };
3075
3076 template<typename _Duration, __format::__char _CharT>
3077 struct formatter<chrono::file_time<_Duration>, _CharT>
3078 {
3079 constexpr typename basic_format_parse_context<_CharT>::iterator
3080 parse(basic_format_parse_context<_CharT>& __pc)
3081 {
3082 using enum __format::_ChronoParts;
3083 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3084 }
3085
3086 template<typename _Out>
3087 typename basic_format_context<_Out, _CharT>::iterator
3088 format(const chrono::file_time<_Duration>& __t,
3089 basic_format_context<_Out, _CharT>& __fc) const
3090 {
3091 using namespace chrono;
3092 __format::_ChronoData<_CharT> __cd{};
3093 __cd._M_fill_utc_zone();
3094
3095 _Duration __ed = __t.time_since_epoch();
3096 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3097 auto __st = chrono::clock_cast<system_clock>(__t);
3098 __cd._M_lseconds
3099 = local_seconds(chrono::floor<seconds>(__st.time_since_epoch()));
3100 return _M_f._M_format_time_point(__cd, __ed, __fc);
3101 }
3102
3103 private:
3104 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3105 __format::__formatter_duration<_CharT>::
3106 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3107
3108 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3109 };
3110
3111 template<typename _Duration, __format::__char _CharT>
3112 struct formatter<chrono::local_time<_Duration>, _CharT>
3113 {
3114 constexpr typename basic_format_parse_context<_CharT>::iterator
3115 parse(basic_format_parse_context<_CharT>& __pc)
3116 {
3117 using enum __format::_ChronoParts;
3118 return _M_f.template _M_parse<_Duration>(__pc, _DateTime, __defSpec);
3119 }
3120
3121 template<typename _Out>
3122 typename basic_format_context<_Out, _CharT>::iterator
3123 format(const chrono::local_time<_Duration>& __lt,
3124 basic_format_context<_Out, _CharT>& __fc) const
3125 {
3126 __format::_ChronoData<_CharT> __cd{};
3127 _Duration __ed = __lt.time_since_epoch();
3128 __cd._M_lseconds = chrono::floor<chrono::seconds>(__lt);
3129 __cd._M_eseconds = __cd._M_lseconds.time_since_epoch();
3130 return _M_f._M_format_time_point(__cd, __ed, __fc);
3131 }
3132
3133 private:
3134 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
3135 {
3136 using enum __format::_ChronoParts;
3137 __format::_ChronoParts __needed = _DateTime;
3138 if constexpr (is_convertible_v<_Duration, chrono::days>)
3139 __needed = _Date;
3140 return __format::__formatter_duration<_CharT>::
3141 template _S_spec_for<_Duration>(__needed);
3142 }();
3143
3144 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3145 };
3146
3147 template<typename _Duration, __format::__char _CharT>
3148 struct formatter<chrono::__detail::__local_time_fmt<_Duration>, _CharT>
3149 {
3150 constexpr typename basic_format_parse_context<_CharT>::iterator
3151 parse(basic_format_parse_context<_CharT>& __pc)
3152 {
3153 using enum __format::_ChronoParts;
3154 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3155 }
3156
3157 template<typename _Out>
3158 typename basic_format_context<_Out, _CharT>::iterator
3159 format(const chrono::__detail::__local_time_fmt<_Duration>& __zt,
3160 basic_format_context<_Out, _CharT>& __fc) const
3161 {
3162 using enum __format::_ChronoParts;
3163 __format::_ChronoData<_CharT> __cd{};
3164
3165 if (_M_f._M_spec._M_needs(_ZoneOffset))
3166 {
3167 if (!__zt._M_offset_sec)
3168 std::__throw_format_error("format error: no timezone available for %z");
3169 __cd._M_zone_offset = *__zt._M_offset_sec;
3170 }
3171
3172 basic_string<_CharT> __zone_store;
3173 if (_M_f._M_spec._M_needs(_ZoneAbbrev))
3174 {
3175 if (!__zt._M_abbrev)
3176 std::__throw_format_error("format error: no timezone available for %Z");
3177
3178 __cd._M_zone_cstr = __zt._M_abbrev->data();
3179 if constexpr (is_same_v<_CharT, char>)
3180 __cd._M_zone_abbrev = *__zt._M_abbrev;
3181 else
3182 {
3183 // TODO: use resize_for_override
3184 __zone_store.resize(__zt._M_abbrev->size());
3185 auto& __ct = use_facet<ctype<_CharT>>(_M_f._M_locale(__fc));
3186 __ct.widen(__zt._M_abbrev->data(),
3187 __zt._M_abbrev->data() + __zt._M_abbrev->size(),
3188 __zone_store.data());
3189 __cd._M_zone_abbrev = __zone_store;
3190 }
3191 }
3192
3193 _Duration __ed = __zt._M_time.time_since_epoch();
3194 __cd._M_lseconds = chrono::floor<chrono::seconds>(__zt._M_time);
3195 __cd._M_eseconds = __cd._M_lseconds.time_since_epoch();
3196 return _M_f._M_format_time_point(__cd, __ed, __fc);
3197 }
3198
3199 private:
3200 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3201 __format::__formatter_duration<_CharT>::
3202 template _S_spec_for<_Duration>(__format::_ChronoParts::_ZonedDateTime);
3203
3204 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3205 };
3206
3207#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
3208 template<typename _Duration, typename _TimeZonePtr, __format::__char _CharT>
3209 struct formatter<chrono::zoned_time<_Duration, _TimeZonePtr>, _CharT>
3210 : formatter<chrono::__detail::__local_time_fmt_for<_Duration>, _CharT>
3211 {
3212 template<typename _Out>
3213 typename basic_format_context<_Out, _CharT>::iterator
3214 format(const chrono::zoned_time<_Duration, _TimeZonePtr>& __tp,
3215 basic_format_context<_Out, _CharT>& __fc) const
3216 {
3217 using _Ltf = chrono::__detail::__local_time_fmt_for<_Duration>;
3218 using _Base = formatter<_Ltf, _CharT>;
3219 const chrono::sys_info __info = __tp.get_info();
3220 const auto __lf = chrono::local_time_format(__tp.get_local_time(),
3221 &__info.abbrev,
3222 &__info.offset);
3223 return _Base::format(__lf, __fc);
3224 }
3225 };
3226#endif
3227
3228namespace chrono
3229{
3230/// @addtogroup chrono
3231/// @{
3232
3233/// @cond undocumented
3234namespace __detail
3235{
3236 template<typename _Duration = seconds>
3237 struct _Parser
3238 {
3239 static_assert(is_same_v<common_type_t<_Duration, seconds>, _Duration>);
3240
3241 explicit
3242 _Parser(__format::_ChronoParts __need) : _M_need(__need) { }
3243
3244 _Parser(_Parser&&) = delete;
3245 void operator=(_Parser&&) = delete;
3246
3247 _Duration _M_time{}; // since midnight
3248 sys_days _M_sys_days{};
3249 year_month_day _M_ymd{};
3250 weekday _M_wd{};
3251 __format::_ChronoParts _M_need;
3252 unsigned _M_is_leap_second : 1 {};
3253 unsigned _M_reserved : 15 {};
3254
3255 template<typename _CharT, typename _Traits, typename _Alloc>
3256 basic_istream<_CharT, _Traits>&
3257 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3258 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3259 minutes* __offset = nullptr);
3260
3261 private:
3262 // Read an unsigned integer from the stream and return it.
3263 // Extract no more than __n digits. Set failbit if an integer isn't read.
3264 template<typename _CharT, typename _Traits>
3265 static int_least32_t
3266 _S_read_unsigned(basic_istream<_CharT, _Traits>& __is,
3267 ios_base::iostate& __err, int __n)
3268 {
3269 int_least32_t __val = _S_try_read_digit(__is, __err);
3270 if (__val == -1) [[unlikely]]
3271 __err |= ios_base::failbit;
3272 else
3273 {
3274 int __n1 = (std::min)(__n, 9);
3275 // Cannot overflow __val unless we read more than 9 digits
3276 for (int __i = 1; __i < __n1; ++__i)
3277 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
3278 {
3279 __val *= 10;
3280 __val += __dig;
3281 }
3282
3283 while (__n1++ < __n) [[unlikely]]
3284 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
3285 {
3286 if (__builtin_mul_overflow(__val, 10, &__val)
3287 || __builtin_add_overflow(__val, __dig, &__val))
3288 {
3289 __err |= ios_base::failbit;
3290 return -1;
3291 }
3292 }
3293 }
3294 return __val;
3295 }
3296
3297 // Read an unsigned integer from the stream and return it.
3298 // Extract no more than __n digits. Set failbit if an integer isn't read.
3299 template<typename _CharT, typename _Traits>
3300 static int_least32_t
3301 _S_read_signed(basic_istream<_CharT, _Traits>& __is,
3302 ios_base::iostate& __err, int __n)
3303 {
3304 auto __sign = __is.peek();
3305 if (__sign == '-' || __sign == '+')
3306 (void) __is.get();
3307 int_least32_t __val = _S_read_unsigned(__is, __err, __n);
3308 if (__err & ios_base::failbit)
3309 {
3310 if (__sign == '-') [[unlikely]]
3311 __val *= -1;
3312 }
3313 return __val;
3314 }
3315
3316 // Read a digit from the stream and return it, or return -1.
3317 // If no digit is read eofbit will be set (but not failbit).
3318 template<typename _CharT, typename _Traits>
3319 static int_least32_t
3320 _S_try_read_digit(basic_istream<_CharT, _Traits>& __is,
3321 ios_base::iostate& __err)
3322 {
3323 int_least32_t __val = -1;
3324 auto __i = __is.peek();
3325 if (!_Traits::eq_int_type(__i, _Traits::eof())) [[likely]]
3326 {
3327 _CharT __c = _Traits::to_char_type(__i);
3328 if (_CharT('0') <= __c && __c <= _CharT('9')) [[likely]]
3329 {
3330 (void) __is.get();
3331 __val = __c - _CharT('0');
3332 }
3333 }
3334 else
3335 __err |= ios_base::eofbit;
3336 return __val;
3337 }
3338
3339 // Read the specified character and return true.
3340 // If the character is not found, set failbit and return false.
3341 template<typename _CharT, typename _Traits>
3342 static bool
3343 _S_read_chr(basic_istream<_CharT, _Traits>& __is,
3344 ios_base::iostate& __err, _CharT __c)
3345 {
3346 auto __i = __is.peek();
3347 if (_Traits::eq_int_type(__i, _Traits::eof()))
3348 __err |= ios_base::eofbit;
3349 else if (_Traits::to_char_type(__i) == __c) [[likely]]
3350 {
3351 (void) __is.get();
3352 return true;
3353 }
3354 __err |= ios_base::failbit;
3355 return false;
3356 }
3357 };
3358
3359 template<typename _Duration>
3360 using _Parser_t = _Parser<common_type_t<_Duration, seconds>>;
3361
3362 template<typename _Duration>
3363 consteval bool
3364 __use_floor()
3365 {
3366 if constexpr (_Duration::period::den == 1)
3367 {
3368 switch (_Duration::period::num)
3369 {
3370 case minutes::period::num:
3371 case hours::period::num:
3372 case days::period::num:
3373 case weeks::period::num:
3374 case years::period::num:
3375 return true;
3376 }
3377 }
3378 return false;
3379 }
3380
3381 // A "do the right thing" rounding function for duration and time_point
3382 // values extracted by from_stream. When treat_as_floating_point is true
3383 // we don't want to do anything, just a straightforward conversion.
3384 // When the destination type has a period of minutes, hours, days, weeks,
3385 // or years, we use chrono::floor to truncate towards negative infinity.
3386 // This ensures that an extracted timestamp such as 2024-09-05 13:00:00
3387 // will produce 2024-09-05 when rounded to days, rather than rounding up
3388 // to 2024-09-06 (a different day).
3389 // Otherwise, use chrono::round to get the nearest value representable
3390 // in the destination type.
3391 template<typename _ToDur, typename _Tp>
3392 constexpr auto
3393 __round(const _Tp& __t)
3394 {
3395 if constexpr (__is_duration_v<_Tp>)
3396 {
3397 if constexpr (treat_as_floating_point_v<typename _Tp::rep>)
3399 else if constexpr (__detail::__use_floor<_ToDur>())
3400 return chrono::floor<_ToDur>(__t);
3401 else
3402 return chrono::round<_ToDur>(__t);
3403 }
3404 else
3405 {
3406 static_assert(__is_time_point_v<_Tp>);
3407 using _Tpt = time_point<typename _Tp::clock, _ToDur>;
3408 return _Tpt(__detail::__round<_ToDur>(__t.time_since_epoch()));
3409 }
3410 }
3411
3412} // namespace __detail
3413/// @endcond
3414
3415 template<typename _CharT, typename _Traits, typename _Rep, typename _Period,
3416 typename _Alloc = allocator<_CharT>>
3417 inline basic_istream<_CharT, _Traits>&
3418 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3420 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3421 minutes* __offset = nullptr)
3422 {
3423 auto __need = __format::_ChronoParts::_TimeOfDay;
3424 __detail::_Parser_t<duration<_Rep, _Period>> __p(__need);
3425 if (__p(__is, __fmt, __abbrev, __offset))
3426 __d = __detail::__round<duration<_Rep, _Period>>(__p._M_time);
3427 return __is;
3428 }
3429
3430 template<typename _CharT, typename _Traits>
3431 inline basic_ostream<_CharT, _Traits>&
3432 operator<<(basic_ostream<_CharT, _Traits>& __os, const day& __d)
3433 {
3434 using _Ctx = __format::__format_context<_CharT>;
3435 using _Str = basic_string_view<_CharT>;
3436 _Str __s = _GLIBCXX_WIDEN("{:02d} is not a valid day");
3437 if (__d.ok())
3438 __s = __s.substr(0, 6);
3439 auto __u = (unsigned)__d;
3440 __os << std::vformat(__s, make_format_args<_Ctx>(__u));
3441 return __os;
3442 }
3443
3444 template<typename _CharT, typename _Traits,
3445 typename _Alloc = allocator<_CharT>>
3446 inline basic_istream<_CharT, _Traits>&
3447 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3448 day& __d,
3449 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3450 minutes* __offset = nullptr)
3451 {
3452 __detail::_Parser<> __p(__format::_ChronoParts::_Day);
3453 if (__p(__is, __fmt, __abbrev, __offset))
3454 __d = __p._M_ymd.day();
3455 return __is;
3456 }
3457
3458 template<typename _CharT, typename _Traits>
3459 inline basic_ostream<_CharT, _Traits>&
3460 operator<<(basic_ostream<_CharT, _Traits>& __os, const month& __m)
3461 {
3462 using _Ctx = __format::__format_context<_CharT>;
3463 using _Str = basic_string_view<_CharT>;
3464 _Str __s = _GLIBCXX_WIDEN("{:L%b}{} is not a valid month");
3465 if (__m.ok())
3466 __os << std::vformat(__os.getloc(), __s.substr(0, 6),
3467 make_format_args<_Ctx>(__m));
3468 else
3469 {
3470 auto __u = (unsigned)__m;
3471 __os << std::vformat(__s.substr(6), make_format_args<_Ctx>(__u));
3472 }
3473 return __os;
3474 }
3475
3476 template<typename _CharT, typename _Traits,
3477 typename _Alloc = allocator<_CharT>>
3478 inline basic_istream<_CharT, _Traits>&
3479 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3480 month& __m,
3481 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3482 minutes* __offset = nullptr)
3483 {
3484 __detail::_Parser<> __p(__format::_ChronoParts::_Month);
3485 if (__p(__is, __fmt, __abbrev, __offset))
3486 __m = __p._M_ymd.month();
3487 return __is;
3488 }
3489
3490 template<typename _CharT, typename _Traits>
3491 inline basic_ostream<_CharT, _Traits>&
3492 operator<<(basic_ostream<_CharT, _Traits>& __os, const year& __y)
3493 {
3494 using _Ctx = __format::__format_context<_CharT>;
3495 using _Str = basic_string_view<_CharT>;
3496 _Str __s = _GLIBCXX_WIDEN("-{:04d} is not a valid year");
3497 if (__y.ok())
3498 __s = __s.substr(0, 7);
3499 int __i = (int)__y;
3500 if (__i >= 0) [[likely]]
3501 __s.remove_prefix(1);
3502 else
3503 __i = -__i;
3504 __os << std::vformat(__s, make_format_args<_Ctx>(__i));
3505 return __os;
3506 }
3507
3508 template<typename _CharT, typename _Traits,
3509 typename _Alloc = allocator<_CharT>>
3510 inline basic_istream<_CharT, _Traits>&
3511 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3512 year& __y,
3513 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3514 minutes* __offset = nullptr)
3515 {
3516 __detail::_Parser<> __p(__format::_ChronoParts::_Year);
3517 if (__p(__is, __fmt, __abbrev, __offset))
3518 __y = __p._M_ymd.year();
3519 return __is;
3520 }
3521
3522 template<typename _CharT, typename _Traits>
3523 inline basic_ostream<_CharT, _Traits>&
3524 operator<<(basic_ostream<_CharT, _Traits>& __os, const weekday& __wd)
3525 {
3526 using _Ctx = __format::__format_context<_CharT>;
3527 using _Str = basic_string_view<_CharT>;
3528 _Str __s = _GLIBCXX_WIDEN("{:L%a}{} is not a valid weekday");
3529 if (__wd.ok())
3530 __os << std::vformat(__os.getloc(), __s.substr(0, 6),
3531 make_format_args<_Ctx>(__wd));
3532 else
3533 {
3534 auto __c = __wd.c_encoding();
3535 __os << std::vformat(__s.substr(6), make_format_args<_Ctx>(__c));
3536 }
3537 return __os;
3538 }
3539
3540 template<typename _CharT, typename _Traits,
3541 typename _Alloc = allocator<_CharT>>
3542 inline basic_istream<_CharT, _Traits>&
3543 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3544 weekday& __wd,
3545 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3546 minutes* __offset = nullptr)
3547 {
3548 __detail::_Parser<> __p(__format::_ChronoParts::_Weekday);
3549 if (__p(__is, __fmt, __abbrev, __offset))
3550 __wd = __p._M_wd;
3551 return __is;
3552 }
3553
3554 template<typename _CharT, typename _Traits>
3555 inline basic_ostream<_CharT, _Traits>&
3556 operator<<(basic_ostream<_CharT, _Traits>& __os,
3557 const weekday_indexed& __wdi)
3558 {
3559 // The standard says to format wdi.weekday() and wdi.index() using
3560 // either "{:L}[{}]" or "{:L}[{} is not a valid index]". The {:L} spec
3561 // means to format the weekday using ostringstream, so just do that.
3562 basic_stringstream<_CharT> __os2;
3563 __os2.imbue(__os.getloc());
3564 __os2 << __wdi.weekday();
3565 const auto __i = __wdi.index();
3566 basic_string_view<_CharT> __s
3567 = _GLIBCXX_WIDEN("[ is not a valid index]");
3568 __os2 << __s[0];
3569 __os2 << std::format(_GLIBCXX_WIDEN("{}"), __i);
3570 if (__i >= 1 && __i <= 5)
3571 __os2 << __s.back();
3572 else
3573 __os2 << __s.substr(1);
3574 __os << __os2.view();
3575 return __os;
3576 }
3577
3578 template<typename _CharT, typename _Traits>
3579 inline basic_ostream<_CharT, _Traits>&
3580 operator<<(basic_ostream<_CharT, _Traits>& __os,
3581 const weekday_last& __wdl)
3582 {
3583 // As above, just write straight to a stringstream, as if by "{:L}[last]"
3584 basic_stringstream<_CharT> __os2;
3585 __os2.imbue(__os.getloc());
3586 __os2 << __wdl.weekday() << _GLIBCXX_WIDEN("[last]");
3587 __os << __os2.view();
3588 return __os;
3589 }
3590
3591 template<typename _CharT, typename _Traits>
3592 inline basic_ostream<_CharT, _Traits>&
3593 operator<<(basic_ostream<_CharT, _Traits>& __os, const month_day& __md)
3594 {
3595 // As above, just write straight to a stringstream, as if by "{:L}/{}"
3596 basic_stringstream<_CharT> __os2;
3597 __os2.imbue(__os.getloc());
3598 __os2 << __md.month();
3599 if constexpr (is_same_v<_CharT, char>)
3600 __os2 << '/';
3601 else
3602 __os2 << L'/';
3603 __os2 << __md.day();
3604 __os << __os2.view();
3605 return __os;
3606 }
3607
3608 template<typename _CharT, typename _Traits,
3609 typename _Alloc = allocator<_CharT>>
3610 inline basic_istream<_CharT, _Traits>&
3611 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3612 month_day& __md,
3613 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3614 minutes* __offset = nullptr)
3615 {
3616 using __format::_ChronoParts;
3617 auto __need = _ChronoParts::_Month | _ChronoParts::_Day;
3618 __detail::_Parser<> __p(__need);
3619 if (__p(__is, __fmt, __abbrev, __offset))
3620 __md = month_day(__p._M_ymd.month(), __p._M_ymd.day());
3621 return __is;
3622 }
3623
3624 template<typename _CharT, typename _Traits>
3625 inline basic_ostream<_CharT, _Traits>&
3626 operator<<(basic_ostream<_CharT, _Traits>& __os,
3627 const month_day_last& __mdl)
3628 {
3629 // As above, just write straight to a stringstream, as if by "{:L}/last"
3630 basic_stringstream<_CharT> __os2;
3631 __os2.imbue(__os.getloc());
3632 __os2 << __mdl.month() << _GLIBCXX_WIDEN("/last");
3633 __os << __os2.view();
3634 return __os;
3635 }
3636
3637 template<typename _CharT, typename _Traits>
3638 inline basic_ostream<_CharT, _Traits>&
3639 operator<<(basic_ostream<_CharT, _Traits>& __os,
3640 const month_weekday& __mwd)
3641 {
3642 // As above, just write straight to a stringstream, as if by "{:L}/{:L}"
3643 basic_stringstream<_CharT> __os2;
3644 __os2.imbue(__os.getloc());
3645 __os2 << __mwd.month();
3646 if constexpr (is_same_v<_CharT, char>)
3647 __os2 << '/';
3648 else
3649 __os2 << L'/';
3650 __os2 << __mwd.weekday_indexed();
3651 __os << __os2.view();
3652 return __os;
3653 }
3654
3655 template<typename _CharT, typename _Traits>
3656 inline basic_ostream<_CharT, _Traits>&
3657 operator<<(basic_ostream<_CharT, _Traits>& __os,
3658 const month_weekday_last& __mwdl)
3659 {
3660 // As above, just write straight to a stringstream, as if by "{:L}/{:L}"
3661 basic_stringstream<_CharT> __os2;
3662 __os2.imbue(__os.getloc());
3663 __os2 << __mwdl.month();
3664 if constexpr (is_same_v<_CharT, char>)
3665 __os2 << '/';
3666 else
3667 __os2 << L'/';
3668 __os2 << __mwdl.weekday_last();
3669 __os << __os2.view();
3670 return __os;
3671 }
3672
3673 template<typename _CharT, typename _Traits>
3674 inline basic_ostream<_CharT, _Traits>&
3675 operator<<(basic_ostream<_CharT, _Traits>& __os, const year_month& __ym)
3676 {
3677 // As above, just write straight to a stringstream, as if by "{}/{:L}"
3678 basic_stringstream<_CharT> __os2;
3679 __os2.imbue(__os.getloc());
3680 __os2 << __ym.year();
3681 if constexpr (is_same_v<_CharT, char>)
3682 __os2 << '/';
3683 else
3684 __os2 << L'/';
3685 __os2 << __ym.month();
3686 __os << __os2.view();
3687 return __os;
3688 }
3689
3690 template<typename _CharT, typename _Traits,
3691 typename _Alloc = allocator<_CharT>>
3692 inline basic_istream<_CharT, _Traits>&
3693 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3694 year_month& __ym,
3695 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3696 minutes* __offset = nullptr)
3697 {
3698 using __format::_ChronoParts;
3699 auto __need = _ChronoParts::_Year | _ChronoParts::_Month;
3700 __detail::_Parser<> __p(__need);
3701 if (__p(__is, __fmt, __abbrev, __offset))
3702 __ym = year_month(__p._M_ymd.year(), __p._M_ymd.month());
3703 return __is;
3704 }
3705
3706 template<typename _CharT, typename _Traits>
3707 inline basic_ostream<_CharT, _Traits>&
3708 operator<<(basic_ostream<_CharT, _Traits>& __os,
3709 const year_month_day& __ymd)
3710 {
3711 using _Ctx = __format::__format_context<_CharT>;
3712 using _Str = basic_string_view<_CharT>;
3713 _Str __s = _GLIBCXX_WIDEN("{:%F} is not a valid date");
3714 __os << std::vformat(__ymd.ok() ? __s.substr(0, 5) : __s,
3715 make_format_args<_Ctx>(__ymd));
3716 return __os;
3717 }
3718
3719 template<typename _CharT, typename _Traits,
3720 typename _Alloc = allocator<_CharT>>
3721 inline basic_istream<_CharT, _Traits>&
3722 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3723 year_month_day& __ymd,
3724 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3725 minutes* __offset = nullptr)
3726 {
3727 using __format::_ChronoParts;
3728 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3729 | _ChronoParts::_Day;
3730 __detail::_Parser<> __p(__need);
3731 if (__p(__is, __fmt, __abbrev, __offset))
3732 __ymd = __p._M_ymd;
3733 return __is;
3734 }
3735
3736 template<typename _CharT, typename _Traits>
3739 const year_month_day_last& __ymdl)
3740 {
3741 // As above, just write straight to a stringstream, as if by "{}/{:L}"
3743 __os2.imbue(__os.getloc());
3744 __os2 << __ymdl.year();
3745 if constexpr (is_same_v<_CharT, char>)
3746 __os2 << '/';
3747 else
3748 __os2 << L'/';
3749 __os2 << __ymdl.month_day_last();
3750 __os << __os2.view();
3751 return __os;
3752 }
3753
3754 template<typename _CharT, typename _Traits>
3755 inline basic_ostream<_CharT, _Traits>&
3756 operator<<(basic_ostream<_CharT, _Traits>& __os,
3757 const year_month_weekday& __ymwd)
3758 {
3759 // As above, just write straight to a stringstream, as if by
3760 // "{}/{:L}/{:L}"
3761 basic_stringstream<_CharT> __os2;
3762 __os2.imbue(__os.getloc());
3763 _CharT __slash;
3764 if constexpr (is_same_v<_CharT, char>)
3765 __slash = '/';
3766 else
3767 __slash = L'/';
3768 __os2 << __ymwd.year() << __slash << __ymwd.month() << __slash
3769 << __ymwd.weekday_indexed();
3770 __os << __os2.view();
3771 return __os;
3772 }
3773
3774 template<typename _CharT, typename _Traits>
3775 inline basic_ostream<_CharT, _Traits>&
3776 operator<<(basic_ostream<_CharT, _Traits>& __os,
3777 const year_month_weekday_last& __ymwdl)
3778 {
3779 // As above, just write straight to a stringstream, as if by
3780 // "{}/{:L}/{:L}"
3781 basic_stringstream<_CharT> __os2;
3782 __os2.imbue(__os.getloc());
3783 _CharT __slash;
3784 if constexpr (is_same_v<_CharT, char>)
3785 __slash = '/';
3786 else
3787 __slash = L'/';
3788 __os2 << __ymwdl.year() << __slash << __ymwdl.month() << __slash
3789 << __ymwdl.weekday_last();
3790 __os << __os2.view();
3791 return __os;
3792 }
3793
3794 template<typename _CharT, typename _Traits, typename _Duration>
3795 inline basic_ostream<_CharT, _Traits>&
3796 operator<<(basic_ostream<_CharT, _Traits>& __os,
3797 const hh_mm_ss<_Duration>& __hms)
3798 {
3799 return __os << format(__os.getloc(), _GLIBCXX_WIDEN("{:L%T}"), __hms);
3800 }
3801
3802#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
3803 /// Writes a sys_info object to an ostream in an unspecified format.
3804 template<typename _CharT, typename _Traits>
3805 basic_ostream<_CharT, _Traits>&
3806 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_info& __i)
3807 {
3808 return __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{}"), __i);
3809 }
3810
3811 /// Writes a local_info object to an ostream in an unspecified format.
3812 template<typename _CharT, typename _Traits>
3813 basic_ostream<_CharT, _Traits>&
3814 operator<<(basic_ostream<_CharT, _Traits>& __os, const local_info& __li)
3815 {
3816 __os << __format::_Separators<_CharT>::_S_squares()[0];
3817 if (__li.result == local_info::unique)
3818 __os << __li.first;
3819 else
3820 {
3821 if (__li.result == local_info::nonexistent)
3822 __os << _GLIBCXX_WIDEN("nonexistent");
3823 else
3824 __os << _GLIBCXX_WIDEN("ambiguous");
3825 __os << _GLIBCXX_WIDEN(" local time between ") << __li.first;
3826 __os << _GLIBCXX_WIDEN(" and ") << __li.second;
3827 }
3828 __os << __format::_Separators<_CharT>::_S_squares()[1];
3829 return __os;
3830 }
3831
3832 template<typename _CharT, typename _Traits, typename _Duration,
3833 typename _TimeZonePtr>
3834 inline basic_ostream<_CharT, _Traits>&
3835 operator<<(basic_ostream<_CharT, _Traits>& __os,
3836 const zoned_time<_Duration, _TimeZonePtr>& __t)
3837 {
3838 __os << format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T %Z}"), __t);
3839 return __os;
3840 }
3841#endif
3842
3843 template<typename _CharT, typename _Traits, typename _Duration>
3844 requires (!treat_as_floating_point_v<typename _Duration::rep>)
3845 && ratio_less_v<typename _Duration::period, days::period>
3846 inline basic_ostream<_CharT, _Traits>&
3847 operator<<(basic_ostream<_CharT, _Traits>& __os,
3848 const sys_time<_Duration>& __tp)
3849 {
3850 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __tp);
3851 return __os;
3852 }
3853
3854 template<typename _CharT, typename _Traits>
3855 inline basic_ostream<_CharT, _Traits>&
3856 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_days& __dp)
3857 {
3858 __os << year_month_day{__dp};
3859 return __os;
3860 }
3861
3862 template<typename _CharT, typename _Traits, typename _Duration,
3863 typename _Alloc = allocator<_CharT>>
3864 basic_istream<_CharT, _Traits>&
3865 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3866 sys_time<_Duration>& __tp,
3867 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3868 minutes* __offset = nullptr)
3869 {
3870 minutes __off{};
3871 if (!__offset)
3872 __offset = &__off;
3873 using __format::_ChronoParts;
3874 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3875 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3876 __detail::_Parser_t<_Duration> __p(__need);
3877 if (__p(__is, __fmt, __abbrev, __offset))
3878 {
3879 if (__p._M_is_leap_second)
3880 __is.setstate(ios_base::failbit);
3881 else
3882 {
3883 auto __st = __p._M_sys_days + __p._M_time - *__offset;
3884 __tp = __detail::__round<_Duration>(__st);
3885 }
3886 }
3887 return __is;
3888 }
3889
3890 template<typename _CharT, typename _Traits, typename _Duration>
3891 inline basic_ostream<_CharT, _Traits>&
3892 operator<<(basic_ostream<_CharT, _Traits>& __os,
3893 const utc_time<_Duration>& __t)
3894 {
3895 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
3896 return __os;
3897 }
3898
3899 template<typename _CharT, typename _Traits, typename _Duration,
3900 typename _Alloc = allocator<_CharT>>
3901 inline basic_istream<_CharT, _Traits>&
3902 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3903 utc_time<_Duration>& __tp,
3904 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3905 minutes* __offset = nullptr)
3906 {
3907 minutes __off{};
3908 if (!__offset)
3909 __offset = &__off;
3910 using __format::_ChronoParts;
3911 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3912 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3913 __detail::_Parser_t<_Duration> __p(__need);
3914 if (__p(__is, __fmt, __abbrev, __offset))
3915 {
3916 // Converting to utc_time before adding _M_time is necessary for
3917 // "23:59:60" to correctly produce a time within a leap second.
3918 auto __ut = utc_clock::from_sys(__p._M_sys_days) + __p._M_time
3919 - *__offset;
3920 __tp = __detail::__round<_Duration>(__ut);
3921 }
3922 return __is;
3923 }
3924
3925 template<typename _CharT, typename _Traits, typename _Duration>
3926 inline basic_ostream<_CharT, _Traits>&
3927 operator<<(basic_ostream<_CharT, _Traits>& __os,
3928 const tai_time<_Duration>& __t)
3929 {
3930 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
3931 return __os;
3932 }
3933
3934 template<typename _CharT, typename _Traits, typename _Duration,
3935 typename _Alloc = allocator<_CharT>>
3936 inline basic_istream<_CharT, _Traits>&
3937 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3938 tai_time<_Duration>& __tp,
3939 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3940 minutes* __offset = nullptr)
3941 {
3942 minutes __off{};
3943 if (!__offset)
3944 __offset = &__off;
3945 using __format::_ChronoParts;
3946 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3947 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3948 __detail::_Parser_t<_Duration> __p(__need);
3949 if (__p(__is, __fmt, __abbrev, __offset))
3950 {
3951 if (__p._M_is_leap_second)
3952 __is.setstate(ios_base::failbit);
3953 else
3954 {
3955 constexpr sys_days __epoch(-days(4383)); // 1958y/1/1
3956 auto __d = __p._M_sys_days - __epoch + __p._M_time - *__offset;
3957 tai_time<common_type_t<_Duration, seconds>> __tt(__d);
3958 __tp = __detail::__round<_Duration>(__tt);
3959 }
3960 }
3961 return __is;
3962 }
3963
3964 template<typename _CharT, typename _Traits, typename _Duration>
3965 inline basic_ostream<_CharT, _Traits>&
3966 operator<<(basic_ostream<_CharT, _Traits>& __os,
3967 const gps_time<_Duration>& __t)
3968 {
3969 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
3970 return __os;
3971 }
3972
3973 template<typename _CharT, typename _Traits, typename _Duration,
3974 typename _Alloc = allocator<_CharT>>
3975 inline basic_istream<_CharT, _Traits>&
3976 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3977 gps_time<_Duration>& __tp,
3978 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3979 minutes* __offset = nullptr)
3980 {
3981 minutes __off{};
3982 if (!__offset)
3983 __offset = &__off;
3984 using __format::_ChronoParts;
3985 auto __need = _ChronoParts::_YearMonthDay | _ChronoParts::_TimeOfDay;
3986 __detail::_Parser_t<_Duration> __p(__need);
3987 if (__p(__is, __fmt, __abbrev, __offset))
3988 {
3989 if (__p._M_is_leap_second)
3990 __is.setstate(ios_base::failbit);
3991 else
3992 {
3993 constexpr sys_days __epoch(days(3657)); // 1980y/1/Sunday[1]
3994 auto __d = __p._M_sys_days - __epoch + __p._M_time - *__offset;
3995 gps_time<common_type_t<_Duration, seconds>> __gt(__d);
3996 __tp = __detail::__round<_Duration>(__gt);
3997 }
3998 }
3999 return __is;
4000 }
4001
4002 template<typename _CharT, typename _Traits, typename _Duration>
4003 inline basic_ostream<_CharT, _Traits>&
4004 operator<<(basic_ostream<_CharT, _Traits>& __os,
4005 const file_time<_Duration>& __t)
4006 {
4007 __os << std::format(__os.getloc(), _GLIBCXX_WIDEN("{:L%F %T}"), __t);
4008 return __os;
4009 }
4010
4011 template<typename _CharT, typename _Traits, typename _Duration,
4012 typename _Alloc = allocator<_CharT>>
4013 inline basic_istream<_CharT, _Traits>&
4014 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4015 file_time<_Duration>& __tp,
4016 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4017 minutes* __offset = nullptr)
4018 {
4019 sys_time<_Duration> __st;
4020 if (chrono::from_stream(__is, __fmt, __st, __abbrev, __offset))
4021 __tp = __detail::__round<_Duration>(file_clock::from_sys(__st));
4022 return __is;
4023 }
4024
4025 template<typename _CharT, typename _Traits, typename _Duration>
4026 inline basic_ostream<_CharT, _Traits>&
4027 operator<<(basic_ostream<_CharT, _Traits>& __os,
4028 const local_time<_Duration>& __lt)
4029 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4030 // 4257. Stream insertion for chrono::local_time should be constrained
4031 requires requires(const sys_time<_Duration>& __st) { __os << __st; }
4032 {
4033 __os << sys_time<_Duration>{__lt.time_since_epoch()};
4034 return __os;
4035 }
4036
4037 template<typename _CharT, typename _Traits, typename _Duration,
4038 typename _Alloc = allocator<_CharT>>
4039 basic_istream<_CharT, _Traits>&
4040 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4041 local_time<_Duration>& __tp,
4042 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4043 minutes* __offset = nullptr)
4044 {
4045 using __format::_ChronoParts;
4046 auto __need = _ChronoParts::_YearMonthDay | _ChronoParts::_TimeOfDay;
4047 __detail::_Parser_t<_Duration> __p(__need);
4048 if (__p(__is, __fmt, __abbrev, __offset))
4049 {
4050 days __d = __p._M_sys_days.time_since_epoch();
4051 auto __t = local_days(__d) + __p._M_time; // ignore offset
4052 __tp = __detail::__round<_Duration>(__t);
4053 }
4054 return __is;
4055 }
4056
4057 // [time.parse] parsing
4058
4059namespace __detail
4060{
4061 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4062 // 3956. chrono::parse uses from_stream as a customization point
4063 void from_stream() = delete;
4064
4065 template<typename _Parsable, typename _CharT,
4066 typename _Traits = std::char_traits<_CharT>,
4067 typename... _OptArgs>
4068 concept __parsable = requires (basic_istream<_CharT, _Traits>& __is,
4069 const _CharT* __fmt, _Parsable& __tp,
4070 _OptArgs*... __args)
4071 { from_stream(__is, __fmt, __tp, __args...); };
4072
4073 template<typename _Parsable, typename _CharT,
4074 typename _Traits = char_traits<_CharT>,
4075 typename _Alloc = allocator<_CharT>>
4076 struct _Parse
4077 {
4078 private:
4079 using __string_type = basic_string<_CharT, _Traits, _Alloc>;
4080
4081 public:
4082 _Parse(const _CharT* __fmt, _Parsable& __tp,
4083 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4084 minutes* __offset = nullptr)
4085 : _M_fmt(__fmt), _M_tp(std::__addressof(__tp)),
4086 _M_abbrev(__abbrev), _M_offset(__offset)
4087 { }
4088
4089 _Parse(_Parse&&) = delete;
4090 _Parse& operator=(_Parse&&) = delete;
4091
4092 private:
4093 using __stream_type = basic_istream<_CharT, _Traits>;
4094
4095 const _CharT* const _M_fmt;
4096 _Parsable* const _M_tp;
4097 __string_type* const _M_abbrev;
4098 minutes* const _M_offset;
4099
4100 friend __stream_type&
4101 operator>>(__stream_type& __is, _Parse&& __p)
4102 {
4103 if (__p._M_offset)
4104 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev,
4105 __p._M_offset);
4106 else if (__p._M_abbrev)
4107 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev);
4108 else
4109 from_stream(__is, __p._M_fmt, *__p._M_tp);
4110 return __is;
4111 }
4112
4113 friend void operator>>(__stream_type&, _Parse&) = delete;
4114 friend void operator>>(__stream_type&, const _Parse&) = delete;
4115 };
4116} // namespace __detail
4117
4118 template<typename _CharT, __detail::__parsable<_CharT> _Parsable>
4119 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4120 inline auto
4121 parse(const _CharT* __fmt, _Parsable& __tp)
4122 { return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp); }
4123
4124 template<typename _CharT, typename _Traits, typename _Alloc,
4125 __detail::__parsable<_CharT, _Traits> _Parsable>
4126 [[nodiscard]]
4127 inline auto
4128 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp)
4129 {
4130 return __detail::_Parse<_Parsable, _CharT, _Traits>(__fmt.c_str(), __tp);
4131 }
4132
4133 template<typename _CharT, typename _Traits, typename _Alloc,
4134 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4135 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
4136 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4137 inline auto
4138 parse(const _CharT* __fmt, _Parsable& __tp,
4139 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
4140 {
4141 auto __pa = std::__addressof(__abbrev);
4142 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
4143 __pa);
4144 }
4145
4146 template<typename _CharT, typename _Traits, typename _Alloc,
4147 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4148 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
4149 [[nodiscard]]
4150 inline auto
4151 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4152 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
4153 {
4154 auto __pa = std::__addressof(__abbrev);
4155 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4156 __tp, __pa);
4157 }
4158
4159 template<typename _CharT, typename _Traits = char_traits<_CharT>,
4160 typename _StrT = basic_string<_CharT, _Traits>,
4161 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4162 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4163 inline auto
4164 parse(const _CharT* __fmt, _Parsable& __tp, minutes& __offset)
4165 {
4166 return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp, nullptr,
4167 &__offset);
4168 }
4169
4170 template<typename _CharT, typename _Traits, typename _Alloc,
4171 typename _StrT = basic_string<_CharT, _Traits>,
4172 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4173 [[nodiscard]]
4174 inline auto
4175 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4176 minutes& __offset)
4177 {
4178 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4179 __tp, nullptr,
4180 &__offset);
4181 }
4182
4183 template<typename _CharT, typename _Traits, typename _Alloc,
4184 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4185 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4186 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4187 inline auto
4188 parse(const _CharT* __fmt, _Parsable& __tp,
4189 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
4190 {
4191 auto __pa = std::__addressof(__abbrev);
4192 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
4193 __pa,
4194 &__offset);
4195 }
4196
4197 template<typename _CharT, typename _Traits, typename _Alloc,
4198 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4199 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4200 [[nodiscard]]
4201 inline auto
4202 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4203 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
4204 {
4205 auto __pa = std::__addressof(__abbrev);
4206 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4207 __tp, __pa,
4208 &__offset);
4209 }
4210
4211 /// @cond undocumented
4212 template<typename _Duration>
4213 template<typename _CharT, typename _Traits, typename _Alloc>
4214 basic_istream<_CharT, _Traits>&
4215 __detail::_Parser<_Duration>::
4216 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4217 basic_string<_CharT, _Traits, _Alloc>* __abbrev,
4218 minutes* __offset)
4219 {
4220 using sentry = typename basic_istream<_CharT, _Traits>::sentry;
4222 if (sentry __cerb(__is, true); __cerb)
4223 {
4224 locale __loc = __is.getloc();
4225 auto& __tmget = std::use_facet<std::time_get<_CharT>>(__loc);
4226 auto& __tmpunct = std::use_facet<std::__timepunct<_CharT>>(__loc);
4227
4228 // RAII type to save and restore stream state.
4229 struct _Stream_state
4230 {
4231 explicit
4232 _Stream_state(basic_istream<_CharT, _Traits>& __i)
4233 : _M_is(__i),
4234 _M_flags(__i.flags(ios_base::skipws | ios_base::dec)),
4235 _M_w(__i.width(0))
4236 { }
4237
4238 ~_Stream_state()
4239 {
4240 _M_is.flags(_M_flags);
4241 _M_is.width(_M_w);
4242 }
4243
4244 _Stream_state(_Stream_state&&) = delete;
4245
4246 basic_istream<_CharT, _Traits>& _M_is;
4247 ios_base::fmtflags _M_flags;
4248 streamsize _M_w;
4249 };
4250
4251 auto __is_failed = [](ios_base::iostate __e) {
4252 return static_cast<bool>(__e & ios_base::failbit);
4253 };
4254
4255 // Read an unsigned integer from the stream and return it.
4256 // Extract no more than __n digits. Set __err on error.
4257 auto __read_unsigned = [&] (int __n) {
4258 return _S_read_unsigned(__is, __err, __n);
4259 };
4260
4261 // Read a signed integer from the stream and return it.
4262 // Extract no more than __n digits. Set __err on error.
4263 auto __read_signed = [&] (int __n) {
4264 return _S_read_signed(__is, __err, __n);
4265 };
4266
4267 // Read an expected character from the stream.
4268 auto __read_chr = [&__is, &__err] (_CharT __c) {
4269 return _S_read_chr(__is, __err, __c);
4270 };
4271
4272 using __format::_ChronoParts;
4273 _ChronoParts __parts{};
4274
4275 const year __bad_y = --year::min(); // SHRT_MIN
4276 const month __bad_mon(255);
4277 const day __bad_day(255);
4278 const weekday __bad_wday(255);
4279 const hours __bad_h(-1);
4280 const minutes __bad_min(-9999);
4281 const seconds __bad_sec(-1);
4282
4283 year __y = __bad_y, __yy = __bad_y; // %Y, %yy
4284 year __iso_y = __bad_y, __iso_yy = __bad_y; // %G, %g
4285 month __m = __bad_mon; // %m
4286 day __d = __bad_day; // %d
4287 weekday __wday = __bad_wday; // %a %A %u %w
4288 hours __h = __bad_h, __h12 = __bad_h; // %H, %I
4289 minutes __min = __bad_min; // %M
4290 _Duration __s = __bad_sec; // %S
4291 int __ampm = 0; // %p
4292 int __iso_wk = -1, __sunday_wk = -1, __monday_wk = -1; // %V, %U, %W
4293 int __century = -1; // %C
4294 int __dayofyear = -1; // %j (for non-duration)
4295
4296 minutes __tz_offset = __bad_min;
4297 basic_string<_CharT, _Traits> __tz_abbr;
4298
4299 if ((_M_need & _ChronoParts::_TimeOfDay) != 0
4300 && (_M_need & _ChronoParts::_Year) != 0)
4301 {
4302 // For time_points assume "00:00:00" is implicitly present,
4303 // so we don't fail to parse if it's not (PR libstdc++/114240).
4304 // We will still fail to parse if there's no year+month+day.
4305 __h = hours(0);
4306 __parts = _ChronoParts::_TimeOfDay;
4307 }
4308
4309 // bool __is_neg = false; // TODO: how is this handled for parsing?
4310
4311 _CharT __mod{}; // One of 'E' or 'O' or nul.
4312 unsigned __num = 0; // Non-zero for N modifier.
4313 bool __is_flag = false; // True if we're processing a % flag.
4314
4315 constexpr bool __is_floating
4316 = treat_as_floating_point_v<typename _Duration::rep>;
4317
4318 // If an out-of-range value is extracted (e.g. 61min for %M),
4319 // do not set failbit immediately because we might not need it
4320 // (e.g. parsing chrono::year doesn't care about invalid %M values).
4321 // Instead set the variable back to its initial 'bad' state,
4322 // and also set related variables corresponding to the same field
4323 // (e.g. a bad %M value for __min should also reset __h and __s).
4324 // If a valid value is needed later the bad value will cause failure.
4325
4326 // For some fields we don't know the correct range when parsing and
4327 // we have to be liberal in what we accept, e.g. we allow 366 for
4328 // day-of-year because that's valid in leap years, and we allow 31
4329 // for day-of-month. If those values are needed to determine the
4330 // result then we can do a correct range check at the end when we
4331 // know the how many days the relevant year or month actually has.
4332
4333 while (*__fmt)
4334 {
4335 _CharT __c = *__fmt++;
4336 if (!__is_flag)
4337 {
4338 if (__c == '%')
4339 __is_flag = true; // This is the start of a flag.
4340 else if (std::isspace(__c, __loc))
4341 std::ws(__is); // Match zero or more whitespace characters.
4342 else if (!__read_chr(__c)) [[unlikely]]
4343 break; // Failed to match the expected character.
4344
4345 continue; // Process next character in the format string.
4346 }
4347
4348 // Now processing a flag.
4349 switch (__c)
4350 {
4351 case 'a': // Locale's weekday name
4352 case 'A': // (full or abbreviated, matched case-insensitively).
4353 if (__mod || __num) [[unlikely]]
4354 __err = ios_base::failbit;
4355 else
4356 {
4357 struct tm __tm{};
4358 __tmget.get(__is, {}, __is, __err, &__tm,
4359 __fmt - 2, __fmt);
4360 if (!__is_failed(__err))
4361 __wday = weekday(__tm.tm_wday);
4362 }
4363 __parts |= _ChronoParts::_Weekday;
4364 break;
4365
4366 case 'b': // Locale's month name
4367 case 'h': // (full or abbreviated, matched case-insensitively).
4368 case 'B':
4369 if (__mod || __num) [[unlikely]]
4370 __err = ios_base::failbit;
4371 else
4372 {
4373 // strptime behaves differently for %b and %B,
4374 // but chrono::parse says they're equivalent.
4375 // Luckily libstdc++ std::time_get works as needed.
4376 struct tm __tm{};
4377 __tmget.get(__is, {}, __is, __err, &__tm,
4378 __fmt - 2, __fmt);
4379 if (!__is_failed(__err))
4380 __m = month(__tm.tm_mon + 1);
4381 }
4382 __parts |= _ChronoParts::_Month;
4383 break;
4384
4385 case 'c': // Locale's date and time representation.
4386 if (__mod == 'O' || __num) [[unlikely]]
4387 __err |= ios_base::failbit;
4388 else
4389 {
4390 struct tm __tm{};
4391 __tmget.get(__is, {}, __is, __err, &__tm,
4392 __fmt - 2 - (__mod == 'E'), __fmt);
4393 if (!__is_failed(__err))
4394 {
4395 __y = year(__tm.tm_year + 1900);
4396 __m = month(__tm.tm_mon + 1);
4397 __d = day(__tm.tm_mday);
4398 __h = hours(__tm.tm_hour);
4399 __min = minutes(__tm.tm_min);
4400 __s = seconds(__tm.tm_sec);
4401 }
4402 }
4403 __parts |= _ChronoParts::_DateTime;
4404 break;
4405
4406 case 'C': // Century
4407 if (!__mod) [[likely]]
4408 {
4409 auto __v = __read_signed(__num ? __num : 2);
4410 if (!__is_failed(__err))
4411 {
4412 int __cmin = (int)year::min() / 100;
4413 int __cmax = (int)year::max() / 100;
4414 if (__cmin <= __v && __v <= __cmax)
4415 __century = __v * 100;
4416 else
4417 __century = -2; // This prevents guessing century.
4418 }
4419 }
4420 else if (__mod == 'E')
4421 {
4422 struct tm __tm{};
4423 __tmget.get(__is, {}, __is, __err, &__tm,
4424 __fmt - 3, __fmt);
4425 if (!__is_failed(__err))
4426 __century = __tm.tm_year;
4427 }
4428 else [[unlikely]]
4429 __err |= ios_base::failbit;
4430 // N.B. don't set this here: __parts |= _ChronoParts::_Year;
4431 break;
4432
4433 case 'd': // Day of month (1-31)
4434 case 'e':
4435 if (!__mod) [[likely]]
4436 {
4437 auto __v = __read_unsigned(__num ? __num : 2);
4438 if (!__is_failed(__err))
4439 __d = day(__v);
4440 }
4441 else if (__mod == 'O')
4442 {
4443 struct tm __tm{};
4444 __tmget.get(__is, {}, __is, __err, &__tm,
4445 __fmt - 3, __fmt);
4446 if (!__is_failed(__err))
4447 __d = day(__tm.tm_mday);
4448 }
4449 else [[unlikely]]
4450 __err |= ios_base::failbit;
4451 __parts |= _ChronoParts::_Day;
4452 break;
4453
4454 case 'D': // %m/%d/%y
4455 if (__mod || __num) [[unlikely]]
4456 __err |= ios_base::failbit;
4457 else
4458 {
4459 auto __month = __read_unsigned(2); // %m
4460 __read_chr('/');
4461 auto __day = __read_unsigned(2); // %d
4462 __read_chr('/');
4463 auto __year = __read_unsigned(2); // %y
4464 if (__is_failed(__err))
4465 break;
4466 __y = year(__year + 1900 + 100 * int(__year < 69));
4467 __m = month(__month);
4468 __d = day(__day);
4469 if (!year_month_day(__y, __m, __d).ok())
4470 {
4471 __y = __yy = __iso_y = __iso_yy = __bad_y;
4472 __m = __bad_mon;
4473 __d = __bad_day;
4474 break;
4475 }
4476 }
4477 __parts |= _ChronoParts::_Date;
4478 break;
4479
4480 case 'F': // %Y-%m-%d - any N modifier only applies to %Y.
4481 if (__mod) [[unlikely]]
4482 __err |= ios_base::failbit;
4483 else
4484 {
4485 auto __year = __read_signed(__num ? __num : 4); // %Y
4486 __read_chr('-');
4487 auto __month = __read_unsigned(2); // %m
4488 __read_chr('-');
4489 auto __day = __read_unsigned(2); // %d
4490 if (__is_failed(__err))
4491 break;
4492 __y = year(__year);
4493 __m = month(__month);
4494 __d = day(__day);
4495 if (!year_month_day(__y, __m, __d).ok())
4496 {
4497 __y = __yy = __iso_y = __iso_yy = __bad_y;
4498 __m = __bad_mon;
4499 __d = __bad_day;
4500 break;
4501 }
4502 }
4503 __parts |= _ChronoParts::_Date;
4504 break;
4505
4506 case 'g': // Last two digits of ISO week-based year.
4507 if (__mod) [[unlikely]]
4508 __err |= ios_base::failbit;
4509 else
4510 {
4511 auto __val = __read_unsigned(__num ? __num : 2);
4512 if (__val >= 0 && __val <= 99)
4513 {
4514 __iso_yy = year(__val);
4515 if (__century == -1) // No %C has been parsed yet.
4516 __century = 2000;
4517 }
4518 else
4519 __iso_yy = __iso_y = __y = __yy = __bad_y;
4520 }
4521 __parts |= _ChronoParts::_Year;
4522 break;
4523
4524 case 'G': // ISO week-based year.
4525 if (__mod) [[unlikely]]
4526 __err |= ios_base::failbit;
4527 else
4528 __iso_y = year(__read_unsigned(__num ? __num : 4));
4529 __parts |= _ChronoParts::_Year;
4530 break;
4531
4532 case 'H': // 24-hour (00-23)
4533 case 'I': // 12-hour (1-12)
4534 if (__mod == 'E') [[unlikely]]
4535 __err |= ios_base::failbit;
4536 else if (__mod == 'O')
4537 {
4538#if 0
4539 struct tm __tm{};
4540 __tm.tm_ampm = 1;
4541 __tmget.get(__is, {}, __is, __err, &__tm,
4542 __fmt - 3, __fmt);
4543 if (!__is_failed(__err))
4544 {
4545 if (__c == 'I')
4546 {
4547 __h12 = hours(__tm.tm_hour);
4548 __h = __bad_h;
4549 }
4550 else
4551 __h = hours(__tm.tm_hour);
4552 }
4553#else
4554 // XXX %OI seems to be unimplementable.
4555 __err |= ios_base::failbit;
4556#endif
4557 }
4558 else
4559 {
4560 auto __val = __read_unsigned(__num ? __num : 2);
4561 if (__c == 'I' && __val >= 1 && __val <= 12)
4562 {
4563 __h12 = hours(__val);
4564 __h = __bad_h;
4565 }
4566 else if (__c == 'H' && __val >= 0 && __val <= 23)
4567 {
4568 __h = hours(__val);
4569 __h12 = __bad_h;
4570 }
4571 else
4572 {
4573 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4574 __err |= ios_base::failbit;
4575 break;
4576 }
4577 }
4578 __parts |= _ChronoParts::_TimeOfDay;
4579 break;
4580
4581 case 'j': // For duration, count of days, otherwise day of year
4582 if (__mod) [[unlikely]]
4583 __err |= ios_base::failbit;
4584 else if (_M_need == _ChronoParts::_TimeOfDay) // duration
4585 {
4586 auto __val = __read_signed(__num ? __num : 3);
4587 if (!__is_failed(__err))
4588 {
4589 __h = days(__val); // __h will get added to _M_time
4590 __parts |= _ChronoParts::_TimeOfDay;
4591 }
4592 }
4593 else
4594 {
4595 __dayofyear = __read_unsigned(__num ? __num : 3);
4596 // N.B. do not alter __parts here, done after loop.
4597 // No need for range checking here either.
4598 }
4599 break;
4600
4601 case 'm': // Month (1-12)
4602 if (__mod == 'E') [[unlikely]]
4603 __err |= ios_base::failbit;
4604 else if (__mod == 'O')
4605 {
4606 struct tm __tm{};
4607 __tmget.get(__is, {}, __is, __err, &__tm,
4608 __fmt - 2, __fmt);
4609 if (!__is_failed(__err))
4610 __m = month(__tm.tm_mon + 1);
4611 }
4612 else
4613 {
4614 auto __val = __read_unsigned(__num ? __num : 2);
4615 if (__val >= 1 && __val <= 12)
4616 __m = month(__val);
4617 else
4618 __m = __bad_mon;
4619 }
4620 __parts |= _ChronoParts::_Month;
4621 break;
4622
4623 case 'M': // Minutes
4624 if (__mod == 'E') [[unlikely]]
4625 __err |= ios_base::failbit;
4626 else if (__mod == 'O')
4627 {
4628 struct tm __tm{};
4629 __tmget.get(__is, {}, __is, __err, &__tm,
4630 __fmt - 2, __fmt);
4631 if (!__is_failed(__err))
4632 __min = minutes(__tm.tm_min);
4633 }
4634 else
4635 {
4636 auto __val = __read_unsigned(__num ? __num : 2);
4637 if (0 <= __val && __val < 60)
4638 __min = minutes(__val);
4639 else
4640 {
4641 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4642 __err |= ios_base::failbit;
4643 break;
4644 }
4645 }
4646 __parts |= _ChronoParts::_TimeOfDay;
4647 break;
4648
4649 case 'p': // Locale's AM/PM designation for 12-hour clock.
4650 if (__mod || __num)
4651 __err |= ios_base::failbit;
4652 else
4653 {
4654 // Can't use std::time_get here as it can't parse %p
4655 // in isolation without %I. This might be faster anyway.
4656 const _CharT* __ampms[2];
4657 __tmpunct._M_am_pm(__ampms);
4658 int __n = 0, __which = 3;
4659 while (__which != 0)
4660 {
4661 auto __i = __is.peek();
4662 if (_Traits::eq_int_type(__i, _Traits::eof()))
4663 {
4665 break;
4666 }
4667 __i = std::toupper(_Traits::to_char_type(__i), __loc);
4668 if (__which & 1)
4669 {
4670 if (__i != std::toupper(__ampms[0][__n], __loc))
4671 __which ^= 1;
4672 else if (__ampms[0][__n + 1] == _CharT())
4673 {
4674 __which = 1;
4675 (void) __is.get();
4676 break;
4677 }
4678 }
4679 if (__which & 2)
4680 {
4681 if (__i != std::toupper(__ampms[1][__n], __loc))
4682 __which ^= 2;
4683 else if (__ampms[1][__n + 1] == _CharT())
4684 {
4685 __which = 2;
4686 (void) __is.get();
4687 break;
4688 }
4689 }
4690 if (__which)
4691 (void) __is.get();
4692 ++__n;
4693 }
4694 if (__which == 0 || __which == 3)
4695 __err |= ios_base::failbit;
4696 else
4697 __ampm = __which;
4698 }
4699 break;
4700
4701 case 'r': // Locale's 12-hour time.
4702 if (__mod || __num)
4703 __err |= ios_base::failbit;
4704 else
4705 {
4706 struct tm __tm{};
4707 __tmget.get(__is, {}, __is, __err, &__tm,
4708 __fmt - 2, __fmt);
4709 if (!__is_failed(__err))
4710 {
4711 __h = hours(__tm.tm_hour);
4712 __min = minutes(__tm.tm_min);
4713 __s = seconds(__tm.tm_sec);
4714 }
4715 }
4716 __parts |= _ChronoParts::_TimeOfDay;
4717 break;
4718
4719 case 'R': // %H:%M
4720 case 'T': // %H:%M:%S
4721 if (__mod || __num) [[unlikely]]
4722 {
4723 __err |= ios_base::failbit;
4724 break;
4725 }
4726 else
4727 {
4728 auto __val = __read_unsigned(2);
4729 if (__val == -1 || __val > 23) [[unlikely]]
4730 {
4731 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4732 __err |= ios_base::failbit;
4733 break;
4734 }
4735 if (!__read_chr(':')) [[unlikely]]
4736 break;
4737 __h = hours(__val);
4738
4739 __val = __read_unsigned(2);
4740 if (__val == -1 || __val > 60) [[unlikely]]
4741 {
4742 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4743 __err |= ios_base::failbit;
4744 break;
4745 }
4746 __min = minutes(__val);
4747
4748 if (__c == 'R')
4749 {
4750 __parts |= _ChronoParts::_TimeOfDay;
4751 break;
4752 }
4753 else if (!__read_chr(':')) [[unlikely]]
4754 break;
4755 }
4756 [[fallthrough]];
4757
4758 case 'S': // Seconds
4759 if (__mod == 'E') [[unlikely]]
4760 __err |= ios_base::failbit;
4761 else if (__mod == 'O')
4762 {
4763 struct tm __tm{};
4764 __tmget.get(__is, {}, __is, __err, &__tm,
4765 __fmt - 3, __fmt);
4766 if (!__is_failed(__err))
4767 __s = seconds(__tm.tm_sec);
4768 }
4769 else if constexpr (_Duration::period::den == 1
4770 && !__is_floating)
4771 {
4772 auto __val = __read_unsigned(__num ? __num : 2);
4773 if (0 <= __val && __val <= 59) [[likely]]
4774 __s = seconds(__val);
4775 else
4776 {
4777 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4778 __err |= ios_base::failbit;
4779 break;
4780 }
4781 }
4782 else // Read fractional seconds
4783 {
4784 basic_stringstream<_CharT> __buf;
4785 auto __digit = _S_try_read_digit(__is, __err);
4786 if (__digit != -1)
4787 {
4788 __buf.put(_CharT('0') + __digit);
4789 __digit = _S_try_read_digit(__is, __err);
4790 if (__digit != -1)
4791 __buf.put(_CharT('0') + __digit);
4792 }
4793
4794 auto __i = __is.peek();
4795 if (_Traits::eq_int_type(__i, _Traits::eof()))
4796 __err |= ios_base::eofbit;
4797 else
4798 {
4799 _CharT __dp = '.';
4800 if (__loc != locale::classic())
4801 {
4802 auto& __np = use_facet<numpunct<_CharT>>(__loc);
4803 __dp = __np.decimal_point();
4804 }
4805 _CharT __c = _Traits::to_char_type(__i);
4806 if (__c == __dp)
4807 {
4808 (void) __is.get();
4809 __buf.put('.');
4810 int __prec
4811 = hh_mm_ss<_Duration>::fractional_width;
4812 do
4813 {
4814 __digit = _S_try_read_digit(__is, __err);
4815 if (__digit != -1)
4816 __buf.put(_CharT('0') + __digit);
4817 else
4818 break;
4819 }
4820 while (--__prec);
4821 }
4822 }
4823
4824 if (!__is_failed(__err)) [[likely]]
4825 {
4826 long double __val{};
4827#if __cpp_lib_to_chars
4828 string __str = std::move(__buf).str();
4829 auto __first = __str.data();
4830 auto __last = __first + __str.size();
4831 using enum chars_format;
4832 auto [ptr, ec] = std::from_chars(__first, __last,
4833 __val, fixed);
4834 if ((bool)ec || ptr != __last) [[unlikely]]
4835 __err |= ios_base::failbit;
4836 else
4837#else
4838 if (__buf >> __val)
4839#endif
4840 {
4841 duration<long double> __fs(__val);
4842 if constexpr (__is_floating)
4843 __s = __fs;
4844 else
4845 __s = chrono::round<_Duration>(__fs);
4846 }
4847 }
4848 }
4849 __parts |= _ChronoParts::_TimeOfDay;
4850 break;
4851
4852 case 'u': // ISO weekday (1-7)
4853 case 'w': // Weekday (0-6)
4854 if (__mod == 'E') [[unlikely]]
4855 __err |= ios_base::failbit;
4856 else if (__mod == 'O')
4857 {
4858 if (__c == 'w')
4859 {
4860 struct tm __tm{};
4861 __tmget.get(__is, {}, __is, __err, &__tm,
4862 __fmt - 3, __fmt);
4863 if (!__is_failed(__err))
4864 __wday = weekday(__tm.tm_wday);
4865 }
4866 else
4867 __err |= ios_base::failbit;
4868 }
4869 else
4870 {
4871 const int __lo = __c == 'u' ? 1 : 0;
4872 const int __hi = __lo + 6;
4873 auto __val = __read_unsigned(__num ? __num : 1);
4874 if (__lo <= __val && __val <= __hi)
4875 __wday = weekday(__val);
4876 else
4877 {
4878 __wday = __bad_wday;
4879 break;
4880 }
4881 }
4882 __parts |= _ChronoParts::_Weekday;
4883 break;
4884
4885 case 'U': // Week number of the year (from first Sunday).
4886 case 'V': // ISO week-based week number.
4887 case 'W': // Week number of the year (from first Monday).
4888 if (__mod == 'E') [[unlikely]]
4889 __err |= ios_base::failbit;
4890 else if (__mod == 'O')
4891 {
4892 if (__c == 'V') [[unlikely]]
4893 __err |= ios_base::failbit;
4894 else
4895 {
4896 // TODO nl_langinfo_l(ALT_DIGITS) ?
4897 // Not implementable using std::time_get.
4898 }
4899 }
4900 else
4901 {
4902 const int __lo = __c == 'V' ? 1 : 0;
4903 const int __hi = 53;
4904 auto __val = __read_unsigned(__num ? __num : 2);
4905 if (__lo <= __val && __val <= __hi)
4906 {
4907 switch (__c)
4908 {
4909 case 'U':
4910 __sunday_wk = __val;
4911 break;
4912 case 'V':
4913 __iso_wk = __val;
4914 break;
4915 case 'W':
4916 __monday_wk = __val;
4917 break;
4918 }
4919 }
4920 else
4921 __iso_wk = __sunday_wk = __monday_wk = -1;
4922 }
4923 // N.B. do not alter __parts here, done after loop.
4924 break;
4925
4926 case 'x': // Locale's date representation.
4927 if (__mod == 'O' || __num) [[unlikely]]
4928 __err |= ios_base::failbit;
4929 else
4930 {
4931 struct tm __tm{};
4932 __tmget.get(__is, {}, __is, __err, &__tm,
4933 __fmt - 2 - (__mod == 'E'), __fmt);
4934 if (!__is_failed(__err))
4935 {
4936 __y = year(__tm.tm_year + 1900);
4937 __m = month(__tm.tm_mon + 1);
4938 __d = day(__tm.tm_mday);
4939 }
4940 }
4941 __parts |= _ChronoParts::_Date;
4942 break;
4943
4944 case 'X': // Locale's time representation.
4945 if (__mod == 'O' || __num) [[unlikely]]
4946 __err |= ios_base::failbit;
4947 else
4948 {
4949 struct tm __tm{};
4950 __tmget.get(__is, {}, __is, __err, &__tm,
4951 __fmt - 2 - (__mod == 'E'), __fmt);
4952 if (!__is_failed(__err))
4953 {
4954 __h = hours(__tm.tm_hour);
4955 __min = minutes(__tm.tm_min);
4956 __s = seconds(__tm.tm_sec);
4957 }
4958 }
4959 __parts |= _ChronoParts::_TimeOfDay;
4960 break;
4961
4962 case 'y': // Last two digits of year.
4963 if (__mod) [[unlikely]]
4964 {
4965 struct tm __tm{};
4966 __tmget.get(__is, {}, __is, __err, &__tm,
4967 __fmt - 3, __fmt);
4968 if (!__is_failed(__err))
4969 {
4970 int __cent = __tm.tm_year < 2000 ? 1900 : 2000;
4971 __yy = year(__tm.tm_year - __cent);
4972 if (__century == -1) // No %C has been parsed yet.
4973 __century = __cent;
4974 }
4975 }
4976 else
4977 {
4978 auto __val = __read_unsigned(__num ? __num : 2);
4979 if (__val >= 0 && __val <= 99)
4980 {
4981 __yy = year(__val);
4982 if (__century == -1) // No %C has been parsed yet.
4983 __century = __val < 69 ? 2000 : 1900;
4984 }
4985 else
4986 __y = __yy = __iso_yy = __iso_y = __bad_y;
4987 }
4988 __parts |= _ChronoParts::_Year;
4989 break;
4990
4991 case 'Y': // Year
4992 if (__mod == 'O') [[unlikely]]
4993 __err |= ios_base::failbit;
4994 else if (__mod == 'E')
4995 {
4996 struct tm __tm{};
4997 __tmget.get(__is, {}, __is, __err, &__tm,
4998 __fmt - 3, __fmt);
4999 if (!__is_failed(__err))
5000 __y = year(__tm.tm_year);
5001 }
5002 else
5003 {
5004 auto __val = __read_unsigned(__num ? __num : 4);
5005 if (!__is_failed(__err))
5006 __y = year(__val);
5007 }
5008 __parts |= _ChronoParts::_Year;
5009 break;
5010
5011 case 'z':
5012 if (__num) [[unlikely]]
5013 __err |= ios_base::failbit;
5014 else
5015 {
5016 // For %Ez and %Oz read [+|-][h]h[:mm].
5017 // For %z read [+|-]hh[mm].
5018
5019 auto __i = __is.peek();
5020 if (_Traits::eq_int_type(__i, _Traits::eof()))
5021 {
5023 break;
5024 }
5025 _CharT __ic = _Traits::to_char_type(__i);
5026 const bool __neg = __ic == _CharT('-');
5027 if (__ic == _CharT('-') || __ic == _CharT('+'))
5028 (void) __is.get();
5029
5030 int_least32_t __hh;
5031 if (__mod)
5032 {
5033 // Read h[h]
5034 __hh = __read_unsigned(2);
5035 }
5036 else
5037 {
5038 // Read hh
5039 __hh = 10 * _S_try_read_digit(__is, __err);
5040 __hh += _S_try_read_digit(__is, __err);
5041 }
5042
5043 if (__is_failed(__err))
5044 break;
5045
5046 __i = __is.peek();
5047 if (_Traits::eq_int_type(__i, _Traits::eof()))
5048 {
5049 __err |= ios_base::eofbit;
5050 __tz_offset = minutes(__hh * (__neg ? -60 : 60));
5051 break;
5052 }
5053 __ic = _Traits::to_char_type(__i);
5054
5055 bool __read_mm = false;
5056 if (__mod)
5057 {
5058 if (__ic == _GLIBCXX_WIDEN(":")[0])
5059 {
5060 // Read [:mm] part.
5061 (void) __is.get();
5062 __read_mm = true;
5063 }
5064 }
5065 else if (_CharT('0') <= __ic && __ic <= _CharT('9'))
5066 {
5067 // Read [mm] part.
5068 __read_mm = true;
5069 }
5070
5071 int_least32_t __mm = 0;
5072 if (__read_mm)
5073 {
5074 __mm = 10 * _S_try_read_digit(__is, __err);
5075 __mm += _S_try_read_digit(__is, __err);
5076 }
5077
5078 if (!__is_failed(__err))
5079 {
5080 auto __z = __hh * 60 + __mm;
5081 __tz_offset = minutes(__neg ? -__z : __z);
5082 }
5083 }
5084 break;
5085
5086 case 'Z':
5087 if (__mod || __num) [[unlikely]]
5088 __err |= ios_base::failbit;
5089 else
5090 {
5091 basic_string_view<_CharT> __x = _GLIBCXX_WIDEN("_/-+");
5092 __tz_abbr.clear();
5093 while (true)
5094 {
5095 auto __i = __is.peek();
5096 if (!_Traits::eq_int_type(__i, _Traits::eof()))
5097 {
5098 _CharT __a = _Traits::to_char_type(__i);
5099 if (std::isalnum(__a, __loc)
5100 || __x.find(__a) != __x.npos)
5101 {
5102 __tz_abbr.push_back(__a);
5103 (void) __is.get();
5104 continue;
5105 }
5106 }
5107 else
5108 __err |= ios_base::eofbit;
5109 break;
5110 }
5111 if (__tz_abbr.empty())
5112 __err |= ios_base::failbit;
5113 }
5114 break;
5115
5116 case 'n': // Exactly one whitespace character.
5117 if (__mod || __num) [[unlikely]]
5118 __err |= ios_base::failbit;
5119 else
5120 {
5121 _CharT __i = __is.peek();
5122 if (_Traits::eq_int_type(__i, _Traits::eof()))
5124 else if (std::isspace(_Traits::to_char_type(__i), __loc))
5125 (void) __is.get();
5126 else
5127 __err |= ios_base::failbit;
5128 }
5129 break;
5130
5131 case 't': // Zero or one whitespace characters.
5132 if (__mod || __num) [[unlikely]]
5133 __err |= ios_base::failbit;
5134 else
5135 {
5136 _CharT __i = __is.peek();
5137 if (_Traits::eq_int_type(__i, _Traits::eof()))
5138 __err |= ios_base::eofbit;
5139 else if (std::isspace(_Traits::to_char_type(__i), __loc))
5140 (void) __is.get();
5141 }
5142 break;
5143
5144 case '%': // A % character.
5145 if (__mod || __num) [[unlikely]]
5146 __err |= ios_base::failbit;
5147 else
5148 __read_chr('%');
5149 break;
5150
5151 case 'O': // Modifiers
5152 case 'E':
5153 if (__mod || __num) [[unlikely]]
5154 {
5155 __err |= ios_base::failbit;
5156 break;
5157 }
5158 __mod = __c;
5159 continue;
5160
5161 default:
5162 if (_CharT('1') <= __c && __c <= _CharT('9'))
5163 {
5164 if (!__mod) [[likely]]
5165 {
5166 // %Nx - extract positive decimal integer N
5167 auto __end = __fmt + _Traits::length(__fmt);
5168 auto [__v, __ptr]
5169 = __format::__parse_integer(__fmt - 1, __end);
5170 if (__ptr) [[likely]]
5171 {
5172 __num = __v;
5173 __fmt = __ptr;
5174 continue;
5175 }
5176 }
5177 }
5178 __err |= ios_base::failbit;
5179 }
5180
5181 if (__is_failed(__err)) [[unlikely]]
5182 break;
5183
5184 __is_flag = false;
5185 __num = 0;
5186 __mod = _CharT();
5187 }
5188
5189 if (__century >= 0)
5190 {
5191 if (__yy != __bad_y && __y == __bad_y)
5192 __y = years(__century) + __yy; // Use %y instead of %Y
5193 if (__iso_yy != __bad_y && __iso_y == __bad_y)
5194 __iso_y = years(__century) + __iso_yy; // Use %g instead of %G
5195 }
5196
5197 bool __can_use_doy = false;
5198 bool __can_use_iso_wk = false;
5199 bool __can_use_sun_wk = false;
5200 bool __can_use_mon_wk = false;
5201
5202 // A year + day-of-year can be converted to a full date.
5203 if (__y != __bad_y && __dayofyear >= 0)
5204 {
5205 __can_use_doy = true;
5206 __parts |= _ChronoParts::_Date;
5207 }
5208 else if (__y != __bad_y && __wday != __bad_wday && __sunday_wk >= 0)
5209 {
5210 __can_use_sun_wk = true;
5211 __parts |= _ChronoParts::_Date;
5212 }
5213 else if (__y != __bad_y && __wday != __bad_wday && __monday_wk >= 0)
5214 {
5215 __can_use_mon_wk = true;
5216 __parts |= _ChronoParts::_Date;
5217 }
5218 else if (__iso_y != __bad_y && __wday != __bad_wday && __iso_wk > 0)
5219 {
5220 // An ISO week date can be converted to a full date.
5221 __can_use_iso_wk = true;
5222 __parts |= _ChronoParts::_Date;
5223 }
5224
5225 if (__is_failed(__err)) [[unlikely]]
5226 ; // Don't bother doing any more work.
5227 else if (__is_flag) [[unlikely]] // incomplete format flag
5228 __err |= ios_base::failbit;
5229 else if ((_M_need & __parts) == _M_need) [[likely]]
5230 {
5231 // We try to avoid calculating _M_sys_days and _M_ymd unless
5232 // necessary, because converting sys_days to year_month_day
5233 // (or vice versa) requires non-trivial calculations.
5234 // If we have y/m/d values then use them to populate _M_ymd
5235 // and only convert it to _M_sys_days if the caller needs that.
5236 // But if we don't have y/m/d and need to calculate the date
5237 // from the day-of-year or a week+weekday then we set _M_sys_days
5238 // and only convert it to _M_ymd if the caller needs that.
5239
5240 // We do more error checking here, but only for the fields that
5241 // we actually need to use. For example, we will not diagnose
5242 // an invalid dayofyear==366 for non-leap years unless actually
5243 // using __dayofyear. This should mean we never produce invalid
5244 // results, but it means not all invalid inputs are diagnosed,
5245 // e.g. "2023-01-01 366" >> "%F %j" ignores the invalid 366.
5246 // We also do not diagnose inconsistent values for the same
5247 // field, e.g. "2021 2022 2023" >> "%C%y %Y %Y" just uses 2023.
5248
5249 // Whether the caller wants _M_wd.
5250 // The _Weekday bit is only set for chrono::weekday.
5251 const bool __need_wday = (_M_need & _ChronoParts::_Weekday) != 0;
5252
5253 // Whether the caller wants _M_sys_days and _M_time.
5254 // Only true for durations and time_points.
5255 const bool __need_time = (_M_need & _ChronoParts::_TimeOfDay) != 0;
5256
5257 if (__need_wday && __wday != __bad_wday)
5258 _M_wd = __wday; // Caller only wants a weekday and we have one.
5259 else if ((_M_need & _ChronoParts::_Date) != 0) // subsumes __need_wday
5260 {
5261 // Whether the caller wants _M_ymd.
5262 // True for chrono::year etc., false for time_points.
5263 const bool __need_ymd = !__need_wday && !__need_time;
5264
5265 if (((_M_need & _ChronoParts::_Year) != 0 && __y == __bad_y)
5266 || ((_M_need & _ChronoParts::_Month) != 0 && __m == __bad_mon)
5267 || ((_M_need & _ChronoParts::_Day) != 0 && __d == __bad_day))
5268 {
5269 // Missing at least one of y/m/d so calculate sys_days
5270 // from the other data we have available.
5271
5272 if (__can_use_doy)
5273 {
5274 if ((0 < __dayofyear && __dayofyear <= 365)
5275 || (__dayofyear == 366 && __y.is_leap()))
5276 [[likely]]
5277 {
5278 _M_sys_days = sys_days(__y/January/1)
5279 + days(__dayofyear - 1);
5280 if (__need_ymd)
5281 _M_ymd = year_month_day(_M_sys_days);
5282 }
5283 else
5284 __err |= ios_base::failbit;
5285 }
5286 else if (__can_use_iso_wk)
5287 {
5288 // Calculate y/m/d from ISO week date.
5289
5290 if (__iso_wk == 53)
5291 {
5292 // A year has 53 weeks iff Jan 1st is a Thursday
5293 // or Jan 1 is a Wednesday and it's a leap year.
5294 const sys_days __jan4(__iso_y/January/4);
5295 weekday __wd1(__jan4 - days(3));
5296 if (__wd1 != Thursday)
5297 if (__wd1 != Wednesday || !__iso_y.is_leap())
5298 __err |= ios_base::failbit;
5299 }
5300
5301 if (!__is_failed(__err)) [[likely]]
5302 {
5303 // First Thursday is always in week one:
5304 sys_days __w(Thursday[1]/January/__iso_y);
5305 // First day of week-based year:
5306 __w -= Thursday - Monday;
5307 __w += days(weeks(__iso_wk - 1));
5308 __w += __wday - Monday;
5309 _M_sys_days = __w;
5310
5311 if (__need_ymd)
5312 _M_ymd = year_month_day(_M_sys_days);
5313 }
5314 }
5315 else if (__can_use_sun_wk)
5316 {
5317 // Calculate y/m/d from week number + weekday.
5318 sys_days __wk1(__y/January/Sunday[1]);
5319 _M_sys_days = __wk1 + weeks(__sunday_wk - 1)
5320 + days(__wday.c_encoding());
5321 _M_ymd = year_month_day(_M_sys_days);
5322 if (_M_ymd.year() != __y) [[unlikely]]
5323 __err |= ios_base::failbit;
5324 }
5325 else if (__can_use_mon_wk)
5326 {
5327 // Calculate y/m/d from week number + weekday.
5328 sys_days __wk1(__y/January/Monday[1]);
5329 _M_sys_days = __wk1 + weeks(__monday_wk - 1)
5330 + days(__wday.c_encoding() - 1);
5331 _M_ymd = year_month_day(_M_sys_days);
5332 if (_M_ymd.year() != __y) [[unlikely]]
5333 __err |= ios_base::failbit;
5334 }
5335 else // Should not be able to get here.
5336 __err |= ios_base::failbit;
5337 }
5338 else
5339 {
5340 // We know that all fields the caller needs are present,
5341 // but check that their values are in range.
5342 // Make unwanted fields valid so that _M_ymd.ok() is true.
5343
5344 if ((_M_need & _ChronoParts::_Year) != 0)
5345 {
5346 if (!__y.ok()) [[unlikely]]
5347 __err |= ios_base::failbit;
5348 }
5349 else if (__y == __bad_y)
5350 __y = 1972y; // Leap year so that Feb 29 is valid.
5351
5352 if ((_M_need & _ChronoParts::_Month) != 0)
5353 {
5354 if (!__m.ok()) [[unlikely]]
5355 __err |= ios_base::failbit;
5356 }
5357 else if (__m == __bad_mon)
5358 __m = January;
5359
5360 if ((_M_need & _ChronoParts::_Day) != 0)
5361 {
5362 if (__d < day(1) || __d > (__y/__m/last).day())
5363 __err |= ios_base::failbit;
5364 }
5365 else if (__d == __bad_day)
5366 __d = 1d;
5367
5368 if (year_month_day __ymd(__y, __m, __d); __ymd.ok())
5369 {
5370 _M_ymd = __ymd;
5371 if (__need_wday || __need_time)
5372 _M_sys_days = sys_days(_M_ymd);
5373 }
5374 else [[unlikely]]
5375 __err |= ios_base::failbit;
5376 }
5377
5378 if (__need_wday)
5379 _M_wd = weekday(_M_sys_days);
5380 }
5381
5382 // Need to set _M_time for both durations and time_points.
5383 if (__need_time)
5384 {
5385 if (__h == __bad_h && __h12 != __bad_h)
5386 {
5387 if (__ampm == 1)
5388 __h = __h12 == hours(12) ? hours(0) : __h12;
5389 else if (__ampm == 2)
5390 __h = __h12 == hours(12) ? __h12 : __h12 + hours(12);
5391 else [[unlikely]]
5392 __err |= ios_base::failbit;
5393 }
5394
5395 auto __t = _M_time.zero();
5396 bool __ok = false;
5397
5398 if (__h != __bad_h)
5399 {
5400 __ok = true;
5401 __t += __h;
5402 }
5403
5404 if (__min != __bad_min)
5405 {
5406 __ok = true;
5407 __t += __min;
5408 }
5409
5410 if (__s != __bad_sec)
5411 {
5412 __ok = true;
5413 __t += __s;
5414 _M_is_leap_second = __s >= seconds(60);
5415 }
5416
5417 if (__ok)
5418 _M_time = __t;
5419 else
5420 __err |= ios_base::failbit;
5421 }
5422
5423 if (!__is_failed(__err)) [[likely]]
5424 {
5425 if (__offset && __tz_offset != __bad_min)
5426 *__offset = __tz_offset;
5427 if (__abbrev && !__tz_abbr.empty())
5428 *__abbrev = std::move(__tz_abbr);
5429 }
5430 }
5431 else
5432 __err |= ios_base::failbit;
5433 }
5434 if (__err)
5435 __is.setstate(__err);
5436 return __is;
5437 }
5438 /// @endcond
5439#undef _GLIBCXX_WIDEN
5440
5441 /// @} group chrono
5442} // namespace chrono
5443
5444_GLIBCXX_END_NAMESPACE_VERSION
5445} // namespace std
5446
5447#endif // C++20
5448
5449#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:178
duration< int64_t, ratio< 604800 > > weeks
weeks
Definition chrono.h:914
constexpr __enable_if_is_duration< _ToDur > floor(const duration< _Rep, _Period > &__d)
Definition chrono.h:392
constexpr enable_if_t< __and_< __is_duration< _ToDur >, __not_< treat_as_floating_point< typename _ToDur::rep > > >::value, _ToDur > round(const duration< _Rep, _Period > &__d)
Definition chrono.h:437
duration< int64_t, ratio< 86400 > > days
days
Definition chrono.h:911
duration< int64_t, ratio< 31556952 > > years
years
Definition chrono.h:917
duration< int64_t, ratio< 3600 > > hours
hours
Definition chrono.h:907
duration< int64_t, ratio< 60 > > minutes
minutes
Definition chrono.h:904
basic_ostream< _CharT, _Traits > & operator<<(std::basic_ostream< _CharT, _Traits > &__os, const duration< _Rep, _Period > &__d)
Definition chrono_io.h:129
duration< int64_t > seconds
seconds
Definition chrono.h:901
constexpr __enable_if_is_duration< _ToDur > duration_cast(const duration< _Rep, _Period > &__d)
Definition chrono.h:279
constexpr complex< _Tp > operator-(const complex< _Tp > &__x, const complex< _Tp > &__y)
Return new complex value x minus y.
Definition complex:404
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition move.h:52
constexpr const _Tp & min(const _Tp &, const _Tp &)
This does what you think it does.
const _Facet & use_facet(const locale &__loc)
Return a facet.
ISO C++ entities toplevel namespace is std.
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:73
chars_format
floating-point format for primitive numerical conversion
Definition charconv:631
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:1094
ios_base & skipws(ios_base &__base)
Calls base.setf(ios_base::skipws).
Definition ios_base.h:1020
constexpr bitset< _Nb > operator|(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1607
basic_istream< _CharT, _Traits > & ws(basic_istream< _CharT, _Traits > &__is)
Quick and easy way to eat whitespace.
Definition istream.tcc:1078
constexpr bitset< _Nb > operator&(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1597
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:562
ISO C++ 2011 namespace for date and time utilities.
locale imbue(const locale &__loc)
Moves to a new locale.
Template class basic_istream.
Definition istream:63
Template class basic_ostream.
Definition ostream.h:67
Controlling output for std::string.
Definition sstream:872
Controlling input and output for std::string.
Definition sstream:1138
Provides output iterator semantics for streambufs.
Provides compile-time rational arithmetic.
Definition ratio:272
A non-owning reference to a string.
Definition string_view:109
Managing sequences of characters and character-like objects.
constexpr iterator begin() noexcept
chrono::duration represents a distance between two points in time
Definition chrono.h:516
_Ios_Iostate iostate
This is a bitmask type.
Definition ios_base.h:453
streamsize precision() const
Flags access.
Definition ios_base.h:765
fmtflags flags() const
Access to format flags.
Definition ios_base.h:694
static const iostate eofbit
Indicates that an input operation reached the end of an input sequence.
Definition ios_base.h:460
static const iostate goodbit
Indicates all is well.
Definition ios_base.h:468
locale getloc() const
Locale access.
Definition ios_base.h:841
static const iostate failbit
Indicates that an input operation failed to read the expected characters, or that an output operation...
Definition ios_base.h:465
static const locale & classic()
Return reference to the C locale.