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