libstdc++: chrono_io.h Source File

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
44#include <bits/streambuf_iterator.h>
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>
63 constexpr basic_string_view<_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>
128 inline basic_ostream<_CharT, _Traits>&
129 operator<<(std::basic_ostream<_CharT, _Traits>& __os,
130 const duration<_Rep, _Period>& __d)
131 {
132 using _Out = ostreambuf_iterator<_CharT, _Traits>;
133 using period = typename _Period::type;
134 std::basic_ostringstream<_CharT, _Traits> __s;
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 _OutIter
1660 _M_subsecs(const _ChronoData<_CharT>& __t, _OutIter __out,
1661 _FormatContext& __ctx) const
1662 {
1663 unsigned __prec = _M_spec._M_prec_kind != _WP_none
1664 ? _M_spec._M_get_precision(__ctx)
1665 : _M_spec._M_prec;
1666 if (__prec == 0)
1667 return __out;
1668
1669 _CharT __dot = _S_dot;
1670 if (_M_spec._M_localized) [[unlikely]]
1671 {
1672 auto __loc = __ctx.locale();
1673 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1674 __dot = __np.decimal_point();
1675 }
1676 *__out = __dot;
1677 ++__out;
1678
1679 if (_M_spec._M_floating_point_rep)
1680 {
1681 _Str_sink<_CharT> __sink;
1682 if (_M_spec._M_localized && _M_spec._M_custom_rep) [[unlikely]]
1683 std::vformat_to(__sink.out(), __ctx.locale(),
1684 _GLIBCXX_WIDEN("{1:0.{2}Lf}"), __t._M_ereps);
1685 else
1686 std::vformat_to(__sink.out(),
1687 _GLIBCXX_WIDEN("{1:0.{2}f}"), __t._M_ereps);
1688
1689 auto __sv = __sink.view();
1690 // Skip leading zero and dot
1691 __sv.remove_prefix(2);
1692 return __format::__write(std::move(__out), __sv);
1693 }
1694
1695 constexpr unsigned __max_prec = _ChronoData<_CharT>::_S_max_prec;
1696 constexpr typename _ChronoData<_CharT>::_Attoseconds::rep __pow10t[]
1697 {
1698 1u,
1699 10u, 100u, 1000u,
1700 10'000u, 100'000u, 1000'000u,
1701 10'000'000u, 100'000'000u, 1000'000'000u,
1702 10'000'000'000u, 100'000'000'000u, 1000'000'000'000u,
1703 10'000'000'000'000u, 100'000'000'000'000u, 1000'000'000'000'000u,
1704 10'000'000'000'000'000u, 100'000'000'000'000'000u, 1000'000'000'000'000'000u,
1705 };
1706
1707 auto __subs = __t._M_subseconds.count();
1708 if (__prec < __max_prec)
1709 __subs /= __pow10t[__max_prec - __prec];
1710 else if (__prec > __max_prec)
1711 __prec = __max_prec;
1712
1713 using _FmtStr = _Dynamic_format_string<_CharT>;
1714 return std::format_to(__out, _FmtStr(_GLIBCXX_WIDEN("{0:0{1}}")),
1715 __subs, __prec);
1716 }
1717
1718 // %t handled in _M_format
1719
1720 template<typename _OutIter, typename _FormatContext>
1721 _OutIter
1722 _M_T(const _ChronoData<_CharT>& __t, _OutIter __out,
1723 _FormatContext& __ctx) const
1724 {
1725 // %T Equivalent to %H:%M:%S, with subseconds
1726 __out = _M_R_X(__t, std::move(__out), true);
1727 return _M_subsecs(__t, std::move(__out), __ctx);
1728 }
1729
1730 template<typename _OutIter>
1731 _OutIter
1732 _M_u_w(chrono::weekday __wd, _OutIter __out, _CharT __conv) const
1733 {
1734 // %u ISO weekday as a decimal number (1-7), where Monday is 1.
1735 // %Ou Locale's alternative numeric rep.
1736 // %w Weekday as a decimal number (0-6), where Sunday is 0.
1737 // %Ow Locale's alternative numeric rep.
1738 unsigned __wdi = __conv == 'u' ? __wd.iso_encoding()
1739 : __wd.c_encoding();
1740 _CharT __buf[3];
1741 return __format::__write(std::move(__out), _S_str_d1(__buf, __wdi));
1742 }
1743
1744 template<typename _OutIter>
1745 _OutIter
1746 _M_U_W(const _ChronoData<_CharT>& __t, _OutIter __out,
1747 _CharT __conv) const
1748 {
1749 // %U Week number of the year as a decimal number, from first Sunday.
1750 // %OU Locale's alternative numeric rep.
1751 // %W Week number of the year as a decimal number, from first Monday.
1752 // %OW Locale's alternative numeric rep.
1753
1754 using namespace chrono;
1755 const weekday __weekstart = __conv == 'U' ? Sunday : Monday;
1756 const days __offset = __t._M_weekday - __weekstart;
1757 auto __weeks = chrono::floor<weeks>(__t._M_day_of_year - __offset - days(1));
1758 return __format::__write(std::move(__out), _S_two_digits(__weeks.count() + 1));
1759 }
1760
1761 template<typename _OutIter>
1762 _OutIter
1763 _M_z(chrono::seconds __ts, _OutIter __out, bool __mod = false) const
1764 {
1765 if (__ts == 0s)
1766 {
1767 __string_view __zero
1768 = __mod ? _GLIBCXX_WIDEN("+00:00") : _GLIBCXX_WIDEN("+0000");
1769 return __format::__write(std::move(__out), __zero);
1770 }
1771
1772 chrono::hh_mm_ss<chrono::seconds> __hms(__ts);
1773 unsigned __mo = 3 + __mod;
1774
1775 _CharT __buf[6];
1776 __buf[0] = _S_plus_minus[__hms.is_negative()];
1777 __buf[3] = _S_colon;
1778 _S_fill_two_digits(__buf + 1, __hms.hours().count());
1779 _S_fill_two_digits(__buf + __mo, __hms.minutes().count());
1780
1781 __string_view __sv(__buf, __mo + 2);
1782 return __format::__write(std::move(__out), __sv);
1783 }
1784
1785 template<typename _OutIter>
1786 _OutIter
1787 _M_Z(__string_view __abbrev, _OutIter __out) const
1788 { return __format::__write(std::move(__out), __abbrev); }
1789
1790 // %% handled in _M_format
1791
1792 // A string view of single digit character, "0".."9".
1793 static basic_string_view<_CharT>
1794 _S_digit(int __n) noexcept
1795 {
1796 // Extra 9s avoid past-the-end read on bad input.
1797 return { _GLIBCXX_WIDEN("0123456789999999") + (__n & 0xf), 1 };
1798 }
1799
1800 // A string view of two digit characters, "00".."99".
1801 static basic_string_view<_CharT>
1802 _S_two_digits(int __n) noexcept
1803 {
1804 return {
1805 _GLIBCXX_WIDEN("0001020304050607080910111213141516171819"
1806 "2021222324252627282930313233343536373839"
1807 "4041424344454647484950515253545556575859"
1808 "6061626364656667686970717273747576777879"
1809 "8081828384858687888990919293949596979899"
1810 "9999999999999999999999999999999999999999"
1811 "9999999999999999") + 2 * (__n & 0x7f),
1812 2
1813 };
1814 }
1815
1816 // Fills __buf[0] and __buf[1] with 2 digit value of __n.
1817 [[__gnu__::__always_inline__]]
1818 static void
1819 _S_fill_two_digits(_CharT* __buf, unsigned __n)
1820 {
1821 auto __sv = _S_two_digits(__n);
1822 __buf[0] = __sv[0];
1823 __buf[1] = __sv[1];
1824 }
1825
1826 // Fills __buf[0] and __buf[1] with "AM", "PM" depending on __h.
1827 [[__gnu__::__always_inline__]]
1828 static void
1829 _S_fill_ampm(_CharT* __buf, chrono::hours __h)
1830 {
1831 auto __hi = __h.count();
1832 if (__hi >= 24) [[unlikely]]
1833 __hi %= 24;
1834
1835 constexpr const _CharT* __apm = _GLIBCXX_WIDEN("APM");
1836 __buf[0] = __apm[__hi >= 12];
1837 __buf[1] = __apm[2];
1838 }
1839
1840 // Returns decimal representation of __n.
1841 // Returned string_view may point to __buf.
1842 [[__gnu__::__always_inline__]]
1843 static basic_string_view<_CharT>
1844 _S_str_d1(span<_CharT, 3> __buf, unsigned __n)
1845 {
1846 if (__n < 10) [[likely]]
1847 return _S_digit(__n);
1848 return _S_str_d2(__buf, __n);
1849 }
1850
1851 // Returns decimal representation of __n, padded to 2 digits.
1852 // Returned string_view may point to __buf.
1853 [[__gnu__::__always_inline__]]
1854 static basic_string_view<_CharT>
1855 _S_str_d2(span<_CharT, 3> __buf, unsigned __n)
1856 {
1857 if (__n < 100) [[likely]]
1858 return _S_two_digits(__n);
1859 return _S_str_d3(__buf, __n);
1860 }
1861
1862 // Returns decimal representation of __n, padded to 3 digits.
1863 // Returned string_view points to __buf.
1864 [[__gnu__::__always_inline__]]
1865 static basic_string_view<_CharT>
1866 _S_str_d3(span<_CharT, 3> __buf, unsigned __n)
1867 {
1868 _S_fill_two_digits(__buf.data(), __n / 10);
1869 __buf[2] = _S_chars[__n % 10];
1870 return __string_view(__buf.data(), 3);
1871 }
1872 };
1873
1874 template<typename _CharT>
1875 struct __formatter_duration : private __formatter_chrono<_CharT>
1876 {
1877 template<typename _Rep, typename _Period>
1878 constexpr static auto
1879 _S_subseconds(const chrono::duration<_Rep, _Period>& __d)
1880 {
1881 if constexpr (chrono::treat_as_floating_point_v<_Rep>)
1882 return chrono::duration<_Rep>(__d);
1883 else if constexpr (_Period::den == 1)
1884 return chrono::seconds(0);
1885 else
1886 {
1887 using _Attoseconds = _ChronoData<_CharT>::_Attoseconds;
1888 using _CRep = common_type_t<_Rep, typename _Attoseconds::rep>;
1889 chrono::duration<_CRep, _Period> __subs(__d.count());
1890 return chrono::duration_cast<_Attoseconds>(__subs);
1891 }
1892 }
1893
1894 public:
1895 template<typename _Duration>
1896 static consteval
1897 _ChronoSpec<_CharT>
1898 _S_spec_for(_ChronoParts __parts)
1899 {
1900 using _Rep = typename _Duration::rep;
1901 using enum _ChronoParts;
1902
1903 _ChronoSpec<_CharT> __res{};
1904 __res._M_floating_point_rep = chrono::treat_as_floating_point_v<_Rep>;
1905 __res._M_custom_rep = !is_arithmetic_v<_Rep>;
1906 __res._M_prec = chrono::hh_mm_ss<_Duration>::fractional_width;
1907 if ((__parts & _TimeOfDay) != 0)
1908 __res._M_localized = __res._M_prec > 0 || __res._M_floating_point_rep;
1909
1910 if ((__parts & _TimeOfDay) != 0)
1911 __res._M_needed |= _TimeOfDay;
1912 if ((__parts & _Date) != 0)
1913 __res._M_needed |= _YearMonthDay;
1914 if ((__parts & _ZoneAbbrev) != 0)
1915 __res._M_needed |= _ZoneAbbrev;
1916
1917 switch (__parts)
1918 {
1919 case _ZonedDateTime:
1920 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ftz();
1921 break;
1922 case _DateTime:
1923 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ft();
1924 break;
1925 case _Date:
1926 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_f();
1927 break;
1928 case _Time:
1929 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_t();
1930 break;
1931 case _None:
1932 break;
1933 default:
1934 __builtin_unreachable();
1935 }
1936 return __res;
1937 };
1938
1939 template<typename _Duration>
1940 static consteval
1941 _ChronoSpec<_CharT>
1942 _S_spec_for_tp()
1943 {
1944 using enum _ChronoParts;
1945 // streaming of local_time is defined in terms of sys_time
1946 constexpr bool __stream_insertable =
1947 requires (basic_ostream<_CharT>& __os, chrono::sys_time<_Duration> __t)
1948 { __os << __t; };
1949 if constexpr (!__stream_insertable)
1950 return _S_spec_for<_Duration>(_None);
1951 else if constexpr (is_convertible_v<_Duration, chrono::days>)
1952 return _S_spec_for<_Duration>(_Date);
1953 else
1954 return _S_spec_for<_Duration>(_DateTime);
1955 }
1956
1957 using __formatter_chrono<_CharT>::__formatter_chrono;
1958 using __formatter_chrono<_CharT>::_M_spec;
1959
1960 template<typename _Duration>
1961 constexpr typename basic_format_parse_context<_CharT>::iterator
1962 _M_parse(basic_format_parse_context<_CharT>& __pc, _ChronoParts __parts,
1963 const _ChronoSpec<_CharT>& __def)
1964 {
1965 using _Rep = typename _Duration::rep;
1966 using enum _ChronoParts;
1967
1968 auto __res
1969 = __formatter_chrono<_CharT>::_M_parse(__pc, __parts, __def);
1970 // n.b. durations do not contain date parts, and for time point all
1971 // date parts are computed, and they are always ok.
1972 _M_spec._M_needs_ok_check = false;
1973
1974 // check for custom floating point durations, if digits of output
1975 // will contain subseconds, then formatters must support specifying
1976 // precision.
1977 if constexpr (!is_floating_point_v<_Rep>)
1978 if constexpr (chrono::treat_as_floating_point_v<_Rep>)
1979 if (_M_spec._M_needs(_Subseconds|_EpochUnits)
1980 || _M_spec._M_prec_kind != _WP_none
1981 || _M_spec._M_prec_value > 0)
1982 {
1983 constexpr const _CharT* __fs = _GLIBCXX_WIDEN("#02.5Lf");
1984 basic_format_parse_context<_CharT> __npc(__fs);
1985 formatter<_Rep, _CharT> __fmtter;
1986 __fmtter.parse(__npc);
1987 }
1988 return __res;
1989 }
1990
1991 // Return the formatting locale.
1992 template<typename _FormatContext>
1993 std::locale
1994 _M_locale(_FormatContext& __fc) const
1995 {
1996 if (!_M_spec._M_localized)
1997 return std::locale::classic();
1998 else
1999 return __fc.locale();
2000 }
2001
2002 // Format duration for empty chrono-specs, e.g. "{}" (C++20 [time.format] p6).
2003 template<typename _Rep, typename _Period, typename _FormatContext>
2004 typename _FormatContext::iterator
2005 _M_format_to_ostream(const chrono::duration<_Rep, _Period>& __d,
2006 bool __is_neg,
2007 _FormatContext& __fc) const
2008 {
2009 basic_ostringstream<_CharT> __os;
2010 __os.imbue(this->_M_locale(__fc));
2011
2012 if (__is_neg) [[unlikely]]
2013 __os << this->_S_plus_minus[1];
2014 __os << __d;
2015
2016 auto __str = std::move(__os).str();
2017 return __format::__write_padded_as_spec(__str, __str.size(),
2018 __fc, _M_spec);
2019 }
2020
2021 template<typename _Rep1, typename _Period1,
2022 typename _Rep2, typename _Period2,
2023 typename _FormatContext>
2024 typename _FormatContext::iterator
2025 _M_format_units(_ChronoData<_CharT>& __cd,
2026 const chrono::duration<_Rep1, _Period1>& __ed,
2027 const chrono::duration<_Rep2, _Period2>& __ss,
2028 _FormatContext& __fc) const
2029 {
2030 __format::_Str_sink<_CharT> __suffix_store;
2031 constexpr auto _S_unit_suffix
2032 = chrono::__detail::__units_suffix<_Period1, _CharT>();
2033 if constexpr (!_S_unit_suffix.empty())
2034 __cd._M_unit_suffix = _S_unit_suffix;
2035 else if (_M_spec._M_needs(_ChronoParts::_UnitSuffix))
2036 {
2037 chrono::__detail::
2038 __fmt_units_suffix<_Period1, _CharT>(__suffix_store.out());
2039 __cd._M_unit_suffix = __suffix_store.view();
2040 }
2041
2042 const auto __prec = _M_spec._M_prec_kind != _WP_none
2043 ? _M_spec._M_get_precision(__fc)
2044 : _M_spec._M_prec;
2045
2046 using _ErasedContext = typename _ChronoData<_CharT>::_FormatContext;
2047 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2048 // 4118. How should duration formatters format custom rep?
2049 auto __ereps = +__ed.count();
2050 if (!_M_spec._M_needs(_ChronoParts::_Subseconds))
2051 {
2052 auto __ssreps = 0u;
2053 auto __args_store
2054 = std::make_format_args<_ErasedContext>(__ereps, __ssreps, __prec);
2055 __cd._M_ereps = __args_store;
2056 return this->_M_format(__cd, __fc);
2057 }
2058
2059 using _Attoseconds = _ChronoData<_CharT>::_Attoseconds;
2060 auto __nss = _S_subseconds(__ss);
2061 __cd._M_subseconds = chrono::duration_cast<_Attoseconds>(__nss);
2062
2063 auto __ssreps = __nss.count();
2064 auto __args_store
2065 = std::make_format_args<_ErasedContext>(__ereps, __ssreps, __prec);
2066 __cd._M_ereps = __args_store;
2067
2068 return this->_M_format(__cd, __fc);
2069 }
2070
2071 // pre: __cd._M_lseconds and __cd._M_eseconds are set.
2072 template<typename _Rep1, typename _Period1, typename _FormatContext>
2073 typename _FormatContext::iterator
2074 _M_format_time_point(_ChronoData<_CharT>& __cd,
2075 const chrono::duration<_Rep1, _Period1>& __ed,
2076 _FormatContext& __fc) const
2077 {
2078 auto __parts = _M_spec._M_needed - _ChronoParts::_TotalSeconds;
2079 if ((__parts & _ChronoParts::_DateTime) != 0)
2080 __cd._M_fill_date_time(__cd._M_lseconds, __parts);
2081 return _M_format_units(__cd, __ed, __ed - __cd._M_eseconds, __fc);
2082 }
2083 };
2084
2085#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
2086 template<typename _CharT>
2087 struct __formatter_chrono_info
2088 {
2089 constexpr typename basic_format_parse_context<_CharT>::iterator
2090 parse(basic_format_parse_context<_CharT>& __pc)
2091 { return _M_f._M_parse(__pc, _ChronoParts(), {}); }
2092
2093 template<typename _Info, typename _Out>
2094 typename basic_format_context<_Out, _CharT>::iterator
2095 format(const _Info& __i,
2096 basic_format_context<_Out, _CharT>& __fc) const
2097 {
2098 // n.b. only acceptable chrono-spec for info is one containing
2099 // only whitespaces and %%, that do not depend on formatted object.
2100 if (!_M_f._M_spec._M_chrono_specs.empty()) [[unlikely]]
2101 return _M_f._M_format(_ChronoData<_CharT>{}, __fc);
2102
2103 const size_t __padwidth = _M_f._M_spec._M_get_width(__fc);
2104 if (__padwidth == 0)
2105 return _M_format_to(__fc.out(), __i);
2106
2107 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth);
2108 _M_format_to(__sink.out(), __i);
2109 return __sink._M_finish(_M_f._M_spec._M_align, _M_f._M_spec._M_fill);
2110 }
2111
2112 private:
2113 template<typename _Out>
2114 _Out
2115 _M_format_to(_Out __out, const chrono::sys_info& __si) const
2116 {
2117 using _FmtStr = _Dynamic_format_string<_CharT>;
2118 // n.b. only decimal separator is locale dependent for specifiers
2119 // used below, as sys_info uses seconds and minutes duration, the
2120 // output is locale-independent.
2121 constexpr auto* __fs
2122 = _GLIBCXX_WIDEN("[{0:%F %T},{1:%F %T},{2:%T},{3:%Q%q},{0:%Z}]");
2123 const chrono::local_seconds __lb(__si.begin.time_since_epoch());
2124 return std::format_to(std::move(__out), _FmtStr(__fs),
2125 chrono::local_time_format(__lb, &__si.abbrev),
2126 __si.end, __si.offset, __si.save);
2127 }
2128
2129 template<typename _Out>
2130 _Out
2131 _M_format_to(_Out __out, const chrono::local_info& __li) const
2132 {
2133 *__out = _Separators<_CharT>::_S_squares()[0];
2134 ++__out;
2135 if (__li.result == chrono::local_info::unique)
2136 __out = _M_format_to(std::move(__out), __li.first);
2137 else
2138 {
2139 basic_string_view<_CharT> __sv;
2140 if (__li.result == chrono::local_info::nonexistent)
2141 __sv =_GLIBCXX_WIDEN("nonexistent");
2142 else
2143 __sv = _GLIBCXX_WIDEN("ambiguous");
2144 __out = __format::__write(std::move(__out), __sv);
2145
2146 __sv = _GLIBCXX_WIDEN(" local time between ");
2147 __out = __format::__write(std::move(__out), __sv);
2148 __out = _M_format_to(std::move(__out), __li.first);
2149
2150 __sv = _GLIBCXX_WIDEN(" and ");
2151 __out = __format::__write(std::move(__out), __sv);
2152 __out = _M_format_to(std::move(__out), __li.second);
2153 }
2154 *__out = _Separators<_CharT>::_S_squares()[1];
2155 ++__out;
2156 return std::move(__out);
2157 }
2158
2159 __formatter_chrono<_CharT> _M_f;
2160 };
2161#endif
2162
2163} // namespace __format
2164/// @endcond
2165
2166 template<typename _Rep, typename _Period, typename _CharT>
2167 requires __format::__formattable_impl<_Rep, _CharT>
2168 struct formatter<chrono::duration<_Rep, _Period>, _CharT>
2169 {
2170 constexpr typename basic_format_parse_context<_CharT>::iterator
2171 parse(basic_format_parse_context<_CharT>& __pc)
2172 {
2173 using enum __format::_ChronoParts;
2174 return _M_f.template _M_parse<_Duration>(__pc, _EpochTime, __defSpec);
2175 }
2176
2177 template<typename _Out>
2178 typename basic_format_context<_Out, _CharT>::iterator
2179 format(const chrono::duration<_Rep, _Period>& __d,
2180 basic_format_context<_Out, _CharT>& __fc) const
2181 {
2182 if constexpr (numeric_limits<_Rep>::is_signed)
2183 if (__d < __d.zero()) [[unlikely]]
2184 {
2185 if constexpr (is_integral_v<_Rep>)
2186 {
2187 // -d is undefined for the most negative integer.
2188 // Convert duration to corresponding unsigned rep.
2189 using _URep = make_unsigned_t<_Rep>;
2190 auto __ucnt = -static_cast<_URep>(__d.count());
2191 auto __ud = chrono::duration<_URep, _Period>(__ucnt);
2192 return _M_format(__ud, true, __fc);
2193 }
2194 else
2195 return _M_format(-__d, true, __fc);
2196 }
2197 return _M_format(__d, false, __fc);
2198 }
2199
2200 private:
2201 using _Duration = chrono::duration<_Rep, _Period>;
2202
2203 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2204 {
2205 using enum __format::_ChronoParts;
2206 auto __res = __format::__formatter_duration<_CharT>::
2207 template _S_spec_for<_Duration>(_None);
2208 __res._M_localized = !is_integral_v<_Rep>;
2209 // n.b. for integral format output is the same as ostream output
2210 if constexpr (is_integral_v<_Rep>)
2211 {
2212 __res._M_needed = _EpochUnits|_UnitSuffix;
2213 __res._M_chrono_specs = _GLIBCXX_WIDEN("%Q%q");
2214 }
2215 return __res;
2216 }();
2217
2218 template<typename _Rep2, typename _Out>
2219 typename basic_format_context<_Out, _CharT>::iterator
2220 _M_format(const chrono::duration<_Rep2, _Period>& __d,
2221 bool __is_neg,
2222 basic_format_context<_Out, _CharT>& __fc) const
2223 {
2224 using namespace chrono;
2225 using enum __format::_ChronoParts;
2226 if constexpr (!is_integral_v<_Rep>)
2227 if (_M_f._M_spec._M_chrono_specs.empty())
2228 return _M_f._M_format_to_ostream(__d, __is_neg, __fc);
2229
2230 __format::_ChronoData<_CharT> __cd;
2231 __cd._M_is_neg = __is_neg;
2232 auto __ts = chrono::floor<chrono::seconds>(__d);
2233 __cd._M_eseconds = __ts;
2234 if (_M_f._M_spec._M_needs(_HoursMinutesSeconds))
2235 __cd._M_fill_time(__ts);
2236 return _M_f._M_format_units(__cd, __d, __d - __ts, __fc);
2237 }
2238
2239 __format::__formatter_duration<_CharT> _M_f{__defSpec};
2240 };
2241
2242#if __glibcxx_print >= 202406L
2243 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2244 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
2245 template<typename _Rep, typename _Period>
2246 constexpr bool
2247 enable_nonlocking_formatter_optimization<chrono::duration<_Rep, _Period>>
2248 = is_arithmetic_v<_Rep>;
2249#endif
2250
2251 template<__format::__char _CharT>
2252 struct formatter<chrono::day, _CharT>
2253 {
2254 constexpr typename basic_format_parse_context<_CharT>::iterator
2255 parse(basic_format_parse_context<_CharT>& __pc)
2256 {
2257 using enum __format::_ChronoParts;
2258 return _M_f._M_parse(__pc, _Day|_WeekdayIndex, __defSpec);
2259 }
2260
2261 template<typename _Out>
2262 typename basic_format_context<_Out, _CharT>::iterator
2263 format(const chrono::day& __t,
2264 basic_format_context<_Out, _CharT>& __fc) const
2265 {
2266 __format::_ChronoData<_CharT> __cd{};
2267 __cd._M_fill_day(__t, __defSpec._M_needed);
2268 return _M_f._M_format(__cd, __fc);
2269 }
2270
2271 private:
2272 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2273 {
2274 using __format::_ChronoFormats;
2275 using enum __format::_ChronoParts;
2276
2277 __format::_ChronoSpec<_CharT> __res{};
2278 __res._M_debug = true;
2279 __res._M_needed = _Day;
2280 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_d();
2281 return __res;
2282 }();
2283
2284 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2285 };
2286
2287#if __glibcxx_print >= 202406L
2288 template<>
2289 inline constexpr bool
2290 enable_nonlocking_formatter_optimization<chrono::day> = true;
2291#endif
2292
2293 template<__format::__char _CharT>
2294 struct formatter<chrono::month, _CharT>
2295 {
2296 constexpr typename basic_format_parse_context<_CharT>::iterator
2297 parse(basic_format_parse_context<_CharT>& __pc)
2298 {
2299 using enum __format::_ChronoParts;
2300 return _M_f._M_parse(__pc, _Month, __defSpec);
2301 }
2302
2303 template<typename _Out>
2304 typename basic_format_context<_Out, _CharT>::iterator
2305 format(const chrono::month& __t,
2306 basic_format_context<_Out, _CharT>& __fc) const
2307 {
2308 __format::_ChronoData<_CharT> __cd{};
2309 __cd._M_month = __t;
2310 return _M_f._M_format(__cd, __fc);
2311 }
2312
2313 private:
2314 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2315 {
2316 using __format::_ChronoFormats;
2317 using enum __format::_ChronoParts;
2318
2319 __format::_ChronoSpec<_CharT> __res{};
2320 __res._M_debug = true;
2321 __res._M_localized = true;
2322 __res._M_locale_specific = true;
2323 __res._M_needed = _Month;
2324 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_m();
2325 return __res;
2326 }();
2327
2328 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2329 };
2330
2331#if __glibcxx_print >= 202406L
2332 template<>
2333 inline constexpr bool
2334 enable_nonlocking_formatter_optimization<chrono::month> = true;
2335#endif
2336
2337 template<__format::__char _CharT>
2338 struct formatter<chrono::year, _CharT>
2339 {
2340 constexpr typename basic_format_parse_context<_CharT>::iterator
2341 parse(basic_format_parse_context<_CharT>& __pc)
2342 {
2343 using enum __format::_ChronoParts;
2344 return _M_f._M_parse(__pc, _Year, __defSpec);
2345 }
2346
2347 template<typename _Out>
2348 typename basic_format_context<_Out, _CharT>::iterator
2349 format(const chrono::year& __t,
2350 basic_format_context<_Out, _CharT>& __fc) const
2351 {
2352 __format::_ChronoData<_CharT> __cd{};
2353 __cd._M_year = __t;
2354 return _M_f._M_format(__cd, __fc);
2355 }
2356
2357 private:
2358 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2359 {
2360 using __format::_ChronoFormats;
2361 using enum __format::_ChronoParts;
2362
2363 __format::_ChronoSpec<_CharT> __res{};
2364 __res._M_debug = true;
2365 __res._M_needed = _Year;
2366 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_y();
2367 return __res;
2368 }();
2369
2370 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2371 };
2372
2373#if __glibcxx_print >= 202406L
2374 template<>
2375 inline constexpr bool
2376 enable_nonlocking_formatter_optimization<chrono::year> = true;
2377#endif
2378
2379 template<__format::__char _CharT>
2380 struct formatter<chrono::weekday, _CharT>
2381 {
2382 constexpr typename basic_format_parse_context<_CharT>::iterator
2383 parse(basic_format_parse_context<_CharT>& __pc)
2384 {
2385 using enum __format::_ChronoParts;
2386 return _M_f._M_parse(__pc, _Weekday, __defSpec);
2387 }
2388
2389 template<typename _Out>
2390 typename basic_format_context<_Out, _CharT>::iterator
2391 format(const chrono::weekday& __t,
2392 basic_format_context<_Out, _CharT>& __fc) const
2393 {
2394 __format::_ChronoData<_CharT> __cd{};
2395 __cd._M_weekday = __t;
2396 return _M_f._M_format(__cd, __fc);
2397 }
2398
2399 private:
2400 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2401 {
2402 using __format::_ChronoFormats;
2403 using enum __format::_ChronoParts;
2404
2405 __format::_ChronoSpec<_CharT> __res{};
2406 __res._M_debug = true;
2407 __res._M_localized = true;
2408 __res._M_locale_specific = true;
2409 __res._M_needed = _Weekday;
2410 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_w();
2411 return __res;
2412 }();
2413
2414 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2415 };
2416
2417#if __glibcxx_print >= 202406L
2418 template<>
2419 inline constexpr bool
2420 enable_nonlocking_formatter_optimization<chrono::weekday> = true;
2421#endif
2422
2423 template<__format::__char _CharT>
2424 struct formatter<chrono::weekday_indexed, _CharT>
2425 {
2426 constexpr typename basic_format_parse_context<_CharT>::iterator
2427 parse(basic_format_parse_context<_CharT>& __pc)
2428 {
2429 using enum __format::_ChronoParts;
2430 return _M_f._M_parse(__pc, _IndexedWeekday, __defSpec);
2431 }
2432
2433 template<typename _Out>
2434 typename basic_format_context<_Out, _CharT>::iterator
2435 format(const chrono::weekday_indexed& __t,
2436 basic_format_context<_Out, _CharT>& __fc) const
2437 {
2438 __format::_ChronoData<_CharT> __cd{};
2439 __cd._M_fill_weekday(__t, __defSpec._M_needed);
2440 return _M_f._M_format(__cd, __fc);
2441 }
2442
2443 private:
2444 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2445 {
2446 using __format::_ChronoFormats;
2447 using enum __format::_ChronoParts;
2448
2449 __format::_ChronoSpec<_CharT> __res{};
2450 __res._M_debug = true;
2451 __res._M_localized = true;
2452 __res._M_locale_specific = true;
2453 __res._M_needed = _IndexedWeekday;
2454 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_wi();
2455 return __res;
2456 }();
2457
2458 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2459 };
2460
2461#if __glibcxx_print >= 202406L
2462 template<>
2463 inline constexpr bool
2464 enable_nonlocking_formatter_optimization<chrono::weekday_indexed> = true;
2465#endif
2466
2467 template<__format::__char _CharT>
2468 struct formatter<chrono::weekday_last, _CharT>
2469 {
2470 constexpr typename basic_format_parse_context<_CharT>::iterator
2471 parse(basic_format_parse_context<_CharT>& __pc)
2472 {
2473 using enum __format::_ChronoParts;
2474 return _M_f._M_parse(__pc, _Weekday, __defSpec);
2475 }
2476
2477 template<typename _Out>
2478 typename basic_format_context<_Out, _CharT>::iterator
2479 format(const chrono::weekday_last& __t,
2480 basic_format_context<_Out, _CharT>& __fc) const
2481 {
2482 __format::_ChronoData<_CharT> __cd{};
2483 __cd._M_weekday = __t.weekday();
2484 return _M_f._M_format(__cd, __fc);
2485 }
2486
2487 private:
2488 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2489 {
2490 using __format::_ChronoFormats;
2491 using enum __format::_ChronoParts;
2492
2493 __format::_ChronoSpec<_CharT> __res{};
2494 __res._M_debug = true;
2495 __res._M_localized = true;
2496 __res._M_locale_specific = true;
2497 __res._M_needed = _Weekday;
2498 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_wl();
2499 return __res;
2500 }();
2501
2502 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2503 };
2504
2505#if __glibcxx_print >= 202406L
2506 template<>
2507 inline constexpr bool
2508 enable_nonlocking_formatter_optimization<chrono::weekday_last> = true;
2509#endif
2510
2511 template<__format::__char _CharT>
2512 struct formatter<chrono::month_day, _CharT>
2513 {
2514 constexpr typename basic_format_parse_context<_CharT>::iterator
2515 parse(basic_format_parse_context<_CharT>& __pc)
2516 {
2517 using enum __format::_ChronoParts;
2518 return _M_f._M_parse(__pc, _Month|_Day|_WeekdayIndex, __defSpec);
2519 }
2520
2521 template<typename _Out>
2522 typename basic_format_context<_Out, _CharT>::iterator
2523 format(const chrono::month_day& __t,
2524 basic_format_context<_Out, _CharT>& __fc) const
2525 {
2526 __format::_ChronoData<_CharT> __cd{};
2527 __cd._M_month = __t.month();
2528 __cd._M_fill_day(__t.day(), __defSpec._M_needed);
2529 return _M_f._M_format(__cd, __fc);
2530 }
2531
2532 private:
2533 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2534 {
2535 using __format::_ChronoFormats;
2536 using enum __format::_ChronoParts;
2537
2538 __format::_ChronoSpec<_CharT> __res{};
2539 __res._M_debug = true;
2540 __res._M_localized = true;
2541 __res._M_locale_specific = true;
2542 __res._M_needed = _Month|_Day;
2543 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_md();
2544 return __res;
2545 }();
2546
2547 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2548 };
2549
2550#if __glibcxx_print >= 202406L
2551 template<>
2552 inline constexpr bool
2553 enable_nonlocking_formatter_optimization<chrono::month_day> = true;
2554#endif
2555
2556 template<__format::__char _CharT>
2557 struct formatter<chrono::month_day_last, _CharT>
2558 {
2559 constexpr typename basic_format_parse_context<_CharT>::iterator
2560 parse(basic_format_parse_context<_CharT>& __pc)
2561 {
2562 using enum __format::_ChronoParts;
2563 return _M_f._M_parse(__pc, _Month, __defSpec);
2564 }
2565
2566 template<typename _Out>
2567 typename basic_format_context<_Out, _CharT>::iterator
2568 format(const chrono::month_day_last& __t,
2569 basic_format_context<_Out, _CharT>& __fc) const
2570 {
2571 __format::_ChronoData<_CharT> __cd{};
2572 __cd._M_month = __t.month();
2573 return _M_f._M_format(__cd, __fc);
2574 }
2575
2576 private:
2577 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2578 {
2579 using __format::_ChronoFormats;
2580 using enum __format::_ChronoParts;
2581
2582 __format::_ChronoSpec<_CharT> __res{};
2583 __res._M_debug = true;
2584 __res._M_localized = true;
2585 __res._M_locale_specific = true;
2586 __res._M_needed = _Month;
2587 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ml();
2588 return __res;
2589 }();
2590
2591 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2592 };
2593
2594#if __glibcxx_print >= 202406L
2595 template<>
2596 inline constexpr bool
2597 enable_nonlocking_formatter_optimization<chrono::month_day_last> = true;
2598#endif
2599
2600 template<__format::__char _CharT>
2601 struct formatter<chrono::month_weekday, _CharT>
2602 {
2603 constexpr typename basic_format_parse_context<_CharT>::iterator
2604 parse(basic_format_parse_context<_CharT>& __pc)
2605 {
2606 using enum __format::_ChronoParts;
2607 return _M_f._M_parse(__pc, _Month|_IndexedWeekday, __defSpec);
2608 }
2609
2610 template<typename _Out>
2611 typename basic_format_context<_Out, _CharT>::iterator
2612 format(const chrono::month_weekday& __t,
2613 basic_format_context<_Out, _CharT>& __fc) const
2614 {
2615 __format::_ChronoData<_CharT> __cd{};
2616 __cd._M_month = __t.month();
2617 __cd._M_fill_weekday(__t.weekday_indexed(), __defSpec._M_needed);
2618 return _M_f._M_format(__cd, __fc);
2619 }
2620
2621 private:
2622 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2623 {
2624 using __format::_ChronoFormats;
2625 using enum __format::_ChronoParts;
2626
2627 __format::_ChronoSpec<_CharT> __res{};
2628 __res._M_debug = true;
2629 __res._M_localized = true;
2630 __res._M_locale_specific = true;
2631 __res._M_needed = _Month|_IndexedWeekday;
2632 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_mwi();
2633 return __res;
2634 }();
2635
2636 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2637 };
2638
2639#if __glibcxx_print >= 202406L
2640 template<>
2641 inline constexpr bool
2642 enable_nonlocking_formatter_optimization<chrono::month_weekday> = true;
2643#endif
2644
2645 template<__format::__char _CharT>
2646 struct formatter<chrono::month_weekday_last, _CharT>
2647 {
2648 constexpr typename basic_format_parse_context<_CharT>::iterator
2649 parse(basic_format_parse_context<_CharT>& __pc)
2650 {
2651 using enum __format::_ChronoParts;
2652 return _M_f._M_parse(__pc, _Month|_Weekday, __defSpec);
2653 }
2654
2655 template<typename _Out>
2656 typename basic_format_context<_Out, _CharT>::iterator
2657 format(const chrono::month_weekday_last& __t,
2658 basic_format_context<_Out, _CharT>& __fc) const
2659 {
2660 __format::_ChronoData<_CharT> __cd{};
2661 __cd._M_month = __t.month();
2662 __cd._M_weekday = __t.weekday_last().weekday();
2663 return _M_f._M_format(__cd, __fc);
2664 }
2665
2666 private:
2667 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2668 {
2669 using __format::_ChronoFormats;
2670 using enum __format::_ChronoParts;
2671
2672 __format::_ChronoSpec<_CharT> __res{};
2673 __res._M_debug = true;
2674 __res._M_localized = true;
2675 __res._M_locale_specific = true;
2676 __res._M_needed = _Month|_Weekday;
2677 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_mwl();
2678 return __res;
2679 }();
2680
2681 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2682 };
2683
2684#if __glibcxx_print >= 202406L
2685 template<>
2686 inline constexpr bool
2687 enable_nonlocking_formatter_optimization<chrono::month_weekday_last> = true;
2688#endif
2689
2690 template<__format::__char _CharT>
2691 struct formatter<chrono::year_month, _CharT>
2692 {
2693 constexpr typename basic_format_parse_context<_CharT>::iterator
2694 parse(basic_format_parse_context<_CharT>& __pc)
2695 {
2696 using enum __format::_ChronoParts;
2697 return _M_f._M_parse(__pc, _Year|_Month, __defSpec);
2698 }
2699
2700 template<typename _Out>
2701 typename basic_format_context<_Out, _CharT>::iterator
2702 format(const chrono::year_month& __t,
2703 basic_format_context<_Out, _CharT>& __fc) const
2704 {
2705 __format::_ChronoData<_CharT> __cd{};
2706 __cd._M_fill_year_month(__t, __defSpec._M_needed);
2707 return _M_f._M_format(__cd, __fc);
2708 }
2709
2710 private:
2711 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2712 {
2713 using __format::_ChronoFormats;
2714 using enum __format::_ChronoParts;
2715
2716 __format::_ChronoSpec<_CharT> __res{};
2717 __res._M_debug = true;
2718 __res._M_localized = true;
2719 __res._M_locale_specific = true;
2720 __res._M_needed = _Year|_Month;
2721 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ym();
2722 return __res;
2723 }();
2724
2725 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2726 };
2727
2728#if __glibcxx_print >= 202406L
2729 template<>
2730 inline constexpr bool
2731 enable_nonlocking_formatter_optimization<chrono::year_month> = true;
2732#endif
2733
2734 template<__format::__char _CharT>
2735 struct formatter<chrono::year_month_day, _CharT>
2736 {
2737 constexpr typename basic_format_parse_context<_CharT>::iterator
2738 parse(basic_format_parse_context<_CharT>& __pc)
2739 {
2740 using enum __format::_ChronoParts;
2741 return _M_f._M_parse(__pc, _Date, __defSpec);
2742 }
2743
2744 template<typename _Out>
2745 typename basic_format_context<_Out, _CharT>::iterator
2746 format(const chrono::year_month_day& __t,
2747 basic_format_context<_Out, _CharT>& __fc) const
2748 {
2749 __format::_ChronoData<_CharT> __cd{};
2750 auto __parts = _M_f._M_spec._M_needed;
2751 __parts = __cd._M_fill_year_month(__t, __parts);
2752 __parts = __cd._M_fill_day(__t.day(), __parts);
2753 if (__parts == 0)
2754 return _M_f._M_format(__cd, __fc);
2755
2756 __cd._M_fill_ldays(chrono::local_days(__t), __parts);
2757 return _M_f._M_format(__cd, __fc);
2758 }
2759
2760 private:
2761 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2762 {
2763 using __format::_ChronoFormats;
2764 using enum __format::_ChronoParts;
2765
2766 __format::_ChronoSpec<_CharT> __res{};
2767 __res._M_debug = true;
2768 __res._M_needed = _YearMonthDay;
2769 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_f();
2770 return __res;
2771 }();
2772
2773 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2774 };
2775
2776#if __glibcxx_print >= 202406L
2777 template<>
2778 inline constexpr bool
2779 enable_nonlocking_formatter_optimization<chrono::year_month_day> = true;
2780#endif
2781
2782 template<__format::__char _CharT>
2783 struct formatter<chrono::year_month_day_last, _CharT>
2784 {
2785 constexpr typename basic_format_parse_context<_CharT>::iterator
2786 parse(basic_format_parse_context<_CharT>& __pc)
2787 {
2788 using enum __format::_ChronoParts;
2789 return _M_f._M_parse(__pc, _Date, __defSpec);
2790 }
2791
2792 template<typename _Out>
2793 typename basic_format_context<_Out, _CharT>::iterator
2794 format(const chrono::year_month_day_last& __t,
2795 basic_format_context<_Out, _CharT>& __fc) const
2796 {
2797 using enum __format::_ChronoParts;
2798
2799 __format::_ChronoData<_CharT> __cd{};
2800 auto __parts = _M_f._M_spec._M_needed;
2801 __parts = __cd._M_fill_year_month(__t, __parts);
2802 if (_M_f._M_spec._M_needs(_Day|_WeekdayIndex))
2803 __parts = __cd._M_fill_day(__t.day(), __parts);
2804 if (__parts == 0)
2805 return _M_f._M_format(__cd, __fc);
2806
2807 __cd._M_fill_ldays(chrono::local_days(__t), __parts);
2808 return _M_f._M_format(__cd, __fc);
2809 }
2810
2811 private:
2812 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2813 {
2814 using __format::_ChronoFormats;
2815 using enum __format::_ChronoParts;
2816
2817 __format::_ChronoSpec<_CharT> __res{};
2818 __res._M_debug = true;
2819 __res._M_localized = true;
2820 __res._M_locale_specific = true;
2821 __res._M_needed = _Year|_Month;
2822 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_yml();
2823 return __res;
2824 }();
2825
2826 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2827 };
2828
2829#if __glibcxx_print >= 202406L
2830 template<>
2831 inline constexpr bool
2832 enable_nonlocking_formatter_optimization<chrono::year_month_day_last> = true;
2833#endif
2834
2835 template<__format::__char _CharT>
2836 struct formatter<chrono::year_month_weekday, _CharT>
2837 {
2838 constexpr typename basic_format_parse_context<_CharT>::iterator
2839 parse(basic_format_parse_context<_CharT>& __pc)
2840 {
2841 using enum __format::_ChronoParts;
2842 return _M_f._M_parse(__pc, _Date, __defSpec);
2843 }
2844
2845 template<typename _Out>
2846 typename basic_format_context<_Out, _CharT>::iterator
2847 format(const chrono::year_month_weekday& __t,
2848 basic_format_context<_Out, _CharT>& __fc) const
2849 {
2850 __format::_ChronoData<_CharT> __cd{};
2851 auto __parts = _M_f._M_spec._M_needed;
2852 __parts = __cd._M_fill_year_month(__t, __parts);
2853 __parts = __cd._M_fill_weekday(__t.weekday_indexed(), __parts);
2854 if (__t.index() == 0) [[unlikely]]
2855 // n.b. day cannot be negative, so any 0th weekday uses
2856 // value-initialized (0) day of month
2857 __parts -= __format::_ChronoParts::_Day;
2858 if (__parts == 0)
2859 return _M_f._M_format(__cd, __fc);
2860
2861 chrono::local_days __ld(__t);
2862 __parts = __cd._M_fill_ldays(__ld, __parts);
2863 if (__parts == 0)
2864 return _M_f._M_format(__cd, __fc);
2865
2866 auto __dom = __ld - chrono::local_days(__t.year()/__t.month()/0);
2867 // n.b. weekday index is supplied by input, do not override it
2868 __cd._M_day = chrono::day(__dom.count());
2869 return _M_f._M_format(__cd, __fc);
2870 }
2871
2872 private:
2873 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2874 {
2875 using __format::_ChronoFormats;
2876 using enum __format::_ChronoParts;
2877
2878 __format::_ChronoSpec<_CharT> __res{};
2879 __res._M_debug = true;
2880 __res._M_localized = true;
2881 __res._M_locale_specific = true;
2882 __res._M_needed = _Year|_Month|_IndexedWeekday;
2883 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ymwi();
2884 return __res;
2885 }();
2886
2887 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2888 };
2889
2890#if __glibcxx_print >= 202406L
2891 template<>
2892 inline constexpr bool
2893 enable_nonlocking_formatter_optimization<chrono::year_month_weekday> = true;
2894#endif
2895
2896 template<__format::__char _CharT>
2897 struct formatter<chrono::year_month_weekday_last, _CharT>
2898 {
2899 constexpr typename basic_format_parse_context<_CharT>::iterator
2900 parse(basic_format_parse_context<_CharT>& __pc)
2901 {
2902 using enum __format::_ChronoParts;
2903 return _M_f._M_parse(__pc, _Date, __defSpec);
2904 }
2905
2906 template<typename _Out>
2907 typename basic_format_context<_Out, _CharT>::iterator
2908 format(const chrono::year_month_weekday_last& __t,
2909 basic_format_context<_Out, _CharT>& __fc) const
2910 {
2911 __format::_ChronoData<_CharT> __cd{};
2912 auto __parts = _M_f._M_spec._M_needed;
2913 __parts = __cd._M_fill_year_month(__t, __parts);
2914 __cd._M_weekday = __t.weekday_last().weekday();
2915 __parts -= __format::_ChronoParts::_Weekday;
2916 if (__parts == 0)
2917 return _M_f._M_format(__cd, __fc);
2918
2919 chrono::local_days __ld(__t);
2920 __parts = __cd._M_fill_ldays(__ld, __parts);
2921 if (__parts == 0)
2922 return _M_f._M_format(__cd, __fc);
2923
2924 auto __dom = __ld - chrono::local_days(__t.year()/__t.month()/0);
2925 __cd._M_fill_day(chrono::day(__dom.count()), __parts);
2926 return _M_f._M_format(__cd, __fc);
2927 }
2928
2929 private:
2930 static constexpr __format::_ChronoSpec<_CharT> __defSpec = []
2931 {
2932 using __format::_ChronoFormats;
2933 using enum __format::_ChronoParts;
2934
2935 __format::_ChronoSpec<_CharT> __res{};
2936 __res._M_debug = true;
2937 __res._M_localized = true;
2938 __res._M_locale_specific = true;
2939 __res._M_needed = _Year|_Month|_Weekday;
2940 __res._M_chrono_specs = _ChronoFormats<_CharT>::_S_ymwl();
2941 return __res;
2942 }();
2943
2944 __format::__formatter_chrono<_CharT> _M_f{__defSpec};
2945 };
2946
2947#if __glibcxx_print >= 202406L
2948 template<>
2949 inline constexpr bool
2950 enable_nonlocking_formatter_optimization<chrono::year_month_weekday_last> = true;
2951#endif
2952
2953 template<typename _Rep, typename _Period, __format::__char _CharT>
2954 struct formatter<chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>, _CharT>
2955 {
2956 constexpr typename basic_format_parse_context<_CharT>::iterator
2957 parse(basic_format_parse_context<_CharT>& __pc)
2958 {
2959 using enum __format::_ChronoParts;
2960 return _M_f.template _M_parse<_Precision>(__pc, _Time, __defSpec);
2961 }
2962
2963 template<typename _Out>
2964 typename basic_format_context<_Out, _CharT>::iterator
2965 format(const chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>& __t,
2966 basic_format_context<_Out, _CharT>& __fc) const
2967 {
2968 using enum __format::_ChronoParts;
2969
2970 __format::_ChronoData<_CharT> __cd;
2971 __cd._M_is_neg = __t.is_negative();
2972 __cd._M_hours = __t.hours();
2973 __cd._M_minutes = __t.minutes();
2974 __cd._M_seconds = __t.seconds();
2975
2976 _Precision __d(0);
2977 // n.b. computing total duration or total seconds may overflow,
2978 // do not compute them if not requested.
2979 if (_M_f._M_spec._M_needs(_EpochUnits))
2980 __d = __t.to_duration();
2981 if (_M_f._M_spec._M_needs(_TotalSeconds))
2982 __cd._M_eseconds
2983 = __cd._M_hours + __cd._M_minutes + __cd._M_seconds;
2984 return _M_f._M_format_units(__cd, __d, __t.subseconds(), __fc);
2985 }
2986
2987 private:
2988 using _Precision
2989 = typename chrono::hh_mm_ss<chrono::duration<_Rep, _Period>>::precision;
2990 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
2991 __format::__formatter_duration<_CharT>::
2992 template _S_spec_for<_Precision>(__format::_ChronoParts::_Time);
2993
2994 __format::__formatter_duration<_CharT> _M_f{__defSpec};
2995 };
2996
2997#if __glibcxx_print >= 202406L
2998 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2999 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3000 template<typename _Duration>
3001 constexpr bool
3002 enable_nonlocking_formatter_optimization<chrono::hh_mm_ss<_Duration>>
3003 = enable_nonlocking_formatter_optimization<_Duration>;
3004#endif
3005
3006#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
3007 template<__format::__char _CharT>
3008 struct formatter<chrono::sys_info, _CharT>
3009 {
3010 constexpr typename basic_format_parse_context<_CharT>::iterator
3011 parse(basic_format_parse_context<_CharT>& __pc)
3012 { return _M_f.parse(__pc); }
3013
3014 template<typename _Out>
3015 typename basic_format_context<_Out, _CharT>::iterator
3016 format(const chrono::sys_info& __i,
3017 basic_format_context<_Out, _CharT>& __fc) const
3018 { return _M_f.format(__i, __fc); }
3019
3020 private:
3021 __format::__formatter_chrono_info<_CharT> _M_f;
3022 };
3023
3024#if __glibcxx_print >= 202406L
3025 template<>
3026 inline constexpr bool
3027 enable_nonlocking_formatter_optimization<chrono::sys_info> = true;
3028#endif
3029
3030 template<__format::__char _CharT>
3031 struct formatter<chrono::local_info, _CharT>
3032 {
3033 constexpr typename basic_format_parse_context<_CharT>::iterator
3034 parse(basic_format_parse_context<_CharT>& __pc)
3035 { return _M_f.parse(__pc); }
3036
3037 template<typename _Out>
3038 typename basic_format_context<_Out, _CharT>::iterator
3039 format(const chrono::local_info& __i,
3040 basic_format_context<_Out, _CharT>& __fc) const
3041 { return _M_f.format(__i, __fc); }
3042
3043 private:
3044 __format::__formatter_chrono_info<_CharT> _M_f;
3045 };
3046
3047#if __glibcxx_print >= 202406L
3048 template<>
3049 inline constexpr bool
3050 enable_nonlocking_formatter_optimization<chrono::local_info> = true;
3051#endif
3052#endif
3053
3054 template<typename _Duration, __format::__char _CharT>
3055 struct formatter<chrono::sys_time<_Duration>, _CharT>
3056 {
3057 constexpr typename basic_format_parse_context<_CharT>::iterator
3058 parse(basic_format_parse_context<_CharT>& __pc)
3059 {
3060 using enum __format::_ChronoParts;
3061 auto __res
3062 = _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3063 if constexpr (__defSpec._M_chrono_specs.empty())
3064 if (_M_f._M_spec._M_chrono_specs.empty())
3065 __format::__invalid_chrono_spec(); // chrono-specs can't be empty
3066 return __res;
3067 }
3068
3069 template<typename _Out>
3070 typename basic_format_context<_Out, _CharT>::iterator
3071 format(const chrono::sys_time<_Duration>& __t,
3072 basic_format_context<_Out, _CharT>& __fc) const
3073 {
3074 __format::_ChronoData<_CharT> __cd{};
3075 __cd._M_fill_utc_zone();
3076
3077 _Duration __ed = __t.time_since_epoch();
3078 __cd._M_eseconds = chrono::floor<chrono::seconds>(__ed);
3079 __cd._M_lseconds = chrono::local_seconds(__cd._M_eseconds);
3080 return _M_f._M_format_time_point(__cd, __ed, __fc);
3081 }
3082
3083 private:
3084 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3085 __format::__formatter_duration<_CharT>::template _S_spec_for_tp<_Duration>();
3086
3087 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3088 };
3089
3090#if __glibcxx_print >= 202406L
3091 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3092 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3093 template<typename _Duration>
3094 constexpr bool
3095 enable_nonlocking_formatter_optimization<chrono::sys_time<_Duration>>
3096 = enable_nonlocking_formatter_optimization<_Duration>;
3097#endif
3098
3099 template<typename _Duration, __format::__char _CharT>
3100 struct formatter<chrono::utc_time<_Duration>, _CharT>
3101 {
3102 constexpr typename basic_format_parse_context<_CharT>::iterator
3103 parse(basic_format_parse_context<_CharT>& __pc)
3104 {
3105 using enum __format::_ChronoParts;
3106 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3107 }
3108
3109 template<typename _Out>
3110 typename basic_format_context<_Out, _CharT>::iterator
3111 format(const chrono::utc_time<_Duration>& __t,
3112 basic_format_context<_Out, _CharT>& __fc) const
3113 {
3114 using __format::_ChronoParts;
3115 using namespace chrono;
3116 __format::_ChronoData<_CharT> __cd{};
3117 __cd._M_fill_utc_zone();
3118
3119 _Duration __ed = __t.time_since_epoch();
3120 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3121 // Adjust by removing leap seconds to get equivalent sys_time.
3122 // We can't just use clock_cast because we want to know if the time
3123 // falls within a leap second insertion, and format seconds as "60".
3124 const auto __li = chrono::get_leap_second_info(__t);
3125 __cd._M_lseconds = local_seconds(__cd._M_eseconds - __li.elapsed);
3126 auto __parts = _M_f._M_spec._M_needed - _ChronoParts::_TotalSeconds;
3127 if ((__parts & _ChronoParts::_DateTime) != 0)
3128 {
3129 __cd._M_fill_date_time(__cd._M_lseconds, __parts);
3130 __cd._M_seconds += seconds(__li.is_leap_second);
3131 }
3132 return _M_f._M_format_units(__cd, __ed, __ed - __cd._M_eseconds, __fc);
3133 }
3134
3135 private:
3136 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3137 __format::__formatter_duration<_CharT>::
3138 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3139
3140 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3141 };
3142
3143#if __glibcxx_print >= 202406L
3144 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3145 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3146 template<typename _Duration>
3147 constexpr bool
3148 enable_nonlocking_formatter_optimization<chrono::utc_time<_Duration>>
3149 = enable_nonlocking_formatter_optimization<_Duration>;
3150#endif
3151
3152 template<typename _Duration, __format::__char _CharT>
3153 struct formatter<chrono::tai_time<_Duration>, _CharT>
3154 {
3155 constexpr typename basic_format_parse_context<_CharT>::iterator
3156 parse(basic_format_parse_context<_CharT>& __pc)
3157 {
3158 using enum __format::_ChronoParts;
3159 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3160 }
3161
3162 template<typename _Out>
3163 typename basic_format_context<_Out, _CharT>::iterator
3164 format(const chrono::tai_time<_Duration>& __t,
3165 basic_format_context<_Out, _CharT>& __fc) const
3166 {
3167 using namespace chrono;
3168 __format::_ChronoData<_CharT> __cd{};
3169 __cd._M_fill_zone("TAI", L"TAI");
3170
3171 _Duration __ed = __t.time_since_epoch();
3172 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3173 // Offset is 1970y/January/1 - 1958y/January/1
3174 constexpr chrono::days __tai_offset = chrono::days(4383);
3175 __cd._M_lseconds = local_seconds(__cd._M_eseconds - __tai_offset);
3176 return _M_f._M_format_time_point(__cd, __ed, __fc);
3177 }
3178
3179 private:
3180 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3181 __format::__formatter_duration<_CharT>::
3182 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3183
3184 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3185 };
3186
3187#if __glibcxx_print >= 202406L
3188 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3189 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3190 template<typename _Duration>
3191 constexpr bool
3192 enable_nonlocking_formatter_optimization<chrono::tai_time<_Duration>>
3193 = enable_nonlocking_formatter_optimization<_Duration>;
3194#endif
3195
3196 template<typename _Duration, __format::__char _CharT>
3197 struct formatter<chrono::gps_time<_Duration>, _CharT>
3198 {
3199 constexpr typename basic_format_parse_context<_CharT>::iterator
3200 parse(basic_format_parse_context<_CharT>& __pc)
3201 {
3202 using enum __format::_ChronoParts;
3203 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3204 }
3205
3206 template<typename _Out>
3207 typename basic_format_context<_Out, _CharT>::iterator
3208 format(const chrono::gps_time<_Duration>& __t,
3209 basic_format_context<_Out, _CharT>& __fc) const
3210 {
3211 using namespace chrono;
3212 __format::_ChronoData<_CharT> __cd{};
3213 __cd._M_fill_zone("GPS", L"GPS");
3214
3215 _Duration __ed = __t.time_since_epoch();
3216 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3217 // Offset is 1980y/January/Sunday[1] - 1970y/January/1
3218 constexpr chrono::days __gps_offset = chrono::days(3657);
3219 __cd._M_lseconds = local_seconds(__cd._M_eseconds + __gps_offset);
3220 return _M_f._M_format_time_point(__cd, __ed, __fc);
3221 }
3222
3223 private:
3224 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3225 __format::__formatter_duration<_CharT>::
3226 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3227
3228 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3229 };
3230
3231#if __glibcxx_print >= 202406L
3232 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3233 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3234 template<typename _Duration>
3235 constexpr bool
3236 enable_nonlocking_formatter_optimization<chrono::gps_time<_Duration>>
3237 = enable_nonlocking_formatter_optimization<_Duration>;
3238#endif
3239
3240 template<typename _Duration, __format::__char _CharT>
3241 struct formatter<chrono::file_time<_Duration>, _CharT>
3242 {
3243 constexpr typename basic_format_parse_context<_CharT>::iterator
3244 parse(basic_format_parse_context<_CharT>& __pc)
3245 {
3246 using enum __format::_ChronoParts;
3247 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3248 }
3249
3250 template<typename _Out>
3251 typename basic_format_context<_Out, _CharT>::iterator
3252 format(const chrono::file_time<_Duration>& __t,
3253 basic_format_context<_Out, _CharT>& __fc) const
3254 {
3255 using namespace chrono;
3256 __format::_ChronoData<_CharT> __cd{};
3257 __cd._M_fill_utc_zone();
3258
3259 _Duration __ed = __t.time_since_epoch();
3260 __cd._M_eseconds = chrono::floor<seconds>(__ed);
3261 auto __st = chrono::clock_cast<system_clock>(__t);
3262 __cd._M_lseconds
3263 = local_seconds(chrono::floor<seconds>(__st.time_since_epoch()));
3264 return _M_f._M_format_time_point(__cd, __ed, __fc);
3265 }
3266
3267 private:
3268 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3269 __format::__formatter_duration<_CharT>::
3270 template _S_spec_for<_Duration>(__format::_ChronoParts::_DateTime);
3271
3272 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3273 };
3274
3275#if __glibcxx_print >= 202406L
3276 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3277 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3278 template<typename _Duration>
3279 constexpr bool
3280 enable_nonlocking_formatter_optimization<chrono::file_time<_Duration>>
3281 = enable_nonlocking_formatter_optimization<_Duration>;
3282#endif
3283
3284 template<typename _Duration, __format::__char _CharT>
3285 struct formatter<chrono::local_time<_Duration>, _CharT>
3286 {
3287 constexpr typename basic_format_parse_context<_CharT>::iterator
3288 parse(basic_format_parse_context<_CharT>& __pc)
3289 {
3290 using enum __format::_ChronoParts;
3291 auto __res
3292 = _M_f.template _M_parse<_Duration>(__pc, _DateTime, __defSpec);
3293 if constexpr (__defSpec._M_chrono_specs.empty())
3294 if (_M_f._M_spec._M_chrono_specs.empty())
3295 __format::__invalid_chrono_spec(); // chrono-specs can't be empty
3296 return __res;
3297 }
3298
3299 template<typename _Out>
3300 typename basic_format_context<_Out, _CharT>::iterator
3301 format(const chrono::local_time<_Duration>& __lt,
3302 basic_format_context<_Out, _CharT>& __fc) const
3303 {
3304 __format::_ChronoData<_CharT> __cd{};
3305 _Duration __ed = __lt.time_since_epoch();
3306 __cd._M_lseconds = chrono::floor<chrono::seconds>(__lt);
3307 __cd._M_eseconds = __cd._M_lseconds.time_since_epoch();
3308 return _M_f._M_format_time_point(__cd, __ed, __fc);
3309 }
3310
3311 private:
3312 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3313 __format::__formatter_duration<_CharT>::template _S_spec_for_tp<_Duration>();
3314
3315 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3316 };
3317
3318#if __glibcxx_print >= 202406L
3319 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3320 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3321 template<typename _Duration>
3322 constexpr bool
3323 enable_nonlocking_formatter_optimization<chrono::local_time<_Duration>>
3324 = enable_nonlocking_formatter_optimization<_Duration>;
3325#endif
3326
3327 template<typename _Duration, __format::__char _CharT>
3328 struct formatter<chrono::__detail::__local_time_fmt<_Duration>, _CharT>
3329 {
3330 constexpr typename basic_format_parse_context<_CharT>::iterator
3331 parse(basic_format_parse_context<_CharT>& __pc)
3332 {
3333 using enum __format::_ChronoParts;
3334 return _M_f.template _M_parse<_Duration>(__pc, _ZonedDateTime, __defSpec);
3335 }
3336
3337 template<typename _Out>
3338 typename basic_format_context<_Out, _CharT>::iterator
3339 format(const chrono::__detail::__local_time_fmt<_Duration>& __zt,
3340 basic_format_context<_Out, _CharT>& __fc) const
3341 {
3342 using enum __format::_ChronoParts;
3343 __format::_ChronoData<_CharT> __cd{};
3344
3345 if (_M_f._M_spec._M_needs(_ZoneOffset))
3346 {
3347 if (!__zt._M_offset_sec)
3348 std::__throw_format_error("format error: no timezone available for %z");
3349 __cd._M_zone_offset = *__zt._M_offset_sec;
3350 }
3351
3352 basic_string<_CharT> __zone_store;
3353 if (_M_f._M_spec._M_needs(_ZoneAbbrev))
3354 {
3355 if (!__zt._M_abbrev)
3356 std::__throw_format_error("format error: no timezone available for %Z");
3357
3358 __cd._M_zone_cstr = __zt._M_abbrev->data();
3359 if constexpr (is_same_v<_CharT, char>)
3360 __cd._M_zone_abbrev = *__zt._M_abbrev;
3361 else
3362 {
3363 // TODO: use resize_and_overwrite
3364 __zone_store.resize(__zt._M_abbrev->size());
3365 auto& __ct = use_facet<ctype<_CharT>>(_M_f._M_locale(__fc));
3366 __ct.widen(__zt._M_abbrev->data(),
3367 __zt._M_abbrev->data() + __zt._M_abbrev->size(),
3368 __zone_store.data());
3369 __cd._M_zone_abbrev = __zone_store;
3370 }
3371 }
3372
3373 _Duration __ed = __zt._M_time.time_since_epoch();
3374 __cd._M_lseconds = chrono::floor<chrono::seconds>(__zt._M_time);
3375 __cd._M_eseconds = __cd._M_lseconds.time_since_epoch();
3376 return _M_f._M_format_time_point(__cd, __ed, __fc);
3377 }
3378
3379 private:
3380 static constexpr __format::_ChronoSpec<_CharT> __defSpec =
3381 __format::__formatter_duration<_CharT>::
3382 template _S_spec_for<_Duration>(__format::_ChronoParts::_ZonedDateTime);
3383
3384 __format::__formatter_duration<_CharT> _M_f{__defSpec};
3385 };
3386
3387#if __glibcxx_print >= 202406L
3388 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3389 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3390 template<typename _Duration>
3391 constexpr bool
3392 enable_nonlocking_formatter_optimization<
3393 chrono::__detail::__local_time_fmt<_Duration>>
3394 = enable_nonlocking_formatter_optimization<_Duration>;
3395#endif
3396
3397#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
3398 template<typename _Duration, typename _TimeZonePtr, __format::__char _CharT>
3399 struct formatter<chrono::zoned_time<_Duration, _TimeZonePtr>, _CharT>
3400 : formatter<chrono::__detail::__local_time_fmt_for<_Duration>, _CharT>
3401 {
3402 template<typename _Out>
3403 typename basic_format_context<_Out, _CharT>::iterator
3404 format(const chrono::zoned_time<_Duration, _TimeZonePtr>& __tp,
3405 basic_format_context<_Out, _CharT>& __fc) const
3406 {
3407 using _Ltf = chrono::__detail::__local_time_fmt_for<_Duration>;
3408 using _Base = formatter<_Ltf, _CharT>;
3409 const chrono::sys_info __info = __tp.get_info();
3410 const auto __lf = chrono::local_time_format(__tp.get_local_time(),
3411 &__info.abbrev,
3412 &__info.offset);
3413 return _Base::format(__lf, __fc);
3414 }
3415 };
3416
3417#if __glibcxx_print >= 202406L
3418 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3419 // 4400. enable_nonlocking_formatter_optimization for durations with custom rep
3420 template<typename _Duration>
3421 constexpr bool
3422 enable_nonlocking_formatter_optimization<
3423 chrono::zoned_time<_Duration, const chrono::time_zone*>>
3424 = enable_nonlocking_formatter_optimization<_Duration>;
3425#endif
3426#endif
3427
3428namespace chrono
3429{
3430/// @addtogroup chrono
3431/// @{
3432
3433/// @cond undocumented
3434namespace __detail
3435{
3436 template<typename _Duration = seconds>
3437 struct _Parser
3438 {
3439 static_assert(is_same_v<common_type_t<_Duration, seconds>, _Duration>);
3440
3441 explicit
3442 _Parser(__format::_ChronoParts __need) : _M_need(__need) { }
3443
3444 _Parser(_Parser&&) = delete;
3445 void operator=(_Parser&&) = delete;
3446
3447 _Duration _M_time{}; // since midnight
3448 sys_days _M_sys_days{};
3449 year_month_day _M_ymd{};
3450 weekday _M_wd{};
3451 __format::_ChronoParts _M_need;
3452 unsigned _M_is_leap_second : 1 {};
3453 unsigned _M_reserved : 15 {};
3454
3455 template<typename _CharT, typename _Traits, typename _Alloc>
3456 basic_istream<_CharT, _Traits>&
3457 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3458 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3459 minutes* __offset = nullptr);
3460
3461 private:
3462 // Read an unsigned integer from the stream and return it.
3463 // Extract no more than __n digits. Set failbit if an integer isn't read.
3464 template<typename _CharT, typename _Traits>
3465 static int_least32_t
3466 _S_read_unsigned(basic_istream<_CharT, _Traits>& __is,
3467 ios_base::iostate& __err, int __n)
3468 {
3469 int_least32_t __val = _S_try_read_digit(__is, __err);
3470 if (__val == -1) [[unlikely]]
3471 __err |= ios_base::failbit;
3472 else
3473 {
3474 int __n1 = (std::min)(__n, 9);
3475 // Cannot overflow __val unless we read more than 9 digits
3476 for (int __i = 1; __i < __n1; ++__i)
3477 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
3478 {
3479 __val *= 10;
3480 __val += __dig;
3481 }
3482
3483 while (__n1++ < __n) [[unlikely]]
3484 if (auto __dig = _S_try_read_digit(__is, __err); __dig != -1)
3485 {
3486 if (__builtin_mul_overflow(__val, 10, &__val)
3487 || __builtin_add_overflow(__val, __dig, &__val))
3488 {
3489 __err |= ios_base::failbit;
3490 return -1;
3491 }
3492 }
3493 }
3494 return __val;
3495 }
3496
3497 // Read an unsigned integer from the stream and return it.
3498 // Extract no more than __n digits. Set failbit if an integer isn't read.
3499 template<typename _CharT, typename _Traits>
3500 static int_least32_t
3501 _S_read_signed(basic_istream<_CharT, _Traits>& __is,
3502 ios_base::iostate& __err, int __n)
3503 {
3504 auto __sign = __is.peek();
3505 if (__sign == '-' || __sign == '+')
3506 (void) __is.get();
3507 int_least32_t __val = _S_read_unsigned(__is, __err, __n);
3508 if (__err & ios_base::failbit)
3509 {
3510 if (__sign == '-') [[unlikely]]
3511 __val *= -1;
3512 }
3513 return __val;
3514 }
3515
3516 // Read a digit from the stream and return it, or return -1.
3517 // If no digit is read eofbit will be set (but not failbit).
3518 template<typename _CharT, typename _Traits>
3519 static int_least32_t
3520 _S_try_read_digit(basic_istream<_CharT, _Traits>& __is,
3521 ios_base::iostate& __err)
3522 {
3523 int_least32_t __val = -1;
3524 auto __i = __is.peek();
3525 if (!_Traits::eq_int_type(__i, _Traits::eof())) [[likely]]
3526 {
3527 _CharT __c = _Traits::to_char_type(__i);
3528 if (_CharT('0') <= __c && __c <= _CharT('9')) [[likely]]
3529 {
3530 (void) __is.get();
3531 __val = __c - _CharT('0');
3532 }
3533 }
3534 else
3535 __err |= ios_base::eofbit;
3536 return __val;
3537 }
3538
3539 // Read the specified character and return true.
3540 // If the character is not found, set failbit and return false.
3541 template<typename _CharT, typename _Traits>
3542 static bool
3543 _S_read_chr(basic_istream<_CharT, _Traits>& __is,
3544 ios_base::iostate& __err, _CharT __c)
3545 {
3546 auto __i = __is.peek();
3547 if (_Traits::eq_int_type(__i, _Traits::eof()))
3548 __err |= ios_base::eofbit;
3549 else if (_Traits::to_char_type(__i) == __c) [[likely]]
3550 {
3551 (void) __is.get();
3552 return true;
3553 }
3554 __err |= ios_base::failbit;
3555 return false;
3556 }
3557 };
3558
3559 template<typename _Duration>
3560 using _Parser_t = _Parser<common_type_t<_Duration, seconds>>;
3561
3562 template<typename _Duration>
3563 consteval bool
3564 __use_floor()
3565 {
3566 if constexpr (_Duration::period::den == 1)
3567 {
3568 switch (_Duration::period::num)
3569 {
3570 case minutes::period::num:
3571 case hours::period::num:
3572 case days::period::num:
3573 case weeks::period::num:
3574 case years::period::num:
3575 return true;
3576 }
3577 }
3578 return false;
3579 }
3580
3581 // A "do the right thing" rounding function for duration and time_point
3582 // values extracted by from_stream. When treat_as_floating_point is true
3583 // we don't want to do anything, just a straightforward conversion.
3584 // When the destination type has a period of minutes, hours, days, weeks,
3585 // or years, we use chrono::floor to truncate towards negative infinity.
3586 // This ensures that an extracted timestamp such as 2024-09-05 13:00:00
3587 // will produce 2024-09-05 when rounded to days, rather than rounding up
3588 // to 2024-09-06 (a different day).
3589 // Otherwise, use chrono::round to get the nearest value representable
3590 // in the destination type.
3591 template<typename _ToDur, typename _Tp>
3592 constexpr auto
3593 __round(const _Tp& __t)
3594 {
3595 if constexpr (__is_duration_v<_Tp>)
3596 {
3597 if constexpr (treat_as_floating_point_v<typename _Tp::rep>)
3598 return chrono::duration_cast<_ToDur>(__t);
3599 else if constexpr (__detail::__use_floor<_ToDur>())
3600 return chrono::floor<_ToDur>(__t);
3601 else
3602 return chrono::round<_ToDur>(__t);
3603 }
3604 else
3605 {
3606 static_assert(__is_time_point_v<_Tp>);
3607 using _Tpt = time_point<typename _Tp::clock, _ToDur>;
3608 return _Tpt(__detail::__round<_ToDur>(__t.time_since_epoch()));
3609 }
3610 }
3611
3612 // Format into a stack buffer via std::format_to_n with the empty
3613 // chrono-spec (_S_empty_fs), then write through __ostream_insert.
3614 // The empty spec lets each formatter use its __defSpec, producing
3615 // output equivalent to the corresponding operator<<.
3616 // _BufSize allows per-type tuning of the stack buffer size.
3617 template<size_t _BufSize, typename _CharT, typename _Traits,
3618 typename _Arg, typename... _OptLocale>
3619 inline basic_ostream<_CharT, _Traits>&
3620 __chrono_write(basic_ostream<_CharT, _Traits>& __os,
3621 const _Arg& __arg, const _OptLocale&... __loc)
3622 {
3623 static_assert(sizeof...(_OptLocale) <= 1);
3624 constexpr auto __fs
3625 = __format::__formatter_chrono<_CharT>::_S_empty_fs;
3626 constexpr size_t __bufsize = _BufSize;
3627 _CharT __buf[__bufsize];
3628 auto __res = std::format_to_n(__buf, __bufsize, __loc...,
3629 __fs(), __arg);
3630
3631 if (static_cast<size_t>(__res.size) <= __bufsize) [[likely]]
3632 return std::__ostream_insert(__os, __buf, __res.size);
3633
3634 auto __s = std::format(__loc..., __fs(), __arg);
3635 return std::__ostream_insert(__os, __s.data(), __s.size());
3636 }
3637
3638} // namespace __detail
3639/// @endcond
3640
3641 template<typename _CharT, typename _Traits, typename _Rep, typename _Period,
3642 typename _Alloc = allocator<_CharT>>
3643 inline basic_istream<_CharT, _Traits>&
3644 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3645 duration<_Rep, _Period>& __d,
3646 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3647 minutes* __offset = nullptr)
3648 {
3649 auto __need = __format::_ChronoParts::_TimeOfDay;
3650 __detail::_Parser_t<duration<_Rep, _Period>> __p(__need);
3651 if (__p(__is, __fmt, __abbrev, __offset))
3652 __d = __detail::__round<duration<_Rep, _Period>>(__p._M_time);
3653 return __is;
3654 }
3655
3656 template<typename _CharT, typename _Traits>
3657 inline basic_ostream<_CharT, _Traits>&
3658 operator<<(basic_ostream<_CharT, _Traits>& __os, const day& __d)
3659 { return __detail::__chrono_write<32>(__os, __d); }
3660
3661 template<typename _CharT, typename _Traits,
3662 typename _Alloc = allocator<_CharT>>
3663 inline basic_istream<_CharT, _Traits>&
3664 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3665 day& __d,
3666 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3667 minutes* __offset = nullptr)
3668 {
3669 __detail::_Parser<> __p(__format::_ChronoParts::_Day);
3670 if (__p(__is, __fmt, __abbrev, __offset))
3671 __d = __p._M_ymd.day();
3672 return __is;
3673 }
3674
3675 template<typename _CharT, typename _Traits>
3676 inline basic_ostream<_CharT, _Traits>&
3677 operator<<(basic_ostream<_CharT, _Traits>& __os, const month& __m)
3678 { return __detail::__chrono_write<64>(__os, __m, __os.getloc()); }
3679
3680 template<typename _CharT, typename _Traits,
3681 typename _Alloc = allocator<_CharT>>
3682 inline basic_istream<_CharT, _Traits>&
3683 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3684 month& __m,
3685 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3686 minutes* __offset = nullptr)
3687 {
3688 __detail::_Parser<> __p(__format::_ChronoParts::_Month);
3689 if (__p(__is, __fmt, __abbrev, __offset))
3690 __m = __p._M_ymd.month();
3691 return __is;
3692 }
3693
3694 template<typename _CharT, typename _Traits>
3695 inline basic_ostream<_CharT, _Traits>&
3696 operator<<(basic_ostream<_CharT, _Traits>& __os, const year& __y)
3697 { return __detail::__chrono_write<32>(__os, __y); }
3698
3699 template<typename _CharT, typename _Traits,
3700 typename _Alloc = allocator<_CharT>>
3701 inline basic_istream<_CharT, _Traits>&
3702 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3703 year& __y,
3704 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3705 minutes* __offset = nullptr)
3706 {
3707 __detail::_Parser<> __p(__format::_ChronoParts::_Year);
3708 if (__p(__is, __fmt, __abbrev, __offset))
3709 __y = __p._M_ymd.year();
3710 return __is;
3711 }
3712
3713 template<typename _CharT, typename _Traits>
3714 inline basic_ostream<_CharT, _Traits>&
3715 operator<<(basic_ostream<_CharT, _Traits>& __os, const weekday& __wd)
3716 { return __detail::__chrono_write<64>(__os, __wd, __os.getloc()); }
3717
3718 template<typename _CharT, typename _Traits,
3719 typename _Alloc = allocator<_CharT>>
3720 inline basic_istream<_CharT, _Traits>&
3721 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3722 weekday& __wd,
3723 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3724 minutes* __offset = nullptr)
3725 {
3726 __detail::_Parser<> __p(__format::_ChronoParts::_Weekday);
3727 if (__p(__is, __fmt, __abbrev, __offset))
3728 __wd = __p._M_wd;
3729 return __is;
3730 }
3731
3732 template<typename _CharT, typename _Traits>
3733 inline basic_ostream<_CharT, _Traits>&
3734 operator<<(basic_ostream<_CharT, _Traits>& __os,
3735 const weekday_indexed& __wdi)
3736 { return __detail::__chrono_write<128>(__os, __wdi, __os.getloc()); }
3737
3738 template<typename _CharT, typename _Traits>
3739 inline basic_ostream<_CharT, _Traits>&
3740 operator<<(basic_ostream<_CharT, _Traits>& __os,
3741 const weekday_last& __wdl)
3742 { return __detail::__chrono_write<128>(__os, __wdl, __os.getloc()); }
3743
3744 template<typename _CharT, typename _Traits>
3745 inline basic_ostream<_CharT, _Traits>&
3746 operator<<(basic_ostream<_CharT, _Traits>& __os, const month_day& __md)
3747 { return __detail::__chrono_write<128>(__os, __md, __os.getloc()); }
3748
3749 template<typename _CharT, typename _Traits,
3750 typename _Alloc = allocator<_CharT>>
3751 inline basic_istream<_CharT, _Traits>&
3752 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3753 month_day& __md,
3754 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3755 minutes* __offset = nullptr)
3756 {
3757 using __format::_ChronoParts;
3758 auto __need = _ChronoParts::_Month | _ChronoParts::_Day;
3759 __detail::_Parser<> __p(__need);
3760 if (__p(__is, __fmt, __abbrev, __offset))
3761 __md = month_day(__p._M_ymd.month(), __p._M_ymd.day());
3762 return __is;
3763 }
3764
3765 template<typename _CharT, typename _Traits>
3766 inline basic_ostream<_CharT, _Traits>&
3767 operator<<(basic_ostream<_CharT, _Traits>& __os,
3768 const month_day_last& __mdl)
3769 { return __detail::__chrono_write<128>(__os, __mdl, __os.getloc()); }
3770
3771 template<typename _CharT, typename _Traits>
3772 inline basic_ostream<_CharT, _Traits>&
3773 operator<<(basic_ostream<_CharT, _Traits>& __os,
3774 const month_weekday& __mwd)
3775 { return __detail::__chrono_write<128>(__os, __mwd, __os.getloc()); }
3776
3777 template<typename _CharT, typename _Traits>
3778 inline basic_ostream<_CharT, _Traits>&
3779 operator<<(basic_ostream<_CharT, _Traits>& __os,
3780 const month_weekday_last& __mwdl)
3781 { return __detail::__chrono_write<128>(__os, __mwdl, __os.getloc()); }
3782
3783 template<typename _CharT, typename _Traits>
3784 inline basic_ostream<_CharT, _Traits>&
3785 operator<<(basic_ostream<_CharT, _Traits>& __os, const year_month& __ym)
3786 { return __detail::__chrono_write<128>(__os, __ym, __os.getloc()); }
3787
3788 template<typename _CharT, typename _Traits,
3789 typename _Alloc = allocator<_CharT>>
3790 inline basic_istream<_CharT, _Traits>&
3791 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3792 year_month& __ym,
3793 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3794 minutes* __offset = nullptr)
3795 {
3796 using __format::_ChronoParts;
3797 auto __need = _ChronoParts::_Year | _ChronoParts::_Month;
3798 __detail::_Parser<> __p(__need);
3799 if (__p(__is, __fmt, __abbrev, __offset))
3800 __ym = year_month(__p._M_ymd.year(), __p._M_ymd.month());
3801 return __is;
3802 }
3803
3804 template<typename _CharT, typename _Traits>
3805 inline basic_ostream<_CharT, _Traits>&
3806 operator<<(basic_ostream<_CharT, _Traits>& __os,
3807 const year_month_day& __ymd)
3808 { return __detail::__chrono_write<64>(__os, __ymd); }
3809
3810 template<typename _CharT, typename _Traits,
3811 typename _Alloc = allocator<_CharT>>
3812 inline basic_istream<_CharT, _Traits>&
3813 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3814 year_month_day& __ymd,
3815 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3816 minutes* __offset = nullptr)
3817 {
3818 using __format::_ChronoParts;
3819 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3820 | _ChronoParts::_Day;
3821 __detail::_Parser<> __p(__need);
3822 if (__p(__is, __fmt, __abbrev, __offset))
3823 __ymd = __p._M_ymd;
3824 return __is;
3825 }
3826
3827 template<typename _CharT, typename _Traits>
3828 inline basic_ostream<_CharT, _Traits>&
3829 operator<<(basic_ostream<_CharT, _Traits>& __os,
3830 const year_month_day_last& __ymdl)
3831 { return __detail::__chrono_write<128>(__os, __ymdl, __os.getloc()); }
3832
3833 template<typename _CharT, typename _Traits>
3834 inline basic_ostream<_CharT, _Traits>&
3835 operator<<(basic_ostream<_CharT, _Traits>& __os,
3836 const year_month_weekday& __ymwd)
3837 { return __detail::__chrono_write<128>(__os, __ymwd, __os.getloc()); }
3838
3839 template<typename _CharT, typename _Traits>
3840 inline basic_ostream<_CharT, _Traits>&
3841 operator<<(basic_ostream<_CharT, _Traits>& __os,
3842 const year_month_weekday_last& __ymwdl)
3843 { return __detail::__chrono_write<128>(__os, __ymwdl, __os.getloc()); }
3844
3845 template<typename _CharT, typename _Traits, typename _Duration>
3846 inline basic_ostream<_CharT, _Traits>&
3847 operator<<(basic_ostream<_CharT, _Traits>& __os,
3848 const hh_mm_ss<_Duration>& __hms)
3849 { return __detail::__chrono_write<64>(__os, __hms, __os.getloc()); }
3850
3851#if _GLIBCXX_USE_CXX11_ABI || ! _GLIBCXX_USE_DUAL_ABI
3852 /// Writes a sys_info object to an ostream in an unspecified format.
3853 template<typename _CharT, typename _Traits>
3854 basic_ostream<_CharT, _Traits>&
3855 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_info& __i)
3856 { return __detail::__chrono_write<128>(__os, __i); }
3857
3858 /// Writes a local_info object to an ostream in an unspecified format.
3859 template<typename _CharT, typename _Traits>
3860 basic_ostream<_CharT, _Traits>&
3861 operator<<(basic_ostream<_CharT, _Traits>& __os, const local_info& __li)
3862 { return __detail::__chrono_write<256>(__os, __li); }
3863
3864 template<typename _CharT, typename _Traits, typename _Duration,
3865 typename _TimeZonePtr>
3866 inline basic_ostream<_CharT, _Traits>&
3867 operator<<(basic_ostream<_CharT, _Traits>& __os,
3868 const zoned_time<_Duration, _TimeZonePtr>& __t)
3869 { return __detail::__chrono_write<128>(__os, __t, __os.getloc()); }
3870#endif
3871
3872 template<typename _CharT, typename _Traits, typename _Duration>
3873 requires (!treat_as_floating_point_v<typename _Duration::rep>)
3874 && ratio_less_v<typename _Duration::period, days::period>
3875 inline basic_ostream<_CharT, _Traits>&
3876 operator<<(basic_ostream<_CharT, _Traits>& __os,
3877 const sys_time<_Duration>& __tp)
3878 { return __detail::__chrono_write<64>(__os, __tp, __os.getloc()); }
3879
3880 template<typename _CharT, typename _Traits>
3881 inline basic_ostream<_CharT, _Traits>&
3882 operator<<(basic_ostream<_CharT, _Traits>& __os, const sys_days& __dp)
3883 { return __detail::__chrono_write<32>(__os, __dp); };
3884
3885 template<typename _CharT, typename _Traits, typename _Duration,
3886 typename _Alloc = allocator<_CharT>>
3887 basic_istream<_CharT, _Traits>&
3888 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3889 sys_time<_Duration>& __tp,
3890 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3891 minutes* __offset = nullptr)
3892 {
3893 minutes __off{};
3894 if (!__offset)
3895 __offset = &__off;
3896 using __format::_ChronoParts;
3897 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3898 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3899 __detail::_Parser_t<_Duration> __p(__need);
3900 if (__p(__is, __fmt, __abbrev, __offset))
3901 {
3902 if (__p._M_is_leap_second)
3903 __is.setstate(ios_base::failbit);
3904 else
3905 {
3906 auto __st = __p._M_sys_days + __p._M_time - *__offset;
3907 __tp = __detail::__round<_Duration>(__st);
3908 }
3909 }
3910 return __is;
3911 }
3912
3913 template<typename _CharT, typename _Traits, typename _Duration>
3914 inline basic_ostream<_CharT, _Traits>&
3915 operator<<(basic_ostream<_CharT, _Traits>& __os,
3916 const utc_time<_Duration>& __t)
3917 { return __detail::__chrono_write<64>(__os, __t, __os.getloc()); }
3918
3919 template<typename _CharT, typename _Traits, typename _Duration,
3920 typename _Alloc = allocator<_CharT>>
3921 inline basic_istream<_CharT, _Traits>&
3922 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3923 utc_time<_Duration>& __tp,
3924 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3925 minutes* __offset = nullptr)
3926 {
3927 minutes __off{};
3928 if (!__offset)
3929 __offset = &__off;
3930 using __format::_ChronoParts;
3931 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3932 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3933 __detail::_Parser_t<_Duration> __p(__need);
3934 if (__p(__is, __fmt, __abbrev, __offset))
3935 {
3936 // Converting to utc_time before adding _M_time is necessary for
3937 // "23:59:60" to correctly produce a time within a leap second.
3938 auto __ut = utc_clock::from_sys(__p._M_sys_days) + __p._M_time
3939 - *__offset;
3940 __tp = __detail::__round<_Duration>(__ut);
3941 }
3942 return __is;
3943 }
3944
3945 template<typename _CharT, typename _Traits, typename _Duration>
3946 inline basic_ostream<_CharT, _Traits>&
3947 operator<<(basic_ostream<_CharT, _Traits>& __os,
3948 const tai_time<_Duration>& __t)
3949 { return __detail::__chrono_write<64>(__os, __t, __os.getloc()); }
3950
3951 template<typename _CharT, typename _Traits, typename _Duration,
3952 typename _Alloc = allocator<_CharT>>
3953 inline basic_istream<_CharT, _Traits>&
3954 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3955 tai_time<_Duration>& __tp,
3956 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3957 minutes* __offset = nullptr)
3958 {
3959 minutes __off{};
3960 if (!__offset)
3961 __offset = &__off;
3962 using __format::_ChronoParts;
3963 auto __need = _ChronoParts::_Year | _ChronoParts::_Month
3964 | _ChronoParts::_Day | _ChronoParts::_TimeOfDay;
3965 __detail::_Parser_t<_Duration> __p(__need);
3966 if (__p(__is, __fmt, __abbrev, __offset))
3967 {
3968 if (__p._M_is_leap_second)
3969 __is.setstate(ios_base::failbit);
3970 else
3971 {
3972 constexpr sys_days __epoch(-days(4383)); // 1958y/1/1
3973 auto __d = __p._M_sys_days - __epoch + __p._M_time - *__offset;
3974 tai_time<common_type_t<_Duration, seconds>> __tt(__d);
3975 __tp = __detail::__round<_Duration>(__tt);
3976 }
3977 }
3978 return __is;
3979 }
3980
3981 template<typename _CharT, typename _Traits, typename _Duration>
3982 inline basic_ostream<_CharT, _Traits>&
3983 operator<<(basic_ostream<_CharT, _Traits>& __os,
3984 const gps_time<_Duration>& __t)
3985 { return __detail::__chrono_write<64>(__os, __t, __os.getloc()); }
3986
3987 template<typename _CharT, typename _Traits, typename _Duration,
3988 typename _Alloc = allocator<_CharT>>
3989 inline basic_istream<_CharT, _Traits>&
3990 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
3991 gps_time<_Duration>& __tp,
3992 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
3993 minutes* __offset = nullptr)
3994 {
3995 minutes __off{};
3996 if (!__offset)
3997 __offset = &__off;
3998 using __format::_ChronoParts;
3999 auto __need = _ChronoParts::_YearMonthDay | _ChronoParts::_TimeOfDay;
4000 __detail::_Parser_t<_Duration> __p(__need);
4001 if (__p(__is, __fmt, __abbrev, __offset))
4002 {
4003 if (__p._M_is_leap_second)
4004 __is.setstate(ios_base::failbit);
4005 else
4006 {
4007 constexpr sys_days __epoch(days(3657)); // 1980y/1/Sunday[1]
4008 auto __d = __p._M_sys_days - __epoch + __p._M_time - *__offset;
4009 gps_time<common_type_t<_Duration, seconds>> __gt(__d);
4010 __tp = __detail::__round<_Duration>(__gt);
4011 }
4012 }
4013 return __is;
4014 }
4015
4016 template<typename _CharT, typename _Traits, typename _Duration>
4017 inline basic_ostream<_CharT, _Traits>&
4018 operator<<(basic_ostream<_CharT, _Traits>& __os,
4019 const file_time<_Duration>& __t)
4020 { return __detail::__chrono_write<64>(__os, __t, __os.getloc()); }
4021
4022 template<typename _CharT, typename _Traits, typename _Duration,
4023 typename _Alloc = allocator<_CharT>>
4024 inline basic_istream<_CharT, _Traits>&
4025 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4026 file_time<_Duration>& __tp,
4027 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4028 minutes* __offset = nullptr)
4029 {
4030 sys_time<_Duration> __st;
4031 if (chrono::from_stream(__is, __fmt, __st, __abbrev, __offset))
4032 __tp = __detail::__round<_Duration>(file_clock::from_sys(__st));
4033 return __is;
4034 }
4035
4036 template<typename _CharT, typename _Traits, typename _Duration>
4037 inline basic_ostream<_CharT, _Traits>&
4038 operator<<(basic_ostream<_CharT, _Traits>& __os,
4039 const local_time<_Duration>& __lt)
4040 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4041 // 4257. Stream insertion for chrono::local_time should be constrained
4042 requires requires(const sys_time<_Duration>& __st) { __os << __st; }
4043 { return __detail::__chrono_write<64>(__os, __lt, __os.getloc()); }
4044
4045 template<typename _CharT, typename _Traits, typename _Duration,
4046 typename _Alloc = allocator<_CharT>>
4047 basic_istream<_CharT, _Traits>&
4048 from_stream(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4049 local_time<_Duration>& __tp,
4050 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4051 minutes* __offset = nullptr)
4052 {
4053 using __format::_ChronoParts;
4054 auto __need = _ChronoParts::_YearMonthDay | _ChronoParts::_TimeOfDay;
4055 __detail::_Parser_t<_Duration> __p(__need);
4056 if (__p(__is, __fmt, __abbrev, __offset))
4057 {
4058 days __d = __p._M_sys_days.time_since_epoch();
4059 auto __t = local_days(__d) + __p._M_time; // ignore offset
4060 __tp = __detail::__round<_Duration>(__t);
4061 }
4062 return __is;
4063 }
4064
4065 // [time.parse] parsing
4066
4067namespace __detail
4068{
4069 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4070 // 3956. chrono::parse uses from_stream as a customization point
4071 void from_stream() = delete;
4072
4073 template<typename _Parsable, typename _CharT,
4074 typename _Traits = std::char_traits<_CharT>,
4075 typename... _OptArgs>
4076 concept __parsable = requires (basic_istream<_CharT, _Traits>& __is,
4077 const _CharT* __fmt, _Parsable& __tp,
4078 _OptArgs*... __args)
4079 { from_stream(__is, __fmt, __tp, __args...); };
4080
4081 template<typename _Parsable, typename _CharT,
4082 typename _Traits = char_traits<_CharT>,
4083 typename _Alloc = allocator<_CharT>>
4084 struct _Parse
4085 {
4086 private:
4087 using __string_type = basic_string<_CharT, _Traits, _Alloc>;
4088
4089 public:
4090 _Parse(const _CharT* __fmt, _Parsable& __tp,
4091 basic_string<_CharT, _Traits, _Alloc>* __abbrev = nullptr,
4092 minutes* __offset = nullptr)
4093 : _M_fmt(__fmt), _M_tp(std::__addressof(__tp)),
4094 _M_abbrev(__abbrev), _M_offset(__offset)
4095 { }
4096
4097 _Parse(_Parse&&) = delete;
4098 _Parse& operator=(_Parse&&) = delete;
4099
4100 private:
4101 using __stream_type = basic_istream<_CharT, _Traits>;
4102
4103 const _CharT* const _M_fmt;
4104 _Parsable* const _M_tp;
4105 __string_type* const _M_abbrev;
4106 minutes* const _M_offset;
4107
4108 friend __stream_type&
4109 operator>>(__stream_type& __is, _Parse&& __p)
4110 {
4111 if (__p._M_offset)
4112 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev,
4113 __p._M_offset);
4114 else if (__p._M_abbrev)
4115 from_stream(__is, __p._M_fmt, *__p._M_tp, __p._M_abbrev);
4116 else
4117 from_stream(__is, __p._M_fmt, *__p._M_tp);
4118 return __is;
4119 }
4120
4121 friend void operator>>(__stream_type&, _Parse&) = delete;
4122 friend void operator>>(__stream_type&, const _Parse&) = delete;
4123 };
4124} // namespace __detail
4125
4126 template<typename _CharT, __detail::__parsable<_CharT> _Parsable>
4127 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4128 inline auto
4129 parse(const _CharT* __fmt, _Parsable& __tp)
4130 { return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp); }
4131
4132 template<typename _CharT, typename _Traits, typename _Alloc,
4133 __detail::__parsable<_CharT, _Traits> _Parsable>
4134 [[nodiscard]]
4135 inline auto
4136 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp)
4137 {
4138 return __detail::_Parse<_Parsable, _CharT, _Traits>(__fmt.c_str(), __tp);
4139 }
4140
4141 template<typename _CharT, typename _Traits, typename _Alloc,
4142 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4143 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
4144 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4145 inline auto
4146 parse(const _CharT* __fmt, _Parsable& __tp,
4147 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
4148 {
4149 auto __pa = std::__addressof(__abbrev);
4150 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
4151 __pa);
4152 }
4153
4154 template<typename _CharT, typename _Traits, typename _Alloc,
4155 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4156 __detail::__parsable<_CharT, _Traits, _StrT> _Parsable>
4157 [[nodiscard]]
4158 inline auto
4159 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4160 basic_string<_CharT, _Traits, _Alloc>& __abbrev)
4161 {
4162 auto __pa = std::__addressof(__abbrev);
4163 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4164 __tp, __pa);
4165 }
4166
4167 template<typename _CharT, typename _Traits = char_traits<_CharT>,
4168 typename _StrT = basic_string<_CharT, _Traits>,
4169 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4170 [[nodiscard, __gnu__::__access__(__read_only__, 1)]]
4171 inline auto
4172 parse(const _CharT* __fmt, _Parsable& __tp, minutes& __offset)
4173 {
4174 return __detail::_Parse<_Parsable, _CharT>(__fmt, __tp, nullptr,
4175 &__offset);
4176 }
4177
4178 template<typename _CharT, typename _Traits, typename _Alloc,
4179 typename _StrT = basic_string<_CharT, _Traits>,
4180 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4181 [[nodiscard]]
4182 inline auto
4183 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4184 minutes& __offset)
4185 {
4186 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4187 __tp, nullptr,
4188 &__offset);
4189 }
4190
4191 template<typename _CharT, typename _Traits, typename _Alloc,
4192 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
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,
4197 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
4198 {
4199 auto __pa = std::__addressof(__abbrev);
4200 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt, __tp,
4201 __pa,
4202 &__offset);
4203 }
4204
4205 template<typename _CharT, typename _Traits, typename _Alloc,
4206 typename _StrT = basic_string<_CharT, _Traits, _Alloc>,
4207 __detail::__parsable<_CharT, _Traits, _StrT, minutes> _Parsable>
4208 [[nodiscard]]
4209 inline auto
4210 parse(const basic_string<_CharT, _Traits, _Alloc>& __fmt, _Parsable& __tp,
4211 basic_string<_CharT, _Traits, _Alloc>& __abbrev, minutes& __offset)
4212 {
4213 auto __pa = std::__addressof(__abbrev);
4214 return __detail::_Parse<_Parsable, _CharT, _Traits, _Alloc>(__fmt.c_str(),
4215 __tp, __pa,
4216 &__offset);
4217 }
4218
4219 /// @cond undocumented
4220 template<typename _Duration>
4221 template<typename _CharT, typename _Traits, typename _Alloc>
4222 basic_istream<_CharT, _Traits>&
4223 __detail::_Parser<_Duration>::
4224 operator()(basic_istream<_CharT, _Traits>& __is, const _CharT* __fmt,
4225 basic_string<_CharT, _Traits, _Alloc>* __abbrev,
4226 minutes* __offset)
4227 {
4228 using sentry = typename basic_istream<_CharT, _Traits>::sentry;
4229 ios_base::iostate __err = ios_base::goodbit;
4230 if (sentry __cerb(__is, true); __cerb)
4231 {
4232 locale __loc = __is.getloc();
4233 auto& __tmget = std::use_facet<std::time_get<_CharT>>(__loc);
4234 auto& __tmpunct = std::use_facet<std::__timepunct<_CharT>>(__loc);
4235
4236 // RAII type to save and restore stream state.
4237 struct _Stream_state
4238 {
4239 explicit
4240 _Stream_state(basic_istream<_CharT, _Traits>& __i)
4241 : _M_is(__i),
4242 _M_flags(__i.flags(ios_base::skipws | ios_base::dec)),
4243 _M_w(__i.width(0))
4244 { }
4245
4246 ~_Stream_state()
4247 {
4248 _M_is.flags(_M_flags);
4249 _M_is.width(_M_w);
4250 }
4251
4252 _Stream_state(_Stream_state&&) = delete;
4253
4254 basic_istream<_CharT, _Traits>& _M_is;
4255 ios_base::fmtflags _M_flags;
4256 streamsize _M_w;
4257 };
4258
4259 auto __is_failed = [](ios_base::iostate __e) {
4260 return static_cast<bool>(__e & ios_base::failbit);
4261 };
4262
4263 // Read an unsigned integer from the stream and return it.
4264 // Extract no more than __n digits. Set __err on error.
4265 auto __read_unsigned = [&] (int __n) {
4266 return _S_read_unsigned(__is, __err, __n);
4267 };
4268
4269 // Read a signed integer from the stream and return it.
4270 // Extract no more than __n digits. Set __err on error.
4271 auto __read_signed = [&] (int __n) {
4272 return _S_read_signed(__is, __err, __n);
4273 };
4274
4275 // Read an expected character from the stream.
4276 auto __read_chr = [&__is, &__err] (_CharT __c) {
4277 return _S_read_chr(__is, __err, __c);
4278 };
4279
4280 using __format::_ChronoParts;
4281 _ChronoParts __parts{};
4282
4283 const year __bad_y = --year::min(); // SHRT_MIN
4284 const month __bad_mon(255);
4285 const day __bad_day(255);
4286 const weekday __bad_wday(255);
4287 const hours __bad_h(-1);
4288 const minutes __bad_min(-9999);
4289 const seconds __bad_sec(-1);
4290
4291 year __y = __bad_y, __yy = __bad_y; // %Y, %yy
4292 year __iso_y = __bad_y, __iso_yy = __bad_y; // %G, %g
4293 month __m = __bad_mon; // %m
4294 day __d = __bad_day; // %d
4295 weekday __wday = __bad_wday; // %a %A %u %w
4296 hours __h = __bad_h, __h12 = __bad_h; // %H, %I
4297 minutes __min = __bad_min; // %M
4298 _Duration __s = __bad_sec; // %S
4299 int __ampm = 0; // %p
4300 int __iso_wk = -1, __sunday_wk = -1, __monday_wk = -1; // %V, %U, %W
4301 int __century = -1; // %C
4302 int __dayofyear = -1; // %j (for non-duration)
4303
4304 minutes __tz_offset = __bad_min;
4305 basic_string<_CharT, _Traits> __tz_abbr;
4306
4307 if ((_M_need & _ChronoParts::_TimeOfDay) != 0
4308 && (_M_need & _ChronoParts::_Year) != 0)
4309 {
4310 // For time_points assume "00:00:00" is implicitly present,
4311 // so we don't fail to parse if it's not (PR libstdc++/114240).
4312 // We will still fail to parse if there's no year+month+day.
4313 __h = hours(0);
4314 __parts = _ChronoParts::_TimeOfDay;
4315 }
4316
4317 // bool __is_neg = false; // TODO: how is this handled for parsing?
4318
4319 _CharT __mod{}; // One of 'E' or 'O' or nul.
4320 unsigned __num = 0; // Non-zero for N modifier.
4321 bool __is_flag = false; // True if we're processing a % flag.
4322
4323 constexpr bool __is_floating
4324 = treat_as_floating_point_v<typename _Duration::rep>;
4325
4326 // If an out-of-range value is extracted (e.g. 61min for %M),
4327 // do not set failbit immediately because we might not need it
4328 // (e.g. parsing chrono::year doesn't care about invalid %M values).
4329 // Instead set the variable back to its initial 'bad' state,
4330 // and also set related variables corresponding to the same field
4331 // (e.g. a bad %M value for __min should also reset __h and __s).
4332 // If a valid value is needed later the bad value will cause failure.
4333
4334 // For some fields we don't know the correct range when parsing and
4335 // we have to be liberal in what we accept, e.g. we allow 366 for
4336 // day-of-year because that's valid in leap years, and we allow 31
4337 // for day-of-month. If those values are needed to determine the
4338 // result then we can do a correct range check at the end when we
4339 // know the how many days the relevant year or month actually has.
4340
4341 while (*__fmt)
4342 {
4343 _CharT __c = *__fmt++;
4344 if (!__is_flag)
4345 {
4346 if (__c == '%')
4347 __is_flag = true; // This is the start of a flag.
4348 else if (std::isspace(__c, __loc))
4349 std::ws(__is); // Match zero or more whitespace characters.
4350 else if (!__read_chr(__c)) [[unlikely]]
4351 break; // Failed to match the expected character.
4352
4353 continue; // Process next character in the format string.
4354 }
4355
4356 // Now processing a flag.
4357 switch (__c)
4358 {
4359 case 'a': // Locale's weekday name
4360 case 'A': // (full or abbreviated, matched case-insensitively).
4361 if (__mod || __num) [[unlikely]]
4362 __err = ios_base::failbit;
4363 else
4364 {
4365 struct tm __tm{};
4366 __tmget.get(__is, {}, __is, __err, &__tm,
4367 __fmt - 2, __fmt);
4368 if (!__is_failed(__err))
4369 __wday = weekday(__tm.tm_wday);
4370 }
4371 __parts |= _ChronoParts::_Weekday;
4372 break;
4373
4374 case 'b': // Locale's month name
4375 case 'h': // (full or abbreviated, matched case-insensitively).
4376 case 'B':
4377 if (__mod || __num) [[unlikely]]
4378 __err = ios_base::failbit;
4379 else
4380 {
4381 // strptime behaves differently for %b and %B,
4382 // but chrono::parse says they're equivalent.
4383 // Luckily libstdc++ std::time_get works as needed.
4384 struct tm __tm{};
4385 __tmget.get(__is, {}, __is, __err, &__tm,
4386 __fmt - 2, __fmt);
4387 if (!__is_failed(__err))
4388 __m = month(__tm.tm_mon + 1);
4389 }
4390 __parts |= _ChronoParts::_Month;
4391 break;
4392
4393 case 'c': // Locale's date and time representation.
4394 if (__mod == 'O' || __num) [[unlikely]]
4395 __err |= ios_base::failbit;
4396 else
4397 {
4398 struct tm __tm{};
4399 __tmget.get(__is, {}, __is, __err, &__tm,
4400 __fmt - 2 - (__mod == 'E'), __fmt);
4401 if (!__is_failed(__err))
4402 {
4403 __y = year(__tm.tm_year + 1900);
4404 __m = month(__tm.tm_mon + 1);
4405 __d = day(__tm.tm_mday);
4406 __h = hours(__tm.tm_hour);
4407 __min = minutes(__tm.tm_min);
4408 __s = seconds(__tm.tm_sec);
4409 }
4410 }
4411 __parts |= _ChronoParts::_DateTime;
4412 break;
4413
4414 case 'C': // Century
4415 if (!__mod) [[likely]]
4416 {
4417 auto __v = __read_signed(__num ? __num : 2);
4418 if (!__is_failed(__err))
4419 {
4420 int __cmin = (int)year::min() / 100;
4421 int __cmax = (int)year::max() / 100;
4422 if (__cmin <= __v && __v <= __cmax)
4423 __century = __v * 100;
4424 else
4425 __century = -2; // This prevents guessing century.
4426 }
4427 }
4428 else if (__mod == 'E')
4429 {
4430 struct tm __tm{};
4431 __tmget.get(__is, {}, __is, __err, &__tm,
4432 __fmt - 3, __fmt);
4433 if (!__is_failed(__err))
4434 __century = __tm.tm_year;
4435 }
4436 else [[unlikely]]
4437 __err |= ios_base::failbit;
4438 // N.B. don't set this here: __parts |= _ChronoParts::_Year;
4439 break;
4440
4441 case 'd': // Day of month (1-31)
4442 case 'e':
4443 if (!__mod) [[likely]]
4444 {
4445 auto __v = __read_unsigned(__num ? __num : 2);
4446 if (!__is_failed(__err))
4447 __d = day(__v);
4448 }
4449 else if (__mod == 'O')
4450 {
4451 struct tm __tm{};
4452 __tmget.get(__is, {}, __is, __err, &__tm,
4453 __fmt - 3, __fmt);
4454 if (!__is_failed(__err))
4455 __d = day(__tm.tm_mday);
4456 }
4457 else [[unlikely]]
4458 __err |= ios_base::failbit;
4459 __parts |= _ChronoParts::_Day;
4460 break;
4461
4462 case 'D': // %m/%d/%y
4463 if (__mod || __num) [[unlikely]]
4464 __err |= ios_base::failbit;
4465 else
4466 {
4467 auto __month = __read_unsigned(2); // %m
4468 __read_chr('/');
4469 auto __day = __read_unsigned(2); // %d
4470 __read_chr('/');
4471 auto __year = __read_unsigned(2); // %y
4472 if (__is_failed(__err))
4473 break;
4474 __y = year(__year + 1900 + 100 * int(__year < 69));
4475 __m = month(__month);
4476 __d = day(__day);
4477 if (!year_month_day(__y, __m, __d).ok())
4478 {
4479 __y = __yy = __iso_y = __iso_yy = __bad_y;
4480 __m = __bad_mon;
4481 __d = __bad_day;
4482 break;
4483 }
4484 }
4485 __parts |= _ChronoParts::_Date;
4486 break;
4487
4488 case 'F': // %Y-%m-%d - any N modifier only applies to %Y.
4489 if (__mod) [[unlikely]]
4490 __err |= ios_base::failbit;
4491 else
4492 {
4493 auto __year = __read_signed(__num ? __num : 4); // %Y
4494 __read_chr('-');
4495 auto __month = __read_unsigned(2); // %m
4496 __read_chr('-');
4497 auto __day = __read_unsigned(2); // %d
4498 if (__is_failed(__err))
4499 break;
4500 __y = year(__year);
4501 __m = month(__month);
4502 __d = day(__day);
4503 if (!year_month_day(__y, __m, __d).ok())
4504 {
4505 __y = __yy = __iso_y = __iso_yy = __bad_y;
4506 __m = __bad_mon;
4507 __d = __bad_day;
4508 break;
4509 }
4510 }
4511 __parts |= _ChronoParts::_Date;
4512 break;
4513
4514 case 'g': // Last two digits of ISO week-based year.
4515 if (__mod) [[unlikely]]
4516 __err |= ios_base::failbit;
4517 else
4518 {
4519 auto __val = __read_unsigned(__num ? __num : 2);
4520 if (__val >= 0 && __val <= 99)
4521 {
4522 __iso_yy = year(__val);
4523 if (__century == -1) // No %C has been parsed yet.
4524 __century = 2000;
4525 }
4526 else
4527 __iso_yy = __iso_y = __y = __yy = __bad_y;
4528 }
4529 __parts |= _ChronoParts::_Year;
4530 break;
4531
4532 case 'G': // ISO week-based year.
4533 if (__mod) [[unlikely]]
4534 __err |= ios_base::failbit;
4535 else
4536 __iso_y = year(__read_unsigned(__num ? __num : 4));
4537 __parts |= _ChronoParts::_Year;
4538 break;
4539
4540 case 'H': // 24-hour (00-23)
4541 case 'I': // 12-hour (1-12)
4542 if (__mod == 'E') [[unlikely]]
4543 __err |= ios_base::failbit;
4544 else if (__mod == 'O')
4545 {
4546#if 0
4547 struct tm __tm{};
4548 __tm.tm_ampm = 1;
4549 __tmget.get(__is, {}, __is, __err, &__tm,
4550 __fmt - 3, __fmt);
4551 if (!__is_failed(__err))
4552 {
4553 if (__c == 'I')
4554 {
4555 __h12 = hours(__tm.tm_hour);
4556 __h = __bad_h;
4557 }
4558 else
4559 __h = hours(__tm.tm_hour);
4560 }
4561#else
4562 // XXX %OI seems to be unimplementable.
4563 __err |= ios_base::failbit;
4564#endif
4565 }
4566 else
4567 {
4568 auto __val = __read_unsigned(__num ? __num : 2);
4569 if (__c == 'I' && __val >= 1 && __val <= 12)
4570 {
4571 __h12 = hours(__val);
4572 __h = __bad_h;
4573 }
4574 else if (__c == 'H' && __val >= 0 && __val <= 23)
4575 {
4576 __h = hours(__val);
4577 __h12 = __bad_h;
4578 }
4579 else
4580 {
4581 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4582 __err |= ios_base::failbit;
4583 break;
4584 }
4585 }
4586 __parts |= _ChronoParts::_TimeOfDay;
4587 break;
4588
4589 case 'j': // For duration, count of days, otherwise day of year
4590 if (__mod) [[unlikely]]
4591 __err |= ios_base::failbit;
4592 else if (_M_need == _ChronoParts::_TimeOfDay) // duration
4593 {
4594 auto __val = __read_signed(__num ? __num : 3);
4595 if (!__is_failed(__err))
4596 {
4597 __h = days(__val); // __h will get added to _M_time
4598 __parts |= _ChronoParts::_TimeOfDay;
4599 }
4600 }
4601 else
4602 {
4603 __dayofyear = __read_unsigned(__num ? __num : 3);
4604 // N.B. do not alter __parts here, done after loop.
4605 // No need for range checking here either.
4606 }
4607 break;
4608
4609 case 'm': // Month (1-12)
4610 if (__mod == 'E') [[unlikely]]
4611 __err |= ios_base::failbit;
4612 else if (__mod == 'O')
4613 {
4614 struct tm __tm{};
4615 __tmget.get(__is, {}, __is, __err, &__tm,
4616 __fmt - 2, __fmt);
4617 if (!__is_failed(__err))
4618 __m = month(__tm.tm_mon + 1);
4619 }
4620 else
4621 {
4622 auto __val = __read_unsigned(__num ? __num : 2);
4623 if (__val >= 1 && __val <= 12)
4624 __m = month(__val);
4625 else
4626 __m = __bad_mon;
4627 }
4628 __parts |= _ChronoParts::_Month;
4629 break;
4630
4631 case 'M': // Minutes
4632 if (__mod == 'E') [[unlikely]]
4633 __err |= ios_base::failbit;
4634 else if (__mod == 'O')
4635 {
4636 struct tm __tm{};
4637 __tmget.get(__is, {}, __is, __err, &__tm,
4638 __fmt - 2, __fmt);
4639 if (!__is_failed(__err))
4640 __min = minutes(__tm.tm_min);
4641 }
4642 else
4643 {
4644 auto __val = __read_unsigned(__num ? __num : 2);
4645 if (0 <= __val && __val < 60)
4646 __min = minutes(__val);
4647 else
4648 {
4649 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4650 __err |= ios_base::failbit;
4651 break;
4652 }
4653 }
4654 __parts |= _ChronoParts::_TimeOfDay;
4655 break;
4656
4657 case 'p': // Locale's AM/PM designation for 12-hour clock.
4658 if (__mod || __num)
4659 __err |= ios_base::failbit;
4660 else
4661 {
4662 // Can't use std::time_get here as it can't parse %p
4663 // in isolation without %I. This might be faster anyway.
4664 const _CharT* __ampms[2];
4665 __tmpunct._M_am_pm(__ampms);
4666 int __n = 0, __which = 3;
4667 while (__which != 0)
4668 {
4669 auto __i = __is.peek();
4670 if (_Traits::eq_int_type(__i, _Traits::eof()))
4671 {
4672 __err |= ios_base::eofbit | ios_base::failbit;
4673 break;
4674 }
4675 __i = std::toupper(_Traits::to_char_type(__i), __loc);
4676 if (__which & 1)
4677 {
4678 if (__i != std::toupper(__ampms[0][__n], __loc))
4679 __which ^= 1;
4680 else if (__ampms[0][__n + 1] == _CharT())
4681 {
4682 __which = 1;
4683 (void) __is.get();
4684 break;
4685 }
4686 }
4687 if (__which & 2)
4688 {
4689 if (__i != std::toupper(__ampms[1][__n], __loc))
4690 __which ^= 2;
4691 else if (__ampms[1][__n + 1] == _CharT())
4692 {
4693 __which = 2;
4694 (void) __is.get();
4695 break;
4696 }
4697 }
4698 if (__which)
4699 (void) __is.get();
4700 ++__n;
4701 }
4702 if (__which == 0 || __which == 3)
4703 __err |= ios_base::failbit;
4704 else
4705 __ampm = __which;
4706 }
4707 break;
4708
4709 case 'r': // Locale's 12-hour time.
4710 if (__mod || __num)
4711 __err |= ios_base::failbit;
4712 else
4713 {
4714 struct tm __tm{};
4715 __tmget.get(__is, {}, __is, __err, &__tm,
4716 __fmt - 2, __fmt);
4717 if (!__is_failed(__err))
4718 {
4719 __h = hours(__tm.tm_hour);
4720 __min = minutes(__tm.tm_min);
4721 __s = seconds(__tm.tm_sec);
4722 }
4723 }
4724 __parts |= _ChronoParts::_TimeOfDay;
4725 break;
4726
4727 case 'R': // %H:%M
4728 case 'T': // %H:%M:%S
4729 if (__mod || __num) [[unlikely]]
4730 {
4731 __err |= ios_base::failbit;
4732 break;
4733 }
4734 else
4735 {
4736 auto __val = __read_unsigned(2);
4737 if (__val == -1 || __val > 23) [[unlikely]]
4738 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4739 {
4740 __err |= ios_base::failbit;
4741 break;
4742 }
4743 if (!__read_chr(':')) [[unlikely]]
4744 break;
4745 __h = hours(__val);
4746
4747 __val = __read_unsigned(2);
4748 if (__val == -1 || __val > 60) [[unlikely]]
4749 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4750 {
4751 __err |= ios_base::failbit;
4752 break;
4753 }
4754 __min = minutes(__val);
4755
4756 if (__c == 'R')
4757 {
4758 __parts |= _ChronoParts::_TimeOfDay;
4759 break;
4760 }
4761 else if (!__read_chr(':')) [[unlikely]]
4762 break;
4763 }
4764 [[fallthrough]];
4765
4766 case 'S': // Seconds
4767 if (__mod == 'E') [[unlikely]]
4768 __err |= ios_base::failbit;
4769 else if (__mod == 'O')
4770 {
4771 struct tm __tm{};
4772 __tmget.get(__is, {}, __is, __err, &__tm,
4773 __fmt - 3, __fmt);
4774 if (!__is_failed(__err))
4775 __s = seconds(__tm.tm_sec);
4776 }
4777 else if constexpr (_Duration::period::den == 1
4778 && !__is_floating)
4779 {
4780 auto __val = __read_unsigned(__num ? __num : 2);
4781 if (0 <= __val && __val <= 59) [[likely]]
4782 __s = seconds(__val);
4783 else
4784 {
4785 if ((_M_need & _ChronoParts::_TimeOfDay) != 0)
4786 __err |= ios_base::failbit;
4787 break;
4788 }
4789 }
4790 else // Read fractional seconds
4791 {
4792 stringstream __buf;
4793 auto __digit = _S_try_read_digit(__is, __err);
4794 if (__digit != -1)
4795 {
4796 __buf.put('0' + __digit);
4797 __digit = _S_try_read_digit(__is, __err);
4798 if (__digit != -1)
4799 __buf.put('0' + __digit);
4800 }
4801
4802 auto __i = __is.peek();
4803 if (_Traits::eq_int_type(__i, _Traits::eof()))
4804 __err |= ios_base::eofbit;
4805 else
4806 {
4807 _CharT __dp = '.';
4808 if (__loc != locale::classic())
4809 {
4810 auto& __np = use_facet<numpunct<_CharT>>(__loc);
4811 __dp = __np.decimal_point();
4812 }
4813 _CharT __c = _Traits::to_char_type(__i);
4814 if (__c == __dp)
4815 {
4816 (void) __is.get();
4817 __buf.put('.');
4818 int __prec
4819 = hh_mm_ss<_Duration>::fractional_width;
4820 do
4821 {
4822 __digit = _S_try_read_digit(__is, __err);
4823 if (__digit != -1)
4824 __buf.put('0' + __digit);
4825 else
4826 break;
4827 }
4828 while (--__prec);
4829 }
4830 }
4831
4832 if (!__is_failed(__err)) [[likely]]
4833 {
4834 long double __val{};
4835#if __cpp_lib_to_chars
4836 string __str = std::move(__buf).str();
4837 auto __first = __str.data();
4838 auto __last = __first + __str.size();
4839 using enum chars_format;
4840 auto [ptr, ec] = std::from_chars(__first, __last,
4841 __val, fixed);
4842 if ((bool)ec || ptr != __last) [[unlikely]]
4843 __err |= ios_base::failbit;
4844 else
4845#else
4846 if (__buf >> __val)
4847#endif
4848 {
4849 duration<long double> __fs(__val);
4850 if constexpr (__is_floating)
4851 __s = __fs;
4852 else
4853 __s = chrono::round<_Duration>(__fs);
4854 }
4855 }
4856 }
4857 __parts |= _ChronoParts::_TimeOfDay;
4858 break;
4859
4860 case 'u': // ISO weekday (1-7)
4861 case 'w': // Weekday (0-6)
4862 if (__mod == 'E') [[unlikely]]
4863 __err |= ios_base::failbit;
4864 else if (__mod == 'O')
4865 {
4866 if (__c == 'w')
4867 {
4868 struct tm __tm{};
4869 __tmget.get(__is, {}, __is, __err, &__tm,
4870 __fmt - 3, __fmt);
4871 if (!__is_failed(__err))
4872 __wday = weekday(__tm.tm_wday);
4873 }
4874 else
4875 __err |= ios_base::failbit;
4876 }
4877 else
4878 {
4879 const int __lo = __c == 'u' ? 1 : 0;
4880 const int __hi = __lo + 6;
4881 auto __val = __read_unsigned(__num ? __num : 1);
4882 if (__lo <= __val && __val <= __hi)
4883 __wday = weekday(__val);
4884 else
4885 {
4886 __wday = __bad_wday;
4887 break;
4888 }
4889 }
4890 __parts |= _ChronoParts::_Weekday;
4891 break;
4892
4893 case 'U': // Week number of the year (from first Sunday).
4894 case 'V': // ISO week-based week number.
4895 case 'W': // Week number of the year (from first Monday).
4896 if (__mod == 'E') [[unlikely]]
4897 __err |= ios_base::failbit;
4898 else if (__mod == 'O')
4899 {
4900 if (__c == 'V') [[unlikely]]
4901 __err |= ios_base::failbit;
4902 else
4903 {
4904 // TODO nl_langinfo_l(ALT_DIGITS) ?
4905 // Not implementable using std::time_get.
4906 }
4907 }
4908 else
4909 {
4910 const int __lo = __c == 'V' ? 1 : 0;
4911 const int __hi = 53;
4912 auto __val = __read_unsigned(__num ? __num : 2);
4913 if (__lo <= __val && __val <= __hi)
4914 {
4915 switch (__c)
4916 {
4917 case 'U':
4918 __sunday_wk = __val;
4919 break;
4920 case 'V':
4921 __iso_wk = __val;
4922 break;
4923 case 'W':
4924 __monday_wk = __val;
4925 break;
4926 }
4927 }
4928 else
4929 __iso_wk = __sunday_wk = __monday_wk = -1;
4930 }
4931 // N.B. do not alter __parts here, done after loop.
4932 break;
4933
4934 case 'x': // Locale's date representation.
4935 if (__mod == 'O' || __num) [[unlikely]]
4936 __err |= ios_base::failbit;
4937 else
4938 {
4939 struct tm __tm{};
4940 __tmget.get(__is, {}, __is, __err, &__tm,
4941 __fmt - 2 - (__mod == 'E'), __fmt);
4942 if (!__is_failed(__err))
4943 {
4944 __y = year(__tm.tm_year + 1900);
4945 __m = month(__tm.tm_mon + 1);
4946 __d = day(__tm.tm_mday);
4947 }
4948 }
4949 __parts |= _ChronoParts::_Date;
4950 break;
4951
4952 case 'X': // Locale's time representation.
4953 if (__mod == 'O' || __num) [[unlikely]]
4954 __err |= ios_base::failbit;
4955 else
4956 {
4957 struct tm __tm{};
4958 __tmget.get(__is, {}, __is, __err, &__tm,
4959 __fmt - 2 - (__mod == 'E'), __fmt);
4960 if (!__is_failed(__err))
4961 {
4962 __h = hours(__tm.tm_hour);
4963 __min = minutes(__tm.tm_min);
4964 __s = seconds(__tm.tm_sec);
4965 }
4966 }
4967 __parts |= _ChronoParts::_TimeOfDay;
4968 break;
4969
4970 case 'y': // Last two digits of year.
4971 if (__mod) [[unlikely]]
4972 {
4973 struct tm __tm{};
4974 __tmget.get(__is, {}, __is, __err, &__tm,
4975 __fmt - 3, __fmt);
4976 if (!__is_failed(__err))
4977 {
4978 int __cent = __tm.tm_year < 2000 ? 1900 : 2000;
4979 __yy = year(__tm.tm_year - __cent);
4980 if (__century == -1) // No %C has been parsed yet.
4981 __century = __cent;
4982 }
4983 }
4984 else
4985 {
4986 auto __val = __read_unsigned(__num ? __num : 2);
4987 if (__val >= 0 && __val <= 99)
4988 {
4989 __yy = year(__val);
4990 if (__century == -1) // No %C has been parsed yet.
4991 __century = __val < 69 ? 2000 : 1900;
4992 }
4993 else
4994 __y = __yy = __iso_yy = __iso_y = __bad_y;
4995 }
4996 __parts |= _ChronoParts::_Year;
4997 break;
4998
4999 case 'Y': // Year
5000 if (__mod == 'O') [[unlikely]]
5001 __err |= ios_base::failbit;
5002 else if (__mod == 'E')
5003 {
5004 struct tm __tm{};
5005 __tmget.get(__is, {}, __is, __err, &__tm,
5006 __fmt - 3, __fmt);
5007 if (!__is_failed(__err))
5008 __y = year(__tm.tm_year);
5009 }
5010 else
5011 {
5012 auto __val = __read_unsigned(__num ? __num : 4);
5013 if (!__is_failed(__err))
5014 __y = year(__val);
5015 }
5016 __parts |= _ChronoParts::_Year;
5017 break;
5018
5019 case 'z':
5020 if (__num) [[unlikely]]
5021 __err |= ios_base::failbit;
5022 else
5023 {
5024 // For %Ez and %Oz read [+|-][h]h[:mm].
5025 // For %z read [+|-]hh[mm].
5026
5027 auto __i = __is.peek();
5028 if (_Traits::eq_int_type(__i, _Traits::eof()))
5029 {
5030 __err |= ios_base::eofbit | ios_base::failbit;
5031 break;
5032 }
5033 _CharT __ic = _Traits::to_char_type(__i);
5034 const bool __neg = __ic == _CharT('-');
5035 if (__ic == _CharT('-') || __ic == _CharT('+'))
5036 (void) __is.get();
5037
5038 int_least32_t __hh;
5039 if (__mod)
5040 {
5041 // Read h[h]
5042 __hh = __read_unsigned(2);
5043 }
5044 else
5045 {
5046 // Read hh
5047 auto __d1 = _S_try_read_digit(__is, __err);
5048 auto __d2 = _S_try_read_digit(__is, __err);
5049 if (__d1 >= 0 && __d2 >= 0) [[likely]]
5050 __hh = 10 * __d1 + __d2;
5051 else
5052 __err |= ios_base::failbit;
5053 }
5054
5055 if (__is_failed(__err))
5056 break;
5057
5058 __i = __is.peek();
5059 if (_Traits::eq_int_type(__i, _Traits::eof()))
5060 {
5061 __err |= ios_base::eofbit;
5062 __tz_offset = minutes(__hh * (__neg ? -60 : 60));
5063 break;
5064 }
5065 __ic = _Traits::to_char_type(__i);
5066
5067 bool __read_mm = false;
5068 if (__mod)
5069 {
5070 if (__ic == _GLIBCXX_WIDEN(":")[0])
5071 {
5072 // Read [:mm] part.
5073 (void) __is.get();
5074 __read_mm = true;
5075 }
5076 }
5077 else if (_CharT('0') <= __ic && __ic <= _CharT('9'))
5078 {
5079 // Read [mm] part.
5080 __read_mm = true;
5081 }
5082
5083 int_least32_t __mm = 0;
5084 if (__read_mm)
5085 {
5086 auto __d1 = _S_try_read_digit(__is, __err);
5087 auto __d2 = _S_try_read_digit(__is, __err);
5088 if (__d1 >= 0 && __d2 >= 0) [[likely]]
5089 __mm = 10 * __d1 + __d2;
5090 else
5091 __err |= ios_base::failbit;
5092 }
5093
5094 if (!__is_failed(__err))
5095 {
5096 auto __z = __hh * 60 + __mm;
5097 __tz_offset = minutes(__neg ? -__z : __z);
5098 }
5099 }
5100 break;
5101
5102 case 'Z':
5103 if (__mod || __num) [[unlikely]]
5104 __err |= ios_base::failbit;
5105 else
5106 {
5107 basic_string_view<_CharT> __x = _GLIBCXX_WIDEN("_/-+");
5108 __tz_abbr.clear();
5109 while (true)
5110 {
5111 auto __i = __is.peek();
5112 if (!_Traits::eq_int_type(__i, _Traits::eof()))
5113 {
5114 _CharT __a = _Traits::to_char_type(__i);
5115 if (std::isalnum(__a, __loc)
5116 || __x.find(__a) != __x.npos)
5117 {
5118 __tz_abbr.push_back(__a);
5119 (void) __is.get();
5120 continue;
5121 }
5122 }
5123 else
5124 __err |= ios_base::eofbit;
5125 break;
5126 }
5127 if (__tz_abbr.empty())
5128 __err |= ios_base::failbit;
5129 }
5130 break;
5131
5132 case 'n': // Exactly one whitespace character.
5133 if (__mod || __num) [[unlikely]]
5134 __err |= ios_base::failbit;
5135 else
5136 {
5137 _CharT __i = __is.peek();
5138 if (_Traits::eq_int_type(__i, _Traits::eof()))
5139 __err |= ios_base::eofbit | ios_base::failbit;
5140 else if (std::isspace(_Traits::to_char_type(__i), __loc))
5141 (void) __is.get();
5142 else
5143 __err |= ios_base::failbit;
5144 }
5145 break;
5146
5147 case 't': // Zero or one whitespace characters.
5148 if (__mod || __num) [[unlikely]]
5149 __err |= ios_base::failbit;
5150 else
5151 {
5152 _CharT __i = __is.peek();
5153 if (_Traits::eq_int_type(__i, _Traits::eof()))
5154 __err |= ios_base::eofbit;
5155 else if (std::isspace(_Traits::to_char_type(__i), __loc))
5156 (void) __is.get();
5157 }
5158 break;
5159
5160 case '%': // A % character.
5161 if (__mod || __num) [[unlikely]]
5162 __err |= ios_base::failbit;
5163 else
5164 __read_chr('%');
5165 break;
5166
5167 case 'O': // Modifiers
5168 case 'E':
5169 if (__mod || __num) [[unlikely]]
5170 {
5171 __err |= ios_base::failbit;
5172 break;
5173 }
5174 __mod = __c;
5175 continue;
5176
5177 default:
5178 if (_CharT('1') <= __c && __c <= _CharT('9'))
5179 {
5180 if (!__mod) [[likely]]
5181 {
5182 // %Nx - extract positive decimal integer N
5183 auto __end = __fmt + _Traits::length(__fmt);
5184 auto [__v, __ptr]
5185 = __format::__parse_integer(__fmt - 1, __end);
5186 if (__ptr) [[likely]]
5187 {
5188 __num = __v;
5189 __fmt = __ptr;
5190 continue;
5191 }
5192 }
5193 }
5194 __err |= ios_base::failbit;
5195 }
5196
5197 if (__is_failed(__err)) [[unlikely]]
5198 break;
5199
5200 __is_flag = false;
5201 __num = 0;
5202 __mod = _CharT();
5203 }
5204
5205 if (__century >= 0)
5206 {
5207 if (__yy != __bad_y && __y == __bad_y)
5208 __y = years(__century) + __yy; // Use %y instead of %Y
5209 if (__iso_yy != __bad_y && __iso_y == __bad_y)
5210 __iso_y = years(__century) + __iso_yy; // Use %g instead of %G
5211 }
5212
5213 bool __can_use_doy = false;
5214 bool __can_use_iso_wk = false;
5215 bool __can_use_sun_wk = false;
5216 bool __can_use_mon_wk = false;
5217
5218 // A year + day-of-year can be converted to a full date.
5219 if (__y != __bad_y && __dayofyear >= 0)
5220 {
5221 __can_use_doy = true;
5222 __parts |= _ChronoParts::_Date;
5223 }
5224 else if (__y != __bad_y && __wday != __bad_wday && __sunday_wk >= 0)
5225 {
5226 __can_use_sun_wk = true;
5227 __parts |= _ChronoParts::_Date;
5228 }
5229 else if (__y != __bad_y && __wday != __bad_wday && __monday_wk >= 0)
5230 {
5231 __can_use_mon_wk = true;
5232 __parts |= _ChronoParts::_Date;
5233 }
5234 else if (__iso_y != __bad_y && __wday != __bad_wday && __iso_wk > 0)
5235 {
5236 // An ISO week date can be converted to a full date.
5237 __can_use_iso_wk = true;
5238 __parts |= _ChronoParts::_Date;
5239 }
5240
5241 if (__is_failed(__err)) [[unlikely]]
5242 ; // Don't bother doing any more work.
5243 else if (__is_flag) [[unlikely]] // incomplete format flag
5244 __err |= ios_base::failbit;
5245 else if ((_M_need & __parts) == _M_need) [[likely]]
5246 {
5247 // We try to avoid calculating _M_sys_days and _M_ymd unless
5248 // necessary, because converting sys_days to year_month_day
5249 // (or vice versa) requires non-trivial calculations.
5250 // If we have y/m/d values then use them to populate _M_ymd
5251 // and only convert it to _M_sys_days if the caller needs that.
5252 // But if we don't have y/m/d and need to calculate the date
5253 // from the day-of-year or a week+weekday then we set _M_sys_days
5254 // and only convert it to _M_ymd if the caller needs that.
5255
5256 // We do more error checking here, but only for the fields that
5257 // we actually need to use. For example, we will not diagnose
5258 // an invalid dayofyear==366 for non-leap years unless actually
5259 // using __dayofyear. This should mean we never produce invalid
5260 // results, but it means not all invalid inputs are diagnosed,
5261 // e.g. "2023-01-01 366" >> "%F %j" ignores the invalid 366.
5262 // We also do not diagnose inconsistent values for the same
5263 // field, e.g. "2021 2022 2023" >> "%C%y %Y %Y" just uses 2023.
5264
5265 // Whether the caller wants _M_wd.
5266 // The _Weekday bit is only set for chrono::weekday.
5267 const bool __need_wday = (_M_need & _ChronoParts::_Weekday) != 0;
5268
5269 // Whether the caller wants _M_sys_days and _M_time.
5270 // Only true for durations and time_points.
5271 const bool __need_time = (_M_need & _ChronoParts::_TimeOfDay) != 0;
5272
5273 if (__need_wday && __wday != __bad_wday)
5274 _M_wd = __wday; // Caller only wants a weekday and we have one.
5275 else if ((_M_need & _ChronoParts::_Date) != 0) // subsumes __need_wday
5276 {
5277 // Whether the caller wants _M_ymd.
5278 // True for chrono::year etc., false for time_points.
5279 const bool __need_ymd = !__need_wday && !__need_time;
5280
5281 if (((_M_need & _ChronoParts::_Year) != 0 && __y == __bad_y)
5282 || ((_M_need & _ChronoParts::_Month) != 0 && __m == __bad_mon)
5283 || ((_M_need & _ChronoParts::_Day) != 0 && __d == __bad_day))
5284 {
5285 // Missing at least one of y/m/d so calculate sys_days
5286 // from the other data we have available.
5287
5288 if (__can_use_doy)
5289 {
5290 if ((0 < __dayofyear && __dayofyear <= 365)
5291 || (__dayofyear == 366 && __y.is_leap()))
5292 [[likely]]
5293 {
5294 _M_sys_days = sys_days(__y/January/1)
5295 + days(__dayofyear - 1);
5296 if (__need_ymd)
5297 _M_ymd = year_month_day(_M_sys_days);
5298 }
5299 else
5300 __err |= ios_base::failbit;
5301 }
5302 else if (__can_use_iso_wk)
5303 {
5304 // Calculate y/m/d from ISO week date.
5305
5306 if (__iso_wk == 53)
5307 {
5308 // A year has 53 weeks iff Jan 1st is a Thursday
5309 // or Jan 1 is a Wednesday and it's a leap year.
5310 const sys_days __jan4(__iso_y/January/4);
5311 weekday __wd1(__jan4 - days(3));
5312 if (__wd1 != Thursday)
5313 if (__wd1 != Wednesday || !__iso_y.is_leap())
5314 __err |= ios_base::failbit;
5315 }
5316
5317 if (!__is_failed(__err)) [[likely]]
5318 {
5319 // First Thursday is always in week one:
5320 sys_days __w(Thursday[1]/January/__iso_y);
5321 // First day of week-based year:
5322 __w -= Thursday - Monday;
5323 __w += days(weeks(__iso_wk - 1));
5324 __w += __wday - Monday;
5325 _M_sys_days = __w;
5326
5327 if (__need_ymd)
5328 _M_ymd = year_month_day(_M_sys_days);
5329 }
5330 }
5331 else if (__can_use_sun_wk)
5332 {
5333 // Calculate y/m/d from week number + weekday.
5334 sys_days __wk1(__y/January/Sunday[1]);
5335 _M_sys_days = __wk1 + weeks(__sunday_wk - 1)
5336 + days(__wday.c_encoding());
5337 _M_ymd = year_month_day(_M_sys_days);
5338 if (_M_ymd.year() != __y) [[unlikely]]
5339 __err |= ios_base::failbit;
5340 }
5341 else if (__can_use_mon_wk)
5342 {
5343 // Calculate y/m/d from week number + weekday.
5344 sys_days __wk1(__y/January/Monday[1]);
5345 _M_sys_days = __wk1 + weeks(__monday_wk - 1)
5346 + days(__wday.c_encoding() - 1);
5347 _M_ymd = year_month_day(_M_sys_days);
5348 if (_M_ymd.year() != __y) [[unlikely]]
5349 __err |= ios_base::failbit;
5350 }
5351 else // Should not be able to get here.
5352 __err |= ios_base::failbit;
5353 }
5354 else
5355 {
5356 // We know that all fields the caller needs are present,
5357 // but check that their values are in range.
5358 // Make unwanted fields valid so that _M_ymd.ok() is true.
5359
5360 if ((_M_need & _ChronoParts::_Year) != 0)
5361 {
5362 if (!__y.ok()) [[unlikely]]
5363 __err |= ios_base::failbit;
5364 }
5365 else if (__y == __bad_y)
5366 __y = 1972y; // Leap year so that Feb 29 is valid.
5367
5368 if ((_M_need & _ChronoParts::_Month) != 0)
5369 {
5370 if (!__m.ok()) [[unlikely]]
5371 __err |= ios_base::failbit;
5372 }
5373 else if (__m == __bad_mon)
5374 __m = January;
5375
5376 if ((_M_need & _ChronoParts::_Day) != 0)
5377 {
5378 if (__d < day(1) || __d > (__y/__m/last).day())
5379 __err |= ios_base::failbit;
5380 }
5381 else if (__d == __bad_day)
5382 __d = 1d;
5383
5384 if (year_month_day __ymd(__y, __m, __d); __ymd.ok())
5385 {
5386 _M_ymd = __ymd;
5387 if (__need_wday || __need_time)
5388 _M_sys_days = sys_days(_M_ymd);
5389 }
5390 else [[unlikely]]
5391 __err |= ios_base::failbit;
5392 }
5393
5394 if (__need_wday)
5395 _M_wd = weekday(_M_sys_days);
5396 }
5397
5398 // Need to set _M_time for both durations and time_points.
5399 if (__need_time)
5400 {
5401 if (__h == __bad_h && __h12 != __bad_h)
5402 {
5403 if (__ampm == 1)
5404 __h = __h12 == hours(12) ? hours(0) : __h12;
5405 else if (__ampm == 2)
5406 __h = __h12 == hours(12) ? __h12 : __h12 + hours(12);
5407 else [[unlikely]]
5408 __err |= ios_base::failbit;
5409 }
5410
5411 auto __t = _M_time.zero();
5412 bool __ok = false;
5413
5414 if (__h != __bad_h)
5415 {
5416 __ok = true;
5417 __t += __h;
5418 }
5419
5420 if (__min != __bad_min)
5421 {
5422 __ok = true;
5423 __t += __min;
5424 }
5425
5426 if (__s != __bad_sec)
5427 {
5428 __ok = true;
5429 __t += __s;
5430 _M_is_leap_second = __s >= seconds(60);
5431 }
5432
5433 if (__ok)
5434 _M_time = __t;
5435 else
5436 __err |= ios_base::failbit;
5437 }
5438
5439 if (!__is_failed(__err)) [[likely]]
5440 {
5441 if (__offset && __tz_offset != __bad_min)
5442 *__offset = __tz_offset;
5443 if (__abbrev && !__tz_abbr.empty())
5444 *__abbrev = std::move(__tz_abbr);
5445 }
5446 }
5447 else
5448 __err |= ios_base::failbit;
5449 }
5450 if (__err)
5451 __is.setstate(__err);
5452 return __is;
5453 }
5454 /// @endcond
5455#undef _GLIBCXX_WIDEN
5456
5457 /// @} group chrono
5458} // namespace chrono
5459
5460_GLIBCXX_END_NAMESPACE_VERSION
5461} // namespace std
5462
5463#endif // C++20
5464
5465#endif //_GLIBCXX_CHRONO_IO_H
charconv
format
sstream
stdexcept
unique_ptr.h
streambuf_iterator.h
std::chrono::local_time_format
__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
std::chrono::weeks
duration< int64_t, ratio< 604800 > > weeks
weeks
Definition chrono.h:918
std::chrono::floor
constexpr __enable_if_is_duration< _ToDur > floor(const duration< _Rep, _Period > &__d)
Definition chrono.h:392
std::chrono::round
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
std::chrono::days
duration< int64_t, ratio< 86400 > > days
days
Definition chrono.h:915
std::chrono::years
duration< int64_t, ratio< 31556952 > > years
years
Definition chrono.h:921
std::chrono::hours
duration< int64_t, ratio< 3600 > > hours
hours
Definition chrono.h:911
std::chrono::minutes
duration< int64_t, ratio< 60 > > minutes
minutes
Definition chrono.h:908
std::chrono::operator<<
basic_ostream< _CharT, _Traits > & operator<<(std::basic_ostream< _CharT, _Traits > &__os, const duration< _Rep, _Period > &__d)
Definition chrono_io.h:129
std::chrono::seconds
duration< int64_t > seconds
seconds
Definition chrono.h:905
std::chrono::duration_cast
constexpr __enable_if_is_duration< _ToDur > duration_cast(const duration< _Rep, _Period > &__d)
Definition chrono.h:279
std::operator-
constexpr complex< _Tp > operator-(const complex< _Tp > &__x, const complex< _Tp > &__y)
Return new complex value x minus y.
Definition complex:404
std::stringstream
basic_stringstream< char > stringstream
Class for char mixed input and output memory streams.
Definition iosfwd_string.h:81
std::move
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
std::__addressof
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition move.h:52
std::min
constexpr const _Tp & min(const _Tp &, const _Tp &)
This does what you think it does.
Definition stl_algobase.h:232
std::use_facet
const _Facet & use_facet(const locale &__loc)
Return a facet.
Definition locale_classes.tcc:220
std
ISO C++ entities toplevel namespace is std.
std::streamsize
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:73
std::chars_format
chars_format
floating-point format for primitive numerical conversion
Definition charconv:631
std::isspace
bool isspace(_CharT __c, const locale &__loc)
Convenience interface to ctype.is(ctype_base::space, __c).
Definition locale_facets.h:2613
std::toupper
_CharT toupper(_CharT __c, const locale &__loc)
Convenience interface to ctype.toupper(__c).
Definition locale_facets.h:2687
std::isalnum
bool isalnum(_CharT __c, const locale &__loc)
Convenience interface to ctype.is(ctype_base::alnum, __c).
Definition locale_facets.h:2667
std::dec
ios_base & dec(ios_base &__base)
Calls base.setf(ios_base::dec, ios_base::basefield).
Definition ios_base.h:1094
std::skipws
ios_base & skipws(ios_base &__base)
Calls base.setf(ios_base::skipws).
Definition ios_base.h:1020
std::fixed
ios_base & fixed(ios_base &__base)
Calls base.setf(ios_base::fixed, ios_base::floatfield).
Definition ios_base.h:1119
std::operator|
constexpr bitset< _Nb > operator|(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1672
std::ws
basic_istream< _CharT, _Traits > & ws(basic_istream< _CharT, _Traits > &__is)
Quick and easy way to eat whitespace.
Definition istream.tcc:1078
std::operator&
constexpr bitset< _Nb > operator&(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1662
std::from_chars
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
std::chrono
ISO C++ 2011 namespace for date and time utilities.
std::chrono::hh_mm_ss
Definition chrono:2337
std::basic_istream
Template class basic_istream.
Definition istream:73
std::ratio
Provides compile-time rational arithmetic.
Definition ratio:272
std::basic_ostringstream
Controlling output for std::string.
Definition sstream:876
std::basic_string_view
A non-owning reference to a string.
Definition string_view:114
std::basic_ios::imbue
locale imbue(const locale &__loc)
Moves to a new locale.
Definition basic_ios.tcc:119
std::basic_string
Managing sequences of characters and character-like objects.
Definition basic_string.h:94
std::chrono::duration
chrono::duration represents a distance between two points in time
Definition chrono.h:516
std::ios_base::iostate
_Ios_Iostate iostate
This is a bitmask type.
Definition ios_base.h:453
std::ios_base::precision
streamsize precision() const
Flags access.
Definition ios_base.h:765
std::ios_base::flags
fmtflags flags() const
Access to format flags.
Definition ios_base.h:694
std::ios_base::eofbit
static const iostate eofbit
Indicates that an input operation reached the end of an input sequence.
Definition ios_base.h:460
std::ios_base::goodbit
static const iostate goodbit
Indicates all is well.
Definition ios_base.h:468
std::ios_base::getloc
locale getloc() const
Locale access.
Definition ios_base.h:841
std::ios_base::failbit
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
std::basic_ostream
Template class basic_ostream.
Definition ostream.h:72
std::ostreambuf_iterator
Provides output iterator semantics for streambufs.
Definition streambuf_iterator.h:249
std::locale::classic
static const locale & classic()
Return reference to the C locale.