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