libstdc++
format
Go to the documentation of this file.
1 // <format> Formatting -*- C++ -*-
2 
3 // Copyright The GNU Toolchain Authors.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10 
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19 
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24 
25 /** @file include/format
26  * This is a Standard C++ Library header.
27  */
28 
29 #ifndef _GLIBCXX_FORMAT
30 #define _GLIBCXX_FORMAT 1
31 
32 #ifdef _GLIBCXX_SYSHDR
33 #pragma GCC system_header
34 #endif
35 
36 #include <bits/requires_hosted.h> // for std::string
37 
38 #define __glibcxx_want_format
39 #define __glibcxx_want_format_ranges
40 #define __glibcxx_want_format_uchar
41 #define __glibcxx_want_constexpr_exceptions
42 #include <bits/version.h>
43 
44 #ifdef __cpp_lib_format // C++ >= 20 && HOSTED
45 
46 #include <array>
47 #include <charconv>
48 #include <concepts>
49 #include <limits>
50 #include <locale>
51 #include <optional>
52 #include <span>
53 #include <string_view>
54 #include <string>
55 #include <bits/monostate.h>
56 #include <bits/formatfwd.h>
57 #include <bits/ranges_base.h> // input_range, range_reference_t
58 #include <bits/ranges_util.h> // subrange
59 #include <bits/ranges_algobase.h> // ranges::copy
60 #include <bits/stl_iterator.h> // counted_iterator
61 #include <bits/stl_pair.h> // __is_pair
62 #include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
63 #include <bits/utility.h> // tuple_size_v
64 #include <ext/numeric_traits.h> // __int_traits
65 
66 #if !__has_builtin(__builtin_toupper)
67 # include <cctype>
68 #endif
69 
70 #pragma GCC diagnostic push
71 #pragma GCC diagnostic ignored "-Wpedantic" // __int128
72 #pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
73 
74 namespace std _GLIBCXX_VISIBILITY(default)
75 {
76 _GLIBCXX_BEGIN_NAMESPACE_VERSION
77 
78  // [format.fmt.string], class template basic_format_string
79  template<typename _CharT, typename... _Args> struct basic_format_string;
80 
81 /// @cond undocumented
82 namespace __format
83 {
84  // STATICALLY-WIDEN, see C++20 [time.general]
85  // It doesn't matter for format strings (which can only be char or wchar_t)
86  // but this returns the narrow string for anything that isn't wchar_t. This
87  // is done because const char* can be inserted into any ostream type, and
88  // will be widened at runtime if necessary.
89  template<typename _CharT>
90  consteval auto
91  _Widen(const char* __narrow, const wchar_t* __wide)
92  {
93  if constexpr (is_same_v<_CharT, wchar_t>)
94  return __wide;
95  else
96  return __narrow;
97  }
98 #define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
99 #define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
100 
101  // Size for stack located buffer
102  template<typename _CharT>
103  constexpr size_t __stackbuf_size = 32 * sizeof(void*) / sizeof(_CharT);
104 
105  // Type-erased character sinks.
106  template<typename _CharT> class _Sink;
107  template<typename _CharT> class _Fixedbuf_sink;
108  template<typename _Out, typename _CharT> class _Padding_sink;
109  template<typename _Out, typename _CharT> class _Escaping_sink;
110 
111  // Output iterator that writes to a type-erase character sink.
112  template<typename _CharT>
113  class _Sink_iter;
114 
115  // Output iterator that ignores the characters
116  template<typename _CharT>
117  class _Drop_iter;
118 
119  // An unspecified output iterator type used in the `formattable` concept.
120  template<typename _CharT>
121  struct _Iter_for
122  { using type = _Drop_iter<_CharT>; };
123 
124  template<typename _CharT>
125  using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
126 
127  template<typename _CharT>
128  struct _Dynamic_format_string
129  {
130  [[__gnu__::__always_inline__]]
131  _Dynamic_format_string(basic_string_view<_CharT> __s) noexcept
132  : _M_str(__s) { }
133 
134  _Dynamic_format_string(const _Dynamic_format_string&) = delete;
135  void operator=(const _Dynamic_format_string&) = delete;
136 
137  private:
138  basic_string_view<_CharT> _M_str;
139 
140  template<typename, typename...> friend struct std::basic_format_string;
141  };
142 
143 } // namespace __format
144 /// @endcond
145 
146  using format_context = __format::__format_context<char>;
147 #ifdef _GLIBCXX_USE_WCHAR_T
148  using wformat_context = __format::__format_context<wchar_t>;
149 #endif
150 
151  // [format.args], class template basic_format_args
152  template<typename _Context> class basic_format_args;
153  using format_args = basic_format_args<format_context>;
154 #ifdef _GLIBCXX_USE_WCHAR_T
155  using wformat_args = basic_format_args<wformat_context>;
156 #endif
157 
158  // [format.arguments], arguments
159  // [format.arg], class template basic_format_arg
160  template<typename _Context>
161  class basic_format_arg;
162 
163  /** A compile-time checked format string for the specified argument types.
164  *
165  * @since C++23 but available as an extension in C++20.
166  */
167  template<typename _CharT, typename... _Args>
168  struct basic_format_string
169  {
170  template<typename _Tp>
171  requires convertible_to<const _Tp&, basic_string_view<_CharT>>
172  consteval
173  basic_format_string(const _Tp& __s);
174 
175  [[__gnu__::__always_inline__]]
176  basic_format_string(__format::_Dynamic_format_string<_CharT> __s) noexcept
177  : _M_str(__s._M_str)
178  { }
179 
180  [[__gnu__::__always_inline__]]
181  constexpr basic_string_view<_CharT>
182  get() const noexcept
183  { return _M_str; }
184 
185  private:
186  basic_string_view<_CharT> _M_str;
187  };
188 
189  template<typename... _Args>
190  using format_string = basic_format_string<char, type_identity_t<_Args>...>;
191 
192 #ifdef _GLIBCXX_USE_WCHAR_T
193  template<typename... _Args>
194  using wformat_string
195  = basic_format_string<wchar_t, type_identity_t<_Args>...>;
196 #endif
197 
198 #if __cpp_lib_format >= 202603L // >= C++26
199  [[__gnu__::__always_inline__]]
200  inline __format::_Dynamic_format_string<char>
201  dynamic_format(string_view __fmt) noexcept
202  { return __fmt; }
203 
204 #ifdef _GLIBCXX_USE_WCHAR_T
205  [[__gnu__::__always_inline__]]
206  inline __format::_Dynamic_format_string<wchar_t>
207  dynamic_format(wstring_view __fmt) noexcept
208  { return __fmt; }
209 #endif
210 #endif // C++26
211 
212  // [format.formatter], formatter
213 
214  /// The primary template of std::formatter is disabled.
215  template<typename _Tp, typename _CharT>
216  struct formatter
217  {
218  formatter() = delete; // No std::formatter specialization for this type.
219  formatter(const formatter&) = delete;
220  formatter& operator=(const formatter&) = delete;
221  };
222 
223 #if __cpp_lib_constexpr_exceptions >= 202502L
224 #define _GLIBCXX_CONSTEXPR_FORMAT_ERROR constexpr
225 #else
226 #define _GLIBCXX_CONSTEXPR_FORMAT_ERROR
227 #endif
228 
229  // [format.error], class format_error
230  class format_error : public runtime_error
231  {
232  public:
233  _GLIBCXX_CONSTEXPR_FORMAT_ERROR explicit format_error(const string& __what)
234  : runtime_error(__what) { }
235  _GLIBCXX_CONSTEXPR_FORMAT_ERROR explicit format_error(const char* __what)
236  : runtime_error(__what) { }
237  };
238 
239  /// @cond undocumented
240  [[noreturn]]
241  inline void
242  __throw_format_error(const char* __what)
243  { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
244 
245 #undef _GLIBCXX_CONSTEXPR_FORMAT_ERROR
246 
247 namespace __format
248 {
249  // XXX use named functions for each constexpr error?
250 
251  [[noreturn]]
252  inline void
253  __unmatched_left_brace_in_format_string()
254  { __throw_format_error("format error: unmatched '{' in format string"); }
255 
256  [[noreturn]]
257  inline void
258  __unmatched_right_brace_in_format_string()
259  { __throw_format_error("format error: unmatched '}' in format string"); }
260 
261  [[noreturn]]
262  inline void
263  __conflicting_indexing_in_format_string()
264  { __throw_format_error("format error: conflicting indexing style in format string"); }
265 
266  [[noreturn]]
267  inline void
268  __invalid_arg_id_in_format_string()
269  { __throw_format_error("format error: invalid arg-id in format string"); }
270 
271  [[noreturn]]
272  inline void
273  __failed_to_parse_format_spec()
274  { __throw_format_error("format error: failed to parse format-spec"); }
275 
276  template<typename _CharT> class _Scanner;
277 
278 } // namespace __format
279  /// @endcond
280 
281  // [format.parse.ctx], class template basic_format_parse_context
282  template<typename _CharT> class basic_format_parse_context;
283  using format_parse_context = basic_format_parse_context<char>;
284 #ifdef _GLIBCXX_USE_WCHAR_T
285  using wformat_parse_context = basic_format_parse_context<wchar_t>;
286 #endif
287 
288  template<typename _CharT>
289  class basic_format_parse_context
290  {
291  public:
292  using char_type = _CharT;
293  using const_iterator = typename basic_string_view<_CharT>::const_iterator;
294  using iterator = const_iterator;
295 
296  constexpr explicit
297  basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
298  : _M_begin(__fmt.begin()), _M_end(__fmt.end())
299  { }
300 
301  basic_format_parse_context(const basic_format_parse_context&) = delete;
302  void operator=(const basic_format_parse_context&) = delete;
303 
304  constexpr const_iterator begin() const noexcept { return _M_begin; }
305  constexpr const_iterator end() const noexcept { return _M_end; }
306 
307  constexpr void
308  advance_to(const_iterator __it) noexcept
309  { _M_begin = __it; }
310 
311  constexpr size_t
312  next_arg_id()
313  {
314  if (_M_indexing == _Manual)
315  __format::__conflicting_indexing_in_format_string();
316  _M_indexing = _Auto;
317 
318  // _GLIBCXX_RESOLVE_LIB_DEFECTS
319  // 3825. Missing compile-time argument id check in next_arg_id
320  if (std::is_constant_evaluated())
321  if (_M_next_arg_id == _M_num_args)
322  __format::__invalid_arg_id_in_format_string();
323  return _M_next_arg_id++;
324  }
325 
326  constexpr void
327  check_arg_id(size_t __id)
328  {
329  if (_M_indexing == _Auto)
330  __format::__conflicting_indexing_in_format_string();
331  _M_indexing = _Manual;
332 
333  if (std::is_constant_evaluated())
334  if (__id >= _M_num_args)
335  __format::__invalid_arg_id_in_format_string();
336  }
337 
338 #if __cpp_lib_format >= 202305L
339  template<typename... _Ts>
340  constexpr void
341  check_dynamic_spec(size_t __id) noexcept
342  {
343  static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
344  "template arguments for check_dynamic_spec<Ts...>(id) "
345  "must be unique and must be one of the allowed types");
346  if consteval {
347  __check_dynamic_spec<_Ts...>(__id);
348  }
349  }
350 
351  constexpr void
352  check_dynamic_spec_integral(size_t __id) noexcept
353  {
354  if consteval {
355  __check_dynamic_spec<int, unsigned, long long,
356  unsigned long long>(__id);
357  }
358  }
359 
360  constexpr void
361  check_dynamic_spec_string(size_t __id) noexcept
362  {
363  if consteval {
364  __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
365  }
366  }
367 
368  private:
369  // True if _Tp occurs exactly once in _Ts.
370  template<typename _Tp, typename... _Ts>
371  static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
372 
373  template<typename... _Ts>
374  consteval bool
375  __valid_types_for_check_dynamic_spec()
376  {
377  // _GLIBCXX_RESOLVE_LIB_DEFECTS
378  // 4142. check_dynamic_spec should require at least one type
379  if constexpr (sizeof...(_Ts) == 0)
380  return false;
381  else
382  {
383  // The types in Ts... are unique. Each type in Ts... is one of
384  // bool, char_type, int, unsigned int, long long int,
385  // unsigned long long int, float, double, long double,
386  // const char_type*, basic_string_view<char_type>, or const void*.
387  unsigned __sum
388  = __once<bool, _Ts...>
389  + __once<char_type, _Ts...>
390  + __once<int, _Ts...>
391  + __once<unsigned int, _Ts...>
392  + __once<long long int, _Ts...>
393  + __once<unsigned long long int, _Ts...>
394  + __once<float, _Ts...>
395  + __once<double, _Ts...>
396  + __once<long double, _Ts...>
397  + __once<const char_type*, _Ts...>
398  + __once<basic_string_view<char_type>, _Ts...>
399  + __once<const void*, _Ts...>;
400  return __sum == sizeof...(_Ts);
401  }
402  }
403 
404  template<typename... _Ts>
405  consteval void
406  __check_dynamic_spec(size_t __id) noexcept;
407 
408  // This must not be constexpr.
409  static void __invalid_dynamic_spec(const char*);
410 
411  friend __format::_Scanner<_CharT>;
412 #endif
413 
414  // This constructor should only be used by the implementation.
415  constexpr explicit
416  basic_format_parse_context(basic_string_view<_CharT> __fmt,
417  size_t __num_args) noexcept
418  : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
419  { }
420 
421  private:
422  iterator _M_begin;
423  iterator _M_end;
424  enum _Indexing { _Unknown, _Manual, _Auto };
425  _Indexing _M_indexing = _Unknown;
426  size_t _M_next_arg_id = 0;
427  size_t _M_num_args = 0;
428  };
429 
430 /// @cond undocumented
431  template<typename _Tp, template<typename...> class _Class>
432  constexpr bool __is_specialization_of = false;
433  template<template<typename...> class _Class, typename... _Args>
434  constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
435 
436 namespace __format
437 {
438  // pre: first != last
439  template<typename _CharT>
440  constexpr pair<unsigned short, const _CharT*>
441  __parse_integer(const _CharT* __first, const _CharT* __last)
442  {
443  if (__first == __last)
444  __builtin_unreachable();
445 
446  if constexpr (is_same_v<_CharT, char>)
447  {
448  const auto __start = __first;
449  unsigned short __val = 0;
450  // N.B. std::from_chars is not constexpr in C++20.
451  if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
452  && __first != __start) [[likely]]
453  return {__val, __first};
454  }
455  else
456  {
457  constexpr int __n = 32;
458  char __buf[__n]{};
459  for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
460  __buf[__i] = __first[__i];
461  auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
462  if (__ptr) [[likely]]
463  return {__v, __first + (__ptr - __buf)};
464  }
465  return {0, nullptr};
466  }
467 
468  template<typename _CharT>
469  constexpr pair<unsigned short, const _CharT*>
470  __parse_arg_id(const _CharT* __first, const _CharT* __last)
471  {
472  if (__first == __last)
473  __builtin_unreachable();
474 
475  if (*__first == '0')
476  return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
477 
478  if ('1' <= *__first && *__first <= '9')
479  {
480  const unsigned short __id = *__first - '0';
481  const auto __next = __first + 1;
482  // Optimize for most likely case of single digit arg-id.
483  if (__next == __last || !('0' <= *__next && *__next <= '9'))
484  return {__id, __next};
485  else
486  return __format::__parse_integer(__first, __last);
487  }
488  return {0, nullptr};
489  }
490 
491  enum class _Pres_type : unsigned char {
492  _Pres_none = 0, // Default type (not valid for integer presentation types).
493  _Pres_s = 1, // For strings, bool, ranges
494  // Presentation types for integral types (including bool and charT).
495  _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
496  // Presentation types for floating-point types
497  _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
498  _Pres_p, _Pres_P,
499  _Pres_max = 0xf,
500  };
501  using enum _Pres_type;
502 
503  enum class _Sign : unsigned char {
504  _Sign_default,
505  _Sign_plus,
506  _Sign_minus, // XXX does this need to be distinct from _Sign_default?
507  _Sign_space,
508  };
509  using enum _Sign;
510 
511  enum _WidthPrec : unsigned char {
512  _WP_none, // No width/prec specified.
513  _WP_value, // Fixed width/prec specified.
514  _WP_from_arg // Use a formatting argument for width/prec.
515  };
516  using enum _WidthPrec;
517 
518  template<typename _Context>
519  size_t
520  __int_from_arg(const basic_format_arg<_Context>& __arg);
521 
522  constexpr bool __is_digit(char __c)
523  { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
524 
525  constexpr bool __is_xdigit(char __c)
526  { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
527 
528  // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
529  // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
530  struct _SpecBase
531  { };
532 
533  template<typename _CharT>
534  struct _Spec : _SpecBase
535  {
536  unsigned short _M_width;
537  unsigned short _M_prec;
538  char32_t _M_fill = ' ';
539  _Align _M_align : 2;
540  _Sign _M_sign : 2;
541  unsigned _M_alt : 1;
542  unsigned _M_localized : 1;
543  unsigned _M_zero_fill : 1;
544  _WidthPrec _M_width_kind : 2;
545  _WidthPrec _M_prec_kind : 2;
546  unsigned _M_debug : 1;
547  _Pres_type _M_type : 4;
548  unsigned _M_reserved : 8;
549  // This class has 8 bits of tail padding, that can be used by
550  // derived classes.
551 
552  using iterator = typename basic_string_view<_CharT>::iterator;
553 
554  static constexpr _Align
555  _S_align(_CharT __c) noexcept
556  {
557  switch (__c)
558  {
559  case '<': return _Align_left;
560  case '>': return _Align_right;
561  case '^': return _Align_centre;
562  default: return _Align_default;
563  }
564  }
565 
566  // pre: __first != __last
567  constexpr iterator
568  _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
569  { return _M_parse_fill_and_align(__first, __last, "{"); }
570 
571  // pre: __first != __last
572  constexpr iterator
573  _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
574  {
575  for (char __c : __not_fill)
576  if (*__first == static_cast<_CharT>(__c))
577  return __first;
578 
579  using namespace __unicode;
580  if constexpr (__literal_encoding_is_unicode<_CharT>())
581  {
582  // Accept any UCS scalar value as fill character.
583  _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
584  if (!__uv.empty())
585  {
586  auto __beg = __uv.begin();
587  char32_t __c = *__beg++;
588  if (__is_scalar_value(__c))
589  if (auto __next = __beg.base(); __next != __last)
590  if (_Align __align = _S_align(*__next); __align != _Align_default)
591  {
592  _M_fill = __c;
593  _M_align = __align;
594  return ++__next;
595  }
596  }
597  }
598  else if (__last - __first >= 2)
599  if (_Align __align = _S_align(__first[1]); __align != _Align_default)
600  {
601  _M_fill = *__first;
602  _M_align = __align;
603  return __first + 2;
604  }
605 
606  if (_Align __align = _S_align(__first[0]); __align != _Align_default)
607  {
608  _M_fill = ' ';
609  _M_align = __align;
610  return __first + 1;
611  }
612  return __first;
613  }
614 
615  static constexpr _Sign
616  _S_sign(_CharT __c) noexcept
617  {
618  switch (__c)
619  {
620  case '+': return _Sign_plus;
621  case '-': return _Sign_minus;
622  case ' ': return _Sign_space;
623  default: return _Sign_default;
624  }
625  }
626 
627  // pre: __first != __last
628  constexpr iterator
629  _M_parse_sign(iterator __first, iterator) noexcept
630  {
631  if (_Sign __sign = _S_sign(*__first); __sign != _Sign_default)
632  {
633  _M_sign = __sign;
634  return __first + 1;
635  }
636  return __first;
637  }
638 
639  // pre: *__first is valid
640  constexpr iterator
641  _M_parse_alternate_form(iterator __first, iterator) noexcept
642  {
643  if (*__first == '#')
644  {
645  _M_alt = true;
646  ++__first;
647  }
648  return __first;
649  }
650 
651  // pre: __first != __last
652  constexpr iterator
653  _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
654  {
655  if (*__first == '0')
656  {
657  _M_zero_fill = true;
658  ++__first;
659  }
660  return __first;
661  }
662 
663  // pre: __first != __last
664  static constexpr iterator
665  _S_parse_width_or_precision(iterator __first, iterator __last,
666  unsigned short& __val, bool& __arg_id,
667  basic_format_parse_context<_CharT>& __pc)
668  {
669  if (__format::__is_digit(*__first))
670  {
671  auto [__v, __ptr] = __format::__parse_integer(__first, __last);
672  if (!__ptr)
673  __throw_format_error("format error: invalid width or precision "
674  "in format-spec");
675  __first = __ptr;
676  __val = __v;
677  }
678  else if (*__first == '{')
679  {
680  __arg_id = true;
681  ++__first;
682  if (__first == __last)
683  __format::__unmatched_left_brace_in_format_string();
684  if (*__first == '}')
685  __val = __pc.next_arg_id();
686  else
687  {
688  auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
689  if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
690  __format::__invalid_arg_id_in_format_string();
691  __first = __ptr;
692  __pc.check_arg_id(__v);
693  __val = __v;
694  }
695 #if __cpp_lib_format >= 202305L
696  __pc.check_dynamic_spec_integral(__val);
697 #endif
698  ++__first; // past the '}'
699  }
700  return __first;
701  }
702 
703  // pre: __first != __last
704  constexpr iterator
705  _M_parse_width(iterator __first, iterator __last,
706  basic_format_parse_context<_CharT>& __pc)
707  {
708  bool __arg_id = false;
709  if (*__first == '0')
710  __throw_format_error("format error: width must be non-zero in "
711  "format string");
712  auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
713  __arg_id, __pc);
714  if (__next != __first)
715  _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
716  return __next;
717  }
718 
719  // pre: __first != __last
720  constexpr iterator
721  _M_parse_precision(iterator __first, iterator __last,
722  basic_format_parse_context<_CharT>& __pc)
723  {
724  if (__first[0] != '.')
725  return __first;
726 
727  iterator __next = ++__first;
728  bool __arg_id = false;
729  if (__next != __last)
730  __next = _S_parse_width_or_precision(__first, __last, _M_prec,
731  __arg_id, __pc);
732  if (__next == __first)
733  __throw_format_error("format error: missing precision after '.' in "
734  "format string");
735  _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
736  return __next;
737  }
738 
739  // pre: __first != __last
740  constexpr iterator
741  _M_parse_locale(iterator __first, iterator /* __last */) noexcept
742  {
743  if (*__first == 'L')
744  {
745  _M_localized = true;
746  ++__first;
747  }
748  return __first;
749  }
750 
751  template<typename _Context>
752  size_t
753  _M_get_width(_Context& __ctx) const
754  {
755  size_t __width = 0;
756  if (_M_width_kind == _WP_value)
757  __width = _M_width;
758  else if (_M_width_kind == _WP_from_arg)
759  __width = __format::__int_from_arg(__ctx.arg(_M_width));
760  return __width;
761  }
762 
763  template<typename _Context>
764  size_t
765  _M_get_precision(_Context& __ctx) const
766  {
767  size_t __prec = -1;
768  if (_M_prec_kind == _WP_value)
769  __prec = _M_prec;
770  else if (_M_prec_kind == _WP_from_arg)
771  __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
772  return __prec;
773  }
774  };
775 
776  template<typename _Int>
777  inline char*
778  __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
779  {
780  if (__i < 0)
781  *__dest = '-';
782  else if (__sign == _Sign_plus)
783  *__dest = '+';
784  else if (__sign == _Sign_space)
785  *__dest = ' ';
786  else
787  ++__dest;
788  return __dest;
789  }
790 
791  // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
792  template<typename _Out, typename _CharT>
793  requires output_iterator<_Out, const _CharT&>
794  inline _Out
795  __write(_Out __out, basic_string_view<_CharT> __str)
796  {
797  if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
798  {
799  if (__str.size())
800  __out = __str;
801  }
802  else
803  for (_CharT __c : __str)
804  *__out++ = __c;
805  return __out;
806  }
807 
808  // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
809  // pre: __align != _Align_default
810  template<typename _Out, typename _CharT>
811  _Out
812  __write_padded(_Out __out, basic_string_view<_CharT> __str,
813  _Align __align, size_t __nfill, char32_t __fill_char)
814  {
815  const size_t __buflen = 0x20;
816  _CharT __padding_chars[__buflen];
817  __padding_chars[0] = _CharT();
818  basic_string_view<_CharT> __padding{__padding_chars, __buflen};
819 
820  auto __pad = [&__padding] (size_t __n, _Out& __o) {
821  if (__n == 0)
822  return;
823  while (__n > __padding.size())
824  {
825  __o = __format::__write(std::move(__o), __padding);
826  __n -= __padding.size();
827  }
828  if (__n != 0)
829  __o = __format::__write(std::move(__o), __padding.substr(0, __n));
830  };
831 
832  size_t __l, __r, __max;
833  if (__align == _Align_centre)
834  {
835  __l = __nfill / 2;
836  __r = __l + (__nfill & 1);
837  __max = __r;
838  }
839  else if (__align == _Align_right)
840  {
841  __l = __nfill;
842  __r = 0;
843  __max = __l;
844  }
845  else
846  {
847  __l = 0;
848  __r = __nfill;
849  __max = __r;
850  }
851 
852  using namespace __unicode;
853  if constexpr (__literal_encoding_is_unicode<_CharT>())
854  if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
855  {
856  // Encode fill char as multiple code units of type _CharT.
857  const char32_t __arr[1]{ __fill_char };
858  _Utf_view<_CharT, span<const char32_t, 1>> __v(__arr);
859  basic_string<_CharT> __padstr(__v.begin(), __v.end());
860  __padding = __padstr;
861  while (__l-- > 0)
862  __out = __format::__write(std::move(__out), __padding);
863  __out = __format::__write(std::move(__out), __str);
864  while (__r-- > 0)
865  __out = __format::__write(std::move(__out), __padding);
866  return __out;
867  }
868 
869  if (__max < __buflen)
870  __padding.remove_suffix(__buflen - __max);
871  else
872  __max = __buflen;
873 
874  char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
875  __pad(__l, __out);
876  __out = __format::__write(std::move(__out), __str);
877  __pad(__r, __out);
878 
879  return __out;
880  }
881 
882  // Write STR to OUT, with alignment and padding as determined by SPEC.
883  // pre: __spec._M_align != _Align_default || __align != _Align_default
884  template<typename _CharT, typename _Out>
885  _Out
886  __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
887  size_t __estimated_width,
888  basic_format_context<_Out, _CharT>& __fc,
889  const _Spec<_CharT>& __spec,
890  _Align __align = _Align_left)
891  {
892  size_t __width = __spec._M_get_width(__fc);
893 
894  if (__width <= __estimated_width)
895  return __format::__write(__fc.out(), __str);
896 
897  const size_t __nfill = __width - __estimated_width;
898 
899  if (__spec._M_align != _Align_default)
900  __align = __spec._M_align;
901 
902  return __format::__write_padded(__fc.out(), __str, __align, __nfill,
903  __spec._M_fill);
904  }
905 
906  template<typename _CharT>
907  size_t
908  __truncate(basic_string_view<_CharT>& __s, size_t __prec)
909  {
910  if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
911  {
912  if (__prec != (size_t)-1)
913  return __unicode::__truncate(__s, __prec);
914  else
915  return __unicode::__field_width(__s);
916  }
917  else
918  {
919  __s = __s.substr(0, __prec);
920  return __s.size();
921  }
922  }
923 
924  enum class _Term_char : unsigned char {
925  _Term_none,
926  _Term_quote,
927  _Term_apos,
928  };
929  using enum _Term_char;
930 
931  template<typename _CharT>
932  struct _Escapes
933  {
934  using _Str_view = basic_string_view<_CharT>;
935 
936  static consteval
937  _Str_view _S_all()
938  { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
939 
940  static consteval
941  _Str_view _S_tab()
942  { return _S_all().substr(0, 3); }
943 
944  static consteval
945  _Str_view _S_newline()
946  { return _S_all().substr(3, 3); }
947 
948  static consteval
949  _Str_view _S_return()
950  { return _S_all().substr(6, 3); }
951 
952  static consteval
953  _Str_view _S_bslash()
954  { return _S_all().substr(9, 3); }
955 
956  static consteval
957  _Str_view _S_quote()
958  { return _S_all().substr(12, 3); }
959 
960  static consteval
961  _Str_view _S_apos()
962  { return _S_all().substr(15, 3); }
963 
964  static consteval
965  _Str_view _S_u()
966  { return _S_all().substr(18, 2); }
967 
968  static consteval
969  _Str_view _S_x()
970  { return _S_all().substr(20, 2); }
971 
972  static constexpr
973  _Str_view _S_term(_Term_char __term)
974  {
975  switch (__term)
976  {
977  case _Term_none:
978  return _Str_view();
979  case _Term_quote:
980  return _S_quote().substr(0, 1);
981  case _Term_apos:
982  return _S_apos().substr(0, 1);
983  }
984  __builtin_unreachable();
985  }
986  };
987 
988  template<typename _CharT>
989  struct _Separators
990  {
991  using _Str_view = basic_string_view<_CharT>;
992 
993  static consteval
994  _Str_view _S_all()
995  { return _GLIBCXX_WIDEN("[]{}(), : "); }
996 
997  static consteval
998  _Str_view _S_squares()
999  { return _S_all().substr(0, 2); }
1000 
1001  static consteval
1002  _Str_view _S_braces()
1003  { return _S_all().substr(2, 2); }
1004 
1005  static consteval
1006  _Str_view _S_parens()
1007  { return _S_all().substr(4, 2); }
1008 
1009  static consteval
1010  _Str_view _S_comma()
1011  { return _S_all().substr(6, 2); }
1012 
1013  static consteval
1014  _Str_view _S_colon()
1015  { return _S_all().substr(8, 2); }
1016  };
1017 
1018  template<typename _CharT>
1019  constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1020  {
1021  using _Esc = _Escapes<_CharT>;
1022  switch (__c)
1023  {
1024  case _Esc::_S_tab()[0]:
1025  case _Esc::_S_newline()[0]:
1026  case _Esc::_S_return()[0]:
1027  case _Esc::_S_bslash()[0]:
1028  return true;
1029  case _Esc::_S_quote()[0]:
1030  return __term == _Term_quote;
1031  case _Esc::_S_apos()[0]:
1032  return __term == _Term_apos;
1033  default:
1034  return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1035  };
1036  }
1037 
1038  // @pre __c <= 0x10FFFF
1039  constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1040  {
1041  if (__unicode::__should_escape_category(__c))
1042  return __c != U' ';
1043  if (!__prev_esc)
1044  return false;
1045  return __unicode::__grapheme_cluster_break_property(__c)
1046  == __unicode::_Gcb_property::_Gcb_Extend;
1047  }
1048 
1049  using uint_least32_t = __UINT_LEAST32_TYPE__;
1050  template<typename _Out, typename _CharT>
1051  _Out
1052  __write_escape_seq(_Out __out, uint_least32_t __val,
1053  basic_string_view<_CharT> __prefix)
1054  {
1055  constexpr size_t __max = 8;
1056  char __buf[__max];
1057  const string_view __narrow(
1058  __buf,
1059  std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1060 
1061  __out = __format::__write(__out, __prefix);
1062  *__out = _Separators<_CharT>::_S_braces()[0];
1063  ++__out;
1064  if constexpr (is_same_v<char, _CharT>)
1065  __out = __format::__write(__out, __narrow);
1066 #ifdef _GLIBCXX_USE_WCHAR_T
1067  else
1068  {
1069  wchar_t __wbuf[__max];
1070  const size_t __n = __narrow.size();
1071  std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1072  __out = __format::__write(__out, wstring_view(__wbuf, __n));
1073  }
1074 #endif
1075  *__out = _Separators<_CharT>::_S_braces()[1];
1076  return ++__out;
1077  }
1078 
1079  template<typename _Out, typename _CharT>
1080  _Out
1081  __write_escape_seqs(_Out __out, basic_string_view<_CharT> __units)
1082  {
1083  using _UChar = make_unsigned_t<_CharT>;
1084  for (_CharT __c : __units)
1085  __out = __format::__write_escape_seq(
1086  __out, static_cast<_UChar>(__c), _Escapes<_CharT>::_S_x());
1087  return __out;
1088  }
1089 
1090  template<typename _Out, typename _CharT>
1091  _Out
1092  __write_escaped_char(_Out __out, _CharT __c)
1093  {
1094  using _UChar = make_unsigned_t<_CharT>;
1095  using _Esc = _Escapes<_CharT>;
1096  switch (__c)
1097  {
1098  case _Esc::_S_tab()[0]:
1099  return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1100  case _Esc::_S_newline()[0]:
1101  return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1102  case _Esc::_S_return()[0]:
1103  return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1104  case _Esc::_S_bslash()[0]:
1105  return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1106  case _Esc::_S_quote()[0]:
1107  return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1108  case _Esc::_S_apos()[0]:
1109  return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1110  default:
1111  return __format::__write_escape_seq(
1112  __out, static_cast<_UChar>(__c), _Esc::_S_u());
1113  }
1114  }
1115 
1116  template<typename _CharT, typename _Out>
1117  _Out
1118  __write_escaped_ascii(_Out __out,
1119  basic_string_view<_CharT> __str,
1120  _Term_char __term)
1121  {
1122  using _Str_view = basic_string_view<_CharT>;
1123  auto __first = __str.begin();
1124  auto const __last = __str.end();
1125  while (__first != __last)
1126  {
1127  auto __print = __first;
1128  // assume anything outside ASCII is printable
1129  while (__print != __last
1130  && !__format::__should_escape_ascii(*__print, __term))
1131  ++__print;
1132 
1133  if (__print != __first)
1134  __out = __format::__write(__out, _Str_view(__first, __print));
1135 
1136  if (__print == __last)
1137  return __out;
1138 
1139  __first = __print;
1140  __out = __format::__write_escaped_char(__out, *__first);
1141  ++__first;
1142  }
1143  return __out;
1144  }
1145 
1146  template<typename _CharT, typename _Out>
1147  _Out
1148  __write_escaped_unicode_part(_Out __out, basic_string_view<_CharT>& __str,
1149  bool& __prev_esc, _Term_char __term)
1150  {
1151  using _Str_view = basic_string_view<_CharT>;
1152  using _Esc = _Escapes<_CharT>;
1153 
1154  static constexpr char32_t __replace = U'\uFFFD';
1155  static constexpr _Str_view __replace_rep = []
1156  {
1157  // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1158  if constexpr (is_same_v<char, _CharT>)
1159  return "\xEF\xBF\xBD";
1160  else
1161  return L"\xFFFD";
1162  }();
1163 
1164  __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1165  __str = {};
1166 
1167  auto __first = __v.begin();
1168  auto const __last = __v.end();
1169  while (__first != __last)
1170  {
1171  bool __esc_ascii = false;
1172  bool __esc_unicode = false;
1173  bool __esc_replace = false;
1174  auto __should_escape = [&](auto const& __it)
1175  {
1176  if (*__it <= 0x7f)
1177  return __esc_ascii
1178  = __format::__should_escape_ascii(*__it.base(), __term);
1179  if (__format::__should_escape_unicode(*__it, __prev_esc))
1180  return __esc_unicode = true;
1181  if (*__it == __replace)
1182  {
1183  _Str_view __units(__it.base(), __it._M_units());
1184  return __esc_replace = (__units != __replace_rep);
1185  }
1186  return false;
1187  };
1188 
1189  auto __print = __first;
1190  while (__print != __last && !__should_escape(__print))
1191  {
1192  __prev_esc = false;
1193  ++__print;
1194  }
1195 
1196  if (__print != __first)
1197  __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1198 
1199  if (__print == __last)
1200  return __out;
1201 
1202  __first = __print;
1203  if (__esc_ascii)
1204  __out = __format::__write_escaped_char(__out, *__first.base());
1205  else if (__esc_unicode)
1206  __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1207  // __esc_replace
1208  else if (_Str_view __units(__first.base(), __first._M_units());
1209  __units.end() != __last.base())
1210  __out = __format::__write_escape_seqs(__out, __units);
1211  else
1212  {
1213  __str = __units;
1214  return __out;
1215  }
1216 
1217  __prev_esc = true;
1218  ++__first;
1219  }
1220 
1221  return __out;
1222  }
1223 
1224  template<typename _CharT, typename _Out>
1225  _Out
1226  __write_escaped_unicode(_Out __out, basic_string_view<_CharT> __str,
1227  _Term_char __term)
1228  {
1229  bool __prev_escape = true;
1230  __out = __format::__write_escaped_unicode_part(__out, __str,
1231  __prev_escape, __term);
1232  __out = __format::__write_escape_seqs(__out, __str);
1233  return __out;
1234  }
1235 
1236  template<typename _CharT, typename _Out>
1237  _Out
1238  __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1239  {
1240  __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1241 
1242  if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1243  __out = __format::__write_escaped_unicode(__out, __str, __term);
1244  else if constexpr (is_same_v<char, _CharT>
1245  && __unicode::__literal_encoding_is_extended_ascii())
1246  __out = __format::__write_escaped_ascii(__out, __str, __term);
1247  else
1248  // TODO Handle non-ascii extended encoding
1249  __out = __format::__write_escaped_ascii(__out, __str, __term);
1250 
1251  return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1252  }
1253 
1254  // A lightweight optional<locale>.
1255  struct _Optional_locale
1256  {
1257  [[__gnu__::__always_inline__]]
1258  _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1259 
1260  _Optional_locale(const locale& __loc) noexcept
1261  : _M_loc(__loc), _M_hasval(true)
1262  { }
1263 
1264  _Optional_locale(const _Optional_locale& __l) noexcept
1265  : _M_dummy(), _M_hasval(__l._M_hasval)
1266  {
1267  if (_M_hasval)
1268  std::construct_at(&_M_loc, __l._M_loc);
1269  }
1270 
1271  _Optional_locale&
1272  operator=(const _Optional_locale& __l) noexcept
1273  {
1274  if (_M_hasval)
1275  {
1276  if (__l._M_hasval)
1277  _M_loc = __l._M_loc;
1278  else
1279  {
1280  _M_loc.~locale();
1281  _M_hasval = false;
1282  }
1283  }
1284  else if (__l._M_hasval)
1285  {
1286  std::construct_at(&_M_loc, __l._M_loc);
1287  _M_hasval = true;
1288  }
1289  return *this;
1290  }
1291 
1292  ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1293 
1294  _Optional_locale&
1295  operator=(locale&& __loc) noexcept
1296  {
1297  if (_M_hasval)
1298  _M_loc = std::move(__loc);
1299  else
1300  {
1301  std::construct_at(&_M_loc, std::move(__loc));
1302  _M_hasval = true;
1303  }
1304  return *this;
1305  }
1306 
1307  const locale&
1308  value() noexcept
1309  {
1310  if (!_M_hasval)
1311  {
1312  std::construct_at(&_M_loc);
1313  _M_hasval = true;
1314  }
1315  return _M_loc;
1316  }
1317 
1318  bool has_value() const noexcept { return _M_hasval; }
1319 
1320  union {
1321  char _M_dummy = '\0';
1322  std::locale _M_loc;
1323  };
1324  bool _M_hasval = false;
1325  };
1326 
1327  template<__char _CharT>
1328  struct __formatter_str
1329  {
1330  __formatter_str() = default;
1331 
1332  constexpr
1333  __formatter_str(_Spec<_CharT> __spec) noexcept
1334  : _M_spec(__spec)
1335  { }
1336 
1337  constexpr typename basic_format_parse_context<_CharT>::iterator
1338  parse(basic_format_parse_context<_CharT>& __pc)
1339  {
1340  auto __first = __pc.begin();
1341  const auto __last = __pc.end();
1342  _Spec<_CharT> __spec{};
1343 
1344  auto __finalize = [this, &__spec] {
1345  _M_spec = __spec;
1346  };
1347 
1348  auto __finished = [&] {
1349  if (__first == __last || *__first == '}')
1350  {
1351  __finalize();
1352  return true;
1353  }
1354  return false;
1355  };
1356 
1357  if (__finished())
1358  return __first;
1359 
1360  __first = __spec._M_parse_fill_and_align(__first, __last);
1361  if (__finished())
1362  return __first;
1363 
1364  __first = __spec._M_parse_width(__first, __last, __pc);
1365  if (__finished())
1366  return __first;
1367 
1368  __first = __spec._M_parse_precision(__first, __last, __pc);
1369  if (__finished())
1370  return __first;
1371 
1372  if (*__first == 's')
1373  {
1374  __spec._M_type = _Pres_s;
1375  ++__first;
1376  }
1377 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1378  else if (*__first == '?')
1379  {
1380  __spec._M_debug = true;
1381  ++__first;
1382  }
1383 #endif
1384 
1385  if (__finished())
1386  return __first;
1387 
1388  __format::__failed_to_parse_format_spec();
1389  }
1390 
1391  template<typename _Out>
1392  _Out
1393  format(basic_string_view<_CharT> __s,
1394  basic_format_context<_Out, _CharT>& __fc) const
1395  {
1396  if (_M_spec._M_debug)
1397  return _M_format_escaped(__s, __fc);
1398 
1399  if (_M_spec._M_width_kind == _WP_none
1400  && _M_spec._M_prec_kind == _WP_none)
1401  return __format::__write(__fc.out(), __s);
1402 
1403  const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1404  const size_t __width = __format::__truncate(__s, __maxwidth);
1405  return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1406  }
1407 
1408  template<typename _Out>
1409  _Out
1410  _M_format_escaped(basic_string_view<_CharT> __s,
1411  basic_format_context<_Out, _CharT>& __fc) const
1412  {
1413  const size_t __padwidth = _M_spec._M_get_width(__fc);
1414  if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1415  return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1416 
1417  const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1418  const size_t __width = __truncate(__s, __maxwidth);
1419  // N.B. Escaping only increases width
1420  if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1421  return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1422 
1423  // N.B. [tab:format.type.string] defines '?' as
1424  // Copies the escaped string ([format.string.escaped]) to the output,
1425  // so precision seem to appy to escaped string.
1426  _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1427  __format::__write_escaped(__sink.out(), __s, _Term_quote);
1428  return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1429  }
1430 
1431 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1432  template<ranges::input_range _Rg, typename _Out>
1433  requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1434  _Out
1435  _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1436  {
1437  using _Range = remove_reference_t<_Rg>;
1438  using _String_view = basic_string_view<_CharT>;
1439  if constexpr (!is_lvalue_reference_v<_Rg>)
1440  return _M_format_range<_Range&>(__rg, __fc);
1441  else if constexpr (!is_const_v<_Range>
1442  && __simply_formattable_range<_Range, _CharT>)
1443  return _M_format_range<const _Range&>(__rg, __fc);
1444  else if constexpr (ranges::contiguous_range<_Rg>)
1445  {
1446  _String_view __str(ranges::data(__rg),
1447  size_t(ranges::distance(__rg)));
1448  return format(__str, __fc);
1449  }
1450  else
1451  {
1452  auto __handle_debug = [this, &__rg]<typename _NOut>(_NOut __nout)
1453  {
1454  if (!_M_spec._M_debug)
1455  return ranges::copy(__rg, std::move(__nout)).out;
1456 
1457  _Escaping_sink<_NOut, _CharT>
1458  __sink(std::move(__nout), _Term_quote);
1459  ranges::copy(__rg, __sink.out());
1460  return __sink._M_finish();
1461  };
1462 
1463  const size_t __padwidth = _M_spec._M_get_width(__fc);
1464  if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1465  return __handle_debug(__fc.out());
1466 
1467  _Padding_sink<_Out, _CharT>
1468  __sink(__fc.out(), __padwidth, _M_spec._M_get_precision(__fc));
1469  __handle_debug(__sink.out());
1470  return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1471  }
1472  }
1473 
1474  constexpr void
1475  set_debug_format() noexcept
1476  { _M_spec._M_debug = true; }
1477 #endif
1478 
1479  private:
1480  _Spec<_CharT> _M_spec{};
1481  };
1482 
1483  template<__char _CharT>
1484  struct __formatter_int
1485  {
1486  // If no presentation type is specified, meaning of "none" depends
1487  // whether we are formatting an integer or a char or a bool.
1488  static constexpr _Pres_type _AsInteger = _Pres_d;
1489  static constexpr _Pres_type _AsBool = _Pres_s;
1490  static constexpr _Pres_type _AsChar = _Pres_c;
1491 
1492  __formatter_int() = default;
1493 
1494  constexpr
1495  __formatter_int(_Spec<_CharT> __spec) noexcept
1496  : _M_spec(__spec)
1497  {
1498  if (_M_spec._M_type == _Pres_none)
1499  _M_spec._M_type = _Pres_d;
1500  }
1501 
1502  constexpr typename basic_format_parse_context<_CharT>::iterator
1503  _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1504  {
1505  _Spec<_CharT> __spec{};
1506  __spec._M_type = __type;
1507 
1508  const auto __last = __pc.end();
1509  auto __first = __pc.begin();
1510 
1511  auto __finalize = [this, &__spec] {
1512  _M_spec = __spec;
1513  };
1514 
1515  auto __finished = [&] {
1516  if (__first == __last || *__first == '}')
1517  {
1518  __finalize();
1519  return true;
1520  }
1521  return false;
1522  };
1523 
1524  if (__finished())
1525  return __first;
1526 
1527  __first = __spec._M_parse_fill_and_align(__first, __last);
1528  if (__finished())
1529  return __first;
1530 
1531  __first = __spec._M_parse_sign(__first, __last);
1532  if (__finished())
1533  return __first;
1534 
1535  __first = __spec._M_parse_alternate_form(__first, __last);
1536  if (__finished())
1537  return __first;
1538 
1539  __first = __spec._M_parse_zero_fill(__first, __last);
1540  if (__finished())
1541  return __first;
1542 
1543  __first = __spec._M_parse_width(__first, __last, __pc);
1544  if (__finished())
1545  return __first;
1546 
1547  __first = __spec._M_parse_locale(__first, __last);
1548  if (__finished())
1549  return __first;
1550 
1551  switch (*__first)
1552  {
1553  case 'b':
1554  __spec._M_type = _Pres_b;
1555  ++__first;
1556  break;
1557  case 'B':
1558  __spec._M_type = _Pres_B;
1559  ++__first;
1560  break;
1561  case 'c':
1562  // _GLIBCXX_RESOLVE_LIB_DEFECTS
1563  // 3586. format should not print bool with 'c'
1564  if (__type != _AsBool)
1565  {
1566  __spec._M_type = _Pres_c;
1567  ++__first;
1568  }
1569  break;
1570  case 'd':
1571  __spec._M_type = _Pres_d;
1572  ++__first;
1573  break;
1574  case 'o':
1575  __spec._M_type = _Pres_o;
1576  ++__first;
1577  break;
1578  case 'x':
1579  __spec._M_type = _Pres_x;
1580  ++__first;
1581  break;
1582  case 'X':
1583  __spec._M_type = _Pres_X;
1584  ++__first;
1585  break;
1586  case 's':
1587  if (__type == _AsBool)
1588  {
1589  __spec._M_type = _Pres_s; // same meaning as "none" for bool
1590  ++__first;
1591  }
1592  break;
1593 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1594  case '?':
1595  if (__type == _AsChar)
1596  {
1597  __spec._M_debug = true;
1598  ++__first;
1599  }
1600 #endif
1601  break;
1602  }
1603 
1604  if (__finished())
1605  return __first;
1606 
1607  __format::__failed_to_parse_format_spec();
1608  }
1609 
1610  template<typename _Tp>
1611  constexpr typename basic_format_parse_context<_CharT>::iterator
1612  _M_parse(basic_format_parse_context<_CharT>& __pc)
1613  {
1614  if constexpr (is_same_v<_Tp, bool>)
1615  {
1616  auto __end = _M_do_parse(__pc, _AsBool);
1617  if (_M_spec._M_type == _Pres_s)
1618  if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1619  || _M_spec._M_zero_fill)
1620  __throw_format_error("format error: format-spec contains "
1621  "invalid formatting options for "
1622  "'bool'");
1623  return __end;
1624  }
1625  else if constexpr (__char<_Tp>)
1626  {
1627  auto __end = _M_do_parse(__pc, _AsChar);
1628  if (_M_spec._M_type == _Pres_c)
1629  if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1630  || _M_spec._M_zero_fill
1631  /* XXX should be invalid? || _M_spec._M_localized */)
1632  __throw_format_error("format error: format-spec contains "
1633  "invalid formatting options for "
1634  "'charT'");
1635  return __end;
1636  }
1637  else
1638  return _M_do_parse(__pc, _AsInteger);
1639  }
1640 
1641  template<typename _Int, typename _Out>
1642  typename basic_format_context<_Out, _CharT>::iterator
1643  format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1644  {
1645  if (_M_spec._M_type == _Pres_c)
1646  return _M_format_character(_S_to_character(__i), __fc);
1647 
1648  constexpr size_t __buf_size = sizeof(_Int) * __CHAR_BIT__ + 3;
1649  char __buf[__buf_size];
1650  to_chars_result __res{};
1651 
1652  string_view __base_prefix;
1653  make_unsigned_t<_Int> __u;
1654  if (__i < 0)
1655  __u = -static_cast<make_unsigned_t<_Int>>(__i);
1656  else
1657  __u = __i;
1658 
1659  char* __start = __buf + 3;
1660  char* const __end = __buf + sizeof(__buf);
1661  char* const __start_digits = __start;
1662 
1663  switch (_M_spec._M_type)
1664  {
1665  case _Pres_b:
1666  case _Pres_B:
1667  __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1668  __res = to_chars(__start, __end, __u, 2);
1669  break;
1670 #if 0
1671  case _Pres_c:
1672  return _M_format_character(_S_to_character(__i), __fc);
1673 #endif
1674  default: // Fallback for _Pres_type values introduces in later versions.
1675  case _Pres_none:
1676  // Should not reach here with _Pres_none for bool or charT, so:
1677  [[fallthrough]];
1678  case _Pres_d:
1679  __res = to_chars(__start, __end, __u, 10);
1680  break;
1681  case _Pres_o:
1682  if (__i != 0)
1683  __base_prefix = "0";
1684  __res = to_chars(__start, __end, __u, 8);
1685  break;
1686  case _Pres_x:
1687  case _Pres_X:
1688  __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1689  __res = to_chars(__start, __end, __u, 16);
1690  if (_M_spec._M_type == _Pres_X)
1691  for (auto __p = __start; __p != __res.ptr; ++__p)
1692 #if __has_builtin(__builtin_toupper)
1693  *__p = __builtin_toupper(*__p);
1694 #else
1695  *__p = std::toupper(*__p);
1696 #endif
1697  break;
1698  }
1699 
1700  if (_M_spec._M_alt && __base_prefix.size())
1701  {
1702  __start -= __base_prefix.size();
1703  __builtin_memcpy(__start, __base_prefix.data(),
1704  __base_prefix.size());
1705  }
1706  __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1707 
1708  string_view __narrow_str(__start, __res.ptr - __start);
1709  size_t __prefix_len = __start_digits - __start;
1710  if constexpr (is_same_v<char, _CharT>)
1711  return _M_format_int(__narrow_str, __prefix_len, __fc);
1712 #ifdef _GLIBCXX_USE_WCHAR_T
1713  else
1714  {
1715  _CharT __wbuf[__buf_size];
1716  size_t __n = __narrow_str.size();
1717  // _GLIBCXX_RESOLVE_LIB_DEFECTS
1718  // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
1719  std::__to_wstring_numeric(__narrow_str.data(), __n, __wbuf);
1720  return _M_format_int(basic_string_view<_CharT>(__wbuf, __n),
1721  __prefix_len, __fc);
1722  }
1723 #endif
1724  }
1725 
1726  template<typename _Out>
1727  typename basic_format_context<_Out, _CharT>::iterator
1728  format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1729  {
1730  if (_M_spec._M_type == _Pres_c)
1731  return _M_format_character(static_cast<unsigned char>(__i), __fc);
1732  if (_M_spec._M_type != _Pres_s)
1733  return format(static_cast<unsigned char>(__i), __fc);
1734 
1735  basic_string<_CharT> __s;
1736  size_t __est_width;
1737  if (_M_spec._M_localized) [[unlikely]]
1738  {
1739  auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1740  __s = __i ? __np.truename() : __np.falsename();
1741  __est_width = __s.size(); // TODO Unicode-aware estimate
1742  }
1743  else
1744  {
1745  if constexpr (is_same_v<char, _CharT>)
1746  __s = __i ? "true" : "false";
1747  else
1748  __s = __i ? L"true" : L"false";
1749  __est_width = __s.size();
1750  }
1751 
1752  return __format::__write_padded_as_spec(__s, __est_width, __fc,
1753  _M_spec);
1754  }
1755 
1756  template<typename _Out>
1757  typename basic_format_context<_Out, _CharT>::iterator
1758  _M_format_character(_CharT __c,
1759  basic_format_context<_Out, _CharT>& __fc) const
1760  {
1761  basic_string_view<_CharT> __in(&__c, 1u);
1762  size_t __width = 1u;
1763  // N.B. single byte cannot encode character of width greater than 1
1764  if constexpr (sizeof(_CharT) > 1u &&
1765  __unicode::__literal_encoding_is_unicode<_CharT>())
1766  __width = __unicode::__field_width(__c);
1767 
1768  if (!_M_spec._M_debug)
1769  return __format::__write_padded_as_spec(__in, __width,
1770  __fc, _M_spec);
1771 
1772  __width += 2;
1773  if (_M_spec._M_get_width(__fc) <= __width)
1774  return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1775 
1776  _CharT __buf[12];
1777  _Fixedbuf_sink<_CharT> __sink(__buf);
1778  __format::__write_escaped(__sink.out(), __in, _Term_apos);
1779 
1780  __in = __sink.view();
1781  if (__in[1] == _Escapes<_CharT>::_S_bslash()[0]) // escape sequence
1782  __width = __in.size();
1783  return __format::__write_padded_as_spec(__in, __width,
1784  __fc, _M_spec);
1785  }
1786 
1787  template<typename _Int>
1788  static _CharT
1789  _S_to_character(_Int __i)
1790  {
1791  using _Traits = __gnu_cxx::__int_traits<_CharT>;
1792  if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1793  {
1794  if (_Traits::__min <= __i && __i <= _Traits::__max)
1795  return static_cast<_CharT>(__i);
1796  }
1797  else if constexpr (is_signed_v<_Int>)
1798  {
1799  if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1800  return static_cast<_CharT>(__i);
1801  }
1802  else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1803  return static_cast<_CharT>(__i);
1804  __throw_format_error("format error: integer not representable as "
1805  "character");
1806  }
1807 
1808  template<typename _Out>
1809  typename basic_format_context<_Out, _CharT>::iterator
1810  _M_format_int(basic_string_view<_CharT> __str, size_t __prefix_len,
1811  basic_format_context<_Out, _CharT>& __fc) const
1812  {
1813  size_t __width = _M_spec._M_get_width(__fc);
1814  if (_M_spec._M_localized)
1815  {
1816  const auto& __l = __fc.locale();
1817  if (__l.name() != "C")
1818  {
1819  auto& __np = use_facet<numpunct<_CharT>>(__l);
1820  string __grp = __np.grouping();
1821  if (!__grp.empty())
1822  {
1823  size_t __n = __str.size() - __prefix_len;
1824  auto __p = (_CharT*)__builtin_alloca(2 * __n
1825  * sizeof(_CharT)
1826  + __prefix_len);
1827  auto __s = __str.data();
1828  char_traits<_CharT>::copy(__p, __s, __prefix_len);
1829  __s += __prefix_len;
1830  auto __end = std::__add_grouping(__p + __prefix_len,
1831  __np.thousands_sep(),
1832  __grp.data(),
1833  __grp.size(),
1834  __s, __s + __n);
1835  __str = {__p, size_t(__end - __p)};
1836  }
1837  }
1838  }
1839 
1840  if (__width <= __str.size())
1841  return __format::__write(__fc.out(), __str);
1842 
1843  char32_t __fill_char = _M_spec._M_fill;
1844  _Align __align = _M_spec._M_align;
1845 
1846  size_t __nfill = __width - __str.size();
1847  auto __out = __fc.out();
1848  if (__align == _Align_default)
1849  {
1850  __align = _Align_right;
1851  if (_M_spec._M_zero_fill)
1852  {
1853  __fill_char = _CharT('0');
1854  // Write sign and base prefix before zero filling.
1855  if (__prefix_len != 0)
1856  {
1857  __out = __format::__write(std::move(__out),
1858  __str.substr(0, __prefix_len));
1859  __str.remove_prefix(__prefix_len);
1860  }
1861  }
1862  else
1863  __fill_char = _CharT(' ');
1864  }
1865  return __format::__write_padded(std::move(__out), __str,
1866  __align, __nfill, __fill_char);
1867  }
1868 
1869  _Spec<_CharT> _M_spec{};
1870  };
1871 
1872 #ifdef __BFLT16_DIG__
1873  using __bflt16_t = decltype(0.0bf16);
1874 #endif
1875 
1876  // Decide how 128-bit floating-point types should be formatted (or not).
1877  // When supported, the typedef __format::__flt128_t is the type that format
1878  // arguments should be converted to before passing them to __formatter_fp.
1879  // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1880  // The __float128, _Float128 will be formatted by converting them to:
1881  // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1882  // long double when _GLIBCXX_FORMAT_F128=2,
1883  // _Float128 when _GLIBCXX_FORMAT_F128=3.
1884 #undef _GLIBCXX_FORMAT_F128
1885 
1886 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1887 
1888  // Format 128-bit floating-point types using __ieee128.
1889  using __flt128_t = __ieee128;
1890 # define _GLIBCXX_FORMAT_F128 1
1891 
1892 #ifdef __LONG_DOUBLE_IEEE128__
1893  // These overloads exist in the library, but are not declared.
1894  // Make them available as std::__format::to_chars.
1895  to_chars_result
1896  to_chars(char*, char*, __ibm128) noexcept
1897  __asm("_ZSt8to_charsPcS_e");
1898 
1899  to_chars_result
1900  to_chars(char*, char*, __ibm128, chars_format) noexcept
1901  __asm("_ZSt8to_charsPcS_eSt12chars_format");
1902 
1903  to_chars_result
1904  to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1905  __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1906 #elif __cplusplus == 202002L
1907  to_chars_result
1908  to_chars(char*, char*, __ieee128) noexcept
1909  __asm("_ZSt8to_charsPcS_u9__ieee128");
1910 
1911  to_chars_result
1912  to_chars(char*, char*, __ieee128, chars_format) noexcept
1913  __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1914 
1915  to_chars_result
1916  to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1917  __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1918 #endif
1919 
1920 #elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1921 
1922  // Format 128-bit floating-point types using long double.
1923  using __flt128_t = long double;
1924 # define _GLIBCXX_FORMAT_F128 2
1925 
1926 #elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1927 
1928  // Format 128-bit floating-point types using _Float128.
1929  using __flt128_t = _Float128;
1930 # define _GLIBCXX_FORMAT_F128 3
1931 
1932 # if __cplusplus == 202002L
1933  // These overloads exist in the library, but are not declared for C++20.
1934  // Make them available as std::__format::to_chars.
1935  to_chars_result
1936  to_chars(char*, char*, _Float128) noexcept
1937 # if _GLIBCXX_INLINE_VERSION
1938  __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1939 # else
1940  __asm("_ZSt8to_charsPcS_DF128_");
1941 # endif
1942 
1943  to_chars_result
1944  to_chars(char*, char*, _Float128, chars_format) noexcept
1945 # if _GLIBCXX_INLINE_VERSION
1946  __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1947 # else
1948  __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1949 # endif
1950 
1951  to_chars_result
1952  to_chars(char*, char*, _Float128, chars_format, int) noexcept
1953 # if _GLIBCXX_INLINE_VERSION
1954  __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1955 # else
1956  __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1957 # endif
1958 # endif
1959 #endif
1960 
1961  using std::to_chars;
1962 
1963  // We can format a floating-point type iff it is usable with to_chars.
1964  template<typename _Tp>
1965  concept __formattable_float
1966  = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1967  { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1968 
1969  template<__char _CharT>
1970  struct __formatter_fp
1971  {
1972  constexpr typename basic_format_parse_context<_CharT>::iterator
1973  parse(basic_format_parse_context<_CharT>& __pc)
1974  {
1975  _Spec<_CharT> __spec{};
1976  const auto __last = __pc.end();
1977  auto __first = __pc.begin();
1978 
1979  auto __finalize = [this, &__spec] {
1980  _M_spec = __spec;
1981  };
1982 
1983  auto __finished = [&] {
1984  if (__first == __last || *__first == '}')
1985  {
1986  __finalize();
1987  return true;
1988  }
1989  return false;
1990  };
1991 
1992  if (__finished())
1993  return __first;
1994 
1995  __first = __spec._M_parse_fill_and_align(__first, __last);
1996  if (__finished())
1997  return __first;
1998 
1999  __first = __spec._M_parse_sign(__first, __last);
2000  if (__finished())
2001  return __first;
2002 
2003  __first = __spec._M_parse_alternate_form(__first, __last);
2004  if (__finished())
2005  return __first;
2006 
2007  __first = __spec._M_parse_zero_fill(__first, __last);
2008  if (__finished())
2009  return __first;
2010 
2011  if (__first[0] != '.')
2012  {
2013  __first = __spec._M_parse_width(__first, __last, __pc);
2014  if (__finished())
2015  return __first;
2016  }
2017 
2018  __first = __spec._M_parse_precision(__first, __last, __pc);
2019  if (__finished())
2020  return __first;
2021 
2022  __first = __spec._M_parse_locale(__first, __last);
2023  if (__finished())
2024  return __first;
2025 
2026  switch (*__first)
2027  {
2028  case 'a':
2029  __spec._M_type = _Pres_a;
2030  ++__first;
2031  break;
2032  case 'A':
2033  __spec._M_type = _Pres_A;
2034  ++__first;
2035  break;
2036  case 'e':
2037  __spec._M_type = _Pres_e;
2038  ++__first;
2039  break;
2040  case 'E':
2041  __spec._M_type = _Pres_E;
2042  ++__first;
2043  break;
2044  case 'f':
2045  __spec._M_type = _Pres_f;
2046  ++__first;
2047  break;
2048  case 'F':
2049  __spec._M_type = _Pres_F;
2050  ++__first;
2051  break;
2052  case 'g':
2053  __spec._M_type = _Pres_g;
2054  ++__first;
2055  break;
2056  case 'G':
2057  __spec._M_type = _Pres_G;
2058  ++__first;
2059  break;
2060  }
2061 
2062  if (__finished())
2063  return __first;
2064 
2065  __format::__failed_to_parse_format_spec();
2066  }
2067 
2068  template<typename _Fp, typename _Out>
2069  typename basic_format_context<_Out, _CharT>::iterator
2070  format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2071  {
2072  std::string __dynbuf;
2073  char __buf[128];
2074  to_chars_result __res{};
2075 
2076  size_t __prec = 6;
2077  bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2078  if (__use_prec)
2079  __prec = _M_spec._M_get_precision(__fc);
2080 
2081  chars_format __fmt{};
2082  bool __upper = false;
2083  bool __trailing_zeros = false;
2084  char __expc = 'e';
2085  size_t __offset = 1; // reserve space for sign
2086 
2087  switch (_M_spec._M_type)
2088  {
2089  case _Pres_P:
2090  if (__builtin_isfinite(__v))
2091  __offset += 2; // reserve space for prefix
2092  [[fallthrough]];
2093  case _Pres_A:
2094  __upper = true;
2095  __expc = 'P';
2096  __fmt = chars_format::hex;
2097  break;
2098  case _Pres_p:
2099  if (__builtin_isfinite(__v))
2100  __offset += 2; // reserve space for prefix
2101  [[fallthrough]];
2102  case _Pres_a:
2103  __expc = 'p';
2104  __fmt = chars_format::hex;
2105  break;
2106  case _Pres_E:
2107  __upper = true;
2108  __expc = 'E';
2109  [[fallthrough]];
2110  case _Pres_e:
2111  __use_prec = true;
2112  __fmt = chars_format::scientific;
2113  break;
2114  case _Pres_F:
2115  __upper = true;
2116  [[fallthrough]];
2117  case _Pres_f:
2118  __use_prec = true;
2119  __fmt = chars_format::fixed;
2120  break;
2121  case _Pres_G:
2122  __upper = true;
2123  __expc = 'E';
2124  [[fallthrough]];
2125  case _Pres_g:
2126  __trailing_zeros = true;
2127  __use_prec = true;
2128  __fmt = chars_format::general;
2129  break;
2130  default: // Fallback for _Pres_type values introduces in later versions.
2131  case _Pres_none:
2132  if (__use_prec)
2133  __fmt = chars_format::general;
2134  break;
2135  }
2136 
2137  char* __start = __buf + __offset;
2138  char* __end = __buf + sizeof(__buf);
2139 
2140  // Write value into buffer using std::to_chars.
2141  auto __to_chars = [&](char* __b, char* __e) {
2142  if (__use_prec)
2143  return __format::to_chars(__b, __e, __v, __fmt, __prec);
2144  else if (__fmt != chars_format{})
2145  return __format::to_chars(__b, __e, __v, __fmt);
2146  else
2147  return __format::to_chars(__b, __e, __v);
2148  };
2149 
2150  // First try using stack buffer.
2151  __res = __to_chars(__start, __end);
2152 
2153  if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2154  {
2155  // If the buffer is too small it's probably because of a large
2156  // precision, or a very large value in fixed format.
2157  size_t __guess = 7 + __offset + __prec;
2158  if (__fmt == chars_format::fixed) // +ddd.prec
2159  {
2160  if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2161  || is_same_v<_Fp, long double>)
2162  {
2163  // The number of digits to the left of the decimal point
2164  // is floor(log10(max(abs(__v),1)))+1
2165  int __exp{};
2166  if constexpr (is_same_v<_Fp, float>)
2167  __builtin_frexpf(__v, &__exp);
2168  else if constexpr (is_same_v<_Fp, double>)
2169  __builtin_frexp(__v, &__exp);
2170  else if constexpr (is_same_v<_Fp, long double>)
2171  __builtin_frexpl(__v, &__exp);
2172  if (__exp > 0)
2173  __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2174  }
2175  else
2176  __guess += numeric_limits<_Fp>::max_exponent10;
2177  }
2178  if (__guess <= sizeof(__buf)) [[unlikely]]
2179  __guess = sizeof(__buf) * 2;
2180  __dynbuf.reserve(__guess);
2181 
2182  do
2183  {
2184  // Mangling of this lambda, and thus resize_and_overwrite
2185  // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2186  // <format> was new in G++ 13, and is experimental, that
2187  // isn't a problem.
2188  auto __overwrite = [&__to_chars, &__res, __offset] (char* __p, size_t __n)
2189  {
2190  __res = __to_chars(__p + __offset, __p + __n - __offset);
2191  return __res.ec == errc{} ? __res.ptr - __p : 0;
2192  };
2193 
2194  __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2195  __overwrite);
2196  __start = __dynbuf.data() + __offset; // reserve space for sign and prefix
2197  __end = __dynbuf.data() + __dynbuf.size();
2198  }
2199  while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2200  }
2201 
2202  if (__offset == 3)
2203  {
2204  __start -= 2;
2205  if (__builtin_signbit(__v))
2206  ranges::copy(string_view("-0x"), __start);
2207  else
2208  ranges::copy(string_view("0x"), __start);
2209  }
2210 
2211  // Use uppercase for 'A', 'P', 'E', and 'G' formats.
2212  if (__upper)
2213  {
2214  for (char* __p = __start; __p != __res.ptr; ++__p)
2215  *__p = std::toupper(*__p);
2216  }
2217 
2218  // Add sign for non-negative values.
2219  if (!__builtin_signbit(__v))
2220  {
2221  if (_M_spec._M_sign == _Sign_plus)
2222  *--__start = '+';
2223  else if (_M_spec._M_sign == _Sign_space)
2224  *--__start = ' ';
2225  else
2226  --__offset;
2227  }
2228 
2229  string_view __narrow_str(__start, __res.ptr - __start);
2230 
2231  // Use alternate form. Ensure decimal point is always present,
2232  // and add trailing zeros (up to precision) for g and G forms.
2233  if (_M_spec._M_alt && __builtin_isfinite(__v))
2234  {
2235  string_view __s = __narrow_str;
2236  size_t __sigfigs; // Number of significant figures.
2237  size_t __z = 0; // Number of trailing zeros to add.
2238  size_t __p; // Position of the exponent character (if any).
2239  size_t __d = __s.find('.'); // Position of decimal point.
2240  if (__d != __s.npos) // Found decimal point.
2241  {
2242  __p = __s.find(__expc, __d + 1);
2243  if (__p == __s.npos)
2244  __p = __s.size();
2245 
2246  // If presentation type is g or G we might need to add zeros.
2247  if (__trailing_zeros)
2248  {
2249  // Find number of digits after first significant figure.
2250  if (__s[__offset] != '0')
2251  // A string like "D.D" or "-D.DDD"
2252  __sigfigs = __p - __offset - 1;
2253  else
2254  // A string like "0.D" or "-0.0DD".
2255  // Safe to assume there is a non-zero digit, because
2256  // otherwise there would be no decimal point.
2257  __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2258  }
2259  }
2260  else // No decimal point, we need to insert one.
2261  {
2262  __p = __s.find(__expc); // Find the exponent, if present.
2263  if (__p == __s.npos)
2264  __p = __s.size();
2265  __d = __p; // Position where '.' should be inserted.
2266  __sigfigs = __d - __offset;
2267  }
2268 
2269  if (__trailing_zeros && __prec != 0)
2270  {
2271  // For g and G presentation types std::to_chars produces
2272  // no more than prec significant figures. Insert this many
2273  // zeros so the result has exactly prec significant figures.
2274  __z = __prec - __sigfigs;
2275  }
2276 
2277  if (size_t __extras = int(__d == __p) + __z) // How many to add.
2278  {
2279  if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2280  {
2281  // The stack buffer is large enough for the result.
2282  // Move exponent to make space for extra chars.
2283  __builtin_memmove(__start + __p + __extras,
2284  __start + __p,
2285  __s.size() - __p);
2286  if (__d == __p)
2287  __start[__p++] = '.';
2288  __builtin_memset(__start + __p, '0', __z);
2289  __narrow_str = {__s.data(), __s.size() + __extras};
2290  }
2291  else // Need to switch to the dynamic buffer.
2292  {
2293  __dynbuf.reserve(__s.size() + __extras);
2294  if (__dynbuf.empty())
2295  {
2296  __dynbuf = __s.substr(0, __p);
2297  if (__d == __p)
2298  __dynbuf += '.';
2299  if (__z)
2300  __dynbuf.append(__z, '0');
2301  __dynbuf.append(__s.substr(__p));
2302  }
2303  else
2304  {
2305  __dynbuf.insert(__p, __extras, '0');
2306  if (__d == __p)
2307  __dynbuf[__p] = '.';
2308  }
2309  __narrow_str = __dynbuf;
2310  }
2311  }
2312  }
2313 
2314  basic_string<_CharT> __wstr;
2315  basic_string_view<_CharT> __str;
2316  if constexpr (is_same_v<_CharT, char>)
2317  __str = __narrow_str;
2318 #ifdef _GLIBCXX_USE_WCHAR_T
2319  else
2320  {
2321  // _GLIBCXX_RESOLVE_LIB_DEFECTS
2322  // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
2323  __wstr = std::__to_wstring_numeric(__narrow_str);
2324  __str = __wstr;
2325  }
2326 #endif
2327 
2328  if (_M_spec._M_localized && __builtin_isfinite(__v))
2329  {
2330  auto __s = _M_localize(__str, __expc, __offset, __fc.locale());
2331  if (!__s.empty())
2332  __str = __wstr = std::move(__s);
2333  }
2334 
2335  size_t __width = _M_spec._M_get_width(__fc);
2336 
2337  if (__width <= __str.size())
2338  return __format::__write(__fc.out(), __str);
2339 
2340  char32_t __fill_char = _M_spec._M_fill;
2341  _Align __align = _M_spec._M_align;
2342 
2343  size_t __nfill = __width - __str.size();
2344  auto __out = __fc.out();
2345  if (__align == _Align_default)
2346  {
2347  __align = _Align_right;
2348  if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2349  {
2350  __fill_char = _CharT('0');
2351  if (__offset > 0)
2352  {
2353  __out = __format::__write(__out, __str.substr(0, __offset));
2354  __str.remove_prefix(__offset);
2355  }
2356  }
2357  else
2358  __fill_char = _CharT(' ');
2359  }
2360  return __format::__write_padded(std::move(__out), __str,
2361  __align, __nfill, __fill_char);
2362  }
2363 
2364  // Locale-specific format.
2365  basic_string<_CharT>
2366  _M_localize(basic_string_view<_CharT> __str, char __expc,
2367  int __offset, const locale& __loc) const
2368  {
2369  basic_string<_CharT> __lstr;
2370 
2371  if (__loc == locale::classic())
2372  return __lstr; // Nothing to do.
2373 
2374  const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2375  const _CharT __point = __np.decimal_point();
2376  const string __grp = __np.grouping();
2377 
2378  _CharT __dot, __exp;
2379  if constexpr (is_same_v<_CharT, char>)
2380  {
2381  __dot = '.';
2382  __exp = __expc;
2383  }
2384  else
2385  {
2386  __dot = L'.';
2387  switch (__expc)
2388  {
2389  case 'e':
2390  __exp = L'e';
2391  break;
2392  case 'E':
2393  __exp = L'E';
2394  break;
2395  case 'p':
2396  __exp = L'p';
2397  break;
2398  case 'P':
2399  __exp = L'P';
2400  break;
2401  default:
2402  __builtin_unreachable();
2403  }
2404  }
2405 
2406  if (__grp.empty() && __point == __dot)
2407  return __lstr; // Locale uses '.' and no grouping.
2408 
2409  size_t __d = __str.find(__dot); // Index of radix character (if any).
2410  size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2411  if (__e == __str.npos)
2412  __e = __str.size();
2413  const size_t __r = __str.size() - __e; // Length of remainder.
2414  auto __overwrite = [&](_CharT* __p, size_t) {
2415  // Copy any +/- sign and "0x" prefix
2416  ranges::copy_n(__str.data(), __offset, __p);
2417  // Apply grouping to the digits before the radix or exponent.
2418  auto __end = std::__add_grouping(__p + __offset, __np.thousands_sep(),
2419  __grp.data(), __grp.size(),
2420  __str.data() + __offset,
2421  __str.data() + __e);
2422  if (__r) // If there's a fractional part or exponent
2423  {
2424  if (__d != __str.npos)
2425  {
2426  *__end = __point; // Add the locale's radix character.
2427  ++__end;
2428  ++__e;
2429  }
2430  const size_t __rlen = __str.size() - __e;
2431  // Append fractional digits and/or exponent:
2432  char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2433  __end += __rlen;
2434  }
2435  return (__end - __p);
2436  };
2437  __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2438  return __lstr;
2439  }
2440 
2441  _Spec<_CharT> _M_spec{};
2442  };
2443 
2444  template<__format::__char _CharT>
2445  struct __formatter_ptr
2446  {
2447  constexpr
2448  __formatter_ptr() noexcept
2449  : _M_spec()
2450  {
2451  _M_spec._M_type = _Pres_x;
2452  _M_spec._M_alt = true;
2453  }
2454 
2455  constexpr
2456  __formatter_ptr(_Spec<_CharT> __spec) noexcept
2457  : _M_spec(__spec)
2458  { _M_set_default(); }
2459 
2460  constexpr typename basic_format_parse_context<_CharT>::iterator
2461  parse(basic_format_parse_context<_CharT>& __pc)
2462  {
2463  __format::_Spec<_CharT> __spec{};
2464  const auto __last = __pc.end();
2465  auto __first = __pc.begin();
2466 
2467  auto __finalize = [this, &__spec] {
2468  _M_spec = __spec;
2469  _M_set_default();
2470  };
2471 
2472  auto __finished = [&] {
2473  if (__first == __last || *__first == '}')
2474  {
2475  __finalize();
2476  return true;
2477  }
2478  return false;
2479  };
2480 
2481  if (__finished())
2482  return __first;
2483 
2484  __first = __spec._M_parse_fill_and_align(__first, __last);
2485  if (__finished())
2486  return __first;
2487 
2488 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2489 // P2510R3 Formatting pointers
2490 #if __glibcxx_format >= 202304L
2491  __first = __spec._M_parse_zero_fill(__first, __last);
2492  if (__finished())
2493  return __first;
2494 #endif
2495 
2496  __first = __spec._M_parse_width(__first, __last, __pc);
2497  if (__finished())
2498  return __first;
2499 
2500  if (*__first == 'p')
2501  {
2502  __spec._M_type = _Pres_x;
2503  __spec._M_alt = true;
2504  ++__first;
2505  }
2506 #if __glibcxx_format >= 202304L
2507  else if (*__first == 'P')
2508  {
2509  __spec._M_type = _Pres_X;
2510  __spec._M_alt = true;
2511  ++__first;
2512  }
2513 #endif
2514 
2515  if (__finished())
2516  return __first;
2517 
2518  __format::__failed_to_parse_format_spec();
2519  }
2520 
2521  template<typename _Out>
2522  typename basic_format_context<_Out, _CharT>::iterator
2523  format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2524  {
2525  auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2526  return __formatter_int<_CharT>(_M_spec).format(__u, __fc);
2527  }
2528 
2529  private:
2530  [[__gnu__::__always_inline__]]
2531  constexpr void
2532  _M_set_default()
2533  {
2534  if (_M_spec._M_type == _Pres_none)
2535  {
2536  _M_spec._M_type = _Pres_x;
2537  _M_spec._M_alt = true;
2538  }
2539  }
2540 
2541  __format::_Spec<_CharT> _M_spec;
2542  };
2543 
2544 } // namespace __format
2545 /// @endcond
2546 
2547  /// Format a character.
2548  template<__format::__char _CharT>
2549  struct formatter<_CharT, _CharT>
2550  {
2551  formatter() = default;
2552 
2553  constexpr typename basic_format_parse_context<_CharT>::iterator
2554  parse(basic_format_parse_context<_CharT>& __pc)
2555  {
2556  return _M_f.template _M_parse<_CharT>(__pc);
2557  }
2558 
2559  template<typename _Out>
2560  typename basic_format_context<_Out, _CharT>::iterator
2561  format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2562  {
2563  if (_M_f._M_spec._M_type == __format::_Pres_c)
2564  return _M_f._M_format_character(__u, __fc);
2565  else
2566  return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2567  }
2568 
2569 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2570  constexpr void
2571  set_debug_format() noexcept
2572  { _M_f._M_spec._M_debug = true; }
2573 #endif
2574 
2575  private:
2576  __format::__formatter_int<_CharT> _M_f;
2577  };
2578 
2579 #if __glibcxx_print >= 202403L
2580  template<__format::__char _CharT>
2581  constexpr bool enable_nonlocking_formatter_optimization<_CharT> = true;
2582 #endif
2583 
2584 #ifdef _GLIBCXX_USE_WCHAR_T
2585  /// Format a char value for wide character output.
2586  template<>
2587  struct formatter<char, wchar_t>
2588  {
2589  formatter() = default;
2590 
2591  constexpr typename basic_format_parse_context<wchar_t>::iterator
2592  parse(basic_format_parse_context<wchar_t>& __pc)
2593  {
2594  return _M_f._M_parse<char>(__pc);
2595  }
2596 
2597  template<typename _Out>
2598  typename basic_format_context<_Out, wchar_t>::iterator
2599  format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2600  {
2601  if (_M_f._M_spec._M_type == __format::_Pres_c)
2602  return _M_f._M_format_character(__u, __fc);
2603  else
2604  return _M_f.format(static_cast<unsigned char>(__u), __fc);
2605  }
2606 
2607 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2608  constexpr void
2609  set_debug_format() noexcept
2610  { _M_f._M_spec._M_debug = true; }
2611 #endif
2612 
2613  private:
2614  __format::__formatter_int<wchar_t> _M_f;
2615  };
2616 #endif // USE_WCHAR_T
2617 
2618  /** Format a string.
2619  * @{
2620  */
2621  template<__format::__char _CharT>
2622  struct formatter<_CharT*, _CharT>
2623  {
2624  formatter() = default;
2625 
2626  [[__gnu__::__always_inline__]]
2627  constexpr typename basic_format_parse_context<_CharT>::iterator
2628  parse(basic_format_parse_context<_CharT>& __pc)
2629  { return _M_f.parse(__pc); }
2630 
2631  template<typename _Out>
2632  [[__gnu__::__nonnull__]]
2633  typename basic_format_context<_Out, _CharT>::iterator
2634  format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2635  { return _M_f.format(__u, __fc); }
2636 
2637 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2638  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2639 #endif
2640 
2641  private:
2642  __format::__formatter_str<_CharT> _M_f;
2643  };
2644 
2645 #if __glibcxx_print >= 202403L
2646  template<__format::__char _CharT>
2647  constexpr bool enable_nonlocking_formatter_optimization<_CharT*> = true;
2648 #endif
2649 
2650  template<__format::__char _CharT>
2651  struct formatter<const _CharT*, _CharT>
2652  {
2653  formatter() = default;
2654 
2655  [[__gnu__::__always_inline__]]
2656  constexpr typename basic_format_parse_context<_CharT>::iterator
2657  parse(basic_format_parse_context<_CharT>& __pc)
2658  { return _M_f.parse(__pc); }
2659 
2660  template<typename _Out>
2661  [[__gnu__::__nonnull__]]
2662  typename basic_format_context<_Out, _CharT>::iterator
2663  format(const _CharT* __u,
2664  basic_format_context<_Out, _CharT>& __fc) const
2665  { return _M_f.format(__u, __fc); }
2666 
2667 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2668  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2669 #endif
2670 
2671  private:
2672  __format::__formatter_str<_CharT> _M_f;
2673  };
2674 
2675 #if __glibcxx_print >= 202403L
2676  template<__format::__char _CharT>
2677  constexpr bool
2678  enable_nonlocking_formatter_optimization<const _CharT*> = true;
2679 #endif
2680 
2681  template<__format::__char _CharT, size_t _Nm>
2682  struct formatter<_CharT[_Nm], _CharT>
2683  {
2684  formatter() = default;
2685 
2686  [[__gnu__::__always_inline__]]
2687  constexpr typename basic_format_parse_context<_CharT>::iterator
2688  parse(basic_format_parse_context<_CharT>& __pc)
2689  { return _M_f.parse(__pc); }
2690 
2691  template<typename _Out>
2692  typename basic_format_context<_Out, _CharT>::iterator
2693  format(const _CharT (&__u)[_Nm],
2694  basic_format_context<_Out, _CharT>& __fc) const
2695  { return _M_f.format({__u, _Nm}, __fc); }
2696 
2697 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2698  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2699 #endif
2700 
2701  private:
2702  __format::__formatter_str<_CharT> _M_f;
2703  };
2704 
2705 #if __glibcxx_print >= 202403L
2706  template<__format::__char _CharT, size_t _Nm>
2707  constexpr bool enable_nonlocking_formatter_optimization<_CharT[_Nm]> = true;
2708 #endif
2709 
2710  template<typename _Traits, typename _Alloc>
2711  struct formatter<basic_string<char, _Traits, _Alloc>, char>
2712  {
2713  formatter() = default;
2714 
2715  [[__gnu__::__always_inline__]]
2716  constexpr typename basic_format_parse_context<char>::iterator
2717  parse(basic_format_parse_context<char>& __pc)
2718  { return _M_f.parse(__pc); }
2719 
2720  template<typename _Out>
2721  typename basic_format_context<_Out, char>::iterator
2722  format(const basic_string<char, _Traits, _Alloc>& __u,
2723  basic_format_context<_Out, char>& __fc) const
2724  { return _M_f.format(__u, __fc); }
2725 
2726 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2727  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2728 #endif
2729 
2730  private:
2731  __format::__formatter_str<char> _M_f;
2732  };
2733 
2734 #if __glibcxx_print >= 202403L
2735  template<typename _Tr, typename _Alloc>
2736  constexpr bool
2737  enable_nonlocking_formatter_optimization<basic_string<char, _Tr, _Alloc>>
2738  = true;
2739 #endif
2740 
2741 #ifdef _GLIBCXX_USE_WCHAR_T
2742  template<typename _Traits, typename _Alloc>
2743  struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2744  {
2745  formatter() = default;
2746 
2747  [[__gnu__::__always_inline__]]
2748  constexpr typename basic_format_parse_context<wchar_t>::iterator
2749  parse(basic_format_parse_context<wchar_t>& __pc)
2750  { return _M_f.parse(__pc); }
2751 
2752  template<typename _Out>
2753  typename basic_format_context<_Out, wchar_t>::iterator
2754  format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2755  basic_format_context<_Out, wchar_t>& __fc) const
2756  { return _M_f.format(__u, __fc); }
2757 
2758 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2759  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2760 #endif
2761 
2762  private:
2763  __format::__formatter_str<wchar_t> _M_f;
2764  };
2765 
2766 #if __glibcxx_print >= 202403L
2767  template<typename _Tr, typename _Alloc>
2768  constexpr bool
2769  enable_nonlocking_formatter_optimization<basic_string<wchar_t, _Tr, _Alloc>>
2770  = true;
2771 #endif
2772 
2773 #endif // USE_WCHAR_T
2774 
2775  template<typename _Traits>
2776  struct formatter<basic_string_view<char, _Traits>, char>
2777  {
2778  formatter() = default;
2779 
2780  [[__gnu__::__always_inline__]]
2781  constexpr typename basic_format_parse_context<char>::iterator
2782  parse(basic_format_parse_context<char>& __pc)
2783  { return _M_f.parse(__pc); }
2784 
2785  template<typename _Out>
2786  typename basic_format_context<_Out, char>::iterator
2787  format(basic_string_view<char, _Traits> __u,
2788  basic_format_context<_Out, char>& __fc) const
2789  { return _M_f.format(__u, __fc); }
2790 
2791 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2792  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2793 #endif
2794 
2795  private:
2796  __format::__formatter_str<char> _M_f;
2797  };
2798 
2799 #if __glibcxx_print >= 202403L
2800  template<typename _Tr>
2801  constexpr bool
2802  enable_nonlocking_formatter_optimization<basic_string_view<char, _Tr>>
2803  = true;
2804 #endif
2805 
2806 #ifdef _GLIBCXX_USE_WCHAR_T
2807  template<typename _Traits>
2808  struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2809  {
2810  formatter() = default;
2811 
2812  [[__gnu__::__always_inline__]]
2813  constexpr typename basic_format_parse_context<wchar_t>::iterator
2814  parse(basic_format_parse_context<wchar_t>& __pc)
2815  { return _M_f.parse(__pc); }
2816 
2817  template<typename _Out>
2818  typename basic_format_context<_Out, wchar_t>::iterator
2819  format(basic_string_view<wchar_t, _Traits> __u,
2820  basic_format_context<_Out, wchar_t>& __fc) const
2821  { return _M_f.format(__u, __fc); }
2822 
2823 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2824  constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2825 #endif
2826 
2827  private:
2828  __format::__formatter_str<wchar_t> _M_f;
2829  };
2830 
2831 #if __glibcxx_print >= 202403L
2832  template<typename _Tr>
2833  constexpr bool
2834  enable_nonlocking_formatter_optimization<basic_string_view<wchar_t, _Tr>>
2835  = true;
2836 #endif
2837 #endif // USE_WCHAR_T
2838  /// @}
2839 
2840 /// @cond undocumented
2841 namespace __format
2842 {
2843  // each cv-unqualified arithmetic type ArithmeticT other than
2844  // char, wchar_t, char8_t, char16_t, or char32_t
2845  template<typename _Tp>
2846  constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2847 
2848 #if defined __SIZEOF_INT128__
2849  template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2850  template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2851  = true;
2852 #endif
2853 
2854  template<> inline constexpr bool __is_formattable_integer<char> = false;
2855  template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2856 #ifdef _GLIBCXX_USE_CHAR8_T
2857  template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2858 #endif
2859  template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2860  template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2861 
2862  template<typename _Tp>
2863  concept __formattable_integer = __is_formattable_integer<_Tp>;
2864 }
2865 /// @endcond
2866 
2867  /// Format an integer.
2868  template<__format::__formattable_integer _Tp, __format::__char _CharT>
2869  struct formatter<_Tp, _CharT>
2870  {
2871  formatter() = default;
2872 
2873  [[__gnu__::__always_inline__]]
2874  constexpr typename basic_format_parse_context<_CharT>::iterator
2875  parse(basic_format_parse_context<_CharT>& __pc)
2876  {
2877  return _M_f.template _M_parse<_Tp>(__pc);
2878  }
2879 
2880  template<typename _Out>
2881  typename basic_format_context<_Out, _CharT>::iterator
2882  format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2883  { return _M_f.format(__u, __fc); }
2884 
2885  private:
2886  __format::__formatter_int<_CharT> _M_f;
2887  };
2888 
2889 #if __glibcxx_print >= 202403L
2890  template<__format::__formattable_integer _Tp>
2891  constexpr bool
2892  enable_nonlocking_formatter_optimization<_Tp> = true;
2893 #endif
2894 
2895 #if defined __glibcxx_to_chars
2896  /// Format a floating-point value.
2897  template<__format::__formattable_float _Tp, __format::__char _CharT>
2898  struct formatter<_Tp, _CharT>
2899  {
2900  formatter() = default;
2901 
2902  [[__gnu__::__always_inline__]]
2903  constexpr typename basic_format_parse_context<_CharT>::iterator
2904  parse(basic_format_parse_context<_CharT>& __pc)
2905  { return _M_f.parse(__pc); }
2906 
2907  template<typename _Out>
2908  typename basic_format_context<_Out, _CharT>::iterator
2909  format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2910  { return _M_f.format(__u, __fc); }
2911 
2912  private:
2913  __format::__formatter_fp<_CharT> _M_f;
2914  };
2915 
2916 #if __glibcxx_print >= 202403L
2917  template<__format::__formattable_float _Tp>
2918  constexpr bool
2919  enable_nonlocking_formatter_optimization<_Tp> = true;
2920 #endif
2921 
2922 #if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2923  // Reuse __formatter_fp<C>::format<double, Out> for long double.
2924  template<__format::__char _CharT>
2925  struct formatter<long double, _CharT>
2926  {
2927  formatter() = default;
2928 
2929  [[__gnu__::__always_inline__]]
2930  constexpr typename basic_format_parse_context<_CharT>::iterator
2931  parse(basic_format_parse_context<_CharT>& __pc)
2932  { return _M_f.parse(__pc); }
2933 
2934  template<typename _Out>
2935  typename basic_format_context<_Out, _CharT>::iterator
2936  format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2937  { return _M_f.format((double)__u, __fc); }
2938 
2939  private:
2940  __format::__formatter_fp<_CharT> _M_f;
2941  };
2942 #endif
2943 
2944 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2945  // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2946  template<__format::__char _CharT>
2947  struct formatter<_Float16, _CharT>
2948  {
2949  formatter() = default;
2950 
2951  [[__gnu__::__always_inline__]]
2952  constexpr typename basic_format_parse_context<_CharT>::iterator
2953  parse(basic_format_parse_context<_CharT>& __pc)
2954  { return _M_f.parse(__pc); }
2955 
2956  template<typename _Out>
2957  typename basic_format_context<_Out, _CharT>::iterator
2958  format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2959  { return _M_f.format((float)__u, __fc); }
2960 
2961  private:
2962  __format::__formatter_fp<_CharT> _M_f;
2963  };
2964 #endif
2965 
2966 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2967  // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2968  template<__format::__char _CharT>
2969  struct formatter<_Float32, _CharT>
2970  {
2971  formatter() = default;
2972 
2973  [[__gnu__::__always_inline__]]
2974  constexpr typename basic_format_parse_context<_CharT>::iterator
2975  parse(basic_format_parse_context<_CharT>& __pc)
2976  { return _M_f.parse(__pc); }
2977 
2978  template<typename _Out>
2979  typename basic_format_context<_Out, _CharT>::iterator
2980  format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2981  { return _M_f.format((float)__u, __fc); }
2982 
2983  private:
2984  __format::__formatter_fp<_CharT> _M_f;
2985  };
2986 #endif
2987 
2988 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2989  // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2990  template<__format::__char _CharT>
2991  struct formatter<_Float64, _CharT>
2992  {
2993  formatter() = default;
2994 
2995  [[__gnu__::__always_inline__]]
2996  constexpr typename basic_format_parse_context<_CharT>::iterator
2997  parse(basic_format_parse_context<_CharT>& __pc)
2998  { return _M_f.parse(__pc); }
2999 
3000  template<typename _Out>
3001  typename basic_format_context<_Out, _CharT>::iterator
3002  format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
3003  { return _M_f.format((double)__u, __fc); }
3004 
3005  private:
3006  __format::__formatter_fp<_CharT> _M_f;
3007  };
3008 #endif
3009 
3010 #if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
3011  // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
3012  template<__format::__char _CharT>
3013  struct formatter<_Float128, _CharT>
3014  {
3015  formatter() = default;
3016 
3017  [[__gnu__::__always_inline__]]
3018  constexpr typename basic_format_parse_context<_CharT>::iterator
3019  parse(basic_format_parse_context<_CharT>& __pc)
3020  { return _M_f.parse(__pc); }
3021 
3022  template<typename _Out>
3023  typename basic_format_context<_Out, _CharT>::iterator
3024  format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3025  { return _M_f.format((__format::__flt128_t)__u, __fc); }
3026 
3027  private:
3028  __format::__formatter_fp<_CharT> _M_f;
3029  };
3030 #endif
3031 
3032 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
3033  // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
3034  // when long double is not 128bit IEEE type.
3035  template<__format::__char _CharT>
3036  struct formatter<__float128, _CharT>
3037  {
3038  formatter() = default;
3039 
3040  [[__gnu__::__always_inline__]]
3041  constexpr typename basic_format_parse_context<_CharT>::iterator
3042  parse(basic_format_parse_context<_CharT>& __pc)
3043  { return _M_f.parse(__pc); }
3044 
3045  template<typename _Out>
3046  typename basic_format_context<_Out, _CharT>::iterator
3047  format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3048  { return _M_f.format((__format::__flt128_t)__u, __fc); }
3049 
3050  private:
3051  __format::__formatter_fp<_CharT> _M_f;
3052  };
3053 #endif
3054 
3055 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3056  // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3057  template<__format::__char _CharT>
3058  struct formatter<__format::__bflt16_t, _CharT>
3059  {
3060  formatter() = default;
3061 
3062  [[__gnu__::__always_inline__]]
3063  constexpr typename basic_format_parse_context<_CharT>::iterator
3064  parse(basic_format_parse_context<_CharT>& __pc)
3065  { return _M_f.parse(__pc); }
3066 
3067  template<typename _Out>
3068  typename basic_format_context<_Out, _CharT>::iterator
3069  format(__gnu_cxx::__bfloat16_t __u,
3070  basic_format_context<_Out, _CharT>& __fc) const
3071  { return _M_f.format((float)__u, __fc); }
3072 
3073  private:
3074  __format::__formatter_fp<_CharT> _M_f;
3075  };
3076 #endif
3077 #endif // __cpp_lib_to_chars
3078 
3079  /** Format a pointer.
3080  * @{
3081  */
3082  template<__format::__char _CharT>
3083  struct formatter<const void*, _CharT>
3084  {
3085  formatter() = default;
3086 
3087  constexpr typename basic_format_parse_context<_CharT>::iterator
3088  parse(basic_format_parse_context<_CharT>& __pc)
3089  { return _M_f.parse(__pc); }
3090 
3091  template<typename _Out>
3092  typename basic_format_context<_Out, _CharT>::iterator
3093  format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3094  { return _M_f.format(__v, __fc); }
3095 
3096  private:
3097  __format::__formatter_ptr<_CharT> _M_f;
3098  };
3099 
3100 #if __glibcxx_print >= 202403L
3101  template<>
3102  inline constexpr bool
3103  enable_nonlocking_formatter_optimization<const void*> = true;
3104 #endif
3105 
3106  template<__format::__char _CharT>
3107  struct formatter<void*, _CharT>
3108  {
3109  formatter() = default;
3110 
3111  [[__gnu__::__always_inline__]]
3112  constexpr typename basic_format_parse_context<_CharT>::iterator
3113  parse(basic_format_parse_context<_CharT>& __pc)
3114  { return _M_f.parse(__pc); }
3115 
3116  template<typename _Out>
3117  typename basic_format_context<_Out, _CharT>::iterator
3118  format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3119  { return _M_f.format(__v, __fc); }
3120 
3121  private:
3122  __format::__formatter_ptr<_CharT> _M_f;
3123  };
3124 
3125 #if __glibcxx_print >= 202403l
3126  template<>
3127  inline constexpr bool
3128  enable_nonlocking_formatter_optimization<void*> = true;
3129 #endif
3130 
3131  template<__format::__char _CharT>
3132  struct formatter<nullptr_t, _CharT>
3133  {
3134  formatter() = default;
3135 
3136  [[__gnu__::__always_inline__]]
3137  constexpr typename basic_format_parse_context<_CharT>::iterator
3138  parse(basic_format_parse_context<_CharT>& __pc)
3139  { return _M_f.parse(__pc); }
3140 
3141  template<typename _Out>
3142  typename basic_format_context<_Out, _CharT>::iterator
3143  format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3144  { return _M_f.format(nullptr, __fc); }
3145 
3146  private:
3147  __format::__formatter_ptr<_CharT> _M_f;
3148  };
3149  /// @}
3150 
3151 #if __glibcxx_print >= 202403L
3152  template<>
3153  inline constexpr bool
3154  enable_nonlocking_formatter_optimization<nullptr_t> = true;
3155 #endif
3156 
3157 #if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3158  // _GLIBCXX_RESOLVE_LIB_DEFECTS
3159  // 3944. Formatters converting sequences of char to sequences of wchar_t
3160 
3161  struct __formatter_disabled
3162  {
3163  __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3164  __formatter_disabled(const __formatter_disabled&) = delete;
3165  __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3166  };
3167 
3168  template<>
3169  struct formatter<char*, wchar_t>
3170  : private __formatter_disabled { };
3171  template<>
3172  struct formatter<const char*, wchar_t>
3173  : private __formatter_disabled { };
3174  template<size_t _Nm>
3175  struct formatter<char[_Nm], wchar_t>
3176  : private __formatter_disabled { };
3177  template<class _Traits, class _Allocator>
3178  struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3179  : private __formatter_disabled { };
3180  template<class _Traits>
3181  struct formatter<basic_string_view<char, _Traits>, wchar_t>
3182  : private __formatter_disabled { };
3183 #endif
3184 
3185  /// An iterator after the last character written, and the number of
3186  /// characters that would have been written.
3187  template<typename _Out>
3188  struct format_to_n_result
3189  {
3190  _Out out;
3191  iter_difference_t<_Out> size;
3192  };
3193 
3194 _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3195 template<typename, typename> class vector;
3196 _GLIBCXX_END_NAMESPACE_CONTAINER
3197 
3198 /// @cond undocumented
3199 namespace __format
3200 {
3201  template<typename _CharT>
3202  class _Drop_iter
3203  {
3204  public:
3205  using iterator_category = output_iterator_tag;
3206  using value_type = void;
3207  using difference_type = ptrdiff_t;
3208  using pointer = void;
3209  using reference = void;
3210 
3211  _Drop_iter() = default;
3212  _Drop_iter(const _Drop_iter&) = default;
3213  _Drop_iter& operator=(const _Drop_iter&) = default;
3214 
3215  [[__gnu__::__always_inline__]]
3216  constexpr _Drop_iter&
3217  operator=(_CharT __c)
3218  { return *this; }
3219 
3220  [[__gnu__::__always_inline__]]
3221  constexpr _Drop_iter&
3222  operator=(basic_string_view<_CharT> __s)
3223  { return *this; }
3224 
3225  [[__gnu__::__always_inline__]]
3226  constexpr _Drop_iter&
3227  operator*() { return *this; }
3228 
3229  [[__gnu__::__always_inline__]]
3230  constexpr _Drop_iter&
3231  operator++() { return *this; }
3232 
3233  [[__gnu__::__always_inline__]]
3234  constexpr _Drop_iter
3235  operator++(int) { return *this; }
3236  };
3237 
3238  template<typename _CharT>
3239  class _Sink_iter
3240  {
3241  _Sink<_CharT>* _M_sink = nullptr;
3242 
3243  public:
3244  using iterator_category = output_iterator_tag;
3245  using value_type = void;
3246  using difference_type = ptrdiff_t;
3247  using pointer = void;
3248  using reference = void;
3249 
3250  _Sink_iter() = default;
3251  _Sink_iter(const _Sink_iter&) = default;
3252  _Sink_iter& operator=(const _Sink_iter&) = default;
3253 
3254  [[__gnu__::__always_inline__]]
3255  explicit constexpr
3256  _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3257 
3258  [[__gnu__::__always_inline__]]
3259  constexpr _Sink_iter&
3260  operator=(_CharT __c)
3261  {
3262  _M_sink->_M_write(__c);
3263  return *this;
3264  }
3265 
3266  [[__gnu__::__always_inline__]]
3267  constexpr _Sink_iter&
3268  operator=(basic_string_view<_CharT> __s)
3269  {
3270  _M_sink->_M_write(__s);
3271  return *this;
3272  }
3273 
3274  [[__gnu__::__always_inline__]]
3275  constexpr _Sink_iter&
3276  operator*() { return *this; }
3277 
3278  [[__gnu__::__always_inline__]]
3279  constexpr _Sink_iter&
3280  operator++() { return *this; }
3281 
3282  [[__gnu__::__always_inline__]]
3283  constexpr _Sink_iter
3284  operator++(int) { return *this; }
3285 
3286  auto
3287  _M_reserve(size_t __n) const
3288  { return _M_sink->_M_reserve(__n); }
3289 
3290  bool
3291  _M_discarding() const
3292  { return _M_sink->_M_discarding(); }
3293  };
3294 
3295  // Abstract base class for type-erased character sinks.
3296  // All formatting and output is done via this type's iterator,
3297  // to reduce the number of different template instantiations.
3298  template<typename _CharT>
3299  class _Sink
3300  {
3301  friend class _Sink_iter<_CharT>;
3302 
3303  span<_CharT> _M_span;
3304  typename span<_CharT>::iterator _M_next;
3305 
3306  // Called when the span is full, to make more space available.
3307  // Precondition: _M_next != _M_span.begin()
3308  // Postcondition: _M_next != _M_span.end()
3309  // TODO: remove the precondition? could make overflow handle it.
3310  virtual void _M_overflow() = 0;
3311 
3312  protected:
3313  // Precondition: __span.size() != 0
3314  [[__gnu__::__always_inline__]]
3315  explicit constexpr
3316  _Sink(span<_CharT> __span) noexcept
3317  : _M_span(__span), _M_next(__span.begin())
3318  { }
3319 
3320  // The portion of the span that has been written to.
3321  [[__gnu__::__always_inline__]]
3322  span<_CharT>
3323  _M_used() const noexcept
3324  { return _M_span.first(_M_next - _M_span.begin()); }
3325 
3326  // The portion of the span that has not been written to.
3327  [[__gnu__::__always_inline__]]
3328  constexpr span<_CharT>
3329  _M_unused() const noexcept
3330  { return _M_span.subspan(_M_next - _M_span.begin()); }
3331 
3332  // Use the start of the span as the next write position.
3333  [[__gnu__::__always_inline__]]
3334  constexpr void
3335  _M_rewind() noexcept
3336  { _M_next = _M_span.begin(); }
3337 
3338  // Replace the current output range.
3339  void
3340  _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3341  {
3342  _M_span = __s;
3343  _M_next = __s.begin() + __pos;
3344  }
3345 
3346  // Called by the iterator for *it++ = c
3347  constexpr void
3348  _M_write(_CharT __c)
3349  {
3350  *_M_next++ = __c;
3351  if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3352  _M_overflow();
3353  }
3354 
3355  constexpr void
3356  _M_write(basic_string_view<_CharT> __s)
3357  {
3358  span __to = _M_unused();
3359  while (__to.size() <= __s.size())
3360  {
3361  __s.copy(__to.data(), __to.size());
3362  _M_next += __to.size();
3363  __s.remove_prefix(__to.size());
3364  _M_overflow();
3365  __to = _M_unused();
3366  }
3367  if (__s.size())
3368  {
3369  __s.copy(__to.data(), __s.size());
3370  _M_next += __s.size();
3371  }
3372  }
3373 
3374  // A successful _Reservation can be used to directly write
3375  // up to N characters to the sink to avoid unwanted buffering.
3376  struct _Reservation
3377  {
3378  // True if the reservation was successful, false otherwise.
3379  explicit operator bool() const noexcept { return _M_sink; }
3380  // A pointer to write directly to the sink.
3381  _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3382  // Add n to the _M_next iterator for the sink.
3383  void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3384  _Sink* _M_sink;
3385  };
3386 
3387  // Attempt to reserve space to write n characters to the sink.
3388  // If anything is written to the reservation then there must be a call
3389  // to _M_bump(N2) before any call to another member function of *this,
3390  // where N2 is the number of characters written.
3391  virtual _Reservation
3392  _M_reserve(size_t __n)
3393  {
3394  if (__n <= _M_unused().size())
3395  return { this };
3396 
3397  if (__n <= _M_span.size()) // Cannot meet the request.
3398  {
3399  _M_overflow(); // Make more space available.
3400  if (__n <= _M_unused().size())
3401  return { this };
3402  }
3403  return { nullptr };
3404  }
3405 
3406  // Update the next output position after writing directly to the sink.
3407  // pre: no calls to _M_write or _M_overflow since _M_reserve.
3408  virtual void
3409  _M_bump(size_t __n)
3410  { _M_next += __n; }
3411 
3412  // Returns true if the _Sink is discarding incoming characters.
3413  virtual bool
3414  _M_discarding() const
3415  { return false; }
3416 
3417  public:
3418  _Sink(const _Sink&) = delete;
3419  _Sink& operator=(const _Sink&) = delete;
3420 
3421  [[__gnu__::__always_inline__]]
3422  constexpr _Sink_iter<_CharT>
3423  out() noexcept
3424  { return _Sink_iter<_CharT>(*this); }
3425  };
3426 
3427 
3428  template<typename _CharT>
3429  class _Fixedbuf_sink final : public _Sink<_CharT>
3430  {
3431  void
3432  _M_overflow() override
3433  {
3434  __glibcxx_assert(false);
3435  this->_M_rewind();
3436  }
3437 
3438  public:
3439  [[__gnu__::__always_inline__]]
3440  constexpr explicit
3441  _Fixedbuf_sink(span<_CharT> __buf)
3442  : _Sink<_CharT>(__buf)
3443  { }
3444 
3445  constexpr basic_string_view<_CharT>
3446  view() const
3447  {
3448  auto __s = this->_M_used();
3449  return basic_string_view<_CharT>(__s.data(), __s.size());
3450  }
3451  };
3452 
3453  // A sink with an internal buffer. This is used to implement concrete sinks.
3454  template<typename _CharT>
3455  class _Buf_sink : public _Sink<_CharT>
3456  {
3457  protected:
3458  _CharT _M_buf[__stackbuf_size<_CharT>];
3459 
3460  [[__gnu__::__always_inline__]]
3461  constexpr
3462  _Buf_sink() noexcept
3463  : _Sink<_CharT>(_M_buf)
3464  { }
3465  };
3466 
3467  using _GLIBCXX_STD_C::vector;
3468 
3469  // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3470  // Writes to a buffer then appends that to the sequence when it fills up.
3471  template<typename _Seq>
3472  class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3473  {
3474  using _CharT = typename _Seq::value_type;
3475 
3476  _Seq _M_seq;
3477  protected:
3478  // Transfer buffer contents to the sequence, so buffer can be refilled.
3479  void
3480  _M_overflow() override
3481  {
3482  auto __s = this->_M_used();
3483  if (__s.empty()) [[unlikely]]
3484  return; // Nothing in the buffer to transfer to _M_seq.
3485 
3486  // If _M_reserve was called then _M_bump must have been called too.
3487  _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3488 
3489  if constexpr (__is_specialization_of<_Seq, basic_string>)
3490  _M_seq.append(__s.data(), __s.size());
3491  else
3492  _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3493 
3494  // Make the whole of _M_buf available for the next write:
3495  this->_M_rewind();
3496  }
3497 
3498  typename _Sink<_CharT>::_Reservation
3499  _M_reserve(size_t __n) override
3500  {
3501  // We might already have n characters available in this->_M_unused(),
3502  // but the whole point of this function is to be an optimization for
3503  // the std::format("{}", x) case. We want to avoid writing to _M_buf
3504  // and then copying that into a basic_string if possible, so this
3505  // function prefers to create space directly in _M_seq rather than
3506  // using _M_buf.
3507 
3508  if constexpr (__is_specialization_of<_Seq, basic_string>
3509  || __is_specialization_of<_Seq, vector>)
3510  {
3511  // Flush the buffer to _M_seq first (should not be needed).
3512  if (this->_M_used().size()) [[unlikely]]
3513  _Seq_sink::_M_overflow();
3514 
3515  // Expand _M_seq to make __n new characters available:
3516  const auto __sz = _M_seq.size();
3517  if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3518  _M_seq.__resize_and_overwrite(__sz + __n,
3519  [](auto, auto __n2) {
3520  return __n2;
3521  });
3522  else
3523  _M_seq.resize(__sz + __n);
3524 
3525  // Set _M_used() to be a span over the original part of _M_seq
3526  // and _M_unused() to be the extra capacity we just created:
3527  this->_M_reset(_M_seq, __sz);
3528  return { this };
3529  }
3530  else // Try to use the base class' buffer.
3531  return _Sink<_CharT>::_M_reserve(__n);
3532  }
3533 
3534  void
3535  _M_bump(size_t __n) override
3536  {
3537  if constexpr (__is_specialization_of<_Seq, basic_string>
3538  || __is_specialization_of<_Seq, vector>)
3539  {
3540  auto __s = this->_M_used();
3541  _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3542  // Truncate the sequence to the part that was actually written to:
3543  _M_seq.resize(__s.size() + __n);
3544  // Switch back to using buffer:
3545  this->_M_reset(this->_M_buf);
3546  }
3547  }
3548 
3549  void _M_trim(span<const _CharT> __s)
3550  requires __is_specialization_of<_Seq, basic_string>
3551  {
3552  _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3553  || __s.data() == _M_seq.data());
3554  if (__s.data() == _M_seq.data())
3555  _M_seq.resize(__s.size());
3556  else
3557  this->_M_reset(this->_M_buf, __s.size());
3558  }
3559 
3560  public:
3561  // TODO: for SSO string, use SSO buffer as initial span, then switch
3562  // to _M_buf if it overflows? Or even do that for all unused capacity?
3563 
3564  [[__gnu__::__always_inline__]]
3565  _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3566  { }
3567 
3568  _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3569  : _M_seq(std::move(__s))
3570  { }
3571 
3572  using _Sink<_CharT>::out;
3573 
3574  _Seq
3575  get() &&
3576  {
3577  if (this->_M_used().size() != 0)
3578  _Seq_sink::_M_overflow();
3579  return std::move(_M_seq);
3580  }
3581 
3582  // A writable span that views everything written to the sink.
3583  // Will be either a view over _M_seq or the used part of _M_buf.
3584  span<_CharT>
3585  _M_span()
3586  {
3587  auto __s = this->_M_used();
3588  if (_M_seq.size())
3589  {
3590  if (__s.size() != 0)
3591  _Seq_sink::_M_overflow();
3592  return _M_seq;
3593  }
3594  return __s;
3595  }
3596 
3597  basic_string_view<_CharT>
3598  view()
3599  {
3600  auto __span = _M_span();
3601  return basic_string_view<_CharT>(__span.data(), __span.size());
3602  }
3603  };
3604 
3605  template<typename _CharT, typename _Alloc = allocator<_CharT>>
3606  using _Str_sink
3607  = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3608 
3609  // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3610  // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3611  // Writes to a fixed-size buffer and then flushes to the output iterator
3612  // when the buffer fills up.
3613  template<typename _CharT, typename _OutIter>
3614  class _Iter_sink : public _Buf_sink<_CharT>
3615  {
3616  _OutIter _M_out;
3617  iter_difference_t<_OutIter> _M_max;
3618 
3619  protected:
3620  size_t _M_count = 0;
3621 
3622  void
3623  _M_overflow() override
3624  {
3625  auto __s = this->_M_used();
3626  if (_M_max < 0) // No maximum.
3627  _M_out = ranges::copy(__s, std::move(_M_out)).out;
3628  else if (_M_count < static_cast<size_t>(_M_max))
3629  {
3630  auto __max = _M_max - _M_count;
3631  span<_CharT> __first;
3632  if (__max < __s.size())
3633  __first = __s.first(static_cast<size_t>(__max));
3634  else
3635  __first = __s;
3636  _M_out = ranges::copy(__first, std::move(_M_out)).out;
3637  }
3638  this->_M_rewind();
3639  _M_count += __s.size();
3640  }
3641 
3642  bool
3643  _M_discarding() const override
3644  {
3645  // format_to_n return total number of characters, that would be written,
3646  // see C++20 [format.functions] p20
3647  return false;
3648  }
3649 
3650  public:
3651  [[__gnu__::__always_inline__]]
3652  explicit
3653  _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3654  : _M_out(std::move(__out)), _M_max(__max)
3655  { }
3656 
3657  using _Sink<_CharT>::out;
3658 
3659  format_to_n_result<_OutIter>
3660  _M_finish() &&
3661  {
3662  if (this->_M_used().size() != 0)
3663  _Iter_sink::_M_overflow();
3664  iter_difference_t<_OutIter> __count(_M_count);
3665  return { std::move(_M_out), __count };
3666  }
3667  };
3668 
3669  // Used for contiguous iterators.
3670  // No buffer is used, characters are written straight to the iterator.
3671  // We do not know the size of the output range, so the span size just grows
3672  // as needed. The end of the span might be an invalid pointer outside the
3673  // valid range, but we never actually call _M_span.end(). This class does
3674  // not introduce any invalid pointer arithmetic or overflows that would not
3675  // have happened anyway.
3676  template<typename _CharT>
3677  class _Ptr_sink : public _Sink<_CharT>
3678  {
3679  static constexpr size_t _S_no_limit = size_t(-1);
3680 
3681  size_t _M_max;
3682  protected:
3683  size_t _M_count = 0;
3684  private:
3685  _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3686 
3687  protected:
3688  void
3689  _M_overflow() override
3690  {
3691  if (this->_M_unused().size() != 0)
3692  return; // No need to switch to internal buffer yet.
3693 
3694  auto __s = this->_M_used();
3695 
3696  if (_M_max != _S_no_limit)
3697  {
3698  _M_count += __s.size();
3699  // Span was already sized for the maximum character count,
3700  // if it overflows then any further output must go to the
3701  // internal buffer, to be discarded.
3702  this->_M_reset(this->_M_buf);
3703  }
3704  else
3705  {
3706  // No maximum character count. Just extend the span to allow
3707  // writing more characters to it.
3708  _M_rebuf(__s.data(), __s.size() + 1024, __s.size());
3709  }
3710  }
3711 
3712  bool
3713  _M_discarding() const override
3714  {
3715  // format_to_n return total number of characters, that would be written,
3716  // see C++20 [format.functions] p20
3717  return false;
3718  }
3719 
3720  typename _Sink<_CharT>::_Reservation
3721  _M_reserve(size_t __n) final
3722  {
3723  auto __avail = this->_M_unused();
3724  if (__n > __avail.size())
3725  {
3726  if (_M_max != _S_no_limit)
3727  return {}; // cannot grow
3728 
3729  auto __s = this->_M_used();
3730  _M_rebuf(__s.data(), __s.size() + __n, __s.size());
3731  }
3732  return { this };
3733  }
3734 
3735  private:
3736  template<typename _IterDifference>
3737  static size_t
3738  _S_trim_max(_IterDifference __max)
3739  {
3740  if (__max < 0)
3741  return _S_no_limit;
3742  if constexpr (!is_integral_v<_IterDifference> || sizeof(__max) > sizeof(size_t))
3743  // __int128 or __detail::__max_diff_type
3744  if (_IterDifference((size_t)-1) < __max)
3745  return _S_no_limit;
3746  return size_t(__max);
3747  }
3748 
3749  [[__gnu__::__always_inline__]]
3750  void
3751  _M_rebuf(_CharT* __ptr, size_t __total, size_t __inuse = 0)
3752  {
3753  std::span<_CharT> __span(__ptr, __total);
3754  this->_M_reset(__span, __inuse);
3755  }
3756 
3757  public:
3758  explicit
3759  _Ptr_sink(_CharT* __ptr, size_t __n = _S_no_limit) noexcept
3760  : _Sink<_CharT>(_M_buf), _M_max(__n)
3761  {
3762  if (__n == 0)
3763  return; // Only write to the internal buffer.
3764  else if (__n != _S_no_limit)
3765  _M_rebuf(__ptr, __n);
3766 #if __has_builtin(__builtin_dynamic_object_size)
3767  else if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3768  _M_rebuf(__ptr, __bytes / sizeof(_CharT));
3769 #endif
3770  else
3771  {
3772  // Avoid forming a pointer to a different memory page.
3773  const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3774  __n = (1024 - __off) / sizeof(_CharT);
3775  if (__n > 0) [[likely]]
3776  _M_rebuf(__ptr, __n);
3777  else // Misaligned/packed buffer of wchar_t?
3778  _M_rebuf(__ptr, 1);
3779  }
3780  }
3781 
3782  template<contiguous_iterator _OutIter>
3783  explicit
3784  _Ptr_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1)
3785  : _Ptr_sink(std::to_address(__out), _S_trim_max(__n))
3786  { }
3787 
3788  template<contiguous_iterator _OutIter>
3789  format_to_n_result<_OutIter>
3790  _M_finish(_OutIter __first) const
3791  {
3792  auto __s = this->_M_used();
3793  if (__s.data() == _M_buf)
3794  {
3795  // Switched to internal buffer, so must have written _M_max.
3796  iter_difference_t<_OutIter> __m(_M_max);
3797  iter_difference_t<_OutIter> __count(_M_count + __s.size());
3798  return { __first + __m, __count };
3799  }
3800  else // Not using internal buffer yet
3801  {
3802  iter_difference_t<_OutIter> __count(__s.size());
3803  return { __first + __count, __count };
3804  }
3805  }
3806  };
3807 
3808  template<typename _CharT, typename _OutIter>
3809  concept __contiguous_char_iter
3810  = contiguous_iterator<_OutIter>
3811  && same_as<iter_value_t<_OutIter>, _CharT>;
3812 
3813  // A sink for handling the padded outputs (_M_padwidth) or truncated
3814  // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3815  // until sufficient number of characters is written. After that if sequence
3816  // is longer than _M_padwidth it's written to _M_out, and further writes are
3817  // either:
3818  // * buffered and forwarded to _M_out, if below _M_maxwidth,
3819  // * ignored otherwise
3820  // If field width of written sequence is no greater than _M_padwidth, the
3821  // sequence is written during _M_finish call.
3822  template<typename _Out, typename _CharT>
3823  class _Padding_sink : public _Str_sink<_CharT>
3824  {
3825  size_t _M_padwidth;
3826  size_t _M_maxwidth;
3827  _Out _M_out;
3828  size_t _M_printwidth;
3829 
3830  [[__gnu__::__always_inline__]]
3831  bool
3832  _M_ignoring() const
3833  { return _M_printwidth >= _M_maxwidth; }
3834 
3835  [[__gnu__::__always_inline__]]
3836  bool
3837  _M_buffering() const
3838  {
3839  if (_M_printwidth < _M_padwidth)
3840  return true;
3841  if (_M_maxwidth != (size_t)-1)
3842  return _M_printwidth < _M_maxwidth;
3843  return false;
3844  }
3845 
3846  void
3847  _M_sync_discarding()
3848  {
3849  if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3850  if (_M_out._M_discarding())
3851  _M_maxwidth = _M_printwidth;
3852  }
3853 
3854  void
3855  _M_flush()
3856  {
3857  span<_CharT> __new = this->_M_used();
3858  basic_string_view<_CharT> __str(__new.data(), __new.size());
3859  _M_out = __format::__write(std::move(_M_out), __str);
3860  _M_sync_discarding();
3861  this->_M_rewind();
3862  }
3863 
3864  bool
3865  _M_force_update()
3866  {
3867  auto __str = this->view();
3868  // Compute actual field width, possibly truncated.
3869  _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3870  if (_M_ignoring())
3871  this->_M_trim(__str);
3872  if (_M_buffering())
3873  return true;
3874 
3875  // We have more characters than padidng, no padding is needed,
3876  // write direclty to _M_out.
3877  if (_M_printwidth >= _M_padwidth)
3878  {
3879  _M_out = __format::__write(std::move(_M_out), __str);
3880  _M_sync_discarding();
3881  }
3882  // We reached _M_maxwidth that is smaller than _M_padwidth.
3883  // Store the prefix sequence in _M_seq, and free _M_buf.
3884  else
3885  _Str_sink<_CharT>::_M_overflow();
3886 
3887  // Use internal buffer for writes to _M_out.
3888  this->_M_reset(this->_M_buf);
3889  return false;
3890  }
3891 
3892  bool
3893  _M_update(size_t __new)
3894  {
3895  _M_printwidth += __new;
3896  // Compute estimated width, to see if is not reduced.
3897  if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3898  return _M_force_update();
3899  return true;
3900  }
3901 
3902  void
3903  _M_overflow() override
3904  {
3905  // Ignore characters in buffer, and override it.
3906  if (_M_ignoring())
3907  this->_M_rewind();
3908  // Write buffer to _M_out, and override it.
3909  else if (!_M_buffering())
3910  _M_flush();
3911  // Update written count, and if input still should be buffered,
3912  // flush the to _M_seq.
3913  else if (_M_update(this->_M_used().size()))
3914  _Str_sink<_CharT>::_M_overflow();
3915  }
3916 
3917  bool
3918  _M_discarding() const override
3919  { return _M_ignoring(); }
3920 
3921  typename _Sink<_CharT>::_Reservation
3922  _M_reserve(size_t __n) override
3923  {
3924  // Ignore characters in buffer, if any.
3925  if (_M_ignoring())
3926  this->_M_rewind();
3927  else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3928  if (!_M_buffering())
3929  {
3930  // Write pending characters if any
3931  if (!this->_M_used().empty())
3932  _M_flush();
3933  // Try to reserve from _M_out sink.
3934  if (auto __reserved = _M_out._M_reserve(__n))
3935  return __reserved;
3936  }
3937  return _Sink<_CharT>::_M_reserve(__n);
3938  }
3939 
3940  void
3941  _M_bump(size_t __n) override
3942  {
3943  // Ignore the written characters.
3944  if (_M_ignoring())
3945  return;
3946  // If reservation was made directy sink associated _M_out,
3947  // _M_bump will be called on that sink.
3948  _Sink<_CharT>::_M_bump(__n);
3949  if (_M_buffering())
3950  _M_update(__n);
3951  }
3952 
3953  public:
3954  [[__gnu__::__always_inline__]]
3955  explicit
3956  _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
3957  : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
3958  _M_out(std::move(__out)), _M_printwidth(0)
3959  { _M_sync_discarding(); }
3960 
3961  [[__gnu__::__always_inline__]]
3962  explicit
3963  _Padding_sink(_Out __out, size_t __padwidth)
3964  : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
3965  { }
3966 
3967  _Out
3968  _M_finish(_Align __align, char32_t __fill_char)
3969  {
3970  // Handle any characters in the buffer.
3971  if (auto __rem = this->_M_used().size())
3972  {
3973  if (_M_ignoring())
3974  this->_M_rewind();
3975  else if (!_M_buffering())
3976  _M_flush();
3977  else
3978  _M_update(__rem);
3979  }
3980 
3981  if (!_M_buffering() || !_M_force_update())
3982  // Characters were already written to _M_out.
3983  if (_M_printwidth >= _M_padwidth)
3984  return std::move(_M_out);
3985 
3986  const auto __str = this->view();
3987  if (_M_printwidth >= _M_padwidth)
3988  return __format::__write(std::move(_M_out), __str);
3989 
3990  const size_t __nfill = _M_padwidth - _M_printwidth;
3991  return __format::__write_padded(std::move(_M_out), __str,
3992  __align, __nfill, __fill_char);
3993  }
3994  };
3995 
3996  template<typename _Out, typename _CharT>
3997  class _Escaping_sink : public _Buf_sink<_CharT>
3998  {
3999  using _Esc = _Escapes<_CharT>;
4000 
4001  _Out _M_out;
4002  _Term_char _M_term : 2;
4003  unsigned _M_prev_escape : 1;
4004  unsigned _M_out_discards : 1;
4005 
4006  void
4007  _M_sync_discarding()
4008  {
4009  if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4010  _M_out_discards = _M_out._M_discarding();
4011  }
4012 
4013  void
4014  _M_write()
4015  {
4016  span<_CharT> __bytes = this->_M_used();
4017  basic_string_view<_CharT> __str(__bytes.data(), __bytes.size());
4018 
4019  size_t __rem = 0;
4020  if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4021  {
4022  bool __prev_escape = _M_prev_escape;
4023  _M_out = __format::__write_escaped_unicode_part(
4024  std::move(_M_out), __str, __prev_escape, _M_term);
4025  _M_prev_escape = __prev_escape;
4026 
4027  __rem = __str.size();
4028  if (__rem > 0 && __str.data() != this->_M_buf) [[unlikely]]
4029  ranges::move(__str, this->_M_buf);
4030  }
4031  else
4032  _M_out = __format::__write_escaped_ascii(
4033  std::move(_M_out), __str, _M_term);
4034 
4035  this->_M_reset(this->_M_buf, __rem);
4036  _M_sync_discarding();
4037  }
4038 
4039  void
4040  _M_overflow() override
4041  {
4042  if (_M_out_discards)
4043  this->_M_rewind();
4044  else
4045  _M_write();
4046  }
4047 
4048  bool
4049  _M_discarding() const override
4050  { return _M_out_discards; }
4051 
4052  public:
4053  [[__gnu__::__always_inline__]]
4054  explicit
4055  _Escaping_sink(_Out __out, _Term_char __term)
4056  : _M_out(std::move(__out)), _M_term(__term),
4057  _M_prev_escape(true), _M_out_discards(false)
4058  {
4059  _M_out = __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4060  _M_sync_discarding();
4061  }
4062 
4063  _Out
4064  _M_finish()
4065  {
4066  if (_M_out_discards)
4067  return std::move(_M_out);
4068 
4069  if (!this->_M_used().empty())
4070  {
4071  _M_write();
4072  if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4073  if (auto __rem = this->_M_used(); !__rem.empty())
4074  {
4075  basic_string_view<_CharT> __str(__rem.data(), __rem.size());
4076  _M_out = __format::__write_escape_seqs(std::move(_M_out), __str);
4077  }
4078  }
4079  return __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4080  }
4081  };
4082 
4083  enum class _Arg_t : unsigned char {
4084  _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
4085  _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
4086  _Arg_i128, _Arg_u128, _Arg_float128,
4087  _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
4088  _Arg_max_,
4089 
4090 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4091  _Arg_ibm128 = _Arg_ldbl,
4092  _Arg_ieee128 = _Arg_float128,
4093 #endif
4094  };
4095  using enum _Arg_t;
4096 
4097  template<typename _Context>
4098  struct _Arg_value
4099  {
4100  using _CharT = typename _Context::char_type;
4101 
4102  class handle
4103  {
4104  using _CharT = typename _Context::char_type;
4105  using _Func = void(*)(basic_format_parse_context<_CharT>&,
4106  _Context&, const void*);
4107 
4108  // Format as const if possible, to reduce instantiations.
4109  template<typename _Tp>
4110  using __maybe_const_t
4111  = __conditional_t<__formattable_with<const _Tp, _Context>,
4112  const _Tp, _Tp>;
4113 
4114  template<typename _Tq>
4115  static void
4116  _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4117  _Context& __format_ctx, const void* __ptr)
4118  {
4119  using _Td = remove_const_t<_Tq>;
4120  typename _Context::template formatter_type<_Td> __f;
4121  __parse_ctx.advance_to(__f.parse(__parse_ctx));
4122  _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4123  __format_ctx.advance_to(__f.format(__val, __format_ctx));
4124  }
4125 
4126  template<typename _Tp>
4127  requires (!is_same_v<remove_cv_t<_Tp>, handle>)
4128  explicit
4129  handle(_Tp& __val) noexcept
4130  : _M_ptr(__builtin_addressof(__val))
4131  , _M_func(&_S_format<__maybe_const_t<_Tp>>)
4132  { }
4133 
4134  friend class basic_format_arg<_Context>;
4135 
4136  public:
4137  handle(const handle&) = default;
4138  handle& operator=(const handle&) = default;
4139 
4140  [[__gnu__::__always_inline__]]
4141  void
4142  format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4143  { _M_func(__pc, __fc, this->_M_ptr); }
4144 
4145  private:
4146  const void* _M_ptr;
4147  _Func _M_func;
4148  };
4149 
4150  union
4151  {
4152  monostate _M_none;
4153  bool _M_bool;
4154  _CharT _M_c;
4155  int _M_i;
4156  unsigned _M_u;
4157  long long _M_ll;
4158  unsigned long long _M_ull;
4159  float _M_flt;
4160  double _M_dbl;
4161 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4162  long double _M_ldbl;
4163 #else
4164  __ibm128 _M_ibm128;
4165  __ieee128 _M_ieee128;
4166 #endif
4167 #ifdef __SIZEOF_FLOAT128__
4168  __float128 _M_float128;
4169 #endif
4170  const _CharT* _M_str;
4171  basic_string_view<_CharT> _M_sv;
4172  const void* _M_ptr;
4173  handle _M_handle;
4174 #ifdef __SIZEOF_INT128__
4175  __int128 _M_i128;
4176  unsigned __int128 _M_u128;
4177 #endif
4178 #ifdef __BFLT16_DIG__
4179  __bflt16_t _M_bf16;
4180 #endif
4181 #ifdef __FLT16_DIG__
4182  _Float16 _M_f16;
4183 #endif
4184 #ifdef __FLT32_DIG__
4185  _Float32 _M_f32;
4186 #endif
4187 #ifdef __FLT64_DIG__
4188  _Float64 _M_f64;
4189 #endif
4190  };
4191 
4192  [[__gnu__::__always_inline__]]
4193  _Arg_value() : _M_none() { }
4194 
4195 #if 0
4196  template<typename _Tp>
4197  _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4198  { _S_get<_Tp>() = __val; }
4199 #endif
4200 
4201  // Returns reference to the _Arg_value member with the type _Tp.
4202  // Value of second argument (if provided), is assigned to that member.
4203  template<typename _Tp, typename _Self, typename... _Value>
4204  [[__gnu__::__always_inline__]]
4205  static auto&
4206  _S_access(_Self& __u, _Value... __value) noexcept
4207  {
4208  static_assert(sizeof...(_Value) <= 1);
4209  if constexpr (is_same_v<_Tp, bool>)
4210  return (__u._M_bool = ... = __value);
4211  else if constexpr (is_same_v<_Tp, _CharT>)
4212  return (__u._M_c = ... = __value);
4213  else if constexpr (is_same_v<_Tp, int>)
4214  return (__u._M_i = ... = __value);
4215  else if constexpr (is_same_v<_Tp, unsigned>)
4216  return (__u._M_u = ... = __value);
4217  else if constexpr (is_same_v<_Tp, long long>)
4218  return (__u._M_ll = ... = __value);
4219  else if constexpr (is_same_v<_Tp, unsigned long long>)
4220  return (__u._M_ull = ... = __value);
4221  else if constexpr (is_same_v<_Tp, float>)
4222  return (__u._M_flt = ... = __value);
4223  else if constexpr (is_same_v<_Tp, double>)
4224  return (__u._M_dbl = ... = __value);
4225 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4226  else if constexpr (is_same_v<_Tp, long double>)
4227  return (__u._M_ldbl = ... = __value);
4228 #else
4229  else if constexpr (is_same_v<_Tp, __ibm128>)
4230  return (__u._M_ibm128 = ... = __value);
4231  else if constexpr (is_same_v<_Tp, __ieee128>)
4232  return (__u._M_ieee128 = ... = __value);
4233 #endif
4234 #ifdef __SIZEOF_FLOAT128__
4235  else if constexpr (is_same_v<_Tp, __float128>)
4236  return (__u._M_float128 = ... = __value);
4237 #endif
4238  else if constexpr (is_same_v<_Tp, const _CharT*>)
4239  return (__u._M_str = ... = __value);
4240  else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4241  return (__u._M_sv = ... = __value);
4242  else if constexpr (is_same_v<_Tp, const void*>)
4243  return (__u._M_ptr = ... = __value);
4244 #ifdef __SIZEOF_INT128__
4245  else if constexpr (is_same_v<_Tp, __int128>)
4246  return (__u._M_i128 = ... = __value);
4247  else if constexpr (is_same_v<_Tp, unsigned __int128>)
4248  return (__u._M_u128 = ... = __value);
4249 #endif
4250 #ifdef __BFLT16_DIG__
4251  else if constexpr (is_same_v<_Tp, __bflt16_t>)
4252  return (__u._M_bf16 = ... = __value);
4253 #endif
4254 #ifdef __FLT16_DIG__
4255  else if constexpr (is_same_v<_Tp, _Float16>)
4256  return (__u._M_f16 = ... = __value);
4257 #endif
4258 #ifdef __FLT32_DIG__
4259  else if constexpr (is_same_v<_Tp, _Float32>)
4260  return (__u._M_f32 = ... = __value);
4261 #endif
4262 #ifdef __FLT64_DIG__
4263  else if constexpr (is_same_v<_Tp, _Float64>)
4264  return (__u._M_f64 = ... = __value);
4265 #endif
4266  else if constexpr (is_same_v<_Tp, handle>)
4267  return __u._M_handle;
4268  // Otherwise, ill-formed.
4269  }
4270 
4271  template<typename _Tp>
4272  [[__gnu__::__always_inline__]]
4273  auto&
4274  _M_get() noexcept
4275  { return _S_access<_Tp>(*this); }
4276 
4277  template<typename _Tp>
4278  [[__gnu__::__always_inline__]]
4279  const auto&
4280  _M_get() const noexcept
4281  { return _S_access<_Tp>(*this); }
4282 
4283  template<typename _Tp>
4284  [[__gnu__::__always_inline__]]
4285  void
4286  _M_set(_Tp __v) noexcept
4287  {
4288  // Explicitly construct types without trivial default constructor.
4289  if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4290  std::construct_at(&_M_sv, __v);
4291  else if constexpr (is_same_v<_Tp, handle>)
4292  std::construct_at(&_M_handle, __v);
4293  else
4294  // Builtin types are trivially default constructible, and assignment
4295  // changes active member per N5032 [class.union.general] p5.
4296  _S_access<_Tp>(*this, __v);
4297  }
4298  };
4299 
4300  // [format.arg.store], class template format-arg-store
4301  template<typename _Context, typename... _Args>
4302  class _Arg_store;
4303 
4304  template<typename _Visitor, typename _Ctx>
4305  decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4306 
4307  template<typename _Ch, typename _Tp>
4308  consteval _Arg_t
4309  __to_arg_t_enum() noexcept;
4310 } // namespace __format
4311 /// @endcond
4312 
4313  template<typename _Context>
4314  class basic_format_arg
4315  {
4316  using _CharT = typename _Context::char_type;
4317 
4318  public:
4319  using handle = __format::_Arg_value<_Context>::handle;
4320 
4321  [[__gnu__::__always_inline__]]
4322  basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4323 
4324  [[nodiscard,__gnu__::__always_inline__]]
4325  explicit operator bool() const noexcept
4326  { return _M_type != __format::_Arg_none; }
4327 
4328 #if __cpp_lib_format >= 202306L // >= C++26
4329  template<typename _Visitor>
4330  decltype(auto)
4331  visit(this basic_format_arg __arg, _Visitor&& __vis)
4332  { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4333 
4334  template<typename _Res, typename _Visitor>
4335  _Res
4336  visit(this basic_format_arg __arg, _Visitor&& __vis)
4337  { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4338 #endif
4339 
4340  private:
4341  template<typename _Ctx>
4342  friend class basic_format_args;
4343 
4344  template<typename _Ctx, typename... _Args>
4345  friend class __format::_Arg_store;
4346 
4347  static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4348 
4349  __format::_Arg_value<_Context> _M_val;
4350  __format::_Arg_t _M_type;
4351 
4352  // Transform incoming argument type to the type stored in _Arg_value.
4353  // e.g. short -> int, std::string -> std::string_view,
4354  // char[3] -> const char*.
4355  template<typename _Tp>
4356  static consteval auto
4357  _S_to_arg_type()
4358  {
4359  using _Td = remove_const_t<_Tp>;
4360  if constexpr (is_same_v<_Td, bool>)
4361  return type_identity<bool>();
4362  else if constexpr (is_same_v<_Td, _CharT>)
4363  return type_identity<_CharT>();
4364  else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4365  return type_identity<_CharT>();
4366 #ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4367  else if constexpr (is_same_v<_Td, __int128>)
4368  return type_identity<__int128>();
4369  else if constexpr (is_same_v<_Td, unsigned __int128>)
4370  return type_identity<unsigned __int128>();
4371 #endif
4372  else if constexpr (__is_signed_integer<_Td>::value)
4373  {
4374  if constexpr (sizeof(_Td) <= sizeof(int))
4375  return type_identity<int>();
4376  else if constexpr (sizeof(_Td) <= sizeof(long long))
4377  return type_identity<long long>();
4378  }
4379  else if constexpr (__is_unsigned_integer<_Td>::value)
4380  {
4381  if constexpr (sizeof(_Td) <= sizeof(unsigned))
4382  return type_identity<unsigned>();
4383  else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4384  return type_identity<unsigned long long>();
4385  }
4386  else if constexpr (is_same_v<_Td, float>)
4387  return type_identity<float>();
4388  else if constexpr (is_same_v<_Td, double>)
4389  return type_identity<double>();
4390 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4391  else if constexpr (is_same_v<_Td, long double>)
4392  return type_identity<long double>();
4393 #else
4394  else if constexpr (is_same_v<_Td, __ibm128>)
4395  return type_identity<__ibm128>();
4396  else if constexpr (is_same_v<_Td, __ieee128>)
4397  return type_identity<__ieee128>();
4398 #endif
4399 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4400  else if constexpr (is_same_v<_Td, __float128>)
4401  return type_identity<__float128>();
4402 #endif
4403 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4404  else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4405  return type_identity<__format::__bflt16_t>();
4406 #endif
4407 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4408  else if constexpr (is_same_v<_Td, _Float16>)
4409  return type_identity<_Float16>();
4410 #endif
4411 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4412  else if constexpr (is_same_v<_Td, _Float32>)
4413  return type_identity<_Float32>();
4414 #endif
4415 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4416  else if constexpr (is_same_v<_Td, _Float64>)
4417  return type_identity<_Float64>();
4418 #endif
4419  else if constexpr (__is_specialization_of<_Td, basic_string_view>
4420  || __is_specialization_of<_Td, basic_string>)
4421  {
4422  if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4423  return type_identity<basic_string_view<_CharT>>();
4424  else
4425  return type_identity<handle>();
4426  }
4427  else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4428  return type_identity<const _CharT*>();
4429  else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4430  return type_identity<const _CharT*>();
4431  else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4432  return type_identity<const void*>();
4433  else if constexpr (is_same_v<_Td, nullptr_t>)
4434  return type_identity<const void*>();
4435  else
4436  return type_identity<handle>();
4437  }
4438 
4439  // Transform a formattable type to the appropriate storage type.
4440  template<typename _Tp>
4441  using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4442 
4443  // Get the _Arg_t value corresponding to a normalized type.
4444  template<typename _Tp>
4445  static consteval __format::_Arg_t
4446  _S_to_enum()
4447  {
4448  using namespace __format;
4449  if constexpr (is_same_v<_Tp, bool>)
4450  return _Arg_bool;
4451  else if constexpr (is_same_v<_Tp, _CharT>)
4452  return _Arg_c;
4453  else if constexpr (is_same_v<_Tp, int>)
4454  return _Arg_i;
4455  else if constexpr (is_same_v<_Tp, unsigned>)
4456  return _Arg_u;
4457  else if constexpr (is_same_v<_Tp, long long>)
4458  return _Arg_ll;
4459  else if constexpr (is_same_v<_Tp, unsigned long long>)
4460  return _Arg_ull;
4461  else if constexpr (is_same_v<_Tp, float>)
4462  return _Arg_flt;
4463  else if constexpr (is_same_v<_Tp, double>)
4464  return _Arg_dbl;
4465 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4466  else if constexpr (is_same_v<_Tp, long double>)
4467  return _Arg_ldbl;
4468 #else
4469  // Don't use _Arg_ldbl for this target, it's ambiguous.
4470  else if constexpr (is_same_v<_Tp, __ibm128>)
4471  return _Arg_ibm128;
4472  else if constexpr (is_same_v<_Tp, __ieee128>)
4473  return _Arg_ieee128;
4474 #endif
4475 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4476  else if constexpr (is_same_v<_Tp, __float128>)
4477  return _Arg_float128;
4478 #endif
4479 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4480  else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4481  return _Arg_bf16;
4482 #endif
4483 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4484  else if constexpr (is_same_v<_Tp, _Float16>)
4485  return _Arg_f16;
4486 #endif
4487 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4488  else if constexpr (is_same_v<_Tp, _Float32>)
4489  return _Arg_f32;
4490 #endif
4491 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4492  else if constexpr (is_same_v<_Tp, _Float64>)
4493  return _Arg_f64;
4494 #endif
4495  else if constexpr (is_same_v<_Tp, const _CharT*>)
4496  return _Arg_str;
4497  else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4498  return _Arg_sv;
4499  else if constexpr (is_same_v<_Tp, const void*>)
4500  return _Arg_ptr;
4501 #ifdef __SIZEOF_INT128__
4502  else if constexpr (is_same_v<_Tp, __int128>)
4503  return _Arg_i128;
4504  else if constexpr (is_same_v<_Tp, unsigned __int128>)
4505  return _Arg_u128;
4506 #endif
4507  else if constexpr (is_same_v<_Tp, handle>)
4508  return _Arg_handle;
4509  }
4510 
4511  template<typename _Tp>
4512  void
4513  _M_set(_Tp __v) noexcept
4514  {
4515  _M_type = _S_to_enum<_Tp>();
4516  _M_val._M_set(__v);
4517  }
4518 
4519  template<typename _Tp>
4520  requires __format::__formattable_with<_Tp, _Context>
4521  explicit
4522  basic_format_arg(_Tp& __v) noexcept
4523  {
4524  using _Td = _Normalize<_Tp>;
4525  if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4526  _M_set(_Td{__v.data(), __v.size()});
4527  else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4528  && is_same_v<_CharT, wchar_t>)
4529  _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4530  else
4531  _M_set(static_cast<_Td>(__v));
4532  }
4533 
4534  template<typename _Ctx, typename... _Argz>
4535  friend auto
4536  make_format_args(_Argz&...) noexcept;
4537 
4538  template<typename _Visitor, typename _Ctx>
4539  friend decltype(auto)
4540  visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4541 
4542  template<typename _Visitor, typename _Ctx>
4543  friend decltype(auto)
4544  __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4545 
4546  template<typename _Ch, typename _Tp>
4547  friend consteval __format::_Arg_t
4548  __format::__to_arg_t_enum() noexcept;
4549 
4550  [[__gnu__::__noinline__]]
4551  handle
4552  _M_handle_unrecognized() const;
4553 
4554  template<typename _Visitor>
4555  decltype(auto)
4556  _M_visit(_Visitor&& __vis)
4557  {
4558  switch (_M_type)
4559  {
4560  using enum __format::_Arg_t;
4561  case _Arg_none:
4562  return std::forward<_Visitor>(__vis)(_M_val._M_none);
4563  case _Arg_bool:
4564  return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4565  case _Arg_c:
4566  return std::forward<_Visitor>(__vis)(_M_val._M_c);
4567  case _Arg_i:
4568  return std::forward<_Visitor>(__vis)(_M_val._M_i);
4569  case _Arg_u:
4570  return std::forward<_Visitor>(__vis)(_M_val._M_u);
4571  case _Arg_ll:
4572  return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4573  case _Arg_ull:
4574  return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4575 #if __glibcxx_to_chars // FIXME: need to be able to format these types!
4576  case _Arg_flt:
4577  return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4578  case _Arg_dbl:
4579  return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4580 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4581  case _Arg_ldbl:
4582  return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4583 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4584  case _Arg_float128:
4585  return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4586 #endif
4587 #else
4588  case _Arg_ibm128:
4589  return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4590  case _Arg_ieee128:
4591  return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4592 #endif
4593 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4594  case _Arg_bf16:
4595  return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4596 #endif
4597 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4598  case _Arg_f16:
4599  return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4600 #endif
4601 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4602  case _Arg_f32:
4603  return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4604 #endif
4605 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4606  case _Arg_f64:
4607  return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4608 #endif
4609 #endif // __glibcxx_to_chars
4610  case _Arg_str:
4611  return std::forward<_Visitor>(__vis)(_M_val._M_str);
4612  case _Arg_sv:
4613  return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4614  case _Arg_ptr:
4615  return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4616  case _Arg_handle:
4617  return std::forward<_Visitor>(__vis)(_M_val._M_handle);
4618 #ifdef __SIZEOF_INT128__
4619  case _Arg_i128:
4620  return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4621  case _Arg_u128:
4622  return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4623 #endif
4624  default:
4625  // Call exported definition of _M_handle_unrecognized from
4626  // libstdc++.so, that should recognize new _Arg_t values and
4627  // return basic_format_arg, containing a handle to that value.
4628  handle __h = _M_handle_unrecognized();
4629  return std::forward<_Visitor>(__vis)(__h);
4630  }
4631  }
4632 
4633  template<typename _Visitor>
4634  decltype(auto)
4635  _M_visit_user(_Visitor&& __vis)
4636  {
4637  return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4638  {
4639  constexpr bool __user_facing = __is_one_of<_Tp,
4640  monostate, bool, _CharT,
4641  int, unsigned int, long long int, unsigned long long int,
4642  float, double, long double,
4643  const _CharT*, basic_string_view<_CharT>,
4644  const void*, handle>::value;
4645  if constexpr (__user_facing)
4646  return std::forward<_Visitor>(__vis)(__val);
4647  else
4648  {
4649  handle __h(__val);
4650  return std::forward<_Visitor>(__vis)(__h);
4651  }
4652  });
4653  }
4654  };
4655 
4656  template<typename _Visitor, typename _Context>
4657  _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4658  inline decltype(auto)
4659  visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4660  { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4661 
4662 /// @cond undocumented
4663 namespace __format
4664 {
4665  template<typename _Visitor, typename _Ctx>
4666  inline decltype(auto)
4667  __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4668  { return __arg._M_visit(std::forward<_Visitor>(__vis)); }
4669 
4670  struct _WidthPrecVisitor
4671  {
4672  template<typename _Tp>
4673  size_t
4674  operator()(_Tp& __arg) const
4675  {
4676  if constexpr (is_same_v<_Tp, monostate>)
4677  __format::__invalid_arg_id_in_format_string();
4678  // _GLIBCXX_RESOLVE_LIB_DEFECTS
4679  // 3720. Restrict the valid types of arg-id for width and precision
4680  // 3721. Allow an arg-id with a value of zero for width
4681  else if constexpr (sizeof(_Tp) <= sizeof(long long))
4682  {
4683  // _GLIBCXX_RESOLVE_LIB_DEFECTS
4684  // 3720. Restrict the valid types of arg-id for width and precision
4685  if constexpr (__is_unsigned_integer<_Tp>::value)
4686  return __arg;
4687  else if constexpr (__is_signed_integer<_Tp>::value)
4688  if (__arg >= 0)
4689  return __arg;
4690  }
4691  __throw_format_error("format error: argument used for width or "
4692  "precision must be a non-negative integer");
4693  }
4694  };
4695 
4696 #pragma GCC diagnostic push
4697 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4698  template<typename _Context>
4699  inline size_t
4700  __int_from_arg(const basic_format_arg<_Context>& __arg)
4701  { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4702 
4703  // Pack _Arg_t enum values into a single 60-bit integer.
4704  template<int _Bits, size_t _Nm>
4705  constexpr auto
4706  __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4707  {
4708  __UINT64_TYPE__ __packed_types = 0;
4709  for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4710  __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4711  return __packed_types;
4712  }
4713 } // namespace __format
4714 /// @endcond
4715 
4716  template<typename _Context>
4717  class basic_format_args
4718  {
4719  static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4720  static constexpr int _S_packed_type_mask = 0b11111;
4721  static constexpr int _S_max_packed_args = 12;
4722 
4723  static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4724 
4725  template<typename... _Args>
4726  using _Store = __format::_Arg_store<_Context, _Args...>;
4727 
4728  template<typename _Ctx, typename... _Args>
4729  friend class __format::_Arg_store;
4730 
4731  using uint64_t = __UINT64_TYPE__;
4732  using _Format_arg = basic_format_arg<_Context>;
4733  using _Format_arg_val = __format::_Arg_value<_Context>;
4734 
4735  // If args are packed then the number of args is in _M_packed_size and
4736  // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4737  // If args are not packed then the number of args is in _M_unpacked_size
4738  // and _M_packed_size is zero.
4739  uint64_t _M_packed_size : 4;
4740  uint64_t _M_unpacked_size : 60;
4741 
4742  union {
4743  const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4744  const _Format_arg* _M_args; // Active when _M_packed_size == 0
4745  };
4746 
4747  size_t
4748  _M_size() const noexcept
4749  { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4750 
4751  typename __format::_Arg_t
4752  _M_type(size_t __i) const noexcept
4753  {
4754  uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4755  return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4756  }
4757 
4758  template<typename _Ctx, typename... _Args>
4759  friend auto
4760  make_format_args(_Args&...) noexcept;
4761 
4762  // An array of _Arg_t enums corresponding to _Args...
4763  template<typename... _Args>
4764  static consteval array<__format::_Arg_t, sizeof...(_Args)>
4765  _S_types_to_pack()
4766  { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4767 
4768  public:
4769  template<typename... _Args>
4770  basic_format_args(const _Store<_Args...>& __store) noexcept;
4771 
4772  [[nodiscard,__gnu__::__always_inline__]]
4773  basic_format_arg<_Context>
4774  get(size_t __i) const noexcept
4775  {
4776  basic_format_arg<_Context> __arg;
4777  if (__i < _M_packed_size)
4778  {
4779  __arg._M_type = _M_type(__i);
4780  __arg._M_val = _M_values[__i];
4781  }
4782  else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4783  __arg = _M_args[__i];
4784  return __arg;
4785  }
4786  };
4787 
4788  // _GLIBCXX_RESOLVE_LIB_DEFECTS
4789  // 3810. CTAD for std::basic_format_args
4790  template<typename _Context, typename... _Args>
4791  basic_format_args(__format::_Arg_store<_Context, _Args...>)
4792  -> basic_format_args<_Context>;
4793 
4794  template<typename _Context, typename... _Args>
4795  auto
4796  make_format_args(_Args&... __fmt_args) noexcept;
4797 
4798  // An array of type-erased formatting arguments.
4799  template<typename _Context, typename... _Args>
4800  class __format::_Arg_store
4801  {
4802  friend std::basic_format_args<_Context>;
4803 
4804  template<typename _Ctx, typename... _Argz>
4805  friend auto std::
4806 #if _GLIBCXX_INLINE_VERSION
4807  __8:: // Needed for PR c++/59256
4808 #endif
4809  make_format_args(_Argz&...) noexcept;
4810 
4811  // For a sufficiently small number of arguments we only store values.
4812  // basic_format_args can get the types from the _Args pack.
4813  static constexpr bool _S_values_only
4814  = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4815 
4816  using _Element_t
4817  = __conditional_t<_S_values_only,
4818  __format::_Arg_value<_Context>,
4819  basic_format_arg<_Context>>;
4820 
4821  _Element_t _M_args[sizeof...(_Args)];
4822 
4823  template<typename _Tp>
4824  static _Element_t
4825  _S_make_elt(_Tp& __v)
4826  {
4827  using _Tq = remove_const_t<_Tp>;
4828  using _CharT = typename _Context::char_type;
4829  static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4830  "std::formatter must be specialized for the type "
4831  "of each format arg");
4832  using __format::__formattable_with;
4833  if constexpr (is_const_v<_Tp>)
4834  if constexpr (!__formattable_with<_Tp, _Context>)
4835  if constexpr (__formattable_with<_Tq, _Context>)
4836  static_assert(__formattable_with<_Tp, _Context>,
4837  "format arg must be non-const because its "
4838  "std::formatter specialization has a "
4839  "non-const reference parameter");
4840  basic_format_arg<_Context> __arg(__v);
4841  if constexpr (_S_values_only)
4842  return __arg._M_val;
4843  else
4844  return __arg;
4845  }
4846 
4847  template<typename... _Tp>
4848  requires (sizeof...(_Tp) == sizeof...(_Args))
4849  [[__gnu__::__always_inline__]]
4850  _Arg_store(_Tp&... __a) noexcept
4851  : _M_args{_S_make_elt(__a)...}
4852  { }
4853  };
4854 
4855  template<typename _Context>
4856  class __format::_Arg_store<_Context>
4857  { };
4858 
4859  template<typename _Context>
4860  template<typename... _Args>
4861  inline
4862  basic_format_args<_Context>::
4863  basic_format_args(const _Store<_Args...>& __store) noexcept
4864  {
4865  if constexpr (sizeof...(_Args) == 0)
4866  {
4867  _M_packed_size = 0;
4868  _M_unpacked_size = 0;
4869  _M_args = nullptr;
4870  }
4871  else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4872  {
4873  // The number of packed arguments:
4874  _M_packed_size = sizeof...(_Args);
4875  // The packed type enums:
4876  _M_unpacked_size
4877  = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4878  // The _Arg_value objects.
4879  _M_values = __store._M_args;
4880  }
4881  else
4882  {
4883  // No packed arguments:
4884  _M_packed_size = 0;
4885  // The number of unpacked arguments:
4886  _M_unpacked_size = sizeof...(_Args);
4887  // The basic_format_arg objects:
4888  _M_args = __store._M_args;
4889  }
4890  }
4891 
4892  /// Capture formatting arguments for use by `std::vformat`.
4893  template<typename _Context = format_context, typename... _Args>
4894  [[nodiscard,__gnu__::__always_inline__]]
4895  inline auto
4896  make_format_args(_Args&... __fmt_args) noexcept
4897  {
4898  using _Fmt_arg = basic_format_arg<_Context>;
4899  using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4900  _Normalize<_Args>...>;
4901  return _Store(__fmt_args...);
4902  }
4903 
4904 #ifdef _GLIBCXX_USE_WCHAR_T
4905  /// Capture formatting arguments for use by `std::vformat` (for wide output).
4906  template<typename... _Args>
4907  [[nodiscard,__gnu__::__always_inline__]]
4908  inline auto
4909  make_wformat_args(_Args&... __args) noexcept
4910  { return std::make_format_args<wformat_context>(__args...); }
4911 #endif
4912 
4913 /// @cond undocumented
4914 namespace __format
4915 {
4916  template<typename _Out, typename _CharT, typename _Context>
4917  _Out
4918  __do_vformat_to(_Out, basic_string_view<_CharT>,
4919  const basic_format_args<_Context>&,
4920  const locale* = nullptr);
4921 
4922  template<typename _CharT> struct __formatter_chrono;
4923 
4924 } // namespace __format
4925 /// @endcond
4926 
4927  /** Context for std::format and similar functions.
4928  *
4929  * A formatting context contains an output iterator and locale to use
4930  * for the formatting operations. Most programs will never need to use
4931  * this class template explicitly. For typical uses of `std::format` the
4932  * library will use the specializations `std::format_context` (for `char`)
4933  * and `std::wformat_context` (for `wchar_t`).
4934  *
4935  * You are not allowed to define partial or explicit specializations of
4936  * this class template.
4937  *
4938  * @since C++20
4939  */
4940  template<typename _Out, typename _CharT>
4941  class basic_format_context
4942  {
4943  static_assert( output_iterator<_Out, const _CharT&> );
4944 
4945  basic_format_args<basic_format_context> _M_args;
4946  _Out _M_out;
4947  __format::_Optional_locale _M_loc;
4948 
4949  basic_format_context(basic_format_args<basic_format_context> __args,
4950  _Out __out)
4951  : _M_args(__args), _M_out(std::move(__out))
4952  { }
4953 
4954  basic_format_context(basic_format_args<basic_format_context> __args,
4955  _Out __out, const std::locale& __loc)
4956  : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4957  { }
4958 
4959  // _GLIBCXX_RESOLVE_LIB_DEFECTS
4960  // 4061. Should std::basic_format_context be
4961  // default-constructible/copyable/movable?
4962  basic_format_context(const basic_format_context&) = delete;
4963  basic_format_context& operator=(const basic_format_context&) = delete;
4964 
4965  template<typename _Out2, typename _CharT2, typename _Context2>
4966  friend _Out2
4967  __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4968  const basic_format_args<_Context2>&,
4969  const locale*);
4970 
4971  friend __format::__formatter_chrono<_CharT>;
4972 
4973  public:
4974  ~basic_format_context() = default;
4975 
4976  using iterator = _Out;
4977  using char_type = _CharT;
4978  template<typename _Tp>
4979  using formatter_type = formatter<_Tp, _CharT>;
4980 
4981  [[nodiscard]]
4982  basic_format_arg<basic_format_context>
4983  arg(size_t __id) const noexcept
4984  { return _M_args.get(__id); }
4985 
4986  [[nodiscard]]
4987  std::locale locale() { return _M_loc.value(); }
4988 
4989  [[nodiscard]]
4990  iterator out() { return std::move(_M_out); }
4991 
4992  void advance_to(iterator __it) { _M_out = std::move(__it); }
4993  };
4994 
4995 #if _GLIBCXX_EXTERN_TEMPLATE
4996  // The defintion _M_handle_unrecognized is placed in format-inst.cc
4997  // source file, to ensure that it will not be inlined by compiler.
4998  extern template basic_format_arg<format_context>::handle
4999  basic_format_arg<format_context>::_M_handle_unrecognized() const;
5000 # ifdef _GLIBCXX_USE_WCHAR_T
5001  extern template basic_format_arg<wformat_context>::handle
5002  basic_format_arg<wformat_context>::_M_handle_unrecognized() const;
5003 # endif
5004 #else
5005  template<typename _Context>
5006  typename basic_format_arg<_Context>::handle
5007  basic_format_arg<_Context>::_M_handle_unrecognized() const
5008  {
5009  // If _M_type corresponds to a new value of _Arg_t introduced after
5010  // GCC 16, this function should return a handle that refers to the
5011  // union member of _M_val corresponding to that _Arg_t value.
5012  __throw_format_error("format error: unrecognized argument type");
5013  }
5014 #endif
5015 
5016 /// @cond undocumented
5017 namespace __format
5018 {
5019  // Abstract base class defining an interface for scanning format strings.
5020  // Scan the characters in a format string, dividing it up into strings of
5021  // ordinary characters, escape sequences, and replacement fields.
5022  // Call virtual functions for derived classes to parse format-specifiers
5023  // or write formatted output.
5024  template<typename _CharT>
5025  struct _Scanner
5026  {
5027  using iterator = typename basic_format_parse_context<_CharT>::iterator;
5028 
5029  struct _Parse_context : basic_format_parse_context<_CharT>
5030  {
5031  using basic_format_parse_context<_CharT>::basic_format_parse_context;
5032  const _Arg_t* _M_types = nullptr;
5033  } _M_pc;
5034 
5035  constexpr explicit
5036  _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
5037  : _M_pc(__str, __nargs)
5038  { }
5039 
5040  constexpr iterator begin() const noexcept { return _M_pc.begin(); }
5041  constexpr iterator end() const noexcept { return _M_pc.end(); }
5042 
5043  constexpr void
5044  _M_scan()
5045  {
5046  basic_string_view<_CharT> __fmt = _M_fmt_str();
5047 
5048  if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5049  {
5050  _M_pc.advance_to(begin() + 1);
5051  _M_format_arg(_M_pc.next_arg_id());
5052  return;
5053  }
5054 
5055  size_t __lbr = __fmt.find('{');
5056  size_t __rbr = __fmt.find('}');
5057 
5058  while (__fmt.size())
5059  {
5060  auto __cmp = __lbr <=> __rbr;
5061  if (__cmp == 0)
5062  {
5063  _M_on_chars(end());
5064  _M_pc.advance_to(end());
5065  return;
5066  }
5067  else if (__cmp < 0)
5068  {
5069  if (__lbr + 1 == __fmt.size()
5070  || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
5071  __format::__unmatched_left_brace_in_format_string();
5072  const bool __is_escape = __fmt[__lbr + 1] == '{';
5073  iterator __last = begin() + __lbr + int(__is_escape);
5074  _M_on_chars(__last);
5075  _M_pc.advance_to(__last + 1);
5076  __fmt = _M_fmt_str();
5077  if (__is_escape)
5078  {
5079  if (__rbr != __fmt.npos)
5080  __rbr -= __lbr + 2;
5081  __lbr = __fmt.find('{');
5082  }
5083  else
5084  {
5085  _M_on_replacement_field();
5086  __fmt = _M_fmt_str();
5087  __lbr = __fmt.find('{');
5088  __rbr = __fmt.find('}');
5089  }
5090  }
5091  else
5092  {
5093  if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
5094  __format::__unmatched_right_brace_in_format_string();
5095  iterator __last = begin() + __rbr;
5096  _M_on_chars(__last);
5097  _M_pc.advance_to(__last + 1);
5098  __fmt = _M_fmt_str();
5099  if (__lbr != __fmt.npos)
5100  __lbr -= __rbr + 1;
5101  __rbr = __fmt.find('}');
5102  }
5103  }
5104  }
5105 
5106  constexpr basic_string_view<_CharT>
5107  _M_fmt_str() const noexcept
5108  { return {begin(), end()}; }
5109 
5110  constexpr virtual void _M_on_chars(iterator) { }
5111 
5112  constexpr void _M_on_replacement_field()
5113  {
5114  auto __next = begin();
5115 
5116  size_t __id;
5117  if (*__next == '}')
5118  __id = _M_pc.next_arg_id();
5119  else if (*__next == ':')
5120  {
5121  __id = _M_pc.next_arg_id();
5122  _M_pc.advance_to(++__next);
5123  }
5124  else
5125  {
5126  auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5127  if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5128  __format::__invalid_arg_id_in_format_string();
5129  _M_pc.check_arg_id(__id = __i);
5130  if (*__ptr == ':')
5131  {
5132  _M_pc.advance_to(++__ptr);
5133  }
5134  else
5135  _M_pc.advance_to(__ptr);
5136  }
5137  _M_format_arg(__id);
5138  if (begin() == end() || *begin() != '}')
5139  __format::__unmatched_left_brace_in_format_string();
5140  _M_pc.advance_to(begin() + 1); // Move past '}'
5141  }
5142 
5143  constexpr virtual void _M_format_arg(size_t __id) = 0;
5144  };
5145 
5146  // Process a format string and format the arguments in the context.
5147  template<typename _Out, typename _CharT>
5148  class _Formatting_scanner : public _Scanner<_CharT>
5149  {
5150  public:
5151  _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5152  basic_string_view<_CharT> __str)
5153  : _Scanner<_CharT>(__str), _M_fc(__fc)
5154  { }
5155 
5156  private:
5157  basic_format_context<_Out, _CharT>& _M_fc;
5158 
5159  using iterator = typename _Scanner<_CharT>::iterator;
5160 
5161  constexpr void
5162  _M_on_chars(iterator __last) override
5163  {
5164  basic_string_view<_CharT> __str(this->begin(), __last);
5165  _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5166  }
5167 
5168  constexpr void
5169  _M_format_arg(size_t __id) override
5170  {
5171  using _Context = basic_format_context<_Out, _CharT>;
5172  using handle = typename basic_format_arg<_Context>::handle;
5173 
5174  __format::__visit_format_arg([this](auto& __arg) {
5175  using _Type = remove_reference_t<decltype(__arg)>;
5176  using _Formatter = typename _Context::template formatter_type<_Type>;
5177  if constexpr (is_same_v<_Type, monostate>)
5178  __format::__invalid_arg_id_in_format_string();
5179  else if constexpr (is_same_v<_Type, handle>)
5180  __arg.format(this->_M_pc, this->_M_fc);
5181  else if constexpr (is_default_constructible_v<_Formatter>)
5182  {
5183  _Formatter __f;
5184  this->_M_pc.advance_to(__f.parse(this->_M_pc));
5185  this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5186  }
5187  else
5188  static_assert(__format::__formattable_with<_Type, _Context>);
5189  }, _M_fc.arg(__id));
5190  }
5191  };
5192 
5193  template<typename _CharT, typename _Tp>
5194  consteval _Arg_t
5195  __to_arg_t_enum() noexcept
5196  {
5197  using _Context = __format::__format_context<_CharT>;
5198  using _Fmt_arg = basic_format_arg<_Context>;
5199  using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5200  return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5201  }
5202 
5203  // Validate a format string for Args.
5204  template<typename _CharT, typename... _Args>
5205  class _Checking_scanner : public _Scanner<_CharT>
5206  {
5207  static_assert(
5208  (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5209  "std::formatter must be specialized for each type being formatted");
5210 
5211  public:
5212  consteval
5213  _Checking_scanner(basic_string_view<_CharT> __str)
5214  : _Scanner<_CharT>(__str, sizeof...(_Args))
5215  {
5216 #if __cpp_lib_format >= 202305L
5217  this->_M_pc._M_types = _M_types.data();
5218 #endif
5219  }
5220 
5221  private:
5222  constexpr void
5223  _M_format_arg(size_t __id) override
5224  {
5225  if constexpr (sizeof...(_Args) != 0)
5226  {
5227  if (__id < sizeof...(_Args))
5228  {
5229  _M_parse_format_spec<_Args...>(__id);
5230  return;
5231  }
5232  }
5233  __builtin_unreachable();
5234  }
5235 
5236  template<typename _Tp, typename... _OtherArgs>
5237  constexpr void
5238  _M_parse_format_spec(size_t __id)
5239  {
5240  if (__id == 0)
5241  {
5242  formatter<_Tp, _CharT> __f;
5243  this->_M_pc.advance_to(__f.parse(this->_M_pc));
5244  }
5245  else if constexpr (sizeof...(_OtherArgs) != 0)
5246  _M_parse_format_spec<_OtherArgs...>(__id - 1);
5247  else
5248  __builtin_unreachable();
5249  }
5250 
5251 #if __cpp_lib_format >= 202305L
5252  array<_Arg_t, sizeof...(_Args)>
5253  _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5254 #endif
5255  };
5256 
5257  template<typename _CharT, unsigned = __unicode::__literal_encoding_is_unicode<_CharT>()>
5258  _Sink_iter<_CharT>
5259  __do_vformat_to(_Sink_iter<_CharT> __out, basic_string_view<_CharT> __fmt,
5260  __format_context<_CharT>& __ctx)
5261  {
5262  if constexpr (is_same_v<_CharT, char>)
5263  // Fast path for "{}" format strings and simple format arg types.
5264  if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5265  {
5266  bool __done = false;
5267  __format::__visit_format_arg([&](auto& __arg) {
5268  using _Tp = remove_cvref_t<decltype(__arg)>;
5269  if constexpr (is_same_v<_Tp, bool>)
5270  {
5271  size_t __len = 4 + !__arg;
5272  const char* __chars[] = { "false", "true" };
5273  if (auto __res = __out._M_reserve(__len))
5274  {
5275  __builtin_memcpy(__res.get(), __chars[__arg], __len);
5276  __res._M_bump(__len);
5277  __done = true;
5278  }
5279  }
5280  else if constexpr (is_same_v<_Tp, char>)
5281  {
5282  if (auto __res = __out._M_reserve(1))
5283  {
5284  *__res.get() = __arg;
5285  __res._M_bump(1);
5286  __done = true;
5287  }
5288  }
5289  else if constexpr (is_integral_v<_Tp>)
5290  {
5291  make_unsigned_t<_Tp> __uval;
5292  const bool __neg = __arg < 0;
5293  if (__neg)
5294  __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5295  else
5296  __uval = __arg;
5297  const auto __n = __detail::__to_chars_len(__uval);
5298  if (auto __res = __out._M_reserve(__n + __neg))
5299  {
5300  auto __ptr = __res.get();
5301  *__ptr = '-';
5302  __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5303  __uval);
5304  __res._M_bump(__n + __neg);
5305  __done = true;
5306  }
5307  }
5308  else if constexpr (is_convertible_v<_Tp, string_view>)
5309  {
5310  string_view __sv = __arg;
5311  if (auto __res = __out._M_reserve(__sv.size()))
5312  {
5313  __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5314  __res._M_bump(__sv.size());
5315  __done = true;
5316  }
5317  }
5318  }, __ctx.arg(0));
5319 
5320  if (__done)
5321  return __out;
5322  }
5323 
5324  _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5325  __scanner._M_scan();
5326  return __out;
5327  }
5328 
5329 // The behavior of the formatters (interpretation of fill character) depends
5330 // on the literal encoding. As explicit instantiation of __do_vformat_to
5331 // instantiates formatters for types stored in basic_format_arg, we can
5332 // support only single encoding, in this case unicode. This should cover
5333 // most common use cases.
5334 #if __cplusplus <= 202002L && _GLIBCXX_EXTERN_TEMPLATE
5335  extern template _Sink_iter<char>
5336  __do_vformat_to<char, 1>(_Sink_iter<char>, string_view,
5337  format_context&);
5338 # ifdef _GLIBCXX_USE_WCHAR_T
5339  extern template _Sink_iter<wchar_t>
5340  __do_vformat_to<wchar_t, 1>(_Sink_iter<wchar_t>, wstring_view,
5341  wformat_context&);
5342 # endif
5343 #endif
5344 
5345  template<typename _Out, typename _CharT, typename _Context>
5346  inline _Out
5347  __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5348  const basic_format_args<_Context>& __args,
5349  const locale* __loc)
5350  {
5351  if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5352  {
5353  auto __ctx = __loc == nullptr
5354  ? _Context(__args, __out)
5355  : _Context(__args, __out, *__loc);
5356  return __format::__do_vformat_to(__out, __fmt, __ctx);
5357  }
5358  else if constexpr (__contiguous_char_iter<_CharT, _Out>)
5359  {
5360  _Ptr_sink<_CharT> __sink(__out);
5361  __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5362  return std::move(__sink)._M_finish(__out).out;
5363  }
5364  else
5365  {
5366  _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5367  __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5368  return std::move(__sink)._M_finish().out;
5369  }
5370  }
5371 
5372  template<typename _Out, typename _CharT>
5373  inline format_to_n_result<_Out>
5374  __do_vformat_to_n(_Out __out, iter_difference_t<_Out> __n,
5375  basic_string_view<_CharT> __fmt,
5376  const type_identity_t<
5377  basic_format_args<__format_context<_CharT>>>& __args,
5378  const locale* __loc = nullptr)
5379  {
5380  if constexpr (__contiguous_char_iter<_CharT, _Out>)
5381  {
5382  _Ptr_sink<_CharT> __sink(__out, __n);
5383  __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5384  return std::move(__sink)._M_finish(__out);
5385  }
5386  else
5387  {
5388  _Iter_sink<_CharT, _Out> __sink(std::move(__out), __n);
5389  __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5390  return std::move(__sink)._M_finish();
5391  }
5392  }
5393 
5394 #pragma GCC diagnostic pop
5395 
5396 } // namespace __format
5397 /// @endcond
5398 
5399 #if __cpp_lib_format >= 202305L // >= C++26
5400  /// @cond undocumented
5401  // Common implementation of check_dynamic_spec{,_string,_integral}
5402  template<typename _CharT>
5403  template<typename... _Ts>
5404  consteval void
5405  basic_format_parse_context<_CharT>::
5406  __check_dynamic_spec(size_t __id) noexcept
5407  {
5408  if (__id >= _M_num_args)
5409  __format::__invalid_arg_id_in_format_string();
5410  if constexpr (sizeof...(_Ts) != 0)
5411  {
5412  using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5413  auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
5414  __format::_Arg_t __types[] = {
5415  __format::__to_arg_t_enum<_CharT, _Ts>()...
5416  };
5417  for (auto __t : __types)
5418  if (__arg == __t)
5419  return;
5420  }
5421  __invalid_dynamic_spec("arg(id) type does not match");
5422  }
5423  /// @endcond
5424 #endif
5425 
5426  template<typename _CharT, typename... _Args>
5427  template<typename _Tp>
5428  requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5429  consteval
5430  basic_format_string<_CharT, _Args...>::
5431  basic_format_string(const _Tp& __s)
5432  : _M_str(__s)
5433  {
5434  __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5435  __scanner(_M_str);
5436  __scanner._M_scan();
5437  }
5438 
5439  // [format.functions], formatting functions
5440 
5441  template<typename _Out> requires output_iterator<_Out, const char&>
5442  [[__gnu__::__always_inline__]]
5443  inline _Out
5444  vformat_to(_Out __out, string_view __fmt, format_args __args)
5445  { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5446 
5447 #ifdef _GLIBCXX_USE_WCHAR_T
5448  template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5449  [[__gnu__::__always_inline__]]
5450  inline _Out
5451  vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5452  { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5453 #endif
5454 
5455  template<typename _Out> requires output_iterator<_Out, const char&>
5456  [[__gnu__::__always_inline__]]
5457  inline _Out
5458  vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5459  format_args __args)
5460  {
5461  return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5462  }
5463 
5464 #ifdef _GLIBCXX_USE_WCHAR_T
5465  template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5466  [[__gnu__::__always_inline__]]
5467  inline _Out
5468  vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5469  wformat_args __args)
5470  {
5471  return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5472  }
5473 #endif
5474 
5475  [[nodiscard]]
5476  inline string
5477  vformat(string_view __fmt, format_args __args)
5478  {
5479  __format::_Str_sink<char> __buf;
5480  std::vformat_to(__buf.out(), __fmt, __args);
5481  return std::move(__buf).get();
5482  }
5483 
5484 #ifdef _GLIBCXX_USE_WCHAR_T
5485  [[nodiscard]]
5486  inline wstring
5487  vformat(wstring_view __fmt, wformat_args __args)
5488  {
5489  __format::_Str_sink<wchar_t> __buf;
5490  std::vformat_to(__buf.out(), __fmt, __args);
5491  return std::move(__buf).get();
5492  }
5493 #endif
5494 
5495  [[nodiscard]]
5496  inline string
5497  vformat(const locale& __loc, string_view __fmt, format_args __args)
5498  {
5499  __format::_Str_sink<char> __buf;
5500  std::vformat_to(__buf.out(), __loc, __fmt, __args);
5501  return std::move(__buf).get();
5502  }
5503 
5504 #ifdef _GLIBCXX_USE_WCHAR_T
5505  [[nodiscard]]
5506  inline wstring
5507  vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5508  {
5509  __format::_Str_sink<wchar_t> __buf;
5510  std::vformat_to(__buf.out(), __loc, __fmt, __args);
5511  return std::move(__buf).get();
5512  }
5513 #endif
5514 
5515  template<typename... _Args>
5516  [[nodiscard]]
5517  inline string
5518  format(format_string<_Args...> __fmt, _Args&&... __args)
5519  { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5520 
5521 #ifdef _GLIBCXX_USE_WCHAR_T
5522  template<typename... _Args>
5523  [[nodiscard]]
5524  inline wstring
5525  format(wformat_string<_Args...> __fmt, _Args&&... __args)
5526  { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5527 #endif
5528 
5529  template<typename... _Args>
5530  [[nodiscard]]
5531  inline string
5532  format(const locale& __loc, format_string<_Args...> __fmt,
5533  _Args&&... __args)
5534  {
5535  return std::vformat(__loc, __fmt.get(),
5536  std::make_format_args(__args...));
5537  }
5538 
5539 #ifdef _GLIBCXX_USE_WCHAR_T
5540  template<typename... _Args>
5541  [[nodiscard]]
5542  inline wstring
5543  format(const locale& __loc, wformat_string<_Args...> __fmt,
5544  _Args&&... __args)
5545  {
5546  return std::vformat(__loc, __fmt.get(),
5547  std::make_wformat_args(__args...));
5548  }
5549 #endif
5550 
5551  template<typename _Out, typename... _Args>
5552  requires output_iterator<_Out, const char&>
5553  inline _Out
5554  format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5555  {
5556  return std::vformat_to(std::move(__out), __fmt.get(),
5557  std::make_format_args(__args...));
5558  }
5559 
5560 #ifdef _GLIBCXX_USE_WCHAR_T
5561  template<typename _Out, typename... _Args>
5562  requires output_iterator<_Out, const wchar_t&>
5563  inline _Out
5564  format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5565  {
5566  return std::vformat_to(std::move(__out), __fmt.get(),
5567  std::make_wformat_args(__args...));
5568  }
5569 #endif
5570 
5571  template<typename _Out, typename... _Args>
5572  requires output_iterator<_Out, const char&>
5573  inline _Out
5574  format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5575  _Args&&... __args)
5576  {
5577  return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5578  std::make_format_args(__args...));
5579  }
5580 
5581 #ifdef _GLIBCXX_USE_WCHAR_T
5582  template<typename _Out, typename... _Args>
5583  requires output_iterator<_Out, const wchar_t&>
5584  inline _Out
5585  format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5586  _Args&&... __args)
5587  {
5588  return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5589  std::make_wformat_args(__args...));
5590  }
5591 #endif
5592 
5593  template<typename _Out, typename... _Args>
5594  requires output_iterator<_Out, const char&>
5595  inline format_to_n_result<_Out>
5596  format_to_n(_Out __out, iter_difference_t<_Out> __n,
5597  format_string<_Args...> __fmt, _Args&&... __args)
5598  {
5599  return __format::__do_vformat_to_n(
5600  std::move(__out), __n, __fmt.get(),
5601  std::make_format_args(__args...));
5602  }
5603 
5604 #ifdef _GLIBCXX_USE_WCHAR_T
5605  template<typename _Out, typename... _Args>
5606  requires output_iterator<_Out, const wchar_t&>
5607  inline format_to_n_result<_Out>
5608  format_to_n(_Out __out, iter_difference_t<_Out> __n,
5609  wformat_string<_Args...> __fmt, _Args&&... __args)
5610  {
5611  return __format::__do_vformat_to_n(
5612  std::move(__out), __n, __fmt.get(),
5613  std::make_wformat_args(__args...));
5614  }
5615 #endif
5616 
5617  template<typename _Out, typename... _Args>
5618  requires output_iterator<_Out, const char&>
5619  inline format_to_n_result<_Out>
5620  format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5621  format_string<_Args...> __fmt, _Args&&... __args)
5622  {
5623  return __format::__do_vformat_to_n(
5624  std::move(__out), __n, __fmt.get(),
5625  std::make_format_args(__args...), &__loc);
5626  }
5627 
5628 #ifdef _GLIBCXX_USE_WCHAR_T
5629  template<typename _Out, typename... _Args>
5630  requires output_iterator<_Out, const wchar_t&>
5631  inline format_to_n_result<_Out>
5632  format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5633  wformat_string<_Args...> __fmt, _Args&&... __args)
5634  {
5635  return __format::__do_vformat_to_n(
5636  std::move(__out), __n, __fmt.get(),
5637  std::make_wformat_args(__args...), &__loc);
5638  }
5639 #endif
5640 
5641 /// @cond undocumented
5642 namespace __format
5643 {
5644 #if 1
5645  template<typename _CharT>
5646  class _Counting_sink final : public _Ptr_sink<_CharT>
5647  {
5648  public:
5649  _Counting_sink() : _Ptr_sink<_CharT>(nullptr, 0) { }
5650 
5651  [[__gnu__::__always_inline__]]
5652  size_t
5653  count() const
5654  { return this->_M_count + this->_M_used().size(); }
5655  };
5656 #else
5657  template<typename _CharT>
5658  class _Counting_sink : public _Buf_sink<_CharT>
5659  {
5660  size_t _M_count = 0;
5661 
5662  void
5663  _M_overflow() override
5664  {
5665  if (!std::is_constant_evaluated())
5666  _M_count += this->_M_used().size();
5667  this->_M_rewind();
5668  }
5669 
5670  public:
5671  _Counting_sink() = default;
5672 
5673  [[__gnu__::__always_inline__]]
5674  size_t
5675  count() noexcept
5676  {
5677  _Counting_sink::_M_overflow();
5678  return _M_count;
5679  }
5680  };
5681 #endif
5682 } // namespace __format
5683 /// @endcond
5684 
5685  template<typename... _Args>
5686  [[nodiscard]]
5687  inline size_t
5688  formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5689  {
5690  __format::_Counting_sink<char> __buf;
5691  std::vformat_to(__buf.out(), __fmt.get(),
5692  std::make_format_args(__args...));
5693  return __buf.count();
5694  }
5695 
5696 #ifdef _GLIBCXX_USE_WCHAR_T
5697  template<typename... _Args>
5698  [[nodiscard]]
5699  inline size_t
5700  formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5701  {
5702  __format::_Counting_sink<wchar_t> __buf;
5703  std::vformat_to(__buf.out(), __fmt.get(),
5704  std::make_wformat_args(__args...));
5705  return __buf.count();
5706  }
5707 #endif
5708 
5709  template<typename... _Args>
5710  [[nodiscard]]
5711  inline size_t
5712  formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5713  _Args&&... __args)
5714  {
5715  __format::_Counting_sink<char> __buf;
5716  std::vformat_to(__buf.out(), __loc, __fmt.get(),
5717  std::make_format_args(__args...));
5718  return __buf.count();
5719  }
5720 
5721 #ifdef _GLIBCXX_USE_WCHAR_T
5722  template<typename... _Args>
5723  [[nodiscard]]
5724  inline size_t
5725  formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5726  _Args&&... __args)
5727  {
5728  __format::_Counting_sink<wchar_t> __buf;
5729  std::vformat_to(__buf.out(), __loc, __fmt.get(),
5730  std::make_wformat_args(__args...));
5731  return __buf.count();
5732  }
5733 #endif
5734 
5735 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5736  /// @cond undocumented
5737  template<typename _Tp>
5738  consteval range_format
5739  __fmt_kind()
5740  {
5741  using _Ref = ranges::range_reference_t<_Tp>;
5742  if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5743  return range_format::disabled;
5744  else if constexpr (requires { typename _Tp::key_type; })
5745  {
5746  if constexpr (requires { typename _Tp::mapped_type; })
5747  {
5748  using _Up = remove_cvref_t<_Ref>;
5749  if constexpr (__is_pair<_Up>)
5750  return range_format::map;
5751  else if constexpr (__is_specialization_of<_Up, tuple>)
5752  if constexpr (tuple_size_v<_Up> == 2)
5753  return range_format::map;
5754  }
5755  return range_format::set;
5756  }
5757  else
5758  return range_format::sequence;
5759  }
5760  /// @endcond
5761 
5762  /// A constant determining how a range should be formatted.
5763  template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5764  constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5765 
5766 /// @cond undocumented
5767 namespace __format
5768 {
5769  template<typename _CharT, typename _Out, typename _Callback>
5770  typename basic_format_context<_Out, _CharT>::iterator
5771  __format_padded(basic_format_context<_Out, _CharT>& __fc,
5772  const _Spec<_CharT>& __spec,
5773  _Callback&& __call)
5774  {
5775  if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5776  return __fc.out();
5777  else
5778  {
5779  // This is required to implement formatting with padding,
5780  // as we need to format to temporary buffer, using the same iterator.
5781  static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5782 
5783  const size_t __padwidth = __spec._M_get_width(__fc);
5784  if (__padwidth == 0)
5785  return __call(__fc);
5786 
5787  struct _Restore_out
5788  {
5789  _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5790  : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5791  { }
5792 
5793  void
5794  _M_disarm()
5795  { _M_ctx = nullptr; }
5796 
5797  ~_Restore_out()
5798  {
5799  if (_M_ctx)
5800  _M_ctx->advance_to(_M_out);
5801  }
5802 
5803  private:
5804  basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5805  _Sink_iter<_CharT> _M_out;
5806  };
5807 
5808  _Restore_out __restore(__fc);
5809  _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5810  __fc.advance_to(__sink.out());
5811  __call(__fc);
5812  __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5813  __restore._M_disarm();
5814  return __fc.out();
5815  }
5816  }
5817 
5818  template<size_t _Pos, typename _Tp, typename _CharT>
5819  struct __indexed_formatter_storage
5820  {
5821  constexpr void
5822  _M_parse()
5823  {
5824  basic_format_parse_context<_CharT> __pc({});
5825  if (_M_formatter.parse(__pc) != __pc.end())
5826  __format::__failed_to_parse_format_spec();
5827  }
5828 
5829  template<typename _Out>
5830  void
5831  _M_format(__maybe_const<_Tp, _CharT>& __elem,
5832  basic_format_context<_Out, _CharT>& __fc,
5833  basic_string_view<_CharT> __sep) const
5834  {
5835  if constexpr (_Pos != 0)
5836  __fc.advance_to(__format::__write(__fc.out(), __sep));
5837  __fc.advance_to(_M_formatter.format(__elem, __fc));
5838  }
5839 
5840  [[__gnu__::__always_inline__]]
5841  constexpr void
5842  set_debug_format()
5843  {
5844  if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5845  _M_formatter.set_debug_format();
5846  }
5847 
5848  private:
5849  formatter<_Tp, _CharT> _M_formatter;
5850  };
5851 
5852  template<typename _CharT, typename... _Tps>
5853  class __tuple_formatter
5854  {
5855  using _String_view = basic_string_view<_CharT>;
5856  using _Seps = __format::_Separators<_CharT>;
5857 
5858  public:
5859  constexpr void
5860  set_separator(basic_string_view<_CharT> __sep) noexcept
5861  { _M_sep = __sep; }
5862 
5863  constexpr void
5864  set_brackets(basic_string_view<_CharT> __open,
5865  basic_string_view<_CharT> __close) noexcept
5866  {
5867  _M_open = __open;
5868  _M_close = __close;
5869  }
5870 
5871  // We deviate from standard, that declares this as template accepting
5872  // unconstrained ParseContext type, which seems unimplementable.
5873  constexpr typename basic_format_parse_context<_CharT>::iterator
5874  parse(basic_format_parse_context<_CharT>& __pc)
5875  {
5876  auto __first = __pc.begin();
5877  const auto __last = __pc.end();
5878  __format::_Spec<_CharT> __spec{};
5879 
5880  auto __finished = [&]
5881  {
5882  if (__first != __last && *__first != '}')
5883  return false;
5884 
5885  _M_spec = __spec;
5886  _M_felems._M_parse();
5887  _M_felems.set_debug_format();
5888  return true;
5889  };
5890 
5891  if (__finished())
5892  return __first;
5893 
5894  __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5895  if (__finished())
5896  return __first;
5897 
5898  __first = __spec._M_parse_width(__first, __last, __pc);
5899  if (__finished())
5900  return __first;
5901 
5902  if (*__first == 'n')
5903  {
5904  ++__first;
5905  _M_open = _M_close = _String_view();
5906  }
5907  else if (*__first == 'm')
5908  {
5909  ++__first;
5910  if constexpr (sizeof...(_Tps) == 2)
5911  {
5912  _M_sep = _Seps::_S_colon();
5913  _M_open = _M_close = _String_view();
5914  }
5915  else
5916  __throw_format_error("format error: 'm' specifier requires range"
5917  " of pair or tuple of two elements");
5918  }
5919 
5920  if (__finished())
5921  return __first;
5922 
5923  __format::__failed_to_parse_format_spec();
5924  }
5925 
5926  protected:
5927  template<typename _Tuple, typename _Out, size_t... _Ids>
5928  typename basic_format_context<_Out, _CharT>::iterator
5929  _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5930  basic_format_context<_Out, _CharT>& __fc) const
5931  { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5932 
5933  template<typename _Out>
5934  typename basic_format_context<_Out, _CharT>::iterator
5935  _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5936  basic_format_context<_Out, _CharT>& __fc) const
5937  {
5938  return __format::__format_padded(
5939  __fc, _M_spec,
5940  [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5941  {
5942  __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5943  _M_felems._M_format(__elems..., __nfc, _M_sep);
5944  return __format::__write(__nfc.out(), _M_close);
5945  });
5946  }
5947 
5948  private:
5949  template<size_t... _Ids>
5950  struct __formatters_storage
5951  : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5952  {
5953  template<size_t _Id, typename _Up>
5954  using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5955 
5956  constexpr void
5957  _M_parse()
5958  {
5959  (_Base<_Ids, _Tps>::_M_parse(), ...);
5960  }
5961 
5962  template<typename _Out>
5963  void
5964  _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5965  basic_format_context<_Out, _CharT>& __fc,
5966  _String_view __sep) const
5967  {
5968  (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5969  }
5970 
5971  constexpr void
5972  set_debug_format()
5973  {
5974  (_Base<_Ids, _Tps>::set_debug_format(), ...);
5975  }
5976  };
5977 
5978  template<size_t... _Ids>
5979  static auto
5980  _S_create_storage(index_sequence<_Ids...>)
5981  -> __formatters_storage<_Ids...>;
5982  using _Formatters
5983  = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5984 
5985  _Spec<_CharT> _M_spec{};
5986  _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5987  _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5988  _String_view _M_sep = _Seps::_S_comma();
5989  _Formatters _M_felems;
5990  };
5991 
5992  template<typename _Tp>
5993  concept __is_map_formattable
5994  = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5995 
5996 } // namespace __format
5997 /// @endcond
5998 
5999  // [format.tuple] Tuple formatter
6000  template<__format::__char _CharT, formattable<_CharT> _Fp,
6001  formattable<_CharT> _Sp>
6002  struct formatter<pair<_Fp, _Sp>, _CharT>
6003  : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
6004  remove_cvref_t<_Sp>>
6005  {
6006  private:
6007  using __maybe_const_pair
6008  = __conditional_t<formattable<const _Fp, _CharT>
6009  && formattable<const _Sp, _CharT>,
6010  const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
6011  public:
6012  // We deviate from standard, that declares this as template accepting
6013  // unconstrained FormatContext type, which seems unimplementable.
6014  template<typename _Out>
6015  typename basic_format_context<_Out, _CharT>::iterator
6016  format(__maybe_const_pair& __p,
6017  basic_format_context<_Out, _CharT>& __fc) const
6018  { return this->_M_format_elems(__p.first, __p.second, __fc); }
6019  };
6020 
6021 #if __glibcxx_print >= 202406L
6022  // _GLIBCXX_RESOLVE_LIB_DEFECTS
6023  // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6024  template<typename _Fp, typename _Sp>
6025  constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
6026  = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
6027  && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
6028 #endif
6029 
6030  template<__format::__char _CharT, formattable<_CharT>... _Tps>
6031  struct formatter<tuple<_Tps...>, _CharT>
6032  : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
6033  {
6034  private:
6035  using __maybe_const_tuple
6036  = __conditional_t<(formattable<const _Tps, _CharT> && ...),
6037  const tuple<_Tps...>, tuple<_Tps...>>;
6038  public:
6039  // We deviate from standard, that declares this as template accepting
6040  // unconstrained FormatContext type, which seems unimplementable.
6041  template<typename _Out>
6042  typename basic_format_context<_Out, _CharT>::iterator
6043  format(__maybe_const_tuple& __t,
6044  basic_format_context<_Out, _CharT>& __fc) const
6045  { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
6046  };
6047 
6048 #if __glibcxx_print >= 202406L
6049  // _GLIBCXX_RESOLVE_LIB_DEFECTS
6050  // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6051  template<typename... _Tps>
6052  constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
6053  = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
6054 #endif
6055 
6056  // [format.range.formatter], class template range_formatter
6057  template<typename _Tp, __format::__char _CharT>
6058  requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
6059  class range_formatter
6060  {
6061  using _String_view = basic_string_view<_CharT>;
6062  using _Seps = __format::_Separators<_CharT>;
6063 
6064  public:
6065  constexpr void
6066  set_separator(basic_string_view<_CharT> __sep) noexcept
6067  { _M_sep = __sep; }
6068 
6069  constexpr void
6070  set_brackets(basic_string_view<_CharT> __open,
6071  basic_string_view<_CharT> __close) noexcept
6072  {
6073  _M_open = __open;
6074  _M_close = __close;
6075  }
6076 
6077  constexpr formatter<_Tp, _CharT>&
6078  underlying() noexcept
6079  { return _M_fval; }
6080 
6081  constexpr const formatter<_Tp, _CharT>&
6082  underlying() const noexcept
6083  { return _M_fval; }
6084 
6085  // We deviate from standard, that declares this as template accepting
6086  // unconstrained ParseContext type, which seems unimplementable.
6087  constexpr typename basic_format_parse_context<_CharT>::iterator
6088  parse(basic_format_parse_context<_CharT>& __pc)
6089  {
6090  auto __first = __pc.begin();
6091  const auto __last = __pc.end();
6092  __format::_Spec<_CharT> __spec{};
6093  bool __no_brace = false;
6094 
6095  auto __finished = [&]
6096  { return __first == __last || *__first == '}'; };
6097 
6098  auto __finalize = [&]
6099  {
6100  _M_spec = __spec;
6101  return __first;
6102  };
6103 
6104  auto __parse_val = [&](_String_view __nfs = _String_view())
6105  {
6106  basic_format_parse_context<_CharT> __npc(__nfs);
6107  if (_M_fval.parse(__npc) != __npc.end())
6108  __format::__failed_to_parse_format_spec();
6109  if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
6110  _M_fval.set_debug_format();
6111  return __finalize();
6112  };
6113 
6114  if (__finished())
6115  return __parse_val();
6116 
6117  __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6118  if (__finished())
6119  return __parse_val();
6120 
6121  __first = __spec._M_parse_width(__first, __last, __pc);
6122  if (__finished())
6123  return __parse_val();
6124 
6125  if (*__first == '?')
6126  {
6127  ++__first;
6128  __spec._M_debug = true;
6129  if (__finished() || *__first != 's')
6130  __throw_format_error("format error: '?' is allowed only in"
6131  " combination with 's'");
6132  }
6133 
6134  if (*__first == 's')
6135  {
6136  ++__first;
6137  if constexpr (same_as<_Tp, _CharT>)
6138  {
6139  __spec._M_type = __format::_Pres_s;
6140  if (__finished())
6141  return __finalize();
6142  __throw_format_error("format error: element format specifier"
6143  " cannot be provided when 's' specifier is used");
6144  }
6145  else
6146  __throw_format_error("format error: 's' specifier requires"
6147  " range of character types");
6148  }
6149 
6150  if (__finished())
6151  return __parse_val();
6152 
6153  if (*__first == 'n')
6154  {
6155  ++__first;
6156  _M_open = _M_close = _String_view();
6157  __no_brace = true;
6158  }
6159 
6160  if (__finished())
6161  return __parse_val();
6162 
6163  if (*__first == 'm')
6164  {
6165  _String_view __m(__first, 1);
6166  ++__first;
6167  if constexpr (__format::__is_map_formattable<_Tp>)
6168  {
6169  _M_sep = _Seps::_S_comma();
6170  if (!__no_brace)
6171  {
6172  _M_open = _Seps::_S_braces().substr(0, 1);
6173  _M_close = _Seps::_S_braces().substr(1, 1);
6174  }
6175  if (__finished())
6176  return __parse_val(__m);
6177  __throw_format_error("format error: element format specifier"
6178  " cannot be provided when 'm' specifier is used");
6179  }
6180  else
6181  __throw_format_error("format error: 'm' specifier requires"
6182  " range of pairs or tuples of two elements");
6183  }
6184 
6185  if (__finished())
6186  return __parse_val();
6187 
6188  if (*__first == ':')
6189  {
6190  __pc.advance_to(++__first);
6191  __first = _M_fval.parse(__pc);
6192  }
6193 
6194  if (__finished())
6195  return __finalize();
6196 
6197  __format::__failed_to_parse_format_spec();
6198  }
6199 
6200  // We deviate from standard, that declares this as template accepting
6201  // unconstrained FormatContext type, which seems unimplementable.
6202  template<ranges::input_range _Rg, typename _Out>
6203  requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6204  same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6205  typename basic_format_context<_Out, _CharT>::iterator
6206  format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6207  {
6208  using _Range = remove_reference_t<_Rg>;
6209  if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6210  return _M_format<const _Range>(__rg, __fc);
6211  else
6212  return _M_format(__rg, __fc);
6213  }
6214 
6215  private:
6216  template<ranges::input_range _Rg, typename _Out>
6217  typename basic_format_context<_Out, _CharT>::iterator
6218  _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6219  {
6220  if constexpr (same_as<_Tp, _CharT>)
6221  if (_M_spec._M_type == __format::_Pres_s)
6222  {
6223  __format::__formatter_str __fstr(_M_spec);
6224  return __fstr._M_format_range(__rg, __fc);
6225  }
6226  return __format::__format_padded(
6227  __fc, _M_spec,
6228  [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6229  { return _M_format_elems(__rg, __nfc); });
6230  }
6231 
6232 
6233  template<ranges::input_range _Rg, typename _Out>
6234  typename basic_format_context<_Out, _CharT>::iterator
6235  _M_format_elems(_Rg& __rg,
6236  basic_format_context<_Out, _CharT>& __fc) const
6237  {
6238  auto __out = __format::__write(__fc.out(), _M_open);
6239 
6240  auto __first = ranges::begin(__rg);
6241  auto const __last = ranges::end(__rg);
6242  if (__first == __last)
6243  return __format::__write(__out, _M_close);
6244 
6245  __fc.advance_to(__out);
6246  __out = _M_fval.format(*__first, __fc);
6247  for (++__first; __first != __last; ++__first)
6248  {
6249  __out = __format::__write(__out, _M_sep);
6250  __fc.advance_to(__out);
6251  __out = _M_fval.format(*__first, __fc);
6252  }
6253 
6254  return __format::__write(__out, _M_close);
6255  }
6256 
6257  __format::_Spec<_CharT> _M_spec{};
6258  _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6259  _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6260  _String_view _M_sep = _Seps::_S_comma();
6261  formatter<_Tp, _CharT> _M_fval;
6262  };
6263 
6264  // In standard this is shown as inheriting from specialization of
6265  // exposition only specialization for range-default-formatter for
6266  // each range_format. We opt for simpler implementation.
6267  // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6268  // specializations for maps, sets, and strings
6269  template<ranges::input_range _Rg, __format::__char _CharT>
6270  requires (format_kind<_Rg> != range_format::disabled)
6271  && formattable<ranges::range_reference_t<_Rg>, _CharT>
6272  struct formatter<_Rg, _CharT>
6273  {
6274  private:
6275  static const bool _S_range_format_is_string =
6276  (format_kind<_Rg> == range_format::string)
6277  || (format_kind<_Rg> == range_format::debug_string);
6278  using _Vt = remove_cvref_t<
6279  ranges::range_reference_t<
6280  __format::__maybe_const_range<_Rg, _CharT>>>;
6281 
6282  static consteval bool _S_is_correct()
6283  {
6284  if constexpr (_S_range_format_is_string)
6285  static_assert(same_as<_Vt, _CharT>);
6286  return true;
6287  }
6288 
6289  static_assert(_S_is_correct());
6290 
6291  public:
6292  constexpr formatter() noexcept
6293  {
6294  using _Seps = __format::_Separators<_CharT>;
6295  if constexpr (format_kind<_Rg> == range_format::map)
6296  {
6297  static_assert(__format::__is_map_formattable<_Vt>);
6298  _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6299  _Seps::_S_braces().substr(1, 1));
6300  _M_under.underlying().set_brackets({}, {});
6301  _M_under.underlying().set_separator(_Seps::_S_colon());
6302  }
6303  else if constexpr (format_kind<_Rg> == range_format::set)
6304  _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6305  _Seps::_S_braces().substr(1, 1));
6306  }
6307 
6308  constexpr void
6309  set_separator(basic_string_view<_CharT> __sep) noexcept
6310  requires (format_kind<_Rg> == range_format::sequence)
6311  { _M_under.set_separator(__sep); }
6312 
6313  constexpr void
6314  set_brackets(basic_string_view<_CharT> __open,
6315  basic_string_view<_CharT> __close) noexcept
6316  requires (format_kind<_Rg> == range_format::sequence)
6317  { _M_under.set_brackets(__open, __close); }
6318 
6319  // We deviate from standard, that declares this as template accepting
6320  // unconstrained ParseContext type, which seems unimplementable.
6321  constexpr typename basic_format_parse_context<_CharT>::iterator
6322  parse(basic_format_parse_context<_CharT>& __pc)
6323  {
6324  auto __res = _M_under.parse(__pc);
6325  if constexpr (format_kind<_Rg> == range_format::debug_string)
6326  _M_under.set_debug_format();
6327  return __res;
6328  }
6329 
6330  // We deviate from standard, that declares this as template accepting
6331  // unconstrained FormatContext type, which seems unimplementable.
6332  template<typename _Out>
6333  typename basic_format_context<_Out, _CharT>::iterator
6334  format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6335  basic_format_context<_Out, _CharT>& __fc) const
6336  {
6337  if constexpr (_S_range_format_is_string)
6338  return _M_under._M_format_range(__rg, __fc);
6339  else
6340  return _M_under.format(__rg, __fc);
6341  }
6342 
6343  private:
6344  using _Formatter_under
6345  = __conditional_t<_S_range_format_is_string,
6346  __format::__formatter_str<_CharT>,
6347  range_formatter<_Vt, _CharT>>;
6348  _Formatter_under _M_under;
6349  };
6350 
6351 #if __glibcxx_print >= 202406L
6352  template<ranges::input_range _Rg>
6353  requires (format_kind<_Rg> != range_format::disabled)
6354  constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6355 #endif
6356 
6357 #endif // C++23 formatting ranges
6358 #undef _GLIBCXX_WIDEN
6359 
6360 _GLIBCXX_END_NAMESPACE_VERSION
6361 } // namespace std
6362 #endif // __cpp_lib_format
6363 #pragma GCC diagnostic pop
6364 #endif // _GLIBCXX_FORMAT