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