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