libstdc++: Fix incorrect PR number in comment
[official-gcc.git] / libstdc++-v3 / include / std / format
blob7440a25ea97e4922f868d4fd842bd851faaa208f
1 // <format> Formatting -*- C++ -*-
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.
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.
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.
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/>.
25 /** @file include/format
26  *  This is a Standard C++ Library header.
27  */
29 #ifndef _GLIBCXX_FORMAT
30 #define _GLIBCXX_FORMAT 1
32 #pragma GCC system_header
34 #include <bits/requires_hosted.h> // for std::string
36 #define __glibcxx_want_format
37 #define __glibcxx_want_format_ranges
38 #define __glibcxx_want_format_uchar
39 #include <bits/version.h>
41 #ifdef __cpp_lib_format // C++ >= 20 && HOSTED
43 #include <array>
44 #include <charconv>
45 #include <concepts>
46 #include <limits>
47 #include <locale>
48 #include <optional>
49 #include <span>
50 #include <string_view>
51 #include <string>
52 #include <variant>             // monostate (TODO: move to bits/utility.h?)
53 #include <bits/ranges_base.h>  // input_range, range_reference_t
54 #include <bits/ranges_util.h>  // subrange
55 #include <bits/ranges_algobase.h> // ranges::copy
56 #include <bits/stl_iterator.h> // back_insert_iterator
57 #include <bits/stl_pair.h>     // __is_pair
58 #include <bits/unicode.h>      // __is_scalar_value, _Utf_view, etc.
59 #include <bits/utility.h>      // tuple_size_v
60 #include <ext/numeric_traits.h> // __int_traits
62 #if !__has_builtin(__builtin_toupper)
63 # include <cctype>
64 #endif
66 namespace std _GLIBCXX_VISIBILITY(default)
68 _GLIBCXX_BEGIN_NAMESPACE_VERSION
70   // [format.context], class template basic_format_context
71   template<typename _Out, typename _CharT> class basic_format_context;
73 /// @cond undocumented
74 namespace __format
76   // Type-erased character sink.
77   template<typename _CharT> class _Sink;
78   // Output iterator that writes to a type-erase character sink.
79   template<typename _CharT>
80     class _Sink_iter;
82   template<typename _CharT>
83     using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
85   template<typename _CharT>
86     struct _Runtime_format_string { basic_string_view<_CharT> _M_str; };
87 } // namespace __format
88 /// @endcond
90   using format_context  = __format::__format_context<char>;
91 #ifdef _GLIBCXX_USE_WCHAR_T
92   using wformat_context = __format::__format_context<wchar_t>;
93 #endif
95   // [format.args], class template basic_format_args
96   template<typename _Context> class basic_format_args;
97   using format_args = basic_format_args<format_context>;
98 #ifdef _GLIBCXX_USE_WCHAR_T
99   using wformat_args = basic_format_args<wformat_context>;
100 #endif
102   // [format.arguments], arguments
103   // [format.arg], class template basic_format_arg
104   template<typename _Context>
105     class basic_format_arg;
107   // [format.fmt.string], class template basic_format_string
109   /** A compile-time checked format string for the specified argument types.
110    *
111    * @since C++23 but available as an extension in C++20.
112    */
113   template<typename _CharT, typename... _Args>
114     struct basic_format_string
115     {
116       template<typename _Tp>
117         requires convertible_to<const _Tp&, basic_string_view<_CharT>>
118         consteval
119         basic_format_string(const _Tp& __s);
121       [[__gnu__::__always_inline__]]
122       basic_format_string(__format::_Runtime_format_string<_CharT>&& __s)
123       : _M_str(__s._M_str)
124       { }
126       [[__gnu__::__always_inline__]]
127       constexpr basic_string_view<_CharT>
128       get() const noexcept
129       { return _M_str; }
131     private:
132       basic_string_view<_CharT> _M_str;
133     };
135   template<typename... _Args>
136     using format_string = basic_format_string<char, type_identity_t<_Args>...>;
138 #ifdef _GLIBCXX_USE_WCHAR_T
139   template<typename... _Args>
140     using wformat_string
141       = basic_format_string<wchar_t, type_identity_t<_Args>...>;
142 #endif
144 #if __cplusplus > 202302L
145   [[__gnu__::__always_inline__]]
146   inline __format::_Runtime_format_string<char>
147   runtime_format(string_view __fmt)
148   { return {__fmt}; }
150 #ifdef _GLIBCXX_USE_WCHAR_T
151   [[__gnu__::__always_inline__]]
152   inline __format::_Runtime_format_string<wchar_t>
153   runtime_format(wstring_view __fmt)
154   { return {__fmt}; }
155 #endif
156 #endif // C++26
158   // [format.formatter], formatter
160   /// The primary template of std::formatter is disabled.
161   template<typename _Tp, typename _CharT = char>
162     struct formatter
163     {
164       formatter() = delete; // No std::formatter specialization for this type.
165       formatter(const formatter&) = delete;
166       formatter& operator=(const formatter&) = delete;
167     };
169   // [format.error], class format_error
170   class format_error : public runtime_error
171   {
172   public:
173     explicit format_error(const string& __what) : runtime_error(__what) { }
174     explicit format_error(const char* __what) : runtime_error(__what) { }
175   };
177   /// @cond undocumented
178   [[noreturn]]
179   inline void
180   __throw_format_error(const char* __what)
181   { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
183 namespace __format
185   // XXX use named functions for each constexpr error?
187   [[noreturn]]
188   inline void
189   __unmatched_left_brace_in_format_string()
190   { __throw_format_error("format error: unmatched '{' in format string"); }
192   [[noreturn]]
193   inline void
194   __unmatched_right_brace_in_format_string()
195   { __throw_format_error("format error: unmatched '}' in format string"); }
197   [[noreturn]]
198   inline void
199   __conflicting_indexing_in_format_string()
200   { __throw_format_error("format error: conflicting indexing style in format string"); }
202   [[noreturn]]
203   inline void
204   __invalid_arg_id_in_format_string()
205   { __throw_format_error("format error: invalid arg-id in format string"); }
207   [[noreturn]]
208   inline void
209   __failed_to_parse_format_spec()
210   { __throw_format_error("format error: failed to parse format-spec"); }
211 } // namespace __format
212   /// @endcond
214   // [format.parse.ctx], class template basic_format_parse_context
215   template<typename _CharT> class basic_format_parse_context;
216   using format_parse_context = basic_format_parse_context<char>;
217 #ifdef _GLIBCXX_USE_WCHAR_T
218   using wformat_parse_context = basic_format_parse_context<wchar_t>;
219 #endif
221   template<typename _CharT>
222     class basic_format_parse_context
223     {
224     public:
225       using char_type = _CharT;
226       using const_iterator = typename basic_string_view<_CharT>::const_iterator;
227       using iterator = const_iterator;
229       constexpr explicit
230       basic_format_parse_context(basic_string_view<_CharT> __fmt,
231                                  size_t __num_args = 0) noexcept
232       : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
233       { }
235       basic_format_parse_context(const basic_format_parse_context&) = delete;
236       void operator=(const basic_format_parse_context&) = delete;
238       constexpr const_iterator begin() const noexcept { return _M_begin; }
239       constexpr const_iterator end() const noexcept { return _M_end; }
241       constexpr void
242       advance_to(const_iterator __it) noexcept
243       { _M_begin = __it; }
245       constexpr size_t
246       next_arg_id()
247       {
248         if (_M_indexing == _Manual)
249           __format::__conflicting_indexing_in_format_string();
250         _M_indexing = _Auto;
252         // _GLIBCXX_RESOLVE_LIB_DEFECTS
253         // 3825. Missing compile-time argument id check in next_arg_id
254         if (std::is_constant_evaluated())
255           if (_M_next_arg_id == _M_num_args)
256             __format::__invalid_arg_id_in_format_string();
257         return _M_next_arg_id++;
258       }
260       constexpr void
261       check_arg_id(size_t __id)
262       {
263         if (_M_indexing == _Auto)
264           __format::__conflicting_indexing_in_format_string();
265         _M_indexing = _Manual;
267         if (std::is_constant_evaluated())
268           if (__id >= _M_num_args)
269             __format::__invalid_arg_id_in_format_string();
270       }
272     private:
273       iterator _M_begin;
274       iterator _M_end;
275       enum _Indexing { _Unknown, _Manual, _Auto };
276       _Indexing _M_indexing = _Unknown;
277       size_t _M_next_arg_id = 0;
278       size_t _M_num_args;
279     };
281 /// @cond undocumented
282   template<typename _Tp, template<typename...> class _Class>
283     static constexpr bool __is_specialization_of = false;
284   template<template<typename...> class _Class, typename... _Args>
285     static constexpr bool __is_specialization_of<_Class<_Args...>, _Class>
286       = true;
288 namespace __format
290   // pre: first != last
291   template<typename _CharT>
292     constexpr pair<unsigned short, const _CharT*>
293     __parse_integer(const _CharT* __first, const _CharT* __last)
294     {
295       if (__first == __last)
296         __builtin_unreachable();
298       if constexpr (is_same_v<_CharT, char>)
299         {
300           const auto __start = __first;
301           unsigned short __val = 0;
302           // N.B. std::from_chars is not constexpr in C++20.
303           if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
304                 && __first != __start) [[likely]]
305             return {__val, __first};
306         }
307       else
308         {
309           constexpr int __n = 32;
310           char __buf[__n]{};
311           for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
312             __buf[__i] = __first[__i];
313           auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
314           if (__ptr) [[likely]]
315             return {__v, __first + (__ptr - __buf)};
316         }
317       return {0, nullptr};
318     }
320   template<typename _CharT>
321     constexpr pair<unsigned short, const _CharT*>
322     __parse_arg_id(const _CharT* __first, const _CharT* __last)
323     {
324       if (__first == __last)
325         __builtin_unreachable();
327       if (*__first == '0')
328         return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
330       if ('1' <= *__first && *__first <= '9')
331         {
332           const unsigned short __id = *__first - '0';
333           const auto __next = __first + 1;
334           // Optimize for most likely case of single digit arg-id.
335           if (__next == __last || !('0' <= *__next && *__next <= '9'))
336             return {__id, __next};
337           else
338             return __format::__parse_integer(__first, __last);
339         }
340       return {0, nullptr};
341     }
343   enum _Pres_type {
344     _Pres_none = 0, // Default type (not valid for integer presentation types).
345     // Presentation types for integral types (including bool and charT).
346     _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
347     // Presentation types for floating-point types.
348     _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
349     _Pres_p = 0, _Pres_P,   // For pointers.
350     _Pres_s = 0,            // For strings and bool.
351     _Pres_esc = 0xf,        // For strings and charT.
352   };
354   enum _Align {
355     _Align_default,
356     _Align_left,
357     _Align_right,
358     _Align_centre,
359   };
361   enum _Sign {
362     _Sign_default,
363     _Sign_plus,
364     _Sign_minus,  // XXX does this need to be distinct from _Sign_default?
365     _Sign_space,
366   };
368   enum _WidthPrec {
369     _WP_none,    // No width/prec specified.
370     _WP_value,   // Fixed width/prec specified.
371     _WP_from_arg // Use a formatting argument for width/prec.
372   };
374   template<typename _Context>
375     size_t
376     __int_from_arg(const basic_format_arg<_Context>& __arg);
378   constexpr bool __is_digit(char __c)
379   { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
381   constexpr bool __is_xdigit(char __c)
382   { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
384   template<typename _CharT>
385     struct _Spec
386     {
387       _Align     _M_align : 2;
388       _Sign      _M_sign : 2;
389       unsigned   _M_alt : 1;
390       unsigned   _M_localized : 1;
391       unsigned   _M_zero_fill : 1;
392       _WidthPrec _M_width_kind : 2;
393       _WidthPrec _M_prec_kind : 2;
394       _Pres_type _M_type : 4;
395       unsigned short _M_width;
396       unsigned short _M_prec;
397       char32_t _M_fill = ' ';
399       using iterator = typename basic_string_view<_CharT>::iterator;
401       static constexpr _Align
402       _S_align(_CharT __c) noexcept
403       {
404         switch (__c)
405         {
406           case '<': return _Align_left;
407           case '>': return _Align_right;
408           case '^': return _Align_centre;
409           default: return _Align_default;
410         }
411       }
413       // pre: __first != __last
414       constexpr iterator
415       _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
416       {
417         if (*__first != '{')
418           {
419             using namespace __unicode;
420             if constexpr (__literal_encoding_is_unicode<_CharT>())
421               {
422                 // Accept any UCS scalar value as fill character.
423                 _Utf32_view __uv(ranges::subrange(__first, __last));
424                 if (!__uv.empty())
425                   {
426                     auto __beg = __uv.begin();
427                     char32_t __c = *__beg++;
428                     if (__is_scalar_value(__c))
429                       if (auto __next = __beg.base(); __next != __last)
430                         if (_Align __align = _S_align(*__next))
431                           {
432                             _M_fill = __c;
433                             _M_align = __align;
434                             return ++__next;
435                           }
436                   }
437               }
438             else if (__last - __first >= 2)
439               if (_Align __align = _S_align(__first[1]))
440                 {
441                   _M_fill = *__first;
442                   _M_align = __align;
443                   return __first + 2;
444                 }
446             if (_Align __align = _S_align(__first[0]))
447               {
448                 _M_fill = ' ';
449                 _M_align = __align;
450                 return __first + 1;
451               }
452           }
453         return __first;
454       }
456       static constexpr _Sign
457       _S_sign(_CharT __c) noexcept
458       {
459         switch (__c)
460         {
461           case '+': return _Sign_plus;
462           case '-': return _Sign_minus;
463           case ' ': return _Sign_space;
464           default:  return _Sign_default;
465         }
466       }
468       // pre: __first != __last
469       constexpr iterator
470       _M_parse_sign(iterator __first, iterator) noexcept
471       {
472         if (_Sign __sign = _S_sign(*__first))
473           {
474             _M_sign = __sign;
475             return __first + 1;
476           }
477         return __first;
478       }
480       // pre: *__first is valid
481       constexpr iterator
482       _M_parse_alternate_form(iterator __first, iterator) noexcept
483       {
484         if (*__first == '#')
485           {
486             _M_alt = true;
487             ++__first;
488           }
489         return __first;
490       }
492       // pre: __first != __last
493       constexpr iterator
494       _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
495       {
496         if (*__first == '0')
497           {
498             _M_zero_fill = true;
499             ++__first;
500           }
501         return __first;
502       }
504       // pre: __first != __last
505       static constexpr iterator
506       _S_parse_width_or_precision(iterator __first, iterator __last,
507                                   unsigned short& __val, bool& __arg_id,
508                                   basic_format_parse_context<_CharT>& __pc)
509       {
510         if (__format::__is_digit(*__first))
511           {
512             auto [__v, __ptr] = __format::__parse_integer(__first, __last);
513             if (!__ptr)
514               __throw_format_error("format error: invalid width or precision "
515                                    "in format-spec");
516             __first = __ptr;
517             __val = __v;
518           }
519         else if (*__first == '{')
520           {
521             __arg_id = true;
522             ++__first;
523             if (__first == __last)
524               __format::__unmatched_left_brace_in_format_string();
525             if (*__first == '}')
526               __val = __pc.next_arg_id();
527             else
528               {
529                 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
530                 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
531                   __format::__invalid_arg_id_in_format_string();
532                 __first = __ptr;
533                 __pc.check_arg_id(__v);
534                 __val = __v;
535               }
536             ++__first; // past the '}'
537           }
538         return __first;
539       }
541       // pre: __first != __last
542       constexpr iterator
543       _M_parse_width(iterator __first, iterator __last,
544                      basic_format_parse_context<_CharT>& __pc)
545       {
546         bool __arg_id = false;
547         if (*__first == '0')
548           __throw_format_error("format error: width must be non-zero in "
549                                "format string");
550         auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
551                                                   __arg_id, __pc);
552         if (__next != __first)
553           _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
554         return __next;
555       }
557       // pre: __first != __last
558       constexpr iterator
559       _M_parse_precision(iterator __first, iterator __last,
560                          basic_format_parse_context<_CharT>& __pc)
561       {
562         if (__first[0] != '.')
563           return __first;
565         iterator __next = ++__first;
566         bool __arg_id = false;
567         if (__next != __last)
568           __next = _S_parse_width_or_precision(__first, __last, _M_prec,
569                                                __arg_id, __pc);
570         if (__next == __first)
571           __throw_format_error("format error: missing precision after '.' in "
572                                "format string");
573         _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
574         return __next;
575       }
577       // pre: __first != __last
578       constexpr iterator
579       _M_parse_locale(iterator __first, iterator /* __last */) noexcept
580       {
581         if (*__first == 'L')
582           {
583             _M_localized = true;
584             ++__first;
585           }
586         return __first;
587       }
589       template<typename _Context>
590         size_t
591         _M_get_width(_Context& __ctx) const
592         {
593           size_t __width = 0;
594           if (_M_width_kind == _WP_value)
595             __width = _M_width;
596           else if (_M_width_kind == _WP_from_arg)
597             __width = __format::__int_from_arg(__ctx.arg(_M_width));
598           return __width;
599         }
601       template<typename _Context>
602         size_t
603         _M_get_precision(_Context& __ctx) const
604         {
605           size_t __prec = -1;
606           if (_M_prec_kind == _WP_value)
607             __prec = _M_prec;
608           else if (_M_prec_kind == _WP_from_arg)
609             __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
610           return __prec;
611         }
612     };
614   template<typename _Int>
615     inline char*
616     __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
617     {
618       if (__i < 0)
619         *__dest = '-';
620       else if (__sign == _Sign_plus)
621         *__dest = '+';
622       else if (__sign == _Sign_space)
623         *__dest = ' ';
624       else
625         ++__dest;
626       return __dest;
627     }
629   // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
630   template<typename _Out, typename _CharT>
631     requires output_iterator<_Out, const _CharT&>
632     inline _Out
633     __write(_Out __out, basic_string_view<_CharT> __str)
634     {
635       if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
636         {
637           if (__str.size())
638             __out = __str;
639         }
640       else
641         for (_CharT __c : __str)
642           *__out++ = __c;
643       return __out;
644     }
646   // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
647   // pre: __align != _Align_default
648   template<typename _Out, typename _CharT>
649     _Out
650     __write_padded(_Out __out, basic_string_view<_CharT> __str,
651                    _Align __align, size_t __nfill, char32_t __fill_char)
652     {
653       const size_t __buflen = 0x20;
654       _CharT __padding_chars[__buflen];
655       __padding_chars[0] = _CharT();
656       basic_string_view<_CharT> __padding{__padding_chars, __buflen};
658       auto __pad = [&__padding] (size_t __n, _Out& __o) {
659         if (__n == 0)
660           return;
661         while (__n > __padding.size())
662           {
663             __o = __format::__write(std::move(__o), __padding);
664             __n -= __padding.size();
665           }
666         if (__n != 0)
667           __o = __format::__write(std::move(__o), __padding.substr(0, __n));
668       };
670       size_t __l, __r, __max;
671       if (__align == _Align_centre)
672         {
673           __l = __nfill / 2;
674           __r = __l + (__nfill & 1);
675           __max = __r;
676         }
677       else if (__align == _Align_right)
678         {
679           __l = __nfill;
680           __r = 0;
681           __max = __l;
682         }
683       else
684         {
685           __l = 0;
686           __r = __nfill;
687           __max = __r;
688         }
690       using namespace __unicode;
691       if constexpr (__literal_encoding_is_unicode<_CharT>())
692         if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
693           {
694             // Encode fill char as multiple code units of type _CharT.
695             const char32_t __arr[1]{ __fill_char };
696             _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
697             basic_string<_CharT> __padstr(__v.begin(), __v.end());
698             __padding = __padstr;
699             while (__l-- > 0)
700               __out = __format::__write(std::move(__out), __padding);
701             __out = __format::__write(std::move(__out), __str);
702             while (__r-- > 0)
703               __out = __format::__write(std::move(__out), __padding);
704             return __out;
705           }
707       if (__max < __buflen)
708         __padding.remove_suffix(__buflen - __max);
709       else
710         __max = __buflen;
712       char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
713       __pad(__l, __out);
714       __out = __format::__write(std::move(__out), __str);
715       __pad(__r, __out);
717       return __out;
718     }
720   // Write STR to OUT, with alignment and padding as determined by SPEC.
721   // pre: __spec._M_align != _Align_default || __align != _Align_default
722   template<typename _CharT, typename _Out>
723     _Out
724     __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
725                            size_t __estimated_width,
726                            basic_format_context<_Out, _CharT>& __fc,
727                            const _Spec<_CharT>& __spec,
728                            _Align __align = _Align_left)
729     {
730       size_t __width = __spec._M_get_width(__fc);
732       if (__width <= __estimated_width)
733         return __format::__write(__fc.out(), __str);
735       const size_t __nfill = __width - __estimated_width;
737       if (__spec._M_align)
738         __align = __spec._M_align;
740       return __format::__write_padded(__fc.out(), __str, __align, __nfill,
741                                       __spec._M_fill);
742     }
744   // A lightweight optional<locale>.
745   struct _Optional_locale
746   {
747     [[__gnu__::__always_inline__]]
748     _Optional_locale() : _M_dummy(), _M_hasval(false) { }
750     _Optional_locale(const locale& __loc) noexcept
751     : _M_loc(__loc), _M_hasval(true)
752     { }
754     _Optional_locale(const _Optional_locale& __l) noexcept
755     : _M_dummy(), _M_hasval(__l._M_hasval)
756     {
757       if (_M_hasval)
758         std::construct_at(&_M_loc, __l._M_loc);
759     }
761     _Optional_locale&
762     operator=(const _Optional_locale& __l) noexcept
763     {
764       if (_M_hasval)
765         {
766           if (__l._M_hasval)
767             _M_loc = __l._M_loc;
768           else
769             {
770               _M_loc.~locale();
771               _M_hasval = false;
772             }
773         }
774       else if (__l._M_hasval)
775         {
776           std::construct_at(&_M_loc, __l._M_loc);
777           _M_hasval = true;
778         }
779       return *this;
780     }
782     ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
784     _Optional_locale&
785     operator=(locale&& __loc) noexcept
786     {
787       if (_M_hasval)
788         _M_loc = std::move(__loc);
789       else
790         {
791           std::construct_at(&_M_loc, std::move(__loc));
792           _M_hasval = true;
793         }
794       return *this;
795     }
797     const locale&
798     value() noexcept
799     {
800       if (!_M_hasval)
801         {
802           std::construct_at(&_M_loc);
803           _M_hasval = true;
804         }
805       return _M_loc;
806     }
808     bool has_value() const noexcept { return _M_hasval; }
810     union {
811       char _M_dummy = '\0';
812       std::locale _M_loc;
813     };
814     bool _M_hasval = false;
815   };
817 #ifdef _GLIBCXX_USE_WCHAR_T
818   template<typename _CharT>
819     concept __char = same_as<_CharT, char> || same_as<_CharT, wchar_t>;
820 #else
821   template<typename _CharT>
822     concept __char = same_as<_CharT, char>;
823 #endif
825   template<__char _CharT>
826     struct __formatter_str
827     {
828       constexpr typename basic_format_parse_context<_CharT>::iterator
829       parse(basic_format_parse_context<_CharT>& __pc)
830       {
831         auto __first = __pc.begin();
832         const auto __last = __pc.end();
833         _Spec<_CharT> __spec{};
835         auto __finalize = [this, &__spec] {
836           _M_spec = __spec;
837         };
839         auto __finished = [&] {
840           if (__first == __last || *__first == '}')
841             {
842               __finalize();
843               return true;
844             }
845           return false;
846         };
848         if (__finished())
849           return __first;
851         __first = __spec._M_parse_fill_and_align(__first, __last);
852         if (__finished())
853           return __first;
855         __first = __spec._M_parse_width(__first, __last, __pc);
856         if (__finished())
857           return __first;
859         __first = __spec._M_parse_precision(__first, __last, __pc);
860         if (__finished())
861           return __first;
863         if (*__first == 's')
864           ++__first;
865 #if __cpp_lib_format_ranges
866         else if (*__first == '?')
867           {
868             __spec._M_type = _Pres_esc;
869             ++__first;
870           }
871 #endif
873         if (__finished())
874           return __first;
876         __format::__failed_to_parse_format_spec();
877       }
879       template<typename _Out>
880         _Out
881         format(basic_string_view<_CharT> __s,
882                basic_format_context<_Out, _CharT>& __fc) const
883         {
884           if (_M_spec._M_type == _Pres_esc)
885             {
886               // TODO: C++23 escaped string presentation
887             }
889           if (_M_spec._M_width_kind == _WP_none
890                 && _M_spec._M_prec_kind == _WP_none)
891             return __format::__write(__fc.out(), __s);
893           size_t __estimated_width;
894           if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
895             {
896               if (_M_spec._M_prec_kind != _WP_none)
897                 {
898                   size_t __prec = _M_spec._M_get_precision(__fc);
899                   __estimated_width = __unicode::__truncate(__s, __prec);
900                 }
901               else
902                 __estimated_width = __unicode::__field_width(__s);
903             }
904           else
905             {
906               __s = __s.substr(0, _M_spec._M_get_precision(__fc));
907               __estimated_width = __s.size();
908             }
910           return __format::__write_padded_as_spec(__s, __estimated_width,
911                                                   __fc, _M_spec);
912         }
914 #if __cpp_lib_format_ranges
915       constexpr void
916       set_debug_format() noexcept
917       { _M_spec._M_type = _Pres_esc; }
918 #endif
920     private:
921       _Spec<_CharT> _M_spec{};
922     };
924   template<__char _CharT>
925     struct __formatter_int
926     {
927       // If no presentation type is specified, meaning of "none" depends
928       // whether we are formatting an integer or a char or a bool.
929       static constexpr _Pres_type _AsInteger = _Pres_d;
930       static constexpr _Pres_type _AsBool = _Pres_s;
931       static constexpr _Pres_type _AsChar = _Pres_c;
933       constexpr typename basic_format_parse_context<_CharT>::iterator
934       _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
935       {
936         _Spec<_CharT> __spec{};
937         __spec._M_type = __type;
939         const auto __last = __pc.end();
940         auto __first = __pc.begin();
942         auto __finalize = [this, &__spec] {
943           _M_spec = __spec;
944         };
946         auto __finished = [&] {
947           if (__first == __last || *__first == '}')
948             {
949               __finalize();
950               return true;
951             }
952           return false;
953         };
955         if (__finished())
956           return __first;
958         __first = __spec._M_parse_fill_and_align(__first, __last);
959         if (__finished())
960           return __first;
962         __first = __spec._M_parse_sign(__first, __last);
963         if (__finished())
964           return __first;
966         __first = __spec._M_parse_alternate_form(__first, __last);
967         if (__finished())
968           return __first;
970         __first = __spec._M_parse_zero_fill(__first, __last);
971         if (__finished())
972           return __first;
974         __first = __spec._M_parse_width(__first, __last, __pc);
975         if (__finished())
976           return __first;
978         __first = __spec._M_parse_locale(__first, __last);
979         if (__finished())
980           return __first;
982         switch (*__first)
983         {
984           case 'b':
985             __spec._M_type = _Pres_b;
986             ++__first;
987             break;
988           case 'B':
989             __spec._M_type = _Pres_B;
990             ++__first;
991             break;
992           case 'c':
993             // _GLIBCXX_RESOLVE_LIB_DEFECTS
994             // 3586. format should not print bool with 'c'
995             if (__type != _AsBool)
996               {
997                 __spec._M_type = _Pres_c;
998                 ++__first;
999               }
1000             break;
1001           case 'd':
1002             __spec._M_type = _Pres_d;
1003             ++__first;
1004             break;
1005           case 'o':
1006             __spec._M_type = _Pres_o;
1007             ++__first;
1008             break;
1009           case 'x':
1010             __spec._M_type = _Pres_x;
1011             ++__first;
1012             break;
1013           case 'X':
1014             __spec._M_type = _Pres_X;
1015             ++__first;
1016             break;
1017           case 's':
1018             if (__type == _AsBool)
1019               {
1020                 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1021                 ++__first;
1022               }
1023             break;
1024 #if __cpp_lib_format_ranges
1025           case '?':
1026             if (__type == _AsChar)
1027               {
1028                 __spec._M_type = _Pres_esc;
1029                 ++__first;
1030               }
1031 #endif
1032             break;
1033           }
1035         if (__finished())
1036           return __first;
1038         __format::__failed_to_parse_format_spec();
1039       }
1041       template<typename _Tp>
1042         constexpr typename basic_format_parse_context<_CharT>::iterator
1043         _M_parse(basic_format_parse_context<_CharT>& __pc)
1044         {
1045           if constexpr (is_same_v<_Tp, bool>)
1046             {
1047               auto __end = _M_do_parse(__pc, _AsBool);
1048               if (_M_spec._M_type == _Pres_s)
1049                 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1050                   __throw_format_error("format error: format-spec contains "
1051                                        "invalid formatting options for "
1052                                        "'bool'");
1053               return __end;
1054             }
1055           else if constexpr (__char<_Tp>)
1056             {
1057               auto __end = _M_do_parse(__pc, _AsChar);
1058               if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1059                 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1060                       /* XXX should be invalid? || _M_spec._M_localized */)
1061                   __throw_format_error("format error: format-spec contains "
1062                                        "invalid formatting options for "
1063                                        "'charT'");
1064               return __end;
1065             }
1066           else
1067             return _M_do_parse(__pc, _AsInteger);
1068         }
1070       template<typename _Int, typename _Out>
1071         typename basic_format_context<_Out, _CharT>::iterator
1072         format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1073         {
1074           if (_M_spec._M_type == _Pres_c)
1075             return _M_format_character(_S_to_character(__i), __fc);
1077           char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1078           to_chars_result __res{};
1080           string_view __base_prefix;
1081           make_unsigned_t<_Int> __u;
1082           if (__i < 0)
1083             __u = -static_cast<make_unsigned_t<_Int>>(__i);
1084           else
1085             __u = __i;
1087           char* __start = __buf + 3;
1088           char* const __end = __buf + sizeof(__buf);
1089           char* const __start_digits = __start;
1091           switch (_M_spec._M_type)
1092           {
1093             case _Pres_b:
1094             case _Pres_B:
1095               __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1096               __res = to_chars(__start, __end, __u, 2);
1097               break;
1098 #if 0
1099             case _Pres_c:
1100               return _M_format_character(_S_to_character(__i), __fc);
1101 #endif
1102             case _Pres_none:
1103               // Should not reach here with _Pres_none for bool or charT, so:
1104               [[fallthrough]];
1105             case _Pres_d:
1106               __res = to_chars(__start, __end, __u, 10);
1107               break;
1108             case _Pres_o:
1109               if (__i != 0)
1110                 __base_prefix = "0";
1111               __res = to_chars(__start, __end, __u, 8);
1112               break;
1113             case _Pres_x:
1114             case _Pres_X:
1115               __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1116               __res = to_chars(__start, __end, __u, 16);
1117               if (_M_spec._M_type == _Pres_X)
1118                 for (auto __p = __start; __p != __res.ptr; ++__p)
1119 #if __has_builtin(__builtin_toupper)
1120                   *__p = __builtin_toupper(*__p);
1121 #else
1122                   *__p = std::toupper(*__p);
1123 #endif
1124               break;
1125             default:
1126               __builtin_unreachable();
1127           }
1129           if (_M_spec._M_alt && __base_prefix.size())
1130             {
1131               __start -= __base_prefix.size();
1132               __builtin_memcpy(__start, __base_prefix.data(),
1133                                __base_prefix.size());
1134             }
1135           __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1137           return _M_format_int(string_view(__start, __res.ptr - __start),
1138                                __start_digits - __start, __fc);
1139         }
1141       template<typename _Out>
1142         typename basic_format_context<_Out, _CharT>::iterator
1143         format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1144         {
1145           if (_M_spec._M_type == _Pres_c)
1146             return _M_format_character(static_cast<unsigned char>(__i), __fc);
1147           if (_M_spec._M_type != _Pres_s)
1148             return format(static_cast<unsigned char>(__i), __fc);
1150           basic_string<_CharT> __s;
1151           size_t __est_width;
1152           if (_M_spec._M_localized) [[unlikely]]
1153             {
1154               auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1155               __s = __i ? __np.truename() : __np.falsename();
1156               __est_width = __s.size(); // TODO Unicode-aware estimate
1157             }
1158           else
1159             {
1160               if constexpr (is_same_v<char, _CharT>)
1161                 __s = __i ? "true" : "false";
1162               else
1163                 __s = __i ? L"true" : L"false";
1164               __est_width = __s.size();
1165             }
1167           return __format::__write_padded_as_spec(__s, __est_width, __fc,
1168                                                   _M_spec);
1169         }
1171       template<typename _Out>
1172         typename basic_format_context<_Out, _CharT>::iterator
1173         _M_format_character(_CharT __c,
1174                       basic_format_context<_Out, _CharT>& __fc) const
1175         {
1176           return __format::__write_padded_as_spec({&__c, 1u}, 1, __fc, _M_spec);
1177         }
1179       template<typename _Int>
1180         static _CharT
1181         _S_to_character(_Int __i)
1182         {
1183           using _Traits = __gnu_cxx::__int_traits<_CharT>;
1184           if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1185             {
1186               if (_Traits::__min <= __i && __i <= _Traits::__max)
1187                 return static_cast<_CharT>(__i);
1188             }
1189           else if constexpr (is_signed_v<_Int>)
1190             {
1191               if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1192                 return static_cast<_CharT>(__i);
1193             }
1194           else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1195             return static_cast<_CharT>(__i);
1196           __throw_format_error("format error: integer not representable as "
1197                                "character");
1198         }
1200       template<typename _Out>
1201         typename basic_format_context<_Out, _CharT>::iterator
1202         _M_format_int(string_view __narrow_str, size_t __prefix_len,
1203                       basic_format_context<_Out, _CharT>& __fc) const
1204         {
1205           size_t __width = _M_spec._M_get_width(__fc);
1207           basic_string_view<_CharT> __str;
1208           if constexpr (is_same_v<char, _CharT>)
1209             __str = __narrow_str;
1210 #ifdef _GLIBCXX_USE_WCHAR_T
1211           else
1212             {
1213               size_t __n = __narrow_str.size();
1214               auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1215               std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1216               __str = {__p, __n};
1217             }
1218 #endif
1220           if (_M_spec._M_localized)
1221             {
1222               const auto& __l = __fc.locale();
1223               if (__l.name() != "C")
1224                 {
1225                   auto& __np = use_facet<numpunct<_CharT>>(__l);
1226                   string __grp = __np.grouping();
1227                   if (!__grp.empty())
1228                     {
1229                       size_t __n = __str.size() - __prefix_len;
1230                       auto __p = (_CharT*)__builtin_alloca(2 * __n
1231                                                              * sizeof(_CharT)
1232                                                              + __prefix_len);
1233                       auto __s = __str.data();
1234                       char_traits<_CharT>::copy(__p, __s, __prefix_len);
1235                       __s += __prefix_len;
1236                       auto __end = std::__add_grouping(__p + __prefix_len,
1237                                                        __np.thousands_sep(),
1238                                                        __grp.data(),
1239                                                        __grp.size(),
1240                                                        __s, __s + __n);
1241                       __str = {__p, size_t(__end - __p)};
1242                     }
1243                 }
1244             }
1246           if (__width <= __str.size())
1247             return __format::__write(__fc.out(), __str);
1249           char32_t __fill_char = _M_spec._M_fill;
1250           _Align __align = _M_spec._M_align;
1252           size_t __nfill = __width - __str.size();
1253           auto __out = __fc.out();
1254           if (__align == _Align_default)
1255             {
1256               __align = _Align_right;
1257               if (_M_spec._M_zero_fill)
1258                 {
1259                   __fill_char = _CharT('0');
1260                   // Write sign and base prefix before zero filling.
1261                   if (__prefix_len != 0)
1262                     {
1263                       __out = __format::__write(std::move(__out),
1264                                                 __str.substr(0, __prefix_len));
1265                       __str.remove_prefix(__prefix_len);
1266                     }
1267                 }
1268               else
1269                 __fill_char = _CharT(' ');
1270             }
1271           return __format::__write_padded(std::move(__out), __str,
1272                                           __align, __nfill, __fill_char);
1273         }
1275 #if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1276       template<typename _Tp>
1277         using make_unsigned_t
1278           = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1279                                      std::make_unsigned<_Tp>,
1280                                      type_identity<unsigned __int128>>::type;
1282       // std::to_chars is not overloaded for int128 in strict mode.
1283       template<typename _Int>
1284         static to_chars_result
1285         to_chars(char* __first, char* __last, _Int __value, int __base)
1286         { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1287 #endif
1289       _Spec<_CharT> _M_spec{};
1290     };
1292   // Decide how 128-bit floating-point types should be formatted (or not).
1293   // When supported, the typedef __format::__float128_t is the type that
1294   // format arguments should be converted to for storage in basic_format_arg.
1295   // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1296   // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1297   // by converting them to long double (or __ieee128 for powerpc64le).
1298   // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1299   // support for _Float128, rather than formatting it as another type.
1300 #undef _GLIBCXX_FORMAT_F128
1302 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1304   // Format 128-bit floating-point types using __ieee128.
1305   using __float128_t = __ieee128;
1306 # define _GLIBCXX_FORMAT_F128 1
1308 #ifdef __LONG_DOUBLE_IEEE128__
1309   // These overloads exist in the library, but are not declared.
1310   // Make them available as std::__format::to_chars.
1311   to_chars_result
1312   to_chars(char*, char*, __ibm128) noexcept
1313     __asm("_ZSt8to_charsPcS_e");
1315   to_chars_result
1316   to_chars(char*, char*, __ibm128, chars_format) noexcept
1317     __asm("_ZSt8to_charsPcS_eSt12chars_format");
1319   to_chars_result
1320   to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1321     __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1322 #elif __cplusplus == 202002L
1323   to_chars_result
1324   to_chars(char*, char*, __ieee128) noexcept
1325     __asm("_ZSt8to_charsPcS_u9__ieee128");
1327   to_chars_result
1328   to_chars(char*, char*, __ieee128, chars_format) noexcept
1329     __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1331   to_chars_result
1332   to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1333     __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1334 #endif
1336 #elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1338   // Format 128-bit floating-point types using long double.
1339   using __float128_t = long double;
1340 # define _GLIBCXX_FORMAT_F128 1
1342 #elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1344   // Format 128-bit floating-point types using _Float128.
1345   using __float128_t = _Float128;
1346 # define _GLIBCXX_FORMAT_F128 2
1348 # if __cplusplus == 202002L
1349   // These overloads exist in the library, but are not declared for C++20.
1350   // Make them available as std::__format::to_chars.
1351   to_chars_result
1352   to_chars(char*, char*, _Float128) noexcept
1353 #  if _GLIBCXX_INLINE_VERSION
1354     __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1355 #  else
1356     __asm("_ZSt8to_charsPcS_DF128_");
1357 #  endif
1359   to_chars_result
1360   to_chars(char*, char*, _Float128, chars_format) noexcept
1361 #  if _GLIBCXX_INLINE_VERSION
1362     __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1363 #  else
1364     __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1365 #  endif
1367   to_chars_result
1368   to_chars(char*, char*, _Float128, chars_format, int) noexcept
1369 #  if _GLIBCXX_INLINE_VERSION
1370     __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1371 #  else
1372     __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1373 #  endif
1374 # endif
1375 #endif
1377   using std::to_chars;
1379   // We can format a floating-point type iff it is usable with to_chars.
1380   template<typename _Tp>
1381     concept __formattable_float = requires (_Tp __t, char* __p)
1382     { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1384   template<__char _CharT>
1385     struct __formatter_fp
1386     {
1387       constexpr typename basic_format_parse_context<_CharT>::iterator
1388       parse(basic_format_parse_context<_CharT>& __pc)
1389       {
1390         _Spec<_CharT> __spec{};
1391         const auto __last = __pc.end();
1392         auto __first = __pc.begin();
1394         auto __finalize = [this, &__spec] {
1395           _M_spec = __spec;
1396         };
1398         auto __finished = [&] {
1399           if (__first == __last || *__first == '}')
1400             {
1401               __finalize();
1402               return true;
1403             }
1404           return false;
1405         };
1407         if (__finished())
1408           return __first;
1410         __first = __spec._M_parse_fill_and_align(__first, __last);
1411         if (__finished())
1412           return __first;
1414         __first = __spec._M_parse_sign(__first, __last);
1415         if (__finished())
1416           return __first;
1418         __first = __spec._M_parse_alternate_form(__first, __last);
1419         if (__finished())
1420           return __first;
1422         __first = __spec._M_parse_zero_fill(__first, __last);
1423         if (__finished())
1424           return __first;
1426         if (__first[0] != '.')
1427           {
1428             __first = __spec._M_parse_width(__first, __last, __pc);
1429             if (__finished())
1430               return __first;
1431           }
1433         __first = __spec._M_parse_precision(__first, __last, __pc);
1434         if (__finished())
1435           return __first;
1437         __first = __spec._M_parse_locale(__first, __last);
1438         if (__finished())
1439           return __first;
1441         switch (*__first)
1442         {
1443           case 'a':
1444             __spec._M_type = _Pres_a;
1445             ++__first;
1446             break;
1447           case 'A':
1448             __spec._M_type = _Pres_A;
1449             ++__first;
1450             break;
1451           case 'e':
1452             __spec._M_type = _Pres_e;
1453             ++__first;
1454             break;
1455           case 'E':
1456             __spec._M_type = _Pres_E;
1457             ++__first;
1458             break;
1459           case 'f':
1460             __spec._M_type = _Pres_f;
1461             ++__first;
1462             break;
1463           case 'F':
1464             __spec._M_type = _Pres_F;
1465             ++__first;
1466             break;
1467           case 'g':
1468             __spec._M_type = _Pres_g;
1469             ++__first;
1470             break;
1471           case 'G':
1472             __spec._M_type = _Pres_G;
1473             ++__first;
1474             break;
1475           }
1477         if (__finished())
1478           return __first;
1480         __format::__failed_to_parse_format_spec();
1481       }
1483       template<typename _Fp, typename _Out>
1484         typename basic_format_context<_Out, _CharT>::iterator
1485         format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
1486         {
1487           std::string __dynbuf;
1488           char __buf[128];
1489           to_chars_result __res{};
1491           size_t __prec = 6;
1492           bool __use_prec = _M_spec._M_prec_kind != _WP_none;
1493           if (__use_prec)
1494             __prec = _M_spec._M_get_precision(__fc);
1496           char* __start = __buf + 1; // reserve space for sign
1497           char* __end = __buf + sizeof(__buf);
1499           chars_format __fmt{};
1500           bool __upper = false;
1501           bool __trailing_zeros = false;
1502           char __expc = 'e';
1504           switch (_M_spec._M_type)
1505           {
1506             case _Pres_A:
1507               __upper = true;
1508               __expc = 'P';
1509               [[fallthrough]];
1510             case _Pres_a:
1511               if (_M_spec._M_type != _Pres_A)
1512                 __expc = 'p';
1513               __fmt = chars_format::hex;
1514               break;
1515             case _Pres_E:
1516               __upper = true;
1517               __expc = 'E';
1518               [[fallthrough]];
1519             case _Pres_e:
1520               __use_prec = true;
1521               __fmt = chars_format::scientific;
1522               break;
1523             case _Pres_F:
1524               __upper = true;
1525               [[fallthrough]];
1526             case _Pres_f:
1527               __use_prec = true;
1528               __fmt = chars_format::fixed;
1529               break;
1530             case _Pres_G:
1531               __upper = true;
1532               __expc = 'E';
1533               [[fallthrough]];
1534             case _Pres_g:
1535               __trailing_zeros = true;
1536               __use_prec = true;
1537               __fmt = chars_format::general;
1538               break;
1539             case _Pres_none:
1540               if (__use_prec)
1541                 __fmt = chars_format::general;
1542               break;
1543             default:
1544               __builtin_unreachable();
1545           }
1547           // Write value into buffer using std::to_chars.
1548           auto __to_chars = [&](char* __b, char* __e) {
1549             if (__use_prec)
1550               return __format::to_chars(__b, __e, __v, __fmt, __prec);
1551             else if (__fmt != chars_format{})
1552               return __format::to_chars(__b, __e, __v, __fmt);
1553             else
1554               return __format::to_chars(__b, __e, __v);
1555           };
1557           // First try using stack buffer.
1558           __res = __to_chars(__start, __end);
1560           if (__builtin_expect(__res.ec == errc::value_too_large, 0))
1561             {
1562               // If the buffer is too small it's probably because of a large
1563               // precision, or a very large value in fixed format.
1564               size_t __guess = 8 + __prec;
1565               if (__fmt == chars_format::fixed) // +ddd.prec
1566                 {
1567                   if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
1568                                   || is_same_v<_Fp, long double>)
1569                     {
1570                       // The number of digits to the left of the decimal point
1571                       // is floor(log10(max(abs(__v),1)))+1
1572                       int __exp{};
1573                       if constexpr (is_same_v<_Fp, float>)
1574                         __builtin_frexpf(__v, &__exp);
1575                       else if constexpr (is_same_v<_Fp, double>)
1576                         __builtin_frexp(__v, &__exp);
1577                       else if constexpr (is_same_v<_Fp, long double>)
1578                         __builtin_frexpl(__v, &__exp);
1579                       if (__exp > 0)
1580                         __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
1581                     }
1582                   else
1583                     __guess += numeric_limits<_Fp>::max_exponent10;
1584                 }
1585               if (__guess <= sizeof(__buf)) [[unlikely]]
1586                 __guess = sizeof(__buf) * 2;
1587               __dynbuf.reserve(__guess);
1589               do
1590                 {
1591                   auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
1592                   {
1593                     __res = __to_chars(__p + 1, __p + __n - 1);
1594                     return __res.ec == errc{} ? __res.ptr - __p : 0;
1595                   };
1597                   __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
1598                                                   __overwrite);
1599                   __start = __dynbuf.data() + 1; // reserve space for sign
1600                   __end = __dynbuf.data() + __dynbuf.size();
1601                 }
1602               while (__builtin_expect(__res.ec == errc::value_too_large, 0));
1603           }
1605           // Use uppercase for 'A', 'E', and 'G' formats.
1606           if (__upper)
1607             {
1608               for (char* __p = __start; __p != __res.ptr; ++__p)
1609                 *__p = std::toupper(*__p);
1610             }
1612           // Add sign for non-negative values.
1613           if (!__builtin_signbit(__v))
1614             {
1615               if (_M_spec._M_sign == _Sign_plus)
1616                 *--__start = '+';
1617               else if (_M_spec._M_sign == _Sign_space)
1618                 *--__start = ' ';
1619             }
1621           string_view __narrow_str(__start, __res.ptr - __start);
1623           // Use alternate form.
1624           if (_M_spec._M_alt && __builtin_isfinite(__v))
1625             {
1626               string_view __s = __narrow_str;
1627               size_t __z = 0;
1628               size_t __p;
1629               size_t __d = __s.find('.');
1630               size_t __sigfigs;
1631               if (__d != __s.npos)
1632                 {
1633                   __p = __s.find(__expc, __d + 1);
1634                   if (__p == __s.npos)
1635                     __p = __s.size();
1636                   __sigfigs = __p - 1;
1637                 }
1638               else
1639                 {
1640                   __p = __s.find(__expc);
1641                   if (__p == __s.npos)
1642                     __p = __s.size();
1643                   __d = __p; // Position where '.' should be inserted.
1644                   __sigfigs = __d;
1645                 }
1647               if (__trailing_zeros && __prec != 0)
1648                 {
1649                   if (!__format::__is_xdigit(__s[0]))
1650                     --__sigfigs;
1651                   __z = __prec - __sigfigs; // Number of zeros to insert.
1652                 }
1654               if (size_t __extras = int(__d == __p) + __z)
1655                 {
1656                   if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
1657                     {
1658                       // Move exponent to make space for extra chars.
1659                       __builtin_memmove(__start + __p + __extras,
1660                                         __start + __p,
1661                                         __s.size() - __p);
1663                       if (__d == __p)
1664                         __start[__p++] = '.';
1665                       __builtin_memset(__start + __p, '0', __z);
1666                       __narrow_str = {__s.data(), __s.size() + __extras};
1667                     }
1668                   else
1669                     {
1670                       __dynbuf.reserve(__s.size() + __extras);
1671                       if (__dynbuf.empty())
1672                         {
1673                           __dynbuf = __s.substr(0, __p);
1674                           if (__d == __p)
1675                             __dynbuf += '.';
1676                           if (__z)
1677                             __dynbuf.append(__z, '0');
1678                         }
1679                       else
1680                         {
1681                           __dynbuf.insert(__p, __extras, '0');
1682                           if (__d == __p)
1683                             __dynbuf[__p] = '.';
1684                         }
1685                       __narrow_str = __dynbuf;
1686                     }
1687                 }
1688             }
1690           basic_string<_CharT> __wstr;
1691           basic_string_view<_CharT> __str;
1692           if constexpr (is_same_v<_CharT, char>)
1693             __str = __narrow_str;
1694 #ifdef _GLIBCXX_USE_WCHAR_T
1695           else
1696             {
1697               __wstr = std::__to_wstring_numeric(__narrow_str);
1698               __str = __wstr;
1699             }
1700 #endif
1702           if (_M_spec._M_localized)
1703             {
1704               __wstr = _M_localize(__str, __expc, __fc.locale());
1705               if (!__wstr.empty())
1706                 __str = __wstr;
1707             }
1709           size_t __width = _M_spec._M_get_width(__fc);
1711           if (__width <= __str.size())
1712             return __format::__write(__fc.out(), __str);
1714           char32_t __fill_char = _M_spec._M_fill;
1715           _Align __align = _M_spec._M_align;
1717           size_t __nfill = __width - __str.size();
1718           auto __out = __fc.out();
1719           if (__align == _Align_default)
1720             {
1721               __align = _Align_right;
1722               if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
1723                 {
1724                   __fill_char = _CharT('0');
1725                   // Write sign before zero filling.
1726                   if (!__format::__is_xdigit(__narrow_str[0]))
1727                     {
1728                       *__out++ = __str[0];
1729                       __str.remove_prefix(1);
1730                     }
1731                 }
1732               else
1733                 __fill_char = _CharT(' ');
1734             }
1735           return __format::__write_padded(std::move(__out), __str,
1736                                           __align, __nfill, __fill_char);
1737         }
1739       // Locale-specific format.
1740       basic_string<_CharT>
1741       _M_localize(basic_string_view<_CharT> __str, char __expc,
1742                   const locale& __loc) const
1743       {
1744         basic_string<_CharT> __lstr;
1746         if (__loc == locale::classic())
1747           return __lstr; // Nothing to do.
1749         const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1750         const _CharT __point = __np.decimal_point();
1751         const string __grp = __np.grouping();
1753         _CharT __dot, __exp;
1754         if constexpr (is_same_v<_CharT, char>)
1755           {
1756             __dot = '.';
1757             __exp = __expc;
1758           }
1759         else
1760           {
1761             __dot = L'.';
1762             switch (__expc)
1763             {
1764               case 'e':
1765                 __exp = L'e';
1766                 break;
1767               case 'E':
1768                 __exp = L'E';
1769                 break;
1770               case 'p':
1771                 __exp = L'p';
1772                 break;
1773               case 'P':
1774                 __exp = L'P';
1775                 break;
1776               default:
1777                 __builtin_unreachable();
1778             }
1779           }
1781         if (__grp.empty() && __point == __dot)
1782           return __lstr; // Locale uses '.' and no grouping.
1784         size_t __d = __str.find(__dot);
1785         size_t __e = min(__d, __str.find(__exp));
1786         if (__e == __str.npos)
1787           __e = __str.size();
1788         const size_t __r = __str.size() - __e;
1789         auto __overwrite = [&](_CharT* __p, size_t) {
1790           auto __end = std::__add_grouping(__p, __np.thousands_sep(),
1791                                            __grp.data(), __grp.size(),
1792                                            __str.data(), __str.data() + __e);
1793           if (__r)
1794             {
1795               if (__d != __str.npos)
1796                 {
1797                   *__end = __point;
1798                   ++__end;
1799                   ++__e;
1800                 }
1801               if (__r > 1)
1802                 __end += __str.copy(__end, __str.npos, __e);
1803             }
1804           return (__end - __p);
1805         };
1806         __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
1807         return __lstr;
1808       }
1810       _Spec<_CharT> _M_spec{};
1811     };
1813 } // namespace __format
1814 /// @endcond
1816   /// Format a character.
1817   template<__format::__char _CharT>
1818     struct formatter<_CharT, _CharT>
1819     {
1820       formatter() = default;
1822       constexpr typename basic_format_parse_context<_CharT>::iterator
1823       parse(basic_format_parse_context<_CharT>& __pc)
1824       {
1825         return _M_f.template _M_parse<_CharT>(__pc);
1826       }
1828       template<typename _Out>
1829         typename basic_format_context<_Out, _CharT>::iterator
1830         format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
1831         {
1832           if (_M_f._M_spec._M_type == __format::_Pres_none
1833               || _M_f._M_spec._M_type == __format::_Pres_c)
1834             return _M_f._M_format_character(__u, __fc);
1835           else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1836             {
1837               // TODO
1838               return __fc.out();
1839             }
1840           else
1841             return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
1842         }
1844 #if __cpp_lib_format_ranges
1845       constexpr void
1846       set_debug_format() noexcept
1847       { _M_f._M_spec._M_type = __format::_Pres_esc; }
1848 #endif
1850     private:
1851       __format::__formatter_int<_CharT> _M_f;
1852     };
1854 #ifdef _GLIBCXX_USE_WCHAR_T
1855   /// Format a char value for wide character output.
1856   template<>
1857     struct formatter<char, wchar_t>
1858     {
1859       formatter() = default;
1861       constexpr typename basic_format_parse_context<wchar_t>::iterator
1862       parse(basic_format_parse_context<wchar_t>& __pc)
1863       {
1864         return _M_f._M_parse<char>(__pc);
1865       }
1867       template<typename _Out>
1868         typename basic_format_context<_Out, wchar_t>::iterator
1869         format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
1870         {
1871           if (_M_f._M_spec._M_type == __format::_Pres_none
1872               || _M_f._M_spec._M_type == __format::_Pres_c)
1873             return _M_f._M_format_character(__u, __fc);
1874           else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1875             {
1876               // TODO
1877               return __fc.out();
1878             }
1879           else
1880             return _M_f.format(static_cast<unsigned char>(__u), __fc);
1881         }
1883 #if __cpp_lib_format_ranges
1884       constexpr void
1885       set_debug_format() noexcept
1886       { _M_f._M_spec._M_type = __format::_Pres_esc; }
1887 #endif
1889     private:
1890       __format::__formatter_int<wchar_t> _M_f;
1891     };
1892 #endif // USE_WCHAR_T
1894   /** Format a string.
1895    * @{
1896    */
1897   template<__format::__char _CharT>
1898     struct formatter<_CharT*, _CharT>
1899     {
1900       formatter() = default;
1902       [[__gnu__::__always_inline__]]
1903       constexpr typename basic_format_parse_context<_CharT>::iterator
1904       parse(basic_format_parse_context<_CharT>& __pc)
1905       { return _M_f.parse(__pc); }
1907       template<typename _Out>
1908         [[__gnu__::__nonnull__]]
1909         typename basic_format_context<_Out, _CharT>::iterator
1910         format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
1911         { return _M_f.format(__u, __fc); }
1913 #if __cpp_lib_format_ranges
1914       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
1915 #endif
1917     private:
1918       __format::__formatter_str<_CharT> _M_f;
1919     };
1921   template<__format::__char _CharT>
1922     struct formatter<const _CharT*, _CharT>
1923     {
1924       formatter() = default;
1926       [[__gnu__::__always_inline__]]
1927       constexpr typename basic_format_parse_context<_CharT>::iterator
1928       parse(basic_format_parse_context<_CharT>& __pc)
1929       { return _M_f.parse(__pc); }
1931       template<typename _Out>
1932         [[__gnu__::__nonnull__]]
1933         typename basic_format_context<_Out, _CharT>::iterator
1934         format(const _CharT* __u,
1935                basic_format_context<_Out, _CharT>& __fc) const
1936         { return _M_f.format(__u, __fc); }
1938 #if __cpp_lib_format_ranges
1939       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
1940 #endif
1942     private:
1943       __format::__formatter_str<_CharT> _M_f;
1944     };
1946   template<__format::__char _CharT, size_t _Nm>
1947     struct formatter<_CharT[_Nm], _CharT>
1948     {
1949       formatter() = default;
1951       [[__gnu__::__always_inline__]]
1952       constexpr typename basic_format_parse_context<_CharT>::iterator
1953       parse(basic_format_parse_context<_CharT>& __pc)
1954       { return _M_f.parse(__pc); }
1956       template<typename _Out>
1957         typename basic_format_context<_Out, _CharT>::iterator
1958         format(const _CharT (&__u)[_Nm],
1959                basic_format_context<_Out, _CharT>& __fc) const
1960         { return _M_f.format({__u, _Nm}, __fc); }
1962 #if __cpp_lib_format_ranges
1963       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
1964 #endif
1966     private:
1967       __format::__formatter_str<_CharT> _M_f;
1968     };
1970   template<typename _Traits, typename _Alloc>
1971     struct formatter<basic_string<char, _Traits, _Alloc>, char>
1972     {
1973       formatter() = default;
1975       [[__gnu__::__always_inline__]]
1976       constexpr typename basic_format_parse_context<char>::iterator
1977       parse(basic_format_parse_context<char>& __pc)
1978       { return _M_f.parse(__pc); }
1980       template<typename _Out>
1981         typename basic_format_context<_Out, char>::iterator
1982         format(const basic_string<char, _Traits, _Alloc>& __u,
1983                basic_format_context<_Out, char>& __fc) const
1984         { return _M_f.format(__u, __fc); }
1986 #if __cpp_lib_format_ranges
1987       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
1988 #endif
1990     private:
1991       __format::__formatter_str<char> _M_f;
1992     };
1994 #ifdef _GLIBCXX_USE_WCHAR_T
1995   template<typename _Traits, typename _Alloc>
1996     struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
1997     {
1998       formatter() = default;
2000       [[__gnu__::__always_inline__]]
2001       constexpr typename basic_format_parse_context<wchar_t>::iterator
2002       parse(basic_format_parse_context<wchar_t>& __pc)
2003       { return _M_f.parse(__pc); }
2005       template<typename _Out>
2006         typename basic_format_context<_Out, wchar_t>::iterator
2007         format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2008                basic_format_context<_Out, wchar_t>& __fc) const
2009         { return _M_f.format(__u, __fc); }
2011 #if __cpp_lib_format_ranges
2012       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2013 #endif
2015     private:
2016       __format::__formatter_str<wchar_t> _M_f;
2017     };
2018 #endif // USE_WCHAR_T
2020   template<typename _Traits>
2021     struct formatter<basic_string_view<char, _Traits>, char>
2022     {
2023       formatter() = default;
2025       [[__gnu__::__always_inline__]]
2026       constexpr typename basic_format_parse_context<char>::iterator
2027       parse(basic_format_parse_context<char>& __pc)
2028       { return _M_f.parse(__pc); }
2030       template<typename _Out>
2031         typename basic_format_context<_Out, char>::iterator
2032         format(basic_string_view<char, _Traits> __u,
2033                basic_format_context<_Out, char>& __fc) const
2034         { return _M_f.format(__u, __fc); }
2036 #if __cpp_lib_format_ranges
2037       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2038 #endif
2040     private:
2041       __format::__formatter_str<char> _M_f;
2042     };
2044 #ifdef _GLIBCXX_USE_WCHAR_T
2045   template<typename _Traits>
2046     struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2047     {
2048       formatter() = default;
2050       [[__gnu__::__always_inline__]]
2051       constexpr typename basic_format_parse_context<wchar_t>::iterator
2052       parse(basic_format_parse_context<wchar_t>& __pc)
2053       { return _M_f.parse(__pc); }
2055       template<typename _Out>
2056         typename basic_format_context<_Out, wchar_t>::iterator
2057         format(basic_string_view<wchar_t, _Traits> __u,
2058                basic_format_context<_Out, wchar_t>& __fc) const
2059         { return _M_f.format(__u, __fc); }
2061 #if __cpp_lib_format_ranges
2062       constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2063 #endif
2065     private:
2066       __format::__formatter_str<wchar_t> _M_f;
2067     };
2068 #endif // USE_WCHAR_T
2069   /// @}
2071   /// Format an integer.
2072   template<integral _Tp, __format::__char _CharT>
2073     requires (!__is_one_of<_Tp, char, wchar_t, char16_t, char32_t>::value)
2074     struct formatter<_Tp, _CharT>
2075     {
2076       formatter() = default;
2078       [[__gnu__::__always_inline__]]
2079       constexpr typename basic_format_parse_context<_CharT>::iterator
2080       parse(basic_format_parse_context<_CharT>& __pc)
2081       {
2082         return _M_f.template _M_parse<_Tp>(__pc);
2083       }
2085       template<typename _Out>
2086         typename basic_format_context<_Out, _CharT>::iterator
2087         format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2088         { return _M_f.format(__u, __fc); }
2090     private:
2091       __format::__formatter_int<_CharT> _M_f;
2092     };
2094 #if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
2095   template<typename _Tp, __format::__char _CharT>
2096     requires (__is_one_of<_Tp, __int128, unsigned __int128>::value)
2097     struct formatter<_Tp, _CharT>
2098     {
2099       formatter() = default;
2101       [[__gnu__::__always_inline__]]
2102       constexpr typename basic_format_parse_context<_CharT>::iterator
2103       parse(basic_format_parse_context<_CharT>& __pc)
2104       {
2105         return _M_f.template _M_parse<_Tp>(__pc);
2106       }
2108       template<typename _Out>
2109         typename basic_format_context<_Out, _CharT>::iterator
2110         format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2111         { return _M_f.format(__u, __fc); }
2113     private:
2114       __format::__formatter_int<_CharT> _M_f;
2115     };
2116 #endif
2118 #if defined __glibcxx_to_chars
2119   /// Format a floating-point value.
2120   template<__format::__formattable_float _Tp, __format::__char _CharT>
2121     struct formatter<_Tp, _CharT>
2122     {
2123       formatter() = default;
2125       [[__gnu__::__always_inline__]]
2126       constexpr typename basic_format_parse_context<_CharT>::iterator
2127       parse(basic_format_parse_context<_CharT>& __pc)
2128       { return _M_f.parse(__pc); }
2130       template<typename _Out>
2131         typename basic_format_context<_Out, _CharT>::iterator
2132         format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2133         { return _M_f.format(__u, __fc); }
2135     private:
2136       __format::__formatter_fp<_CharT> _M_f;
2137     };
2139 #if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2140   // Reuse __formatter_fp<C>::format<double, Out> for long double.
2141   template<__format::__char _CharT>
2142     struct formatter<long double, _CharT>
2143     {
2144       formatter() = default;
2146       [[__gnu__::__always_inline__]]
2147       constexpr typename basic_format_parse_context<_CharT>::iterator
2148       parse(basic_format_parse_context<_CharT>& __pc)
2149       { return _M_f.parse(__pc); }
2151       template<typename _Out>
2152         typename basic_format_context<_Out, _CharT>::iterator
2153         format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2154         { return _M_f.format((double)__u, __fc); }
2156     private:
2157       __format::__formatter_fp<_CharT> _M_f;
2158     };
2159 #endif
2161 #ifdef __STDCPP_FLOAT16_T__
2162   // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2163   template<__format::__char _CharT>
2164     struct formatter<_Float16, _CharT>
2165     {
2166       formatter() = default;
2168       [[__gnu__::__always_inline__]]
2169       constexpr typename basic_format_parse_context<_CharT>::iterator
2170       parse(basic_format_parse_context<_CharT>& __pc)
2171       { return _M_f.parse(__pc); }
2173       template<typename _Out>
2174         typename basic_format_context<_Out, _CharT>::iterator
2175         format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2176         { return _M_f.format((float)__u, __fc); }
2178     private:
2179       __format::__formatter_fp<_CharT> _M_f;
2180     };
2181 #endif
2183 #if defined(__FLT32_DIG__)
2184   // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2185   template<__format::__char _CharT>
2186     struct formatter<_Float32, _CharT>
2187     {
2188       formatter() = default;
2190       [[__gnu__::__always_inline__]]
2191       constexpr typename basic_format_parse_context<_CharT>::iterator
2192       parse(basic_format_parse_context<_CharT>& __pc)
2193       { return _M_f.parse(__pc); }
2195       template<typename _Out>
2196         typename basic_format_context<_Out, _CharT>::iterator
2197         format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2198         { return _M_f.format((float)__u, __fc); }
2200     private:
2201       __format::__formatter_fp<_CharT> _M_f;
2202     };
2203 #endif
2205 #if defined(__FLT64_DIG__)
2206   // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2207   template<__format::__char _CharT>
2208     struct formatter<_Float64, _CharT>
2209     {
2210       formatter() = default;
2212       [[__gnu__::__always_inline__]]
2213       constexpr typename basic_format_parse_context<_CharT>::iterator
2214       parse(basic_format_parse_context<_CharT>& __pc)
2215       { return _M_f.parse(__pc); }
2217       template<typename _Out>
2218         typename basic_format_context<_Out, _CharT>::iterator
2219         format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2220         { return _M_f.format((double)__u, __fc); }
2222     private:
2223       __format::__formatter_fp<_CharT> _M_f;
2224     };
2225 #endif
2227 #if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2228   // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2229   template<__format::__char _CharT>
2230     struct formatter<_Float128, _CharT>
2231     {
2232       formatter() = default;
2234       [[__gnu__::__always_inline__]]
2235       constexpr typename basic_format_parse_context<_CharT>::iterator
2236       parse(basic_format_parse_context<_CharT>& __pc)
2237       { return _M_f.parse(__pc); }
2239       template<typename _Out>
2240         typename basic_format_context<_Out, _CharT>::iterator
2241         format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2242         { return _M_f.format((__format::__float128_t)__u, __fc); }
2244     private:
2245       __format::__formatter_fp<_CharT> _M_f;
2246     };
2247 #endif
2249 #ifdef __STDCPP_BFLOAT16_T__
2250   // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2251   template<__format::__char _CharT>
2252     struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2253     {
2254       formatter() = default;
2256       [[__gnu__::__always_inline__]]
2257       constexpr typename basic_format_parse_context<_CharT>::iterator
2258       parse(basic_format_parse_context<_CharT>& __pc)
2259       { return _M_f.parse(__pc); }
2261       template<typename _Out>
2262         typename basic_format_context<_Out, _CharT>::iterator
2263         format(__gnu_cxx::__bfloat16_t __u,
2264                basic_format_context<_Out, _CharT>& __fc) const
2265         { return _M_f.format((float)__u, __fc); }
2267     private:
2268       __format::__formatter_fp<_CharT> _M_f;
2269     };
2270 #endif
2271 #endif // __cpp_lib_to_chars
2273   /** Format a pointer.
2274    * @{
2275    */
2276   template<__format::__char _CharT>
2277     struct formatter<const void*, _CharT>
2278     {
2279       formatter() = default;
2281       constexpr typename basic_format_parse_context<_CharT>::iterator
2282       parse(basic_format_parse_context<_CharT>& __pc)
2283       {
2284         __format::_Spec<_CharT> __spec{};
2285         const auto __last = __pc.end();
2286         auto __first = __pc.begin();
2288         auto __finalize = [this, &__spec] {
2289           _M_spec = __spec;
2290         };
2292         auto __finished = [&] {
2293           if (__first == __last || *__first == '}')
2294             {
2295               __finalize();
2296               return true;
2297             }
2298           return false;
2299         };
2301         if (__finished())
2302           return __first;
2304         __first = __spec._M_parse_fill_and_align(__first, __last);
2305         if (__finished())
2306           return __first;
2308 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2309 // P2510R3 Formatting pointers
2310 #if __cplusplus > 202302L || ! defined __STRICT_ANSI__
2311 #define _GLIBCXX_P2518R3 1
2312 #else
2313 #define _GLIBCXX_P2518R3 0
2314 #endif
2316 #if _GLIBCXX_P2518R3
2317         __first = __spec._M_parse_zero_fill(__first, __last);
2318         if (__finished())
2319           return __first;
2320 #endif
2322         __first = __spec._M_parse_width(__first, __last, __pc);
2324         if (__first != __last)
2325           {
2326             if (*__first == 'p')
2327               ++__first;
2328 #if _GLIBCXX_P2518R3
2329             else if (*__first == 'P')
2330             {
2331               // _GLIBCXX_RESOLVE_LIB_DEFECTS
2332               // P2510R3 Formatting pointers
2333               __spec._M_type = __format::_Pres_P;
2334               ++__first;
2335             }
2336 #endif
2337           }
2339         if (__finished())
2340           return __first;
2342         __format::__failed_to_parse_format_spec();
2343       }
2345       template<typename _Out>
2346         typename basic_format_context<_Out, _CharT>::iterator
2347         format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2348         {
2349           auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2350           char __buf[2 + sizeof(__v) * 2];
2351           auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2352                                              __u, 16);
2353           int __n = __ptr - __buf;
2354           __buf[0] = '0';
2355           __buf[1] = 'x';
2356 #if _GLIBCXX_P2518R3
2357           if (_M_spec._M_type == __format::_Pres_P)
2358             {
2359               __buf[1] = 'X';
2360               for (auto __p = __buf + 2; __p != __ptr; ++__p)
2361 #if __has_builtin(__builtin_toupper)
2362                 *__p = __builtin_toupper(*__p);
2363 #else
2364                 *__p = std::toupper(*__p);
2365 #endif
2366             }
2367 #endif
2369           basic_string_view<_CharT> __str;
2370           if constexpr (is_same_v<_CharT, char>)
2371             __str = string_view(__buf, __n);
2372 #ifdef _GLIBCXX_USE_WCHAR_T
2373           else
2374             {
2375               auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2376               std::__to_wstring_numeric(__buf, __n, __p);
2377               __str = wstring_view(__p, __n);
2378             }
2379 #endif
2381 #if _GLIBCXX_P2518R3
2382           if (_M_spec._M_zero_fill)
2383             {
2384               size_t __width = _M_spec._M_get_width(__fc);
2385               if (__width <= __str.size())
2386                 return __format::__write(__fc.out(), __str);
2388               auto __out = __fc.out();
2389               // Write "0x" or "0X" prefix before zero-filling.
2390               __out = __format::__write(std::move(__out), __str.substr(0, 2));
2391               __str.remove_prefix(2);
2392               size_t __nfill = __width - __n;
2393               return __format::__write_padded(std::move(__out), __str,
2394                                               __format::_Align_right,
2395                                               __nfill, _CharT('0'));
2396             }
2397 #endif
2399           return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2400                                                   __format::_Align_right);
2401         }
2403     private:
2404       __format::_Spec<_CharT> _M_spec{};
2405     };
2407   template<__format::__char _CharT>
2408     struct formatter<void*, _CharT>
2409     {
2410       formatter() = default;
2412       [[__gnu__::__always_inline__]]
2413       constexpr typename basic_format_parse_context<_CharT>::iterator
2414       parse(basic_format_parse_context<_CharT>& __pc)
2415       { return _M_f.parse(__pc); }
2417       template<typename _Out>
2418         typename basic_format_context<_Out, _CharT>::iterator
2419         format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2420         { return _M_f.format(__v, __fc); }
2422     private:
2423       formatter<const void*, _CharT> _M_f;
2424     };
2426   template<__format::__char _CharT>
2427     struct formatter<nullptr_t, _CharT>
2428     {
2429       formatter() = default;
2431       [[__gnu__::__always_inline__]]
2432       constexpr typename basic_format_parse_context<_CharT>::iterator
2433       parse(basic_format_parse_context<_CharT>& __pc)
2434       { return _M_f.parse(__pc); }
2436       template<typename _Out>
2437         typename basic_format_context<_Out, _CharT>::iterator
2438         format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2439         { return _M_f.format(nullptr, __fc); }
2441     private:
2442       formatter<const void*, _CharT> _M_f;
2443     };
2444   /// @}
2447 /// @cond undocumented
2448 namespace __format
2450   template<typename _Tp, typename _Context,
2451            typename _Formatter
2452              = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2453            typename _ParseContext
2454              = basic_format_parse_context<typename _Context::char_type>>
2455     concept __parsable_with
2456       = semiregular<_Formatter>
2457           && requires (_Formatter __f, _ParseContext __pc)
2458     {
2459       { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
2460     };
2462   template<typename _Tp, typename _Context,
2463            typename _Formatter
2464              = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2465            typename _ParseContext
2466              = basic_format_parse_context<typename _Context::char_type>>
2467     concept __formattable_with
2468       = semiregular<_Formatter>
2469           && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
2470     {
2471       { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
2472     };
2474   // An unspecified output iterator type used in the `formattable` concept.
2475   template<typename _CharT>
2476     using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
2478   template<typename _Tp, typename _CharT,
2479            typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
2480     concept __formattable_impl
2481       = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
2483 } // namespace __format
2484 /// @endcond
2486 #if __cplusplus > 202002L
2487   // [format.formattable], concept formattable
2488   template<typename _Tp, typename _CharT>
2489     concept formattable
2490       = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
2491 #endif
2493 #if __cpp_lib_format_ranges
2494   /// @cond undocumented
2495 namespace __format
2497   template<typename _Rg, typename _CharT>
2498     concept __const_formattable_range
2499       = ranges::input_range<const _Rg>
2500           && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
2502   template<typename _Rg, typename _CharT>
2503     using __maybe_const_range
2504       = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
2505 } // namespace __format
2506   /// @endcond
2507 #endif // format_ranges
2509   /// An iterator after the last character written, and the number of
2510   /// characters that would have been written.
2511   template<typename _Out>
2512     struct format_to_n_result
2513     {
2514       _Out out;
2515       iter_difference_t<_Out> size;
2516     };
2518 _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
2519 template<typename, typename> class vector;
2520 _GLIBCXX_END_NAMESPACE_CONTAINER
2522 /// @cond undocumented
2523 namespace __format
2525   template<typename _CharT>
2526     class _Sink_iter
2527     {
2528       _Sink<_CharT>* _M_sink = nullptr;
2530     public:
2531       using iterator_category = output_iterator_tag;
2532       using value_type = void;
2533       using difference_type = ptrdiff_t;
2534       using pointer = void;
2535       using reference = void;
2537       _Sink_iter() = default;
2538       _Sink_iter(const _Sink_iter&) = default;
2539       _Sink_iter& operator=(const _Sink_iter&) = default;
2541       [[__gnu__::__always_inline__]]
2542       explicit constexpr
2543       _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
2545       [[__gnu__::__always_inline__]]
2546       constexpr _Sink_iter&
2547       operator=(_CharT __c)
2548       {
2549         _M_sink->_M_write(__c);
2550         return *this;
2551       }
2553       [[__gnu__::__always_inline__]]
2554       constexpr _Sink_iter&
2555       operator=(basic_string_view<_CharT> __s)
2556       {
2557         _M_sink->_M_write(__s);
2558         return *this;
2559       }
2561       [[__gnu__::__always_inline__]]
2562       constexpr _Sink_iter&
2563       operator*() { return *this; }
2565       [[__gnu__::__always_inline__]]
2566       constexpr _Sink_iter&
2567       operator++() { return *this; }
2569       [[__gnu__::__always_inline__]]
2570       constexpr _Sink_iter
2571       operator++(int) { return *this; }
2573       auto
2574       _M_reserve(size_t __n) const
2575       { return _M_sink->_M_reserve(__n); }
2576     };
2578   // Abstract base class for type-erased character sinks.
2579   // All formatting and output is done via this type's iterator,
2580   // to reduce the number of different template instantiations.
2581   template<typename _CharT>
2582     class _Sink
2583     {
2584       friend class _Sink_iter<_CharT>;
2586       span<_CharT> _M_span;
2587       typename span<_CharT>::iterator _M_next;
2589       // Called when the span is full, to make more space available.
2590       // Precondition: _M_next != _M_span.begin()
2591       // Postcondition: _M_next != _M_span.end()
2592       // TODO: remove the precondition? could make overflow handle it.
2593       virtual void _M_overflow() = 0;
2595     protected:
2596       // Precondition: __span.size() != 0
2597       [[__gnu__::__always_inline__]]
2598       explicit constexpr
2599       _Sink(span<_CharT> __span) noexcept
2600       : _M_span(__span), _M_next(__span.begin())
2601       { }
2603       // The portion of the span that has been written to.
2604       [[__gnu__::__always_inline__]]
2605       span<_CharT>
2606       _M_used() const noexcept
2607       { return _M_span.first(_M_next - _M_span.begin()); }
2609       // The portion of the span that has not been written to.
2610       [[__gnu__::__always_inline__]]
2611       constexpr span<_CharT>
2612       _M_unused() const noexcept
2613       { return _M_span.subspan(_M_next - _M_span.begin()); }
2615       // Use the start of the span as the next write position.
2616       [[__gnu__::__always_inline__]]
2617       constexpr void
2618       _M_rewind() noexcept
2619       { _M_next = _M_span.begin(); }
2621       // Replace the current output range.
2622       void
2623       _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
2624       {
2625         _M_span = __s;
2626         _M_next = __s.begin() + __pos;
2627       }
2629       // Called by the iterator for *it++ = c
2630       constexpr void
2631       _M_write(_CharT __c)
2632       {
2633         *_M_next++ = __c;
2634         if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
2635           _M_overflow();
2636       }
2638       constexpr void
2639       _M_write(basic_string_view<_CharT> __s)
2640       {
2641         span __to = _M_unused();
2642         while (__to.size() <= __s.size())
2643           {
2644             __s.copy(__to.data(), __to.size());
2645             _M_next += __to.size();
2646             __s.remove_prefix(__to.size());
2647             _M_overflow();
2648             __to = _M_unused();
2649           }
2650         if (__s.size())
2651           {
2652             __s.copy(__to.data(), __s.size());
2653             _M_next += __s.size();
2654           }
2655       }
2657       // A successful _Reservation can be used to directly write
2658       // up to N characters to the sink to avoid unwanted buffering.
2659       struct _Reservation
2660       {
2661         // True if the reservation was successful, false otherwise.
2662         explicit operator bool() const noexcept { return _M_sink; }
2663         // A pointer to write directly to the sink.
2664         _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
2665         // Add n to the _M_next iterator for the sink.
2666         void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
2667         _Sink* _M_sink;
2668       };
2670       // Attempt to reserve space to write n characters to the sink.
2671       // If anything is written to the reservation then there must be a call
2672       // to _M_bump(N2) before any call to another member function of *this,
2673       // where N2 is the number of characters written.
2674       virtual _Reservation
2675       _M_reserve(size_t __n)
2676       {
2677         if (__n <= _M_unused().size())
2678           return { this };
2680         if (__n <= _M_span.size()) // Cannot meet the request.
2681           {
2682             _M_overflow(); // Make more space available.
2683             if (__n <= _M_unused().size())
2684               return { this };
2685           }
2686         return { nullptr };
2687       }
2689       // Update the next output position after writing directly to the sink.
2690       // pre: no calls to _M_write or _M_overflow since _M_reserve.
2691       virtual void
2692       _M_bump(size_t __n)
2693       { _M_next += __n; }
2695     public:
2696       _Sink(const _Sink&) = delete;
2697       _Sink& operator=(const _Sink&) = delete;
2699       [[__gnu__::__always_inline__]]
2700       constexpr _Sink_iter<_CharT>
2701       out() noexcept
2702       { return _Sink_iter<_CharT>(*this); }
2703     };
2705   // A sink with an internal buffer. This is used to implement concrete sinks.
2706   template<typename _CharT>
2707     class _Buf_sink : public _Sink<_CharT>
2708     {
2709     protected:
2710       _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
2712       [[__gnu__::__always_inline__]]
2713       constexpr
2714       _Buf_sink() noexcept
2715       : _Sink<_CharT>(_M_buf)
2716       { }
2717     };
2719   using _GLIBCXX_STD_C::vector;
2721   // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
2722   // Writes to a buffer then appends that to the sequence when it fills up.
2723   template<typename _Seq>
2724     class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
2725     {
2726       using _CharT = typename _Seq::value_type;
2728       _Seq _M_seq;
2730       // Transfer buffer contents to the sequence, so buffer can be refilled.
2731       void
2732       _M_overflow() override
2733       {
2734         auto __s = this->_M_used();
2735         if (__s.empty()) [[unlikely]]
2736           return; // Nothing in the buffer to transfer to _M_seq.
2738         // If _M_reserve was called then _M_bump must have been called too.
2739         _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
2741         if constexpr (__is_specialization_of<_Seq, basic_string>)
2742           _M_seq.append(__s.data(), __s.size());
2743         else
2744           _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
2746         // Make the whole of _M_buf available for the next write:
2747         this->_M_rewind();
2748       }
2750       typename _Sink<_CharT>::_Reservation
2751       _M_reserve(size_t __n) override
2752       {
2753         // We might already have n characters available in this->_M_unused(),
2754         // but the whole point of this function is to be an optimization for
2755         // the std::format("{}", x) case. We want to avoid writing to _M_buf
2756         // and then copying that into a basic_string if possible, so this
2757         // function prefers to create space directly in _M_seq rather than
2758         // using _M_buf.
2760         if constexpr (__is_specialization_of<_Seq, basic_string>
2761                         || __is_specialization_of<_Seq, vector>)
2762           {
2763             // Flush the buffer to _M_seq first (should not be needed).
2764             if (this->_M_used().size()) [[unlikely]]
2765               _Seq_sink::_M_overflow();
2767             // Expand _M_seq to make __n new characters available:
2768             const auto __sz = _M_seq.size();
2769             if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
2770               _M_seq.__resize_and_overwrite(__sz + __n,
2771                                             [](auto, auto __n2) {
2772                                               return __n2;
2773                                             });
2774             else
2775               _M_seq.resize(__sz + __n);
2777             // Set _M_used() to be a span over the original part of _M_seq
2778             // and _M_unused() to be the extra capacity we just created:
2779             this->_M_reset(_M_seq, __sz);
2780             return { this };
2781           }
2782         else // Try to use the base class' buffer.
2783           return _Sink<_CharT>::_M_reserve(__n);
2784       }
2786       void
2787       _M_bump(size_t __n) override
2788       {
2789         if constexpr (__is_specialization_of<_Seq, basic_string>
2790                         || __is_specialization_of<_Seq, vector>)
2791           {
2792             auto __s = this->_M_used();
2793             _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
2794             // Truncate the sequence to the part that was actually written to:
2795             _M_seq.resize(__s.size() + __n);
2796             // Switch back to using buffer:
2797             this->_M_reset(this->_M_buf);
2798           }
2799       }
2801     public:
2802       // TODO: for SSO string, use SSO buffer as initial span, then switch
2803       // to _M_buf if it overflows? Or even do that for all unused capacity?
2805       [[__gnu__::__always_inline__]]
2806       _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
2807       { }
2809       _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
2810       : _M_seq(std::move(__s))
2811       { }
2813       using _Sink<_CharT>::out;
2815       _Seq
2816       get() &&
2817       {
2818         if (this->_M_used().size() != 0)
2819           _Seq_sink::_M_overflow();
2820         return std::move(_M_seq);
2821       }
2823       // A writable span that views everything written to the sink.
2824       // Will be either a view over _M_seq or the used part of _M_buf.
2825       span<_CharT>
2826       view()
2827       {
2828         auto __s = this->_M_used();
2829         if (_M_seq.size())
2830           {
2831             if (__s.size() != 0)
2832               _Seq_sink::_M_overflow();
2833             return _M_seq;
2834           }
2835         return __s;
2836       }
2837     };
2839   template<typename _CharT, typename _Alloc = allocator<_CharT>>
2840     using _Str_sink
2841       = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
2843   // template<typename _CharT, typename _Alloc = allocator<_CharT>>
2844     // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
2846   // A sink that writes to an output iterator.
2847   // Writes to a fixed-size buffer and then flushes to the output iterator
2848   // when the buffer fills up.
2849   template<typename _CharT, typename _OutIter>
2850     class _Iter_sink : public _Buf_sink<_CharT>
2851     {
2852       _OutIter _M_out;
2853       iter_difference_t<_OutIter> _M_max;
2855     protected:
2856       size_t _M_count = 0;
2858       void
2859       _M_overflow() override
2860       {
2861         auto __s = this->_M_used();
2862         if (_M_max < 0) // No maximum.
2863           _M_out = ranges::copy(__s, std::move(_M_out)).out;
2864         else if (_M_count < static_cast<size_t>(_M_max))
2865           {
2866             auto __max = _M_max - _M_count;
2867             span<_CharT> __first;
2868             if (__max < __s.size())
2869               __first = __s.first(static_cast<size_t>(__max));
2870             else
2871               __first = __s;
2872             _M_out = ranges::copy(__first, std::move(_M_out)).out;
2873           }
2874         this->_M_rewind();
2875         _M_count += __s.size();
2876       }
2878     public:
2879       [[__gnu__::__always_inline__]]
2880       explicit
2881       _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
2882       : _M_out(std::move(__out)), _M_max(__max)
2883       { }
2885       using _Sink<_CharT>::out;
2887       format_to_n_result<_OutIter>
2888       _M_finish() &&
2889       {
2890         if (this->_M_used().size() != 0)
2891           _Iter_sink::_M_overflow();
2892         iter_difference_t<_OutIter> __count(_M_count);
2893         return { std::move(_M_out), __count };
2894       }
2895     };
2897   // Partial specialization for contiguous iterators.
2898   // No buffer is used, characters are written straight to the iterator.
2899   // We do not know the size of the output range, so the span size just grows
2900   // as needed. The end of the span might be an invalid pointer outside the
2901   // valid range, but we never actually call _M_span.end(). This class does
2902   // not introduce any invalid pointer arithmetic or overflows that would not
2903   // have happened anyway.
2904   template<typename _CharT, contiguous_iterator _OutIter>
2905     requires same_as<iter_value_t<_OutIter>, _CharT>
2906     class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
2907     {
2908       _OutIter _M_first;
2909       iter_difference_t<_OutIter> _M_max = -1;
2910     protected:
2911       size_t _M_count = 0;
2912     private:
2913       _CharT _M_buf[64]; // Write here after outputting _M_max characters.
2915     protected:
2916       void
2917       _M_overflow() override
2918       {
2919         if (this->_M_unused().size() != 0)
2920           return; // No need to switch to internal buffer yet.
2922         auto __s = this->_M_used();
2924         if (_M_max >= 0)
2925           {
2926             _M_count += __s.size();
2927             // Span was already sized for the maximum character count,
2928             // if it overflows then any further output must go to the
2929             // internal buffer, to be discarded.
2930             this->_M_reset(this->_M_buf);
2931           }
2932         else
2933           {
2934             // No maximum character count. Just extend the span to allow
2935             // writing more characters to it.
2936             this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
2937           }
2938       }
2940       typename _Sink<_CharT>::_Reservation
2941       _M_reserve(size_t __n) final
2942       {
2943         auto __avail = this->_M_unused();
2944         if (__n > __avail.size())
2945           {
2946             if (_M_max >= 0)
2947               return {}; // cannot grow
2949             auto __s = this->_M_used();
2950             this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
2951           }
2952         return { this };
2953       }
2955     private:
2956       static span<_CharT>
2957       _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
2958                    span<_CharT> __buf) noexcept
2959       {
2960         if (__n == 0)
2961           return __buf; // Only write to the internal buffer.
2963         if (__n > 0)
2964           {
2965             if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
2966                             || sizeof(__n) > sizeof(size_t))
2967               {
2968                 // __int128 or __detail::__max_diff_type
2969                 auto __m = iter_difference_t<_OutIter>((size_t)-1);
2970                 if (__n > __m)
2971                   __n = __m;
2972               }
2973             return {__ptr, (size_t)__n};
2974           }
2976 #if __has_builtin(__builtin_dynamic_object_size)
2977         if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
2978           return {__ptr, __bytes / sizeof(_CharT)};
2979 #endif
2980         // Avoid forming a pointer to a different memory page.
2981         const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
2982         __n = (1024 - __off) / sizeof(_CharT);
2983         if (__n > 0) [[likely]]
2984           return {__ptr, static_cast<size_t>(__n)};
2985         else // Misaligned/packed buffer of wchar_t?
2986           return {__ptr, 1};
2987       }
2989     public:
2990       explicit
2991       _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
2992       : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
2993         _M_first(__out), _M_max(__n)
2994       { }
2996       format_to_n_result<_OutIter>
2997       _M_finish() &&
2998       {
2999         auto __s = this->_M_used();
3000         if (__s.data() == _M_buf)
3001           {
3002             // Switched to internal buffer, so must have written _M_max.
3003             iter_difference_t<_OutIter> __count(_M_count + __s.size());
3004             return { _M_first + _M_max, __count };
3005           }
3006         else // Not using internal buffer yet
3007           {
3008             iter_difference_t<_OutIter> __count(__s.size());
3009             return { _M_first + __count, __count };
3010           }
3011       }
3012     };
3014   enum _Arg_t : unsigned char {
3015     _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3016     _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3017     _Arg_i128, _Arg_u128,
3018     _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3019 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3020     _Arg_next_value_,
3021     _Arg_f128 = _Arg_ldbl,
3022     _Arg_ibm128 = _Arg_next_value_,
3023 #else
3024     _Arg_f128,
3025 #endif
3026     _Arg_max_
3027   };
3029   template<typename _Context>
3030     struct _Arg_value
3031     {
3032       using _CharT = typename _Context::char_type;
3034       struct _HandleBase
3035       {
3036         const void* _M_ptr;
3037         void (*_M_func)();
3038       };
3040       union
3041       {
3042         monostate _M_none;
3043         bool _M_bool;
3044         _CharT _M_c;
3045         int _M_i;
3046         unsigned _M_u;
3047         long long _M_ll;
3048         unsigned long long _M_ull;
3049         float _M_flt;
3050         double _M_dbl;
3051 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3052         long double _M_ldbl;
3053 #endif
3054         const _CharT* _M_str;
3055         basic_string_view<_CharT> _M_sv;
3056         const void* _M_ptr;
3057         _HandleBase _M_handle;
3058 #ifdef __SIZEOF_INT128__
3059         __int128 _M_i128;
3060         unsigned __int128 _M_u128;
3061 #endif
3062 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3063         __ieee128 _M_f128;
3064         __ibm128  _M_ibm128;
3065 #elif _GLIBCXX_FORMAT_F128 == 2
3066         __float128_t _M_f128;
3067 #endif
3068       };
3070       [[__gnu__::__always_inline__]]
3071       _Arg_value() : _M_none() { }
3073 #if 0
3074       template<typename _Tp>
3075         _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3076         { _S_get<_Tp>() = __val; }
3077 #endif
3079       template<typename _Tp, typename _Self>
3080         [[__gnu__::__always_inline__]]
3081         static auto&
3082         _S_get(_Self& __u) noexcept
3083         {
3084           if constexpr (is_same_v<_Tp, bool>)
3085             return __u._M_bool;
3086           else if constexpr (is_same_v<_Tp, _CharT>)
3087             return __u._M_c;
3088           else if constexpr (is_same_v<_Tp, int>)
3089             return __u._M_i;
3090           else if constexpr (is_same_v<_Tp, unsigned>)
3091             return __u._M_u;
3092           else if constexpr (is_same_v<_Tp, long long>)
3093             return __u._M_ll;
3094           else if constexpr (is_same_v<_Tp, unsigned long long>)
3095             return __u._M_ull;
3096           else if constexpr (is_same_v<_Tp, float>)
3097             return __u._M_flt;
3098           else if constexpr (is_same_v<_Tp, double>)
3099             return __u._M_dbl;
3100 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3101           else if constexpr (is_same_v<_Tp, long double>)
3102             return __u._M_ldbl;
3103 #else
3104           else if constexpr (is_same_v<_Tp, __ieee128>)
3105             return __u._M_f128;
3106           else if constexpr (is_same_v<_Tp, __ibm128>)
3107             return __u._M_ibm128;
3108 #endif
3109           else if constexpr (is_same_v<_Tp, const _CharT*>)
3110             return __u._M_str;
3111           else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3112             return __u._M_sv;
3113           else if constexpr (is_same_v<_Tp, const void*>)
3114             return __u._M_ptr;
3115 #ifdef __SIZEOF_INT128__
3116           else if constexpr (is_same_v<_Tp, __int128>)
3117             return __u._M_i128;
3118           else if constexpr (is_same_v<_Tp, unsigned __int128>)
3119             return __u._M_u128;
3120 #endif
3121 #if _GLIBCXX_FORMAT_F128 == 2
3122           else if constexpr (is_same_v<_Tp, __float128_t>)
3123             return __u._M_f128;
3124 #endif
3125           else if constexpr (derived_from<_Tp, _HandleBase>)
3126             return static_cast<_Tp&>(__u._M_handle);
3127           // Otherwise, ill-formed.
3128         }
3130       template<typename _Tp>
3131         [[__gnu__::__always_inline__]]
3132         auto&
3133         _M_get() noexcept
3134         { return _S_get<_Tp>(*this); }
3136       template<typename _Tp>
3137         [[__gnu__::__always_inline__]]
3138         const auto&
3139         _M_get() const noexcept
3140         { return _S_get<_Tp>(*this); }
3142       template<typename _Tp>
3143         [[__gnu__::__always_inline__]]
3144         void
3145         _M_set(_Tp __v) noexcept
3146         {
3147           if constexpr (derived_from<_Tp, _HandleBase>)
3148             std::construct_at(&_M_handle, __v);
3149           else
3150             _S_get<_Tp>(*this) = __v;
3151         }
3152       };
3154   // [format.arg.store], class template format-arg-store
3155   template<typename _Context, typename... _Args>
3156     class _Arg_store;
3158 } // namespace __format
3159 /// @endcond
3161   template<typename _Context>
3162     class basic_format_arg
3163     {
3164       using _CharT = typename _Context::char_type;
3166       template<typename _Tp>
3167         static constexpr bool __formattable
3168           = __format::__formattable_with<_Tp, _Context>;
3170     public:
3171       class handle : public __format::_Arg_value<_Context>::_HandleBase
3172       {
3173         using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3175         // Format as const if possible, to reduce instantiations.
3176         template<typename _Tp>
3177           using __maybe_const_t
3178             = __conditional_t<__format::__formattable_with<_Tp, _Context>,
3179                               const _Tp, _Tp>;
3181         template<typename _Tq>
3182           static void
3183           _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3184                     _Context& __format_ctx, const void* __ptr)
3185           {
3186             using _Td = remove_const_t<_Tq>;
3187             typename _Context::template formatter_type<_Td> __f;
3188             __parse_ctx.advance_to(__f.parse(__parse_ctx));
3189             _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3190             __format_ctx.advance_to(__f.format(__val, __format_ctx));
3191           }
3193         template<typename _Tp>
3194           explicit
3195           handle(_Tp& __val) noexcept
3196           {
3197             if constexpr (!__format::__formattable_with<const _Tp, _Context>)
3198               static_assert(!is_const_v<_Tp>, "std::format argument must be "
3199                                               "non-const for this type");
3201             this->_M_ptr = __builtin_addressof(__val);
3202             auto __func = _S_format<__maybe_const_t<_Tp>>;
3203             this->_M_func = reinterpret_cast<void(*)()>(__func);
3204           }
3206         friend class basic_format_arg<_Context>;
3208       public:
3209         handle(const handle&) = default;
3210         handle& operator=(const handle&) = default;
3212         [[__gnu__::__always_inline__]]
3213         void
3214         format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3215         {
3216           using _Func = void(*)(basic_format_parse_context<_CharT>&,
3217                                 _Context&, const void*);
3218           auto __f = reinterpret_cast<_Func>(this->_M_func);
3219           __f(__pc, __fc, this->_M_ptr);
3220         }
3221       };
3223       [[__gnu__::__always_inline__]]
3224       basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3226       [[nodiscard,__gnu__::__always_inline__]]
3227       explicit operator bool() const noexcept
3228       { return _M_type != __format::_Arg_none; }
3230     private:
3231       template<typename _Ctx>
3232         friend class basic_format_args;
3234       template<typename _Ctx, typename... _Args>
3235         friend class __format::_Arg_store;
3237       static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3239       __format::_Arg_value<_Context> _M_val;
3240       __format::_Arg_t _M_type;
3242       // Transform incoming argument type to the type stored in _Arg_value.
3243       // e.g. short -> int, std::string -> std::string_view,
3244       // char[3] -> const char*.
3245       template<typename _Tp>
3246         static consteval auto
3247         _S_to_arg_type()
3248         {
3249           using _Td = remove_const_t<_Tp>;
3250           if constexpr (is_same_v<_Td, bool>)
3251             return type_identity<bool>();
3252           else if constexpr (is_same_v<_Td, _CharT>)
3253             return type_identity<_CharT>();
3254           else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3255             return type_identity<_CharT>();
3256 #ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3257           else if constexpr (is_same_v<_Td, __int128>)
3258             return type_identity<__int128>();
3259           else if constexpr (is_same_v<_Td, unsigned __int128>)
3260             return type_identity<unsigned __int128>();
3261 #endif
3262           else if constexpr (__is_signed_integer<_Td>::value)
3263             {
3264               if constexpr (sizeof(_Td) <= sizeof(int))
3265                 return type_identity<int>();
3266               else if constexpr (sizeof(_Td) <= sizeof(long long))
3267                 return type_identity<long long>();
3268             }
3269           else if constexpr (__is_unsigned_integer<_Td>::value)
3270             {
3271               if constexpr (sizeof(_Td) <= sizeof(unsigned))
3272                 return type_identity<unsigned>();
3273               else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3274                 return type_identity<unsigned long long>();
3275             }
3276           else if constexpr (is_same_v<_Td, float>)
3277             return type_identity<float>();
3278           else if constexpr (is_same_v<_Td, double>)
3279             return type_identity<double>();
3280 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3281           else if constexpr (is_same_v<_Td, long double>)
3282             return type_identity<long double>();
3283 #else
3284           else if constexpr (is_same_v<_Td, __ibm128>)
3285             return type_identity<__ibm128>();
3286           else if constexpr (is_same_v<_Td, __ieee128>)
3287             return type_identity<__ieee128>();
3288 #endif
3290 #if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3291           else if constexpr (is_same_v<_Td, _Float16>)
3292             return type_identity<float>();
3293 #endif
3295 #if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3296           else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3297             return type_identity<float>();
3298 #endif
3300 #ifdef __FLT32_DIG__
3301           else if constexpr (is_same_v<_Td, _Float32>)
3302 # ifdef _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3303             return type_identity<float>();
3304 # else
3305             return type_identity<_Float32>();
3306 # endif
3307 #endif
3308 #ifdef __FLT64_DIG__
3309           else if constexpr (is_same_v<_Td, _Float64>)
3310 # ifdef _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3311             return type_identity<double>();
3312 # else
3313             return type_identity<_Float64>();
3314 # endif
3315 #endif
3316 #if _GLIBCXX_FORMAT_F128
3317 # if __FLT128_DIG__
3318           else if constexpr (is_same_v<_Td, _Float128>)
3319             return type_identity<__format::__float128_t>();
3320 # endif
3321 # if __SIZEOF_FLOAT128__
3322           else if constexpr (is_same_v<_Td, __float128>)
3323             return type_identity<__format::__float128_t>();
3324 # endif
3325 #endif
3326           else if constexpr (__is_specialization_of<_Td, basic_string_view>
3327                             || __is_specialization_of<_Td, basic_string>)
3328             {
3329               if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3330                 return type_identity<basic_string_view<_CharT>>();
3331               else
3332                 return type_identity<handle>();
3333             }
3334           else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3335             return type_identity<const _CharT*>();
3336           else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3337             return type_identity<const _CharT*>();
3338           else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3339             return type_identity<const void*>();
3340           else if constexpr (is_same_v<_Td, nullptr_t>)
3341             return type_identity<const void*>();
3342           else
3343             return type_identity<handle>();
3344         }
3346       // Transform a formattable type to the appropriate storage type.
3347       template<typename _Tp>
3348         using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3350       // Get the _Arg_t value corresponding to a normalized type.
3351       template<typename _Tp>
3352         static consteval __format::_Arg_t
3353         _S_to_enum()
3354         {
3355           using namespace __format;
3356           if constexpr (is_same_v<_Tp, bool>)
3357             return _Arg_bool;
3358           else if constexpr (is_same_v<_Tp, _CharT>)
3359             return _Arg_c;
3360           else if constexpr (is_same_v<_Tp, int>)
3361             return _Arg_i;
3362           else if constexpr (is_same_v<_Tp, unsigned>)
3363             return _Arg_u;
3364           else if constexpr (is_same_v<_Tp, long long>)
3365             return _Arg_ll;
3366           else if constexpr (is_same_v<_Tp, unsigned long long>)
3367             return _Arg_ull;
3368           else if constexpr (is_same_v<_Tp, float>)
3369             return _Arg_flt;
3370           else if constexpr (is_same_v<_Tp, double>)
3371             return _Arg_dbl;
3372 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3373           else if constexpr (is_same_v<_Tp, long double>)
3374             return _Arg_ldbl;
3375 #else
3376           // Don't use _Arg_ldbl for this target, it's ambiguous.
3377           else if constexpr (is_same_v<_Tp, __ibm128>)
3378             return _Arg_ibm128;
3379           else if constexpr (is_same_v<_Tp, __ieee128>)
3380             return _Arg_f128;
3381 #endif
3382           else if constexpr (is_same_v<_Tp, const _CharT*>)
3383             return _Arg_str;
3384           else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3385             return _Arg_sv;
3386           else if constexpr (is_same_v<_Tp, const void*>)
3387             return _Arg_ptr;
3388 #ifdef __SIZEOF_INT128__
3389           else if constexpr (is_same_v<_Tp, __int128>)
3390             return _Arg_i128;
3391           else if constexpr (is_same_v<_Tp, unsigned __int128>)
3392             return _Arg_u128;
3393 #endif
3395           // N.B. some of these types will never actually be used here,
3396           // because they get normalized to a standard floating-point type.
3397 #if defined __FLT32_DIG__ && ! _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3398           else if constexpr (is_same_v<_Tp, _Float32>)
3399             return _Arg_f32;
3400 #endif
3401 #if defined __FLT64_DIG__ && ! _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3402           else if constexpr (is_same_v<_Tp, _Float64>)
3403             return _Arg_f64;
3404 #endif
3405 #if _GLIBCXX_FORMAT_F128 == 2
3406           else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3407             return _Arg_f128;
3408 #endif
3409           else if constexpr (is_same_v<_Tp, handle>)
3410             return _Arg_handle;
3411         }
3413       template<typename _Tp>
3414         void
3415         _M_set(_Tp __v) noexcept
3416         {
3417           _M_type = _S_to_enum<_Tp>();
3418           _M_val._M_set(__v);
3419         }
3421       template<typename _Tp>
3422         requires __format::__formattable_with<_Tp, _Context>
3423         explicit
3424         basic_format_arg(_Tp& __v) noexcept
3425         {
3426           using _Td = _Normalize<_Tp>;
3427           if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3428             _M_set(_Td{__v.data(), __v.size()});
3429           else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3430                                && is_same_v<_CharT, wchar_t>)
3431             _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3432           else
3433             _M_set(static_cast<_Td>(__v));
3434         }
3436       template<typename _Ctx, typename... _Argz>
3437         friend auto
3438         make_format_args(_Argz&...) noexcept;
3440       template<typename _Visitor, typename _Ctx>
3441         friend decltype(auto)
3442         visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3444       template<typename _Visitor>
3445         decltype(auto)
3446         _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
3447         {
3448           using namespace __format;
3449           switch (__type)
3450           {
3451             case _Arg_none:
3452               return std::forward<_Visitor>(__vis)(_M_val._M_none);
3453             case _Arg_bool:
3454               return std::forward<_Visitor>(__vis)(_M_val._M_bool);
3455             case _Arg_c:
3456               return std::forward<_Visitor>(__vis)(_M_val._M_c);
3457             case _Arg_i:
3458               return std::forward<_Visitor>(__vis)(_M_val._M_i);
3459             case _Arg_u:
3460               return std::forward<_Visitor>(__vis)(_M_val._M_u);
3461             case _Arg_ll:
3462               return std::forward<_Visitor>(__vis)(_M_val._M_ll);
3463             case _Arg_ull:
3464               return std::forward<_Visitor>(__vis)(_M_val._M_ull);
3465 #if __glibcxx_to_chars // FIXME: need to be able to format these types!
3466             case _Arg_flt:
3467               return std::forward<_Visitor>(__vis)(_M_val._M_flt);
3468             case _Arg_dbl:
3469               return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
3470 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3471             case _Arg_ldbl:
3472               return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
3473 #else
3474             case _Arg_f128:
3475               return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3476             case _Arg_ibm128:
3477               return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
3478 #endif
3479 #endif
3480             case _Arg_str:
3481               return std::forward<_Visitor>(__vis)(_M_val._M_str);
3482             case _Arg_sv:
3483               return std::forward<_Visitor>(__vis)(_M_val._M_sv);
3484             case _Arg_ptr:
3485               return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
3486             case _Arg_handle:
3487             {
3488               auto& __h = static_cast<handle&>(_M_val._M_handle);
3489               return std::forward<_Visitor>(__vis)(__h);
3490             }
3491 #ifdef __SIZEOF_INT128__
3492             case _Arg_i128:
3493               return std::forward<_Visitor>(__vis)(_M_val._M_i128);
3494             case _Arg_u128:
3495               return std::forward<_Visitor>(__vis)(_M_val._M_u128);
3496 #endif
3498 #if _GLIBCXX_FORMAT_F128 == 2
3499             case _Arg_f128:
3500               return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3501 #endif
3503             default:
3504               // _Arg_f16 etc.
3505               __builtin_unreachable();
3506           }
3507         }
3508     };
3510   template<typename _Visitor, typename _Context>
3511     inline decltype(auto)
3512     visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
3513     {
3514       return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
3515     }
3517 /// @cond undocumented
3518 namespace __format
3520   struct _WidthPrecVisitor
3521   {
3522     template<typename _Tp>
3523       size_t
3524       operator()(_Tp& __arg) const
3525       {
3526         if constexpr (is_same_v<_Tp, monostate>)
3527           __format::__invalid_arg_id_in_format_string();
3528         // _GLIBCXX_RESOLVE_LIB_DEFECTS
3529         // 3720. Restrict the valid types of arg-id for width and precision
3530         // 3721. Allow an arg-id with a value of zero for width
3531         else if constexpr (sizeof(_Tp) <= sizeof(long long))
3532           {
3533             // _GLIBCXX_RESOLVE_LIB_DEFECTS
3534             // 3720. Restrict the valid types of arg-id for width and precision
3535             if constexpr (__is_unsigned_integer<_Tp>::value)
3536               return __arg;
3537             else if constexpr (__is_signed_integer<_Tp>::value)
3538               if (__arg >= 0)
3539                 return __arg;
3540           }
3541         __throw_format_error("format error: argument used for width or "
3542                              "precision must be a non-negative integer");
3543       }
3544   };
3546   template<typename _Context>
3547     inline size_t
3548     __int_from_arg(const basic_format_arg<_Context>& __arg)
3549     { return std::visit_format_arg(_WidthPrecVisitor(), __arg); }
3551   // Pack _Arg_t enum values into a single 60-bit integer.
3552   template<int _Bits, size_t _Nm>
3553     constexpr auto
3554     __pack_arg_types(const array<_Arg_t, _Nm>& __types)
3555     {
3556       __UINT64_TYPE__ __packed_types = 0;
3557       for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
3558         __packed_types = (__packed_types << _Bits) | *__i;
3559       return __packed_types;
3560     }
3561 } // namespace __format
3562 /// @endcond
3564   template<typename _Context>
3565     class basic_format_args
3566     {
3567       static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
3568       static constexpr int _S_packed_type_mask = 0b11111;
3569       static constexpr int _S_max_packed_args = 12;
3571       static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
3573       template<typename... _Args>
3574         using _Store = __format::_Arg_store<_Context, _Args...>;
3576       template<typename _Ctx, typename... _Args>
3577         friend class __format::_Arg_store;
3579       using uint64_t = __UINT64_TYPE__;
3580       using _Format_arg = basic_format_arg<_Context>;
3581       using _Format_arg_val = __format::_Arg_value<_Context>;
3583       // If args are packed then the number of args is in _M_packed_size and
3584       // the packed types are in _M_unpacked_size, accessed via _M_type(i).
3585       // If args are not packed then the number of args is in _M_unpacked_size
3586       // and _M_packed_size is zero.
3587       uint64_t _M_packed_size : 4;
3588       uint64_t _M_unpacked_size : 60;
3590       union {
3591         const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
3592         const _Format_arg* _M_args;       // Active when _M_packed_size == 0
3593       };
3595       size_t
3596       _M_size() const noexcept
3597       { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
3599       typename __format::_Arg_t
3600       _M_type(size_t __i) const noexcept
3601       {
3602         uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
3603         return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
3604       }
3606       template<typename _Ctx, typename... _Args>
3607         friend auto
3608         make_format_args(_Args&...) noexcept;
3610       // An array of _Arg_t enums corresponding to _Args...
3611       template<typename... _Args>
3612         static consteval array<__format::_Arg_t, sizeof...(_Args)>
3613         _S_types_to_pack()
3614         { return {_Format_arg::template _S_to_enum<_Args>()...}; }
3616     public:
3617       basic_format_args() noexcept = default;
3619       template<typename... _Args>
3620         basic_format_args(const _Store<_Args...>& __store) noexcept;
3622       [[nodiscard,__gnu__::__always_inline__]]
3623       basic_format_arg<_Context>
3624       get(size_t __i) const noexcept
3625       {
3626         basic_format_arg<_Context> __arg;
3627         if (__i < _M_packed_size)
3628           {
3629             __arg._M_type = _M_type(__i);
3630             __arg._M_val = _M_values[__i];
3631           }
3632         else if (_M_packed_size == 0 && __i < _M_unpacked_size)
3633           __arg = _M_args[__i];
3634         return __arg;
3635       }
3636     };
3638   // _GLIBCXX_RESOLVE_LIB_DEFECTS
3639   // 3810. CTAD for std::basic_format_args
3640   template<typename _Context, typename... _Args>
3641     basic_format_args(__format::_Arg_store<_Context, _Args...>)
3642       -> basic_format_args<_Context>;
3644   template<typename _Context, typename... _Args>
3645     auto
3646     make_format_args(_Args&... __fmt_args) noexcept;
3648   // An array of type-erased formatting arguments.
3649   template<typename _Context, typename... _Args>
3650     class __format::_Arg_store
3651     {
3652       friend std::basic_format_args<_Context>;
3654       template<typename _Ctx, typename... _Argz>
3655         friend auto std::
3656 #if _GLIBCXX_INLINE_VERSION
3657         __8:: // Needed for PR c++/59256
3658 #endif
3659         make_format_args(_Argz&...) noexcept;
3661       // For a sufficiently small number of arguments we only store values.
3662       // basic_format_args can get the types from the _Args pack.
3663       static constexpr bool _S_values_only
3664         = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
3666       using _Element_t
3667         = __conditional_t<_S_values_only,
3668                           __format::_Arg_value<_Context>,
3669                           basic_format_arg<_Context>>;
3671       _Element_t _M_args[sizeof...(_Args)];
3673       template<typename _Tp>
3674         static _Element_t
3675         _S_make_elt(_Tp& __v)
3676         {
3677           basic_format_arg<_Context> __arg(__v);
3678           if constexpr (_S_values_only)
3679             return __arg._M_val;
3680           else
3681             return __arg;
3682         }
3684       template<typename... _Tp>
3685         requires (sizeof...(_Tp) == sizeof...(_Args))
3686         [[__gnu__::__always_inline__]]
3687         _Arg_store(_Tp&... __a) noexcept
3688         : _M_args{_S_make_elt(__a)...}
3689         { }
3690     };
3692   template<typename _Context>
3693     class __format::_Arg_store<_Context>
3694     { };
3696   template<typename _Context>
3697     template<typename... _Args>
3698       inline
3699       basic_format_args<_Context>::
3700       basic_format_args(const _Store<_Args...>& __store) noexcept
3701       {
3702         if constexpr (sizeof...(_Args) == 0)
3703           {
3704             _M_packed_size = 0;
3705             _M_unpacked_size = 0;
3706             _M_args = nullptr;
3707           }
3708         else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
3709           {
3710             // The number of packed arguments:
3711             _M_packed_size = sizeof...(_Args);
3712             // The packed type enums:
3713             _M_unpacked_size
3714               = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
3715             // The _Arg_value objects.
3716             _M_values = __store._M_args;
3717           }
3718         else
3719           {
3720             // No packed arguments:
3721             _M_packed_size = 0;
3722             // The number of unpacked arguments:
3723             _M_unpacked_size = sizeof...(_Args);
3724             // The basic_format_arg objects:
3725             _M_args = __store._M_args;
3726           }
3727       }
3729   /// Capture formatting arguments for use by `std::vformat`.
3730   template<typename _Context = format_context, typename... _Args>
3731     [[nodiscard,__gnu__::__always_inline__]]
3732     inline auto
3733     make_format_args(_Args&... __fmt_args) noexcept
3734     {
3735       using _Fmt_arg = basic_format_arg<_Context>;
3736       using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
3737                      _Normalize<_Args>...>;
3738       return _Store(__fmt_args...);
3739     }
3741 #ifdef _GLIBCXX_USE_WCHAR_T
3742   /// Capture formatting arguments for use by `std::vformat` (for wide output).
3743   template<typename... _Args>
3744     [[nodiscard,__gnu__::__always_inline__]]
3745     inline auto
3746     make_wformat_args(_Args&... __args) noexcept
3747     { return std::make_format_args<wformat_context>(__args...); }
3748 #endif
3750 /// @cond undocumented
3751 namespace __format
3753   template<typename _Out, typename _CharT, typename _Context>
3754     _Out
3755     __do_vformat_to(_Out, basic_string_view<_CharT>,
3756                     const basic_format_args<_Context>&,
3757                     const locale* = nullptr);
3758 } // namespace __format
3759 /// @endcond
3761   /** Context for std::format and similar functions.
3762    *
3763    * A formatting context contains an output iterator and locale to use
3764    * for the formatting operations. Most programs will never need to use
3765    * this class template explicitly. For typical uses of `std::format` the
3766    * library will use the specializations `std::format_context` (for `char`)
3767    * and `std::wformat_context` (for `wchar_t`).
3768    */
3769   template<typename _Out, typename _CharT>
3770     class basic_format_context
3771     {
3772       static_assert( output_iterator<_Out, const _CharT&> );
3774       basic_format_args<basic_format_context> _M_args;
3775       _Out _M_out;
3776       __format::_Optional_locale _M_loc;
3778       basic_format_context(basic_format_args<basic_format_context> __args,
3779                            _Out __out)
3780       : _M_args(__args), _M_out(std::move(__out))
3781       { }
3783       basic_format_context(basic_format_args<basic_format_context> __args,
3784                            _Out __out, const std::locale& __loc)
3785       : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
3786       { }
3788       template<typename _Out2, typename _CharT2, typename _Context2>
3789         friend _Out2
3790         __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
3791                                   const basic_format_args<_Context2>&,
3792                                   const locale*);
3794     public:
3795       basic_format_context() = default;
3796       ~basic_format_context() = default;
3798       using iterator = _Out;
3799       using char_type = _CharT;
3800       template<typename _Tp>
3801         using formatter_type = formatter<_Tp, _CharT>;
3803       [[nodiscard]]
3804       basic_format_arg<basic_format_context>
3805       arg(size_t __id) const noexcept
3806       { return _M_args.get(__id); }
3808       [[nodiscard]]
3809       std::locale locale() { return _M_loc.value(); }
3811       [[nodiscard]]
3812       iterator out() { return std::move(_M_out); }
3814       void advance_to(iterator __it) { _M_out = std::move(__it); }
3815     };
3818 /// @cond undocumented
3819 namespace __format
3821   // Abstract base class defining an interface for scanning format strings.
3822   // Scan the characters in a format string, dividing it up into strings of
3823   // ordinary characters, escape sequences, and replacement fields.
3824   // Call virtual functions for derived classes to parse format-specifiers
3825   // or write formatted output.
3826   template<typename _CharT>
3827     struct _Scanner
3828     {
3829       using iterator = typename basic_format_parse_context<_CharT>::iterator;
3831       basic_format_parse_context<_CharT> _M_pc;
3833       constexpr explicit
3834       _Scanner(basic_string_view<_CharT> __str, size_t __nargs = -1)
3835       : _M_pc(__str, __nargs)
3836       { }
3838       constexpr iterator begin() const noexcept { return _M_pc.begin(); }
3839       constexpr iterator end() const noexcept { return _M_pc.end(); }
3841       constexpr void
3842       _M_scan()
3843       {
3844         basic_string_view<_CharT> __fmt = _M_fmt_str();
3846         if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
3847           {
3848             _M_pc.advance_to(begin() + 1);
3849             _M_format_arg(_M_pc.next_arg_id());
3850             return;
3851           }
3853         size_t __lbr = __fmt.find('{');
3854         size_t __rbr = __fmt.find('}');
3856         while (__fmt.size())
3857           {
3858             auto __cmp = __lbr <=> __rbr;
3859             if (__cmp == 0)
3860               {
3861                 _M_on_chars(end());
3862                 _M_pc.advance_to(end());
3863                 return;
3864               }
3865             else if (__cmp < 0)
3866               {
3867                 if (__lbr + 1 == __fmt.size()
3868                       || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
3869                   __format::__unmatched_left_brace_in_format_string();
3870                 const bool __is_escape = __fmt[__lbr + 1] == '{';
3871                 iterator __last = begin() + __lbr + int(__is_escape);
3872                 _M_on_chars(__last);
3873                 _M_pc.advance_to(__last + 1);
3874                 __fmt = _M_fmt_str();
3875                 if (__is_escape)
3876                   {
3877                     if (__rbr != __fmt.npos)
3878                       __rbr -= __lbr + 2;
3879                     __lbr = __fmt.find('{');
3880                   }
3881                 else
3882                   {
3883                     _M_on_replacement_field();
3884                     __fmt = _M_fmt_str();
3885                     __lbr = __fmt.find('{');
3886                     __rbr = __fmt.find('}');
3887                   }
3888               }
3889             else
3890               {
3891                 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
3892                   __format::__unmatched_right_brace_in_format_string();
3893                 iterator __last = begin() + __rbr;
3894                 _M_on_chars(__last);
3895                 _M_pc.advance_to(__last + 1);
3896                 __fmt = _M_fmt_str();
3897                 if (__lbr != __fmt.npos)
3898                   __lbr -= __rbr + 1;
3899                 __rbr = __fmt.find('}');
3900               }
3901           }
3902       }
3904       constexpr basic_string_view<_CharT>
3905       _M_fmt_str() const noexcept
3906       { return {begin(), end()}; }
3908       constexpr virtual void _M_on_chars(iterator) { }
3910       constexpr void _M_on_replacement_field()
3911       {
3912         auto __next = begin();
3914         size_t __id;
3915         if (*__next == '}')
3916           __id = _M_pc.next_arg_id();
3917         else if (*__next == ':')
3918           {
3919             __id = _M_pc.next_arg_id();
3920             _M_pc.advance_to(++__next);
3921           }
3922         else
3923           {
3924             auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
3925             if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
3926               __format::__invalid_arg_id_in_format_string();
3927             _M_pc.check_arg_id(__id = __i);
3928             if (*__ptr == ':')
3929               {
3930                 _M_pc.advance_to(++__ptr);
3931               }
3932             else
3933               _M_pc.advance_to(__ptr);
3934           }
3935         _M_format_arg(__id);
3936         if (begin() == end() || *begin() != '}')
3937           __format::__unmatched_left_brace_in_format_string();
3938         _M_pc.advance_to(begin() + 1); // Move past '}'
3939       }
3941       constexpr virtual void _M_format_arg(size_t __id) = 0;
3942     };
3944   // Process a format string and format the arguments in the context.
3945   template<typename _Out, typename _CharT>
3946     class _Formatting_scanner : public _Scanner<_CharT>
3947     {
3948     public:
3949       _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
3950                           basic_string_view<_CharT> __str)
3951       : _Scanner<_CharT>(__str), _M_fc(__fc)
3952       { }
3954     private:
3955       basic_format_context<_Out, _CharT>& _M_fc;
3957       using iterator = typename _Scanner<_CharT>::iterator;
3959       constexpr void
3960       _M_on_chars(iterator __last) override
3961       {
3962         basic_string_view<_CharT> __str(this->begin(), __last);
3963         _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
3964       }
3966       constexpr void
3967       _M_format_arg(size_t __id) override
3968       {
3969         using _Context = basic_format_context<_Out, _CharT>;
3970         using handle = typename basic_format_arg<_Context>::handle;
3972         std::visit_format_arg([this](auto& __arg) {
3973           using _Type = remove_reference_t<decltype(__arg)>;
3974           using _Formatter = typename _Context::template formatter_type<_Type>;
3975           if constexpr (is_same_v<_Type, monostate>)
3976             __format::__invalid_arg_id_in_format_string();
3977           else if constexpr (is_same_v<_Type, handle>)
3978             __arg.format(this->_M_pc, this->_M_fc);
3979           else if constexpr (is_default_constructible_v<_Formatter>)
3980             {
3981               _Formatter __f;
3982               this->_M_pc.advance_to(__f.parse(this->_M_pc));
3983               this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
3984             }
3985           else
3986             static_assert(__format::__formattable_with<_Type, _Context>);
3987         }, _M_fc.arg(__id));
3988       }
3989     };
3991   // Validate a format string for Args.
3992   template<typename _CharT, typename... _Args>
3993     class _Checking_scanner : public _Scanner<_CharT>
3994     {
3995       static_assert(
3996         (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
3997         "std::formatter must be specialized for each type being formatted");
3999     public:
4000       constexpr
4001       _Checking_scanner(basic_string_view<_CharT> __str)
4002       : _Scanner<_CharT>(__str, sizeof...(_Args))
4003       { }
4005     private:
4006       constexpr void
4007       _M_format_arg(size_t __id) override
4008       {
4009         if constexpr (sizeof...(_Args) != 0)
4010           {
4011             if (__id < sizeof...(_Args))
4012               {
4013                 _M_parse_format_spec<_Args...>(__id);
4014                 return;
4015               }
4016           }
4017         __builtin_unreachable();
4018       }
4020       template<typename _Tp, typename... _OtherArgs>
4021         constexpr void
4022         _M_parse_format_spec(size_t __id)
4023         {
4024           if (__id == 0)
4025             {
4026               formatter<_Tp, _CharT> __f;
4027               this->_M_pc.advance_to(__f.parse(this->_M_pc));
4028             }
4029           else if constexpr (sizeof...(_OtherArgs) != 0)
4030             _M_parse_format_spec<_OtherArgs...>(__id - 1);
4031           else
4032             __builtin_unreachable();
4033         }
4034     };
4036   template<typename _Out, typename _CharT, typename _Context>
4037     inline _Out
4038     __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4039                     const basic_format_args<_Context>& __args,
4040                     const locale* __loc)
4041     {
4042       _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4043       _Sink_iter<_CharT> __sink_out;
4045       if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4046         __sink_out = __out; // Already a sink iterator, safe to use post-move.
4047       else
4048         __sink_out = __sink.out();
4050       if constexpr (is_same_v<_CharT, char>)
4051         if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4052           {
4053             bool __done = false;
4054             std::visit_format_arg([&](auto& __arg) {
4055               using _Tp = remove_cvref_t<decltype(__arg)>;
4056               if constexpr (is_same_v<_Tp, bool>)
4057                 {
4058                   size_t __len = 4 + !__arg;
4059                   const char* __chars[] = { "false", "true" };
4060                   if (auto __res = __sink_out._M_reserve(__len))
4061                     {
4062                       __builtin_memcpy(__res.get(), __chars[__arg], __len);
4063                       __res._M_bump(__len);
4064                       __done = true;
4065                     }
4066                 }
4067               else if constexpr (is_same_v<_Tp, char>)
4068                 {
4069                   if (auto __res = __sink_out._M_reserve(1))
4070                     {
4071                       *__res.get() = __arg;
4072                       __res._M_bump(1);
4073                       __done = true;
4074                     }
4075                 }
4076               else if constexpr (is_integral_v<_Tp>)
4077                 {
4078                   make_unsigned_t<_Tp> __uval;
4079                   const bool __neg = __arg < 0;
4080                   if (__neg)
4081                     __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4082                   else
4083                     __uval = __arg;
4084                   const auto __n = __detail::__to_chars_len(__uval) + __neg;
4085                   if (auto __res = __sink_out._M_reserve(__n))
4086                     {
4087                       auto __ptr = __res.get();
4088                       *__ptr = '-';
4089                       __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4090                                                    __uval);
4091                       __res._M_bump(__n);
4092                       __done = true;
4093                     }
4094                 }
4095               else if constexpr (is_convertible_v<_Tp, string_view>)
4096                 {
4097                   string_view __sv = __arg;
4098                   if (auto __res = __sink_out._M_reserve(__sv.size()))
4099                     {
4100                       __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4101                       __res._M_bump(__sv.size());
4102                       __done = true;
4103                     }
4104                 }
4105             }, __args.get(0));
4107             if (__done)
4108               {
4109                 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4110                   return __sink_out;
4111                 else
4112                   return std::move(__sink)._M_finish().out;
4113               }
4114           }
4116       auto __ctx = __loc == nullptr
4117                      ? _Context(__args, __sink_out)
4118                      : _Context(__args, __sink_out, *__loc);
4119       _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4120       __scanner._M_scan();
4122       if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4123         return __ctx.out();
4124       else
4125         return std::move(__sink)._M_finish().out;
4126     }
4128 } // namespace __format
4129 /// @endcond
4131   template<typename _CharT, typename... _Args>
4132     template<typename _Tp>
4133       requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4134       consteval
4135       basic_format_string<_CharT, _Args...>::
4136       basic_format_string(const _Tp& __s)
4137       : _M_str(__s)
4138       {
4139         __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4140           __scanner(_M_str);
4141         __scanner._M_scan();
4142       }
4144   // [format.functions], formatting functions
4146   template<typename _Out> requires output_iterator<_Out, const char&>
4147     [[__gnu__::__always_inline__]]
4148     inline _Out
4149     vformat_to(_Out __out, string_view __fmt, format_args __args)
4150     { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4152 #ifdef _GLIBCXX_USE_WCHAR_T
4153   template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4154     [[__gnu__::__always_inline__]]
4155     inline _Out
4156     vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4157     { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4158 #endif
4160   template<typename _Out> requires output_iterator<_Out, const char&>
4161     [[__gnu__::__always_inline__]]
4162     inline _Out
4163     vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4164                format_args __args)
4165     {
4166       return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4167     }
4169 #ifdef _GLIBCXX_USE_WCHAR_T
4170   template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4171     [[__gnu__::__always_inline__]]
4172     inline _Out
4173     vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4174                wformat_args __args)
4175     {
4176       return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4177     }
4178 #endif
4180   [[nodiscard]]
4181   inline string
4182   vformat(string_view __fmt, format_args __args)
4183   {
4184     __format::_Str_sink<char> __buf;
4185     std::vformat_to(__buf.out(), __fmt, __args);
4186     return std::move(__buf).get();
4187   }
4189 #ifdef _GLIBCXX_USE_WCHAR_T
4190   [[nodiscard]]
4191   inline wstring
4192   vformat(wstring_view __fmt, wformat_args __args)
4193   {
4194     __format::_Str_sink<wchar_t> __buf;
4195     std::vformat_to(__buf.out(), __fmt, __args);
4196     return std::move(__buf).get();
4197   }
4198 #endif
4200   [[nodiscard]]
4201   inline string
4202   vformat(const locale& __loc, string_view __fmt, format_args __args)
4203   {
4204     __format::_Str_sink<char> __buf;
4205     std::vformat_to(__buf.out(), __loc, __fmt, __args);
4206     return std::move(__buf).get();
4207   }
4209 #ifdef _GLIBCXX_USE_WCHAR_T
4210   [[nodiscard]]
4211   inline wstring
4212   vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4213   {
4214     __format::_Str_sink<wchar_t> __buf;
4215     std::vformat_to(__buf.out(), __loc, __fmt, __args);
4216     return std::move(__buf).get();
4217   }
4218 #endif
4220   template<typename... _Args>
4221     [[nodiscard]]
4222     inline string
4223     format(format_string<_Args...> __fmt, _Args&&... __args)
4224     { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4226 #ifdef _GLIBCXX_USE_WCHAR_T
4227   template<typename... _Args>
4228     [[nodiscard]]
4229     inline wstring
4230     format(wformat_string<_Args...> __fmt, _Args&&... __args)
4231     { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4232 #endif
4234   template<typename... _Args>
4235     [[nodiscard]]
4236     inline string
4237     format(const locale& __loc, format_string<_Args...> __fmt,
4238            _Args&&... __args)
4239     {
4240       return std::vformat(__loc, __fmt.get(),
4241                           std::make_format_args(__args...));
4242     }
4244 #ifdef _GLIBCXX_USE_WCHAR_T
4245   template<typename... _Args>
4246     [[nodiscard]]
4247     inline wstring
4248     format(const locale& __loc, wformat_string<_Args...> __fmt,
4249            _Args&&... __args)
4250     {
4251       return std::vformat(__loc, __fmt.get(),
4252                           std::make_wformat_args(__args...));
4253     }
4254 #endif
4256   template<typename _Out, typename... _Args>
4257     requires output_iterator<_Out, const char&>
4258     inline _Out
4259     format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4260     {
4261       return std::vformat_to(std::move(__out), __fmt.get(),
4262                              std::make_format_args(__args...));
4263     }
4265 #ifdef _GLIBCXX_USE_WCHAR_T
4266   template<typename _Out, typename... _Args>
4267     requires output_iterator<_Out, const wchar_t&>
4268     inline _Out
4269     format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4270     {
4271       return std::vformat_to(std::move(__out), __fmt.get(),
4272                              std::make_wformat_args(__args...));
4273     }
4274 #endif
4276   template<typename _Out, typename... _Args>
4277     requires output_iterator<_Out, const char&>
4278     inline _Out
4279     format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4280               _Args&&... __args)
4281     {
4282       return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4283                              std::make_format_args(__args...));
4284     }
4286 #ifdef _GLIBCXX_USE_WCHAR_T
4287   template<typename _Out, typename... _Args>
4288     requires output_iterator<_Out, const wchar_t&>
4289     inline _Out
4290     format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4291               _Args&&... __args)
4292     {
4293       return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4294                              std::make_wformat_args(__args...));
4295     }
4296 #endif
4298   template<typename _Out, typename... _Args>
4299     requires output_iterator<_Out, const char&>
4300     inline format_to_n_result<_Out>
4301     format_to_n(_Out __out, iter_difference_t<_Out> __n,
4302                 format_string<_Args...> __fmt, _Args&&... __args)
4303     {
4304       __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4305       std::vformat_to(__sink.out(), __fmt.get(),
4306                       std::make_format_args(__args...));
4307       return std::move(__sink)._M_finish();
4308     }
4310 #ifdef _GLIBCXX_USE_WCHAR_T
4311   template<typename _Out, typename... _Args>
4312     requires output_iterator<_Out, const wchar_t&>
4313     inline format_to_n_result<_Out>
4314     format_to_n(_Out __out, iter_difference_t<_Out> __n,
4315                 wformat_string<_Args...> __fmt, _Args&&... __args)
4316     {
4317       __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4318       std::vformat_to(__sink.out(), __fmt.get(),
4319                       std::make_wformat_args(__args...));
4320       return std::move(__sink)._M_finish();
4321     }
4322 #endif
4324   template<typename _Out, typename... _Args>
4325     requires output_iterator<_Out, const char&>
4326     inline format_to_n_result<_Out>
4327     format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4328                 format_string<_Args...> __fmt, _Args&&... __args)
4329     {
4330       __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4331       std::vformat_to(__sink.out(), __loc, __fmt.get(),
4332                       std::make_format_args(__args...));
4333       return std::move(__sink)._M_finish();
4334     }
4336 #ifdef _GLIBCXX_USE_WCHAR_T
4337   template<typename _Out, typename... _Args>
4338     requires output_iterator<_Out, const wchar_t&>
4339     inline format_to_n_result<_Out>
4340     format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4341                 wformat_string<_Args...> __fmt, _Args&&... __args)
4342     {
4343       __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4344       std::vformat_to(__sink.out(), __loc, __fmt.get(),
4345                       std::make_wformat_args(__args...));
4346       return std::move(__sink)._M_finish();
4347     }
4348 #endif
4350 /// @cond undocumented
4351 namespace __format
4353 #if 1
4354   template<typename _CharT>
4355     class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
4356     {
4357     public:
4358       _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
4360       [[__gnu__::__always_inline__]]
4361       size_t
4362       count() const
4363       { return this->_M_count + this->_M_used().size(); }
4364     };
4365 #else
4366   template<typename _CharT>
4367     class _Counting_sink : public _Buf_sink<_CharT>
4368     {
4369       size_t _M_count = 0;
4371       void
4372       _M_overflow() override
4373       {
4374         if (!std::is_constant_evaluated())
4375           _M_count += this->_M_used().size();
4376         this->_M_rewind();
4377       }
4379     public:
4380       _Counting_sink() = default;
4382       [[__gnu__::__always_inline__]]
4383       size_t
4384       count() noexcept
4385       {
4386         _Counting_sink::_M_overflow();
4387         return _M_count;
4388       }
4389     };
4390 #endif
4391 } // namespace __format
4392 /// @endcond
4394   template<typename... _Args>
4395     [[nodiscard]]
4396     inline size_t
4397     formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
4398     {
4399       __format::_Counting_sink<char> __buf;
4400       std::vformat_to(__buf.out(), __fmt.get(),
4401                       std::make_format_args(__args...));
4402       return __buf.count();
4403     }
4405 #ifdef _GLIBCXX_USE_WCHAR_T
4406   template<typename... _Args>
4407     [[nodiscard]]
4408     inline size_t
4409     formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
4410     {
4411       __format::_Counting_sink<wchar_t> __buf;
4412       std::vformat_to(__buf.out(), __fmt.get(),
4413                       std::make_wformat_args(__args...));
4414       return __buf.count();
4415     }
4416 #endif
4418   template<typename... _Args>
4419     [[nodiscard]]
4420     inline size_t
4421     formatted_size(const locale& __loc, format_string<_Args...> __fmt,
4422                    _Args&&... __args)
4423     {
4424       __format::_Counting_sink<char> __buf;
4425       std::vformat_to(__buf.out(), __loc, __fmt.get(),
4426                       std::make_format_args(__args...));
4427       return __buf.count();
4428     }
4430 #ifdef _GLIBCXX_USE_WCHAR_T
4431   template<typename... _Args>
4432     [[nodiscard]]
4433     inline size_t
4434     formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
4435                    _Args&&... __args)
4436     {
4437       __format::_Counting_sink<wchar_t> __buf;
4438       std::vformat_to(__buf.out(), __loc, __fmt.get(),
4439                       std::make_wformat_args(__args...));
4440       return __buf.count();
4441     }
4442 #endif
4444 #if __cpp_lib_format_ranges
4445   // [format.range], formatting of ranges
4446   // [format.range.fmtkind], variable template format_kind
4447   enum class range_format {
4448     disabled,
4449     map,
4450     set,
4451     sequence,
4452     string,
4453     debug_string
4454   };
4456   /// @cond undocumented
4457   template<typename _Rg>
4458     constexpr auto format_kind = not defined(format_kind<_Rg>);
4460   template<typename _Tp>
4461     consteval range_format
4462     __fmt_kind()
4463     {
4464       using _Ref = ranges::range_reference_t<_Tp>;
4465       if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
4466         return range_format::disabled;
4467       else if constexpr (requires { typename _Tp::key_type; })
4468         {
4469           if constexpr (requires { typename _Tp::mapped_type; })
4470             {
4471               using _Up = remove_cvref_t<_Ref>;
4472               if constexpr (__is_pair<_Up>)
4473                 return range_format::map;
4474               else if constexpr (__is_specialization_of<_Up, tuple>)
4475                 if constexpr (tuple_size_v<_Up> == 2)
4476                   return range_format::map;
4477             }
4478           return range_format::set;
4479         }
4480       else
4481         return range_format::sequence;
4482     }
4483   /// @endcond
4485   /// A constant determining how a range should be formatted.
4486   template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
4487     constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
4489   // [format.range.formatter], class template range_formatter
4490   template<typename _Tp, typename _CharT = char>
4491     requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
4492     class range_formatter; // TODO
4494 /// @cond undocumented
4495 namespace __format
4497   // [format.range.fmtdef], class template range-default-formatter
4498   template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
4499     struct __range_default_formatter; // TODO
4500 } // namespace __format
4501 /// @endcond
4503   // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
4504   // specializations for maps, sets, and strings
4505   template<ranges::input_range _Rg, typename _CharT>
4506     requires (format_kind<_Rg> != range_format::disabled)
4507       && formattable<ranges::range_reference_t<_Rg>, _CharT>
4508     struct formatter<_Rg, _CharT>
4509     : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
4510     { };
4511 #endif // C++23 formatting ranges
4513 _GLIBCXX_END_NAMESPACE_VERSION
4514 } // namespace std
4515 #endif // __cpp_lib_format
4516 #endif // _GLIBCXX_FORMAT