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