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 // A format sink that writes directly to a basic_streambuf.
3546 // Prefers zero-copy writes into the streambuf's put area
3547 // (pptr/epptr/pbump), falling back to the stack buffer
3548 // (_M_buf) and bulk sputn.
3549 template<typename _CharT>
3550 class _Streambuf_sink : public _Buf_sink<_CharT>
3551 {
3552 protected:
3553 basic_streambuf<_CharT>* _M_sbuf;
3554 bool _M_write_failed = false;
3555
3556 bool
3557 _M_on_stack() const noexcept
3558 { return this->_M_used().data() == this->_M_buf; }
3559
3560 // Try to point our span directly into the streambuf's put
3561 // area for zero-copy writes. Caller must fall back to
3562 // using local buffer (_M_reset(_M_buf)).
3563 bool
3564 _M_reserve_put_area(size_t __n = 0)
3565 {
3566 if (auto __p = _M_sbuf->pptr())
3567 if (auto __e = _M_sbuf->epptr(); __e > __p)
3568 if (size_t __a(__e - __p); __a >= __n)
3569 {
3570 this->_M_reset(span<_CharT>(__p, __a));
3571 return true;
3572 }
3573 return false;
3574 }
3575
3576 // Write characters to the streambuf, tracking errors.
3577 // I/O exceptions from sputn are caught and converted to
3578 // _M_write_failed so they do not propagate as vformat exceptions
3579 // per [ostream.formatted.print]/(4.2).
3580 void
3581 _M_flush()
3582 {
3583 span<const _CharT> __s = this->_M_used();
3584 if (__s.empty() || _M_write_failed) [[unlikely]]
3585 return;
3586
3587 __try
3588 {
3589 if (!_M_on_stack())
3590 _M_sbuf->__safe_pbump(__s.size());
3591 else if (_M_sbuf->sputn(__s.data(), __s.size())
3592 != static_cast<streamsize>(__s.size()))
3593 _M_write_failed = true;
3594 }
3595 __catch(const __cxxabiv1::__forced_unwind&)
3596 { throw; }
3597 __catch(...)
3598 { _M_write_failed = true; }
3599 }
3600
3601 void
3602 _M_overflow() override
3603 {
3604 _M_flush();
3605 if (!_M_write_failed) [[likely]]
3606 if (_M_reserve_put_area())
3607 return;
3608 this->_M_reset(this->_M_buf);
3609 }
3610
3611 public:
3612 [[__gnu__::__always_inline__]]
3613 explicit
3614 _Streambuf_sink(basic_streambuf<_CharT>* __sbuf) noexcept
3615 : _M_sbuf(__sbuf), _M_write_failed(!__sbuf)
3616 {
3617 if (!_M_write_failed) [[likely]]
3618 _M_reserve_put_area();
3619 }
3620
3621 // _M_bump is not overridden: the default advances _M_next within
3622 // the current span (stack buffer or put area). Actual commit
3623 // to the streambuf happens via _M_flush, called from _M_overflow
3624 // (buffer full) or _M_finish (end of formatting).
3625
3626 typename _Sink<_CharT>::_Reservation
3627 _M_reserve(size_t __n) override
3628 {
3629 if (_M_write_failed) [[unlikely]]
3630 return { nullptr };
3631
3632 if (__n <= this->_M_unused().size())
3633 return { this };
3634
3635 if (!this->_M_used().empty())
3636 _M_flush();
3637
3638 // Try to write directly into the streambuf's put area.
3639 if (_M_reserve_put_area(__n))
3640 return { this };
3641
3642 // Otherwise reset to the stack buffer.
3643 this->_M_reset(this->_M_buf);
3644 if (__n <= this->_M_unused().size())
3645 return { this };
3646
3647 return { nullptr };
3648 }
3649
3650 bool
3651 _M_discarding() const override
3652 { return _M_write_failed; }
3653
3654 void
3655 _M_finish()
3656 { _M_flush(); }
3657
3658 bool
3659 _M_failed() const noexcept
3660 { return _M_write_failed; }
3661 };
3662
3663 using _GLIBCXX_STD_C::vector;
3664
3665 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3666 // Writes to a buffer then appends that to the sequence when it fills up.
3667 template<typename _Seq>
3668 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3669 {
3670 using _CharT = typename _Seq::value_type;
3671
3672 _Seq _M_seq;
3673 protected:
3674 // Transfer buffer contents to the sequence, so buffer can be refilled.
3675 _GLIBCXX_CONSTEXPR_FORMAT void
3676 _M_overflow() override
3677 {
3678 auto __s = this->_M_used();
3679 if (__s.empty()) [[unlikely]]
3680 return; // Nothing in the buffer to transfer to _M_seq.
3681
3682 // If _M_reserve was called then _M_bump must have been called too.
3683 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3684
3685 if constexpr (__is_specialization_of<_Seq, basic_string>)
3686 _M_seq.append(__s.data(), __s.size());
3687 else
3688 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3689
3690 // Make the whole of _M_buf available for the next write:
3691 this->_M_rewind();
3692 }
3693
3694 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
3695 _M_reserve(size_t __n) override
3696 {
3697 // We might already have n characters available in this->_M_unused(),
3698 // but the whole point of this function is to be an optimization for
3699 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3700 // and then copying that into a basic_string if possible, so this
3701 // function prefers to create space directly in _M_seq rather than
3702 // using _M_buf.
3703
3704 if constexpr (__is_specialization_of<_Seq, basic_string>
3705 || __is_specialization_of<_Seq, vector>)
3706 {
3707 // Flush the buffer to _M_seq first (should not be needed).
3708 if (this->_M_used().size()) [[unlikely]]
3709 _Seq_sink::_M_overflow();
3710
3711 // Expand _M_seq to make __n new characters available:
3712 const auto __sz = _M_seq.size();
3713 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3714 _M_seq.__resize_and_overwrite(__sz + __n,
3715 [](auto, auto __n2) {
3716 return __n2;
3717 });
3718 else
3719 _M_seq.resize(__sz + __n);
3720
3721 // Set _M_used() to be a span over the original part of _M_seq
3722 // and _M_unused() to be the extra capacity we just created:
3723 this->_M_reset(_M_seq, __sz);
3724 return { this };
3725 }
3726 else // Try to use the base class' buffer.
3727 return _Sink<_CharT>::_M_reserve(__n);
3728 }
3729
3730 _GLIBCXX_CONSTEXPR_FORMAT void
3731 _M_bump(size_t __n) override
3732 {
3733 if constexpr (__is_specialization_of<_Seq, basic_string>
3734 || __is_specialization_of<_Seq, vector>)
3735 {
3736 auto __s = this->_M_used();
3737 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3738 // Truncate the sequence to the part that was actually written to:
3739 _M_seq.resize(__s.size() + __n);
3740 // Switch back to using buffer:
3741 this->_M_reset(this->_M_buf);
3742 }
3743 }
3744
3745 _GLIBCXX_CONSTEXPR_FORMAT void
3746 _M_trim(span<const _CharT> __s)
3747 requires __is_specialization_of<_Seq, basic_string>
3748 {
3749 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3750 || __s.data() == _M_seq.data());
3751 if (__s.data() == _M_seq.data())
3752 _M_seq.resize(__s.size());
3753 else
3754 this->_M_reset(this->_M_buf, __s.size());
3755 }
3756
3757 public:
3758 // TODO: for SSO string, use SSO buffer as initial span, then switch
3759 // to _M_buf if it overflows? Or even do that for all unused capacity?
3760
3761 [[__gnu__::__always_inline__]]
3762 _GLIBCXX_CONSTEXPR_FORMAT
3763 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3764 { }
3765
3766 _GLIBCXX_CONSTEXPR_FORMAT
3767 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3768 : _M_seq(std::move(__s))
3769 { }
3770
3771 using _Sink<_CharT>::out;
3772
3773 _GLIBCXX_CONSTEXPR_FORMAT _Seq
3774 get() &&
3775 {
3776 if (this->_M_used().size() != 0)
3777 _Seq_sink::_M_overflow();
3778 return std::move(_M_seq);
3779 }
3780
3781 // A writable span that views everything written to the sink.
3782 // Will be either a view over _M_seq or the used part of _M_buf.
3783 _GLIBCXX_CONSTEXPR_FORMAT span<_CharT>
3784 _M_span()
3785 {
3786 auto __s = this->_M_used();
3787 if (_M_seq.size())
3788 {
3789 if (__s.size() != 0)
3790 _Seq_sink::_M_overflow();
3791 return _M_seq;
3792 }
3793 return __s;
3794 }
3795
3796 _GLIBCXX_CONSTEXPR_FORMAT basic_string_view<_CharT>
3797 view()
3798 {
3799 auto __span = _M_span();
3800 return basic_string_view<_CharT>(__span.data(), __span.size());
3801 }
3802 };
3803
3804 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3805 using _Str_sink
3806 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3807
3808 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3809 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3810 // Writes to a fixed-size buffer and then flushes to the output iterator
3811 // when the buffer fills up.
3812 template<typename _CharT, typename _OutIter>
3813 class _Iter_sink : public _Buf_sink<_CharT>
3814 {
3815 _OutIter _M_out;
3816 iter_difference_t<_OutIter> _M_max;
3817
3818 protected:
3819 size_t _M_count = 0;
3820
3821 _GLIBCXX_CONSTEXPR_FORMAT void
3822 _M_overflow() override
3823 {
3824 auto __s = this->_M_used();
3825 if (_M_max < 0) // No maximum.
3826 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3827 else if (_M_count < static_cast<size_t>(_M_max))
3828 {
3829 auto __max = _M_max - _M_count;
3830 span<_CharT> __first;
3831 if (__max < __s.size())
3832 __first = __s.first(static_cast<size_t>(__max));
3833 else
3834 __first = __s;
3835 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3836 }
3837 this->_M_rewind();
3838 _M_count += __s.size();
3839 }
3840
3841 _GLIBCXX_CONSTEXPR_FORMAT bool
3842 _M_discarding() const override
3843 {
3844 // format_to_n return total number of characters, that would be written,
3845 // see C++20 [format.functions] p20
3846 return false;
3847 }
3848
3849 public:
3850 [[__gnu__::__always_inline__]]
3851 _GLIBCXX_CONSTEXPR_FORMAT explicit
3852 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3853 : _M_out(std::move(__out)), _M_max(__max)
3854 { }
3855
3856 using _Sink<_CharT>::out;
3857
3858 _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_OutIter>
3859 _M_finish() &&
3860 {
3861 if (this->_M_used().size() != 0)
3862 _Iter_sink::_M_overflow();
3863 iter_difference_t<_OutIter> __count(_M_count);
3864 return { std::move(_M_out), __count };
3865 }
3866 };
3867
3868 // Specialization replacing per-character sputc with bulk sputn
3869 // and zero-copy writes into the streambuf's put area.
3870 template<typename _CharT>
3871 class _Iter_sink<_CharT, ostreambuf_iterator<_CharT>>
3872 : public _Streambuf_sink<_CharT>
3873 {
3874 using _Base = _Streambuf_sink<_CharT>;
3875 using _OutIter = ostreambuf_iterator<_CharT>;
3876
3877 static constexpr size_t _S_no_limit = size_t(-1);
3878
3879 void
3880 _M_trim_buf()
3881 {
3882 const size_t __avail = _M_max - _M_count;
3883 if (this->_M_unused().size() > __avail)
3884 this->_M_reset(this->_M_unused().first(__avail));
3885 }
3886
3887 protected:
3888 size_t _M_max = _S_no_limit;
3889 size_t _M_count = 0;
3890
3891 void
3892 _M_overflow() override
3893 {
3894 const size_t __new = this->_M_used().size();
3895 const size_t __pcount = _M_count;
3896 _M_count += __new;
3897
3898 if (__pcount >= _M_max)
3899 this->_M_reset(this->_M_buf);
3900 else if (size_t __avail = _M_max - __pcount; __avail > __new)
3901 {
3902 _Base::_M_overflow();
3903 _M_trim_buf();
3904 }
3905 else
3906 {
3907 this->_M_flush();
3908 this->_M_reset(this->_M_buf);
3909 }
3910 }
3911
3912 bool
3913 _M_discarding() const override
3914 { return false; }
3915
3916 public:
3917 [[__gnu__::__always_inline__]]
3918 explicit
3919 _Iter_sink(_OutIter __out)
3920 : _Base(__out._M_sbuf)
3921 { }
3922
3923 [[__gnu__::__always_inline__]]
3924 explicit
3925 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max)
3926 : _Base(__out._M_sbuf), _M_max(__max < 0 ? _S_no_limit : size_t(__max))
3927 { _M_trim_buf(); }
3928
3929 typename _Sink<_CharT>::_Reservation
3930 _M_reserve(size_t __n) override
3931 {
3932 if (_M_count < _M_max)
3933 if (size_t __avail = _M_max - _M_count; __avail >= __n)
3934 return _Base::_M_reserve(__n);
3935 return { nullptr };
3936 }
3937
3938 format_to_n_result<_OutIter>
3939 _M_finish() &&
3940 {
3941 _M_count += this->_M_used().size();
3942 if (_M_count <= _M_max)
3943 this->_M_flush();
3944
3945 _OutIter __out(this->_M_sbuf);
3946 __out._M_failed = this->_M_write_failed;
3947 return { std::move(__out), ptrdiff_t(_M_count) };
3948 }
3949 };
3950
3951 // Used for contiguous iterators.
3952 // No buffer is used, characters are written straight to the iterator.
3953 // We do not know the size of the output range, so the span size just grows
3954 // as needed. The end of the span might be an invalid pointer outside the
3955 // valid range, but we never actually call _M_span.end(). This class does
3956 // not introduce any invalid pointer arithmetic or overflows that would not
3957 // have happened anyway.
3958 template<typename _CharT>
3959 class _Ptr_sink : public _Sink<_CharT>
3960 {
3961 static constexpr size_t _S_no_limit = size_t(-1);
3962
3963 size_t _M_max;
3964 protected:
3965 size_t _M_count = 0;
3966 private:
3967 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3968
3969 protected:
3970 _GLIBCXX_CONSTEXPR_FORMAT void
3971 _M_overflow() override
3972 {
3973 if (this->_M_unused().size() != 0)
3974 return; // No need to switch to internal buffer yet.
3975
3976 auto __s = this->_M_used();
3977
3978 if (_M_max != _S_no_limit)
3979 {
3980 _M_count += __s.size();
3981 // Span was already sized for the maximum character count,
3982 // if it overflows then any further output must go to the
3983 // internal buffer, to be discarded.
3984 this->_M_reset(this->_M_buf);
3985 }
3986 else
3987 {
3988 // No maximum character count. Just extend the span to allow
3989 // writing more characters to it.
3990 _M_rebuf(__s.data(), __s.size() + 1024, __s.size());
3991 }
3992 }
3993
3994 _GLIBCXX_CONSTEXPR_FORMAT bool
3995 _M_discarding() const override
3996 {
3997 // format_to_n return total number of characters, that would be written,
3998 // see C++20 [format.functions] p20
3999 return false;
4000 }
4001
4002 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
4003 _M_reserve(size_t __n) final
4004 {
4005 auto __avail = this->_M_unused();
4006 if (__n > __avail.size())
4007 {
4008 if (_M_max != _S_no_limit)
4009 return {}; // cannot grow
4010
4011 auto __s = this->_M_used();
4012 _M_rebuf(__s.data(), __s.size() + __n, __s.size());
4013 }
4014 return { this };
4015 }
4016
4017 private:
4018 template<typename _IterDifference>
4019 static _GLIBCXX_CONSTEXPR_FORMAT size_t
4020 _S_trim_max(_IterDifference __max)
4021 {
4022 if (__max < 0)
4023 return _S_no_limit;
4024 if constexpr (!is_integral_v<_IterDifference> || sizeof(__max) > sizeof(size_t))
4025 // __int128 or __detail::__max_diff_type
4026 if (_IterDifference((size_t)-1) < __max)
4027 return _S_no_limit;
4028 return size_t(__max);
4029 }
4030
4031 [[__gnu__::__always_inline__]]
4032 _GLIBCXX_CONSTEXPR_FORMAT void
4033 _M_rebuf(_CharT* __ptr, size_t __total, size_t __inuse = 0)
4034 {
4035 std::span<_CharT> __span(__ptr, __total);
4036 this->_M_reset(__span, __inuse);
4037 }
4038
4039 public:
4040 _GLIBCXX_CONSTEXPR_FORMAT explicit
4041 _Ptr_sink(_CharT* __ptr, size_t __n = _S_no_limit) noexcept
4042 : _Sink<_CharT>(_M_buf), _M_max(__n)
4043 {
4044 if (__n == 0)
4045 return; // Only write to the internal buffer.
4046 else if (__n != _S_no_limit)
4047 _M_rebuf(__ptr, __n);
4048#if __has_builtin(__builtin_dynamic_object_size)
4049 else if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
4050 _M_rebuf(__ptr, __bytes / sizeof(_CharT));
4051#endif
4052 else
4053 {
4054 // Avoid forming a pointer to a different memory page.
4055 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
4056 __n = (1024 - __off) / sizeof(_CharT);
4057 if (__n > 0) [[likely]]
4058 _M_rebuf(__ptr, __n);
4059 else // Misaligned/packed buffer of wchar_t?
4060 _M_rebuf(__ptr, 1);
4061 }
4062 }
4063
4064 template<contiguous_iterator _OutIter>
4065 _GLIBCXX_CONSTEXPR_FORMAT explicit
4066 _Ptr_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1)
4067 : _Ptr_sink(std::to_address(__out), _S_trim_max(__n))
4068 { }
4069
4070 template<contiguous_iterator _OutIter>
4071 _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_OutIter>
4072 _M_finish(_OutIter __first) const
4073 {
4074 auto __s = this->_M_used();
4075 if (__s.data() == _M_buf)
4076 {
4077 // Switched to internal buffer, so must have written _M_max.
4078 iter_difference_t<_OutIter> __m(_M_max);
4079 iter_difference_t<_OutIter> __count(_M_count + __s.size());
4080 return { __first + __m, __count };
4081 }
4082 else // Not using internal buffer yet
4083 {
4084 iter_difference_t<_OutIter> __count(__s.size());
4085 return { __first + __count, __count };
4086 }
4087 }
4088 };
4089
4090 template<typename _CharT, typename _OutIter>
4091 concept __contiguous_char_iter
4092 = contiguous_iterator<_OutIter>
4093 && same_as<iter_value_t<_OutIter>, _CharT>;
4094
4095 // A sink for handling the padded outputs (_M_padwidth) or truncated
4096 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
4097 // until sufficient number of characters is written. After that if sequence
4098 // is longer than _M_padwidth it's written to _M_out, and further writes are
4099 // either:
4100 // * buffered and forwarded to _M_out, if below _M_maxwidth,
4101 // * ignored otherwise
4102 // If field width of written sequence is no greater than _M_padwidth, the
4103 // sequence is written during _M_finish call.
4104 template<typename _Out, typename _CharT>
4105 class _Padding_sink : public _Str_sink<_CharT>
4106 {
4107 size_t _M_padwidth;
4108 size_t _M_maxwidth;
4109 _Out _M_out;
4110 size_t _M_printwidth;
4111
4112 [[__gnu__::__always_inline__]]
4113 _GLIBCXX_CONSTEXPR_FORMAT bool
4114 _M_ignoring() const
4115 { return _M_printwidth >= _M_maxwidth; }
4116
4117 [[__gnu__::__always_inline__]]
4118 _GLIBCXX_CONSTEXPR_FORMAT bool
4119 _M_buffering() const
4120 {
4121 if (_M_printwidth < _M_padwidth)
4122 return true;
4123 if (_M_maxwidth != (size_t)-1)
4124 return _M_printwidth < _M_maxwidth;
4125 return false;
4126 }
4127
4128 _GLIBCXX_CONSTEXPR_FORMAT void
4129 _M_sync_discarding()
4130 {
4131 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4132 if (_M_out._M_discarding())
4133 _M_maxwidth = _M_printwidth;
4134 }
4135
4136 _GLIBCXX_CONSTEXPR_FORMAT void
4137 _M_flush()
4138 {
4139 span<_CharT> __new = this->_M_used();
4140 basic_string_view<_CharT> __str(__new.data(), __new.size());
4141 _M_out = __format::__write(std::move(_M_out), __str);
4142 _M_sync_discarding();
4143 this->_M_rewind();
4144 }
4145
4146 _GLIBCXX_CONSTEXPR_FORMAT bool
4147 _M_force_update()
4148 {
4149 auto __str = this->view();
4150 // Compute actual field width, possibly truncated.
4151 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
4152 if (_M_ignoring())
4153 this->_M_trim(__str);
4154 if (_M_buffering())
4155 return true;
4156
4157 // We have more characters than padidng, no padding is needed,
4158 // write direclty to _M_out.
4159 if (_M_printwidth >= _M_padwidth)
4160 {
4161 _M_out = __format::__write(std::move(_M_out), __str);
4162 _M_sync_discarding();
4163 }
4164 // We reached _M_maxwidth that is smaller than _M_padwidth.
4165 // Store the prefix sequence in _M_seq, and free _M_buf.
4166 else
4167 _Str_sink<_CharT>::_M_overflow();
4168
4169 // Use internal buffer for writes to _M_out.
4170 this->_M_reset(this->_M_buf);
4171 return false;
4172 }
4173
4174 _GLIBCXX_CONSTEXPR_FORMAT bool
4175 _M_update(size_t __new)
4176 {
4177 _M_printwidth += __new;
4178 // Compute estimated width, to see if is not reduced.
4179 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
4180 return _M_force_update();
4181 return true;
4182 }
4183
4184 _GLIBCXX_CONSTEXPR_FORMAT void
4185 _M_overflow() override
4186 {
4187 // Ignore characters in buffer, and override it.
4188 if (_M_ignoring())
4189 this->_M_rewind();
4190 // Write buffer to _M_out, and override it.
4191 else if (!_M_buffering())
4192 _M_flush();
4193 // Update written count, and if input still should be buffered,
4194 // flush the to _M_seq.
4195 else if (_M_update(this->_M_used().size()))
4196 _Str_sink<_CharT>::_M_overflow();
4197 }
4198
4199 _GLIBCXX_CONSTEXPR_FORMAT bool
4200 _M_discarding() const override
4201 { return _M_ignoring(); }
4202
4203 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
4204 _M_reserve(size_t __n) override
4205 {
4206 // Ignore characters in buffer, if any.
4207 if (_M_ignoring())
4208 this->_M_rewind();
4209 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4210 if (!_M_buffering())
4211 {
4212 // Write pending characters if any
4213 if (!this->_M_used().empty())
4214 _M_flush();
4215 // Try to reserve from _M_out sink.
4216 if (auto __reserved = _M_out._M_reserve(__n))
4217 return __reserved;
4218 }
4219 return _Sink<_CharT>::_M_reserve(__n);
4220 }
4221
4222 _GLIBCXX_CONSTEXPR_FORMAT void
4223 _M_bump(size_t __n) override
4224 {
4225 // Ignore the written characters.
4226 if (_M_ignoring())
4227 return;
4228 // If reservation was made directy sink associated _M_out,
4229 // _M_bump will be called on that sink.
4230 _Sink<_CharT>::_M_bump(__n);
4231 if (_M_buffering())
4232 _M_update(__n);
4233 }
4234
4235 public:
4236 [[__gnu__::__always_inline__]]
4237 _GLIBCXX_CONSTEXPR_FORMAT explicit
4238 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
4239 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
4240 _M_out(std::move(__out)), _M_printwidth(0)
4241 { _M_sync_discarding(); }
4242
4243 [[__gnu__::__always_inline__]]
4244 _GLIBCXX_CONSTEXPR_FORMAT explicit
4245 _Padding_sink(_Out __out, size_t __padwidth)
4246 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
4247 { }
4248
4249 _GLIBCXX_CONSTEXPR_FORMAT _Out
4250 _M_finish(_Align __align, char32_t __fill_char)
4251 {
4252 // Handle any characters in the buffer.
4253 if (auto __rem = this->_M_used().size())
4254 {
4255 if (_M_ignoring())
4256 this->_M_rewind();
4257 else if (!_M_buffering())
4258 _M_flush();
4259 else
4260 _M_update(__rem);
4261 }
4262
4263 if (!_M_buffering() || !_M_force_update())
4264 // Characters were already written to _M_out.
4265 if (_M_printwidth >= _M_padwidth)
4266 return std::move(_M_out);
4267
4268 const auto __str = this->view();
4269 if (_M_printwidth >= _M_padwidth)
4270 return __format::__write(std::move(_M_out), __str);
4271
4272 const size_t __nfill = _M_padwidth - _M_printwidth;
4273 return __format::__write_padded(std::move(_M_out), __str,
4274 __align, __nfill, __fill_char);
4275 }
4276 };
4277
4278 template<typename _Out, typename _CharT>
4279 class _Escaping_sink : public _Buf_sink<_CharT>
4280 {
4281 using _Esc = _Escapes<_CharT>;
4282
4283 _Out _M_out;
4284 _Term_char _M_term : 2;
4285 unsigned _M_prev_escape : 1;
4286 unsigned _M_out_discards : 1;
4287
4288 _GLIBCXX_CONSTEXPR_FORMAT void
4289 _M_sync_discarding()
4290 {
4291 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4292 _M_out_discards = _M_out._M_discarding();
4293 }
4294
4295 _GLIBCXX_CONSTEXPR_FORMAT void
4296 _M_write()
4297 {
4298 span<_CharT> __bytes = this->_M_used();
4299 basic_string_view<_CharT> __str(__bytes.data(), __bytes.size());
4300
4301 size_t __rem = 0;
4302 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4303 {
4304 bool __prev_escape = _M_prev_escape;
4305 _M_out = __format::__write_escaped_unicode_part(
4306 std::move(_M_out), __str, __prev_escape, _M_term);
4307 _M_prev_escape = __prev_escape;
4308
4309 __rem = __str.size();
4310 if (__rem > 0 && __str.data() != this->_M_buf) [[unlikely]]
4311 ranges::move(__str, this->_M_buf);
4312 }
4313 else
4314 _M_out = __format::__write_escaped_ascii(
4315 std::move(_M_out), __str, _M_term);
4316
4317 this->_M_reset(this->_M_buf, __rem);
4318 _M_sync_discarding();
4319 }
4320
4321 _GLIBCXX_CONSTEXPR_FORMAT void
4322 _M_overflow() override
4323 {
4324 if (_M_out_discards)
4325 this->_M_rewind();
4326 else
4327 _M_write();
4328 }
4329
4330 _GLIBCXX_CONSTEXPR_FORMAT bool
4331 _M_discarding() const override
4332 { return _M_out_discards; }
4333
4334 public:
4335 [[__gnu__::__always_inline__]]
4336 _GLIBCXX_CONSTEXPR_FORMAT explicit
4337 _Escaping_sink(_Out __out, _Term_char __term)
4338 : _M_out(std::move(__out)), _M_term(__term),
4339 _M_prev_escape(true), _M_out_discards(false)
4340 {
4341 _M_out = __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4342 _M_sync_discarding();
4343 }
4344
4345 _GLIBCXX_CONSTEXPR_FORMAT _Out
4346 _M_finish()
4347 {
4348 if (_M_out_discards)
4349 return std::move(_M_out);
4350
4351 if (!this->_M_used().empty())
4352 {
4353 _M_write();
4354 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4355 if (auto __rem = this->_M_used(); !__rem.empty())
4356 {
4357 basic_string_view<_CharT> __str(__rem.data(), __rem.size());
4358 _M_out = __format::__write_escape_seqs(std::move(_M_out), __str);
4359 }
4360 }
4361 return __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4362 }
4363 };
4364
4365 template<typename _Context>
4366 struct _Arg_value
4367 {
4368 using _CharT = typename _Context::char_type;
4369
4370 class handle
4371 {
4372 using _CharT = typename _Context::char_type;
4373 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4374 _Context&, const void*);
4375
4376 // Format as const if possible, to reduce instantiations.
4377 template<typename _Tp>
4378 using __maybe_const_t
4379 = __conditional_t<__formattable_with<const _Tp, _Context>,
4380 const _Tp, _Tp>;
4381
4382 template<typename _Tq>
4383 static _GLIBCXX_CONSTEXPR_FORMAT void
4384 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4385 _Context& __format_ctx, const void* __ptr)
4386 {
4387 using _Td = remove_const_t<_Tq>;
4388 typename _Context::template formatter_type<_Td> __f;
4389 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4390 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4391 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4392 }
4393
4394 template<typename _Tp>
4395 requires (!is_same_v<remove_cv_t<_Tp>, handle>)
4396 explicit _GLIBCXX_CONSTEXPR_FORMAT
4397 handle(_Tp& __val) noexcept
4398 : _M_ptr(__builtin_addressof(__val))
4399 , _M_func(&_S_format<__maybe_const_t<_Tp>>)
4400 { }
4401
4402 friend class basic_format_arg<_Context>;
4403
4404 public:
4405 handle(const handle&) = default;
4406 handle& operator=(const handle&) = default;
4407
4408 [[__gnu__::__always_inline__]]
4409 void _GLIBCXX_CONSTEXPR_FORMAT
4410 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4411 { _M_func(__pc, __fc, this->_M_ptr); }
4412
4413 private:
4414 const void* _M_ptr;
4415 _Func _M_func;
4416 };
4417
4418 union
4419 {
4420 monostate _M_none;
4421 bool _M_bool;
4422 _CharT _M_c;
4423 int _M_i;
4424 unsigned _M_u;
4425 long long _M_ll;
4426 unsigned long long _M_ull;
4427 float _M_flt;
4428 double _M_dbl;
4429#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4430 long double _M_ldbl;
4431#else
4432 __ibm128 _M_ibm128;
4433 __ieee128 _M_ieee128;
4434#endif
4435#ifdef __SIZEOF_FLOAT128__
4436 __float128 _M_float128;
4437#endif
4438 const _CharT* _M_str;
4439 basic_string_view<_CharT> _M_sv;
4440 const void* _M_ptr;
4441 handle _M_handle;
4442#ifdef __SIZEOF_INT128__
4443 __int128 _M_i128;
4444 unsigned __int128 _M_u128;
4445#endif
4446#ifdef __BFLT16_DIG__
4447 __bflt16_t _M_bf16;
4448#endif
4449#ifdef __FLT16_DIG__
4450 _Float16 _M_f16;
4451#endif
4452#ifdef __FLT32_DIG__
4453 _Float32 _M_f32;
4454#endif
4455#ifdef __FLT64_DIG__
4456 _Float64 _M_f64;
4457#endif
4458 };
4459
4460 [[__gnu__::__always_inline__]]
4461 _GLIBCXX_CONSTEXPR_FORMAT
4462 _Arg_value() : _M_none() { }
4463
4464#if 0
4465 template<typename _Tp>
4466 _GLIBCXX_CONSTEXPR_FORMAT
4467 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4468 { _S_get<_Tp>() = __val; }
4469#endif
4470
4471 // Returns reference to the _Arg_value member with the type _Tp.
4472 // Value of second argument (if provided), is assigned to that member.
4473 template<typename _Tp, typename _Self, typename... _Value>
4474 [[__gnu__::__always_inline__]]
4475 static _GLIBCXX_CONSTEXPR_FORMAT auto&
4476 _S_access(_Self& __u, _Value... __value) noexcept
4477 {
4478 static_assert(sizeof...(_Value) <= 1);
4479 if constexpr (is_same_v<_Tp, bool>)
4480 return (__u._M_bool = ... = __value);
4481 else if constexpr (is_same_v<_Tp, _CharT>)
4482 return (__u._M_c = ... = __value);
4483 else if constexpr (is_same_v<_Tp, int>)
4484 return (__u._M_i = ... = __value);
4485 else if constexpr (is_same_v<_Tp, unsigned>)
4486 return (__u._M_u = ... = __value);
4487 else if constexpr (is_same_v<_Tp, long long>)
4488 return (__u._M_ll = ... = __value);
4489 else if constexpr (is_same_v<_Tp, unsigned long long>)
4490 return (__u._M_ull = ... = __value);
4491 else if constexpr (is_same_v<_Tp, float>)
4492 return (__u._M_flt = ... = __value);
4493 else if constexpr (is_same_v<_Tp, double>)
4494 return (__u._M_dbl = ... = __value);
4495#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4496 else if constexpr (is_same_v<_Tp, long double>)
4497 return (__u._M_ldbl = ... = __value);
4498#else
4499 else if constexpr (is_same_v<_Tp, __ibm128>)
4500 return (__u._M_ibm128 = ... = __value);
4501 else if constexpr (is_same_v<_Tp, __ieee128>)
4502 return (__u._M_ieee128 = ... = __value);
4503#endif
4504#ifdef __SIZEOF_FLOAT128__
4505 else if constexpr (is_same_v<_Tp, __float128>)
4506 return (__u._M_float128 = ... = __value);
4507#endif
4508 else if constexpr (is_same_v<_Tp, const _CharT*>)
4509 return (__u._M_str = ... = __value);
4510 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4511 return (__u._M_sv = ... = __value);
4512 else if constexpr (is_same_v<_Tp, const void*>)
4513 return (__u._M_ptr = ... = __value);
4514#ifdef __SIZEOF_INT128__
4515 else if constexpr (is_same_v<_Tp, __int128>)
4516 return (__u._M_i128 = ... = __value);
4517 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4518 return (__u._M_u128 = ... = __value);
4519#endif
4520#ifdef __BFLT16_DIG__
4521 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4522 return (__u._M_bf16 = ... = __value);
4523#endif
4524#ifdef __FLT16_DIG__
4525 else if constexpr (is_same_v<_Tp, _Float16>)
4526 return (__u._M_f16 = ... = __value);
4527#endif
4528#ifdef __FLT32_DIG__
4529 else if constexpr (is_same_v<_Tp, _Float32>)
4530 return (__u._M_f32 = ... = __value);
4531#endif
4532#ifdef __FLT64_DIG__
4533 else if constexpr (is_same_v<_Tp, _Float64>)
4534 return (__u._M_f64 = ... = __value);
4535#endif
4536 else if constexpr (is_same_v<_Tp, handle>)
4537 return __u._M_handle;
4538 // Otherwise, ill-formed.
4539 __builtin_unreachable();
4540 }
4541
4542 template<typename _Tp>
4543 [[__gnu__::__always_inline__]]
4544 _GLIBCXX_CONSTEXPR_FORMAT auto&
4545 _M_get() noexcept
4546 { return _S_access<_Tp>(*this); }
4547
4548 template<typename _Tp>
4549 [[__gnu__::__always_inline__]]
4550 _GLIBCXX_CONSTEXPR_FORMAT const auto&
4551 _M_get() const noexcept
4552 { return _S_access<_Tp>(*this); }
4553
4554 template<typename _Tp>
4555 [[__gnu__::__always_inline__]]
4556 _GLIBCXX_CONSTEXPR_FORMAT void
4557 _M_set(_Tp __v) noexcept
4558 {
4559 // Explicitly construct types without trivial default constructor.
4560 if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4561 std::construct_at(&_M_sv, __v);
4562 else if constexpr (is_same_v<_Tp, handle>)
4563 std::construct_at(&_M_handle, __v);
4564 else
4565 // Builtin types are trivially default constructible, and assignment
4566 // changes active member per N5032 [class.union.general] p5.
4567 _S_access<_Tp>(*this, __v);
4568 }
4569 };
4570
4571 // [format.arg.store], class template format-arg-store
4572 template<typename _Context, typename... _Args>
4573 class _Arg_store;
4574
4575 template<typename _Visitor, typename _Ctx>
4576 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4577 __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4578
4579 template<typename _Ch, typename _Tp>
4580 consteval _Arg_t
4581 __to_arg_t_enum() noexcept;
4582} // namespace __format
4583/// @endcond
4584
4585 template<typename _Context>
4586 class basic_format_arg
4587 {
4588 using _CharT = typename _Context::char_type;
4589
4590 public:
4591 using handle = __format::_Arg_value<_Context>::handle;
4592
4593 [[__gnu__::__always_inline__]]
4594 _GLIBCXX_CONSTEXPR_FORMAT
4595 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4596
4597 [[nodiscard,__gnu__::__always_inline__]]
4598 explicit _GLIBCXX_CONSTEXPR_FORMAT operator bool() const noexcept
4599 { return _M_type != __format::_Arg_none; }
4600
4601#if __cpp_lib_format >= 202306L // >= C++26
4602 template<typename _Visitor>
4603 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4604 visit(this basic_format_arg __arg, _Visitor&& __vis)
4605 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4606
4607 template<typename _Res, typename _Visitor>
4608 _GLIBCXX_CONSTEXPR_FORMAT _Res
4609 visit(this basic_format_arg __arg, _Visitor&& __vis)
4610 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4611#endif
4612
4613 private:
4614 template<typename _Ctx>
4615 friend class basic_format_args;
4616
4617 template<typename _Ctx, typename... _Args>
4618 friend class __format::_Arg_store;
4619
4620 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4621
4622 __format::_Arg_value<_Context> _M_val;
4623 __format::_Arg_t _M_type;
4624
4625 // Transform incoming argument type to the type stored in _Arg_value.
4626 // e.g. short -> int, std::string -> std::string_view,
4627 // char[3] -> const char*.
4628 template<typename _Tp>
4629 static consteval auto
4630 _S_to_arg_type()
4631 {
4632 using _Td = remove_const_t<_Tp>;
4633 if constexpr (is_same_v<_Td, bool>)
4634 return type_identity<bool>();
4635 else if constexpr (is_same_v<_Td, _CharT>)
4636 return type_identity<_CharT>();
4637 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4638 return type_identity<_CharT>();
4639#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4640 else if constexpr (is_same_v<_Td, __int128>)
4641 return type_identity<__int128>();
4642 else if constexpr (is_same_v<_Td, unsigned __int128>)
4643 return type_identity<unsigned __int128>();
4644#endif
4645 else if constexpr (__is_signed_integer<_Td>::value)
4646 {
4647 if constexpr (sizeof(_Td) <= sizeof(int))
4648 return type_identity<int>();
4649 else if constexpr (sizeof(_Td) <= sizeof(long long))
4650 return type_identity<long long>();
4651 }
4652 else if constexpr (__is_unsigned_integer<_Td>::value)
4653 {
4654 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4655 return type_identity<unsigned>();
4656 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4657 return type_identity<unsigned long long>();
4658 }
4659 else if constexpr (is_same_v<_Td, float>)
4660 return type_identity<float>();
4661 else if constexpr (is_same_v<_Td, double>)
4662 return type_identity<double>();
4663#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4664 else if constexpr (is_same_v<_Td, long double>)
4665 return type_identity<long double>();
4666#else
4667 else if constexpr (is_same_v<_Td, __ibm128>)
4668 return type_identity<__ibm128>();
4669 else if constexpr (is_same_v<_Td, __ieee128>)
4670 return type_identity<__ieee128>();
4671#endif
4672#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4673 else if constexpr (is_same_v<_Td, __float128>)
4674 return type_identity<__float128>();
4675#endif
4676#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4677 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4678 return type_identity<__format::__bflt16_t>();
4679#endif
4680#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4681 else if constexpr (is_same_v<_Td, _Float16>)
4682 return type_identity<_Float16>();
4683#endif
4684#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4685 else if constexpr (is_same_v<_Td, _Float32>)
4686 return type_identity<_Float32>();
4687#endif
4688#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4689 else if constexpr (is_same_v<_Td, _Float64>)
4690 return type_identity<_Float64>();
4691#endif
4692 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4693 || __is_specialization_of<_Td, basic_string>)
4694 {
4695 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4696 return type_identity<basic_string_view<_CharT>>();
4697 else
4698 return type_identity<handle>();
4699 }
4700 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4701 return type_identity<const _CharT*>();
4702 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4703 return type_identity<const _CharT*>();
4704 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4705 return type_identity<const void*>();
4706 else if constexpr (is_same_v<_Td, nullptr_t>)
4707 return type_identity<const void*>();
4708 else
4709 return type_identity<handle>();
4710 }
4711
4712 // Transform a formattable type to the appropriate storage type.
4713 template<typename _Tp>
4714 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4715
4716 // Get the _Arg_t value corresponding to a normalized type.
4717 template<typename _Tp>
4718 static consteval __format::_Arg_t
4719 _S_to_enum()
4720 {
4721 using namespace __format;
4722 if constexpr (is_same_v<_Tp, bool>)
4723 return _Arg_bool;
4724 else if constexpr (is_same_v<_Tp, _CharT>)
4725 return _Arg_c;
4726 else if constexpr (is_same_v<_Tp, int>)
4727 return _Arg_i;
4728 else if constexpr (is_same_v<_Tp, unsigned>)
4729 return _Arg_u;
4730 else if constexpr (is_same_v<_Tp, long long>)
4731 return _Arg_ll;
4732 else if constexpr (is_same_v<_Tp, unsigned long long>)
4733 return _Arg_ull;
4734 else if constexpr (is_same_v<_Tp, float>)
4735 return _Arg_flt;
4736 else if constexpr (is_same_v<_Tp, double>)
4737 return _Arg_dbl;
4738#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4739 else if constexpr (is_same_v<_Tp, long double>)
4740 return _Arg_ldbl;
4741#else
4742 // Don't use _Arg_ldbl for this target, it's ambiguous.
4743 else if constexpr (is_same_v<_Tp, __ibm128>)
4744 return _Arg_ibm128;
4745 else if constexpr (is_same_v<_Tp, __ieee128>)
4746 return _Arg_ieee128;
4747#endif
4748#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4749 else if constexpr (is_same_v<_Tp, __float128>)
4750 return _Arg_float128;
4751#endif
4752#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4753 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4754 return _Arg_bf16;
4755#endif
4756#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4757 else if constexpr (is_same_v<_Tp, _Float16>)
4758 return _Arg_f16;
4759#endif
4760#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4761 else if constexpr (is_same_v<_Tp, _Float32>)
4762 return _Arg_f32;
4763#endif
4764#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4765 else if constexpr (is_same_v<_Tp, _Float64>)
4766 return _Arg_f64;
4767#endif
4768 else if constexpr (is_same_v<_Tp, const _CharT*>)
4769 return _Arg_str;
4770 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4771 return _Arg_sv;
4772 else if constexpr (is_same_v<_Tp, const void*>)
4773 return _Arg_ptr;
4774#ifdef __SIZEOF_INT128__
4775 else if constexpr (is_same_v<_Tp, __int128>)
4776 return _Arg_i128;
4777 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4778 return _Arg_u128;
4779#endif
4780 else if constexpr (is_same_v<_Tp, handle>)
4781 return _Arg_handle;
4782 }
4783
4784 template<typename _Tp>
4785 _GLIBCXX_CONSTEXPR_FORMAT void
4786 _M_set(_Tp __v) noexcept
4787 {
4788 _M_type = _S_to_enum<_Tp>();
4789 _M_val._M_set(__v);
4790 }
4791
4792 template<typename _Tp>
4793 requires __format::__formattable_with<_Tp, _Context>
4794 _GLIBCXX_CONSTEXPR_FORMAT explicit
4795 basic_format_arg(_Tp& __v) noexcept
4796 {
4797 using _Td = _Normalize<_Tp>;
4798 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4799 _M_set(_Td{__v.data(), __v.size()});
4800 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4801 && is_same_v<_CharT, wchar_t>)
4802 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4803 else
4804 _M_set(static_cast<_Td>(__v));
4805 }
4806
4807 template<typename _Ctx, typename... _Argz>
4808 friend _GLIBCXX_CONSTEXPR_FORMAT auto
4809 make_format_args(_Argz&...) noexcept;
4810
4811 template<typename _Visitor, typename _Ctx>
4812 friend _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4813 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4814
4815 template<typename _Visitor, typename _Ctx>
4816 friend _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4817 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4818
4819 template<typename _Ch, typename _Tp>
4820 friend consteval __format::_Arg_t
4821 __format::__to_arg_t_enum() noexcept;
4822
4823 [[__gnu__::__noinline__]]
4824 handle
4825 _M_handle_unrecognized() const;
4826
4827 template<typename _Visitor>
4828 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4829 _M_visit(_Visitor&& __vis)
4830 {
4831 switch (_M_type)
4832 {
4833 using enum __format::_Arg_t;
4834 case _Arg_none:
4835 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4836 case _Arg_bool:
4837 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4838 case _Arg_c:
4839 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4840 case _Arg_i:
4841 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4842 case _Arg_u:
4843 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4844 case _Arg_ll:
4845 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4846 case _Arg_ull:
4847 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4848#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4849 case _Arg_flt:
4850 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4851 case _Arg_dbl:
4852 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4853#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4854 case _Arg_ldbl:
4855 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4856#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4857 case _Arg_float128:
4858 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4859#endif
4860#else
4861 case _Arg_ibm128:
4862 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4863 case _Arg_ieee128:
4864 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4865#endif
4866#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4867 case _Arg_bf16:
4868 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4869#endif
4870#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4871 case _Arg_f16:
4872 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4873#endif
4874#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4875 case _Arg_f32:
4876 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4877#endif
4878#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4879 case _Arg_f64:
4880 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4881#endif
4882#endif // __glibcxx_to_chars
4883 case _Arg_str:
4884 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4885 case _Arg_sv:
4886 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4887 case _Arg_ptr:
4888 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4889 case _Arg_handle:
4890 return std::forward<_Visitor>(__vis)(_M_val._M_handle);
4891#ifdef __SIZEOF_INT128__
4892 case _Arg_i128:
4893 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4894 case _Arg_u128:
4895 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4896#endif
4897 default:
4898 // Call exported definition of _M_handle_unrecognized from
4899 // libstdc++.so, that should recognize new _Arg_t values and
4900 // return basic_format_arg, containing a handle to that value.
4901 handle __h = _M_handle_unrecognized();
4902 return std::forward<_Visitor>(__vis)(__h);
4903 }
4904 }
4905
4906 template<typename _Visitor>
4907 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4908 _M_visit_user(_Visitor&& __vis)
4909 {
4910 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4911 {
4912 constexpr bool __user_facing = __is_one_of<_Tp,
4913 monostate, bool, _CharT,
4914 int, unsigned int, long long int, unsigned long long int,
4915 float, double, long double,
4916 const _CharT*, basic_string_view<_CharT>,
4917 const void*, handle>::value;
4918 if constexpr (__user_facing)
4919 return std::forward<_Visitor>(__vis)(__val);
4920 else
4921 {
4922 handle __h(__val);
4923 return std::forward<_Visitor>(__vis)(__h);
4924 }
4925 });
4926 }
4927 };
4928
4929 template<typename _Visitor, typename _Context>
4930 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4931 inline _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4932 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4933 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4934
4935/// @cond undocumented
4936namespace __format
4937{
4938 template<typename _Visitor, typename _Ctx>
4939 inline _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4940 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4941 { return __arg._M_visit(std::forward<_Visitor>(__vis)); }
4942
4943 struct _WidthPrecVisitor
4944 {
4945 template<typename _Tp>
4946 _GLIBCXX_CONSTEXPR_FORMAT size_t
4947 operator()(_Tp& __arg) const
4948 {
4949 if constexpr (is_same_v<_Tp, monostate>)
4950 __format::__invalid_arg_id_in_format_string();
4951 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4952 // 3720. Restrict the valid types of arg-id for width and precision
4953 // 3721. Allow an arg-id with a value of zero for width
4954 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4955 {
4956 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4957 // 3720. Restrict the valid types of arg-id for width and precision
4958 if constexpr (__is_unsigned_integer<_Tp>::value)
4959 return __arg;
4960 else if constexpr (__is_signed_integer<_Tp>::value)
4961 if (__arg >= 0)
4962 return __arg;
4963 }
4964 __throw_format_error("format error: argument used for width or "
4965 "precision must be a non-negative integer");
4966 }
4967 };
4968
4969#pragma GCC diagnostic push
4970#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4971 template<typename _Context>
4972 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
4973 __int_from_arg(const basic_format_arg<_Context>& __arg)
4974 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4975
4976 // Pack _Arg_t enum values into a single 60-bit integer.
4977 template<int _Bits, size_t _Nm>
4978 constexpr auto
4979 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4980 {
4981 __UINT64_TYPE__ __packed_types = 0;
4982 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4983 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4984 return __packed_types;
4985 }
4986} // namespace __format
4987/// @endcond
4988
4989 template<typename _Context>
4990 class basic_format_args
4991 {
4992 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4993 static constexpr int _S_packed_type_mask = 0b11111;
4994 static constexpr int _S_max_packed_args = 12;
4995
4996 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4997
4998 template<typename... _Args>
4999 using _Store = __format::_Arg_store<_Context, _Args...>;
5000
5001 template<typename _Ctx, typename... _Args>
5002 friend class __format::_Arg_store;
5003
5004 using uint64_t = __UINT64_TYPE__;
5005 using _Format_arg = basic_format_arg<_Context>;
5006 using _Format_arg_val = __format::_Arg_value<_Context>;
5007
5008 // If args are packed then the number of args is in _M_packed_size and
5009 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
5010 // If args are not packed then the number of args is in _M_unpacked_size
5011 // and _M_packed_size is zero.
5012 uint64_t _M_packed_size : 4;
5013 uint64_t _M_unpacked_size : 60;
5014
5015 union {
5016 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
5017 const _Format_arg* _M_args; // Active when _M_packed_size == 0
5018 };
5019
5020 _GLIBCXX_CONSTEXPR_FORMAT size_t
5021 _M_size() const noexcept
5022 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
5023
5024 _GLIBCXX_CONSTEXPR_FORMAT typename __format::_Arg_t
5025 _M_type(size_t __i) const noexcept
5026 {
5027 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
5028 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
5029 }
5030
5031 template<typename _Ctx, typename... _Args>
5032 friend _GLIBCXX_CONSTEXPR_FORMAT auto
5033 make_format_args(_Args&...) noexcept;
5034
5035 // An array of _Arg_t enums corresponding to _Args...
5036 template<typename... _Args>
5037 static consteval array<__format::_Arg_t, sizeof...(_Args)>
5038 _S_types_to_pack()
5039 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
5040
5041 public:
5042 template<typename... _Args>
5043 _GLIBCXX_CONSTEXPR_FORMAT
5044 basic_format_args(const _Store<_Args...>& __store) noexcept;
5045
5046 [[nodiscard,__gnu__::__always_inline__]]
5047 _GLIBCXX_CONSTEXPR_FORMAT basic_format_arg<_Context>
5048 get(size_t __i) const noexcept
5049 {
5050 basic_format_arg<_Context> __arg;
5051 if (__i < _M_packed_size)
5052 {
5053 __arg._M_type = _M_type(__i);
5054 __arg._M_val = _M_values[__i];
5055 }
5056 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
5057 __arg = _M_args[__i];
5058 return __arg;
5059 }
5060 };
5061
5062 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5063 // 3810. CTAD for std::basic_format_args
5064 template<typename _Context, typename... _Args>
5065 basic_format_args(__format::_Arg_store<_Context, _Args...>)
5066 -> basic_format_args<_Context>;
5067
5068 template<typename _Context, typename... _Args>
5069 _GLIBCXX_CONSTEXPR_FORMAT auto
5070 make_format_args(_Args&... __fmt_args) noexcept;
5071
5072 // An array of type-erased formatting arguments.
5073 template<typename _Context, typename... _Args>
5074 class __format::_Arg_store
5075 {
5076 friend std::basic_format_args<_Context>;
5077
5078 template<typename _Ctx, typename... _Argz>
5079 friend _GLIBCXX_CONSTEXPR_FORMAT auto std::
5080#if _GLIBCXX_INLINE_VERSION
5081 __8:: // Needed for PR c++/59256
5082#endif
5083 make_format_args(_Argz&...) noexcept;
5084
5085 // For a sufficiently small number of arguments we only store values.
5086 // basic_format_args can get the types from the _Args pack.
5087 static constexpr bool _S_values_only
5088 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
5089
5090 using _Element_t
5091 = __conditional_t<_S_values_only,
5092 __format::_Arg_value<_Context>,
5093 basic_format_arg<_Context>>;
5094
5095 _Element_t _M_args[sizeof...(_Args)];
5096
5097 template<typename _Tp>
5098 static _GLIBCXX_CONSTEXPR_FORMAT _Element_t
5099 _S_make_elt(_Tp& __v)
5100 {
5101 using _Tq = remove_const_t<_Tp>;
5102 using _CharT = typename _Context::char_type;
5103 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
5104 "std::formatter must be specialized for the type "
5105 "of each format arg");
5106 using __format::__formattable_with;
5107 if constexpr (is_const_v<_Tp>)
5108 if constexpr (!__formattable_with<_Tp, _Context>)
5109 if constexpr (__formattable_with<_Tq, _Context>)
5110 static_assert(__formattable_with<_Tp, _Context>,
5111 "format arg must be non-const because its "
5112 "std::formatter specialization has a "
5113 "non-const reference parameter");
5114 basic_format_arg<_Context> __arg(__v);
5115 if constexpr (_S_values_only)
5116 return __arg._M_val;
5117 else
5118 return __arg;
5119 }
5120
5121 template<typename... _Tp>
5122 requires (sizeof...(_Tp) == sizeof...(_Args))
5123 [[__gnu__::__always_inline__]]
5124 _GLIBCXX_CONSTEXPR_FORMAT
5125 _Arg_store(_Tp&... __a) noexcept
5126 : _M_args{_S_make_elt(__a)...}
5127 { }
5128 };
5129
5130 template<typename _Context>
5131 class __format::_Arg_store<_Context>
5132 { };
5133
5134 template<typename _Context>
5135 template<typename... _Args>
5136 inline _GLIBCXX_CONSTEXPR_FORMAT
5137 basic_format_args<_Context>::
5138 basic_format_args(const _Store<_Args...>& __store) noexcept
5139 {
5140 if constexpr (sizeof...(_Args) == 0)
5141 {
5142 _M_packed_size = 0;
5143 _M_unpacked_size = 0;
5144 _M_args = nullptr;
5145 }
5146 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
5147 {
5148 // The number of packed arguments:
5149 _M_packed_size = sizeof...(_Args);
5150 // The packed type enums:
5151 _M_unpacked_size
5152 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
5153 // The _Arg_value objects.
5154 _M_values = __store._M_args;
5155 }
5156 else
5157 {
5158 // No packed arguments:
5159 _M_packed_size = 0;
5160 // The number of unpacked arguments:
5161 _M_unpacked_size = sizeof...(_Args);
5162 // The basic_format_arg objects:
5163 _M_args = __store._M_args;
5164 }
5165 }
5166
5167 /// Capture formatting arguments for use by `std::vformat`.
5168 template<typename _Context = format_context, typename... _Args>
5169 [[nodiscard,__gnu__::__always_inline__]]
5170 inline _GLIBCXX_CONSTEXPR_FORMAT auto
5171 make_format_args(_Args&... __fmt_args) noexcept
5172 {
5173 using _Fmt_arg = basic_format_arg<_Context>;
5174 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
5175 _Normalize<_Args>...>;
5176 return _Store(__fmt_args...);
5177 }
5178
5179#ifdef _GLIBCXX_USE_WCHAR_T
5180 /// Capture formatting arguments for use by `std::vformat` (for wide output).
5181 template<typename... _Args>
5182 [[nodiscard,__gnu__::__always_inline__]]
5183 inline _GLIBCXX_CONSTEXPR_FORMAT auto
5184 make_wformat_args(_Args&... __args) noexcept
5185 { return std::make_format_args<wformat_context>(__args...); }
5186#endif
5187
5188/// @cond undocumented
5189namespace __format
5190{
5191 template<typename _Out, typename _CharT, typename _Context>
5192 _GLIBCXX_CONSTEXPR_FORMAT _Out
5193 __do_vformat_to(_Out, basic_string_view<_CharT>,
5194 const basic_format_args<_Context>&,
5195 const locale* = nullptr);
5196
5197 template<typename _CharT> struct __formatter_chrono;
5198
5199} // namespace __format
5200/// @endcond
5201
5202 /** Context for std::format and similar functions.
5203 *
5204 * A formatting context contains an output iterator and locale to use
5205 * for the formatting operations. Most programs will never need to use
5206 * this class template explicitly. For typical uses of `std::format` the
5207 * library will use the specializations `std::format_context` (for `char`)
5208 * and `std::wformat_context` (for `wchar_t`).
5209 *
5210 * You are not allowed to define partial or explicit specializations of
5211 * this class template.
5212 *
5213 * @since C++20
5214 */
5215 template<typename _Out, typename _CharT>
5216 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5217 // 3975. Specializations of basic_format_context should not be permitted
5218 class _GLIBCXX_NO_SPECIALIZATIONS basic_format_context
5219 {
5220 static_assert( output_iterator<_Out, const _CharT&> );
5221
5222 basic_format_args<basic_format_context> _M_args;
5223 _Out _M_out;
5224 __format::_Optional_locale _M_loc;
5225
5226 _GLIBCXX_CONSTEXPR_FORMAT
5227 basic_format_context(basic_format_args<basic_format_context> __args,
5228 _Out __out)
5229 : _M_args(__args), _M_out(std::move(__out))
5230 { }
5231
5232 _GLIBCXX_CONSTEXPR_FORMAT
5233 basic_format_context(basic_format_args<basic_format_context> __args,
5234 _Out __out, const std::locale& __loc)
5235 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
5236 { }
5237
5238 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5239 // 4061. Should std::basic_format_context be
5240 // default-constructible/copyable/movable?
5241 basic_format_context(const basic_format_context&) = delete;
5242 basic_format_context& operator=(const basic_format_context&) = delete;
5243
5244 template<typename _Out2, typename _CharT2, typename _Context2>
5245 friend _GLIBCXX_CONSTEXPR_FORMAT _Out2
5246 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
5247 const basic_format_args<_Context2>&,
5248 const locale*);
5249
5250 friend __format::__formatter_chrono<_CharT>;
5251
5252 public:
5253 ~basic_format_context() = default;
5254
5255 using iterator = _Out;
5256 using char_type = _CharT;
5257 template<typename _Tp>
5258 using formatter_type = formatter<_Tp, _CharT>;
5259
5260 [[nodiscard]]
5261 _GLIBCXX_CONSTEXPR_FORMAT basic_format_arg<basic_format_context>
5262 arg(size_t __id) const noexcept
5263 { return _M_args.get(__id); }
5264
5265 [[nodiscard]]
5266 std::locale locale() { return _M_loc.value(); }
5267
5268 [[nodiscard]]
5269 _GLIBCXX_CONSTEXPR_FORMAT iterator
5270 out() { return std::move(_M_out); }
5271
5272 _GLIBCXX_CONSTEXPR_FORMAT void
5273 advance_to(iterator __it) { _M_out = std::move(__it); }
5274 };
5275
5276#if _GLIBCXX_EXTERN_TEMPLATE
5277 // The defintion _M_handle_unrecognized is placed in format-inst.cc
5278 // source file, to ensure that it will not be inlined by compiler.
5279 extern template basic_format_arg<format_context>::handle
5280 basic_format_arg<format_context>::_M_handle_unrecognized() const;
5281# ifdef _GLIBCXX_USE_WCHAR_T
5282 extern template basic_format_arg<wformat_context>::handle
5283 basic_format_arg<wformat_context>::_M_handle_unrecognized() const;
5284# endif
5285#else
5286 template<typename _Context>
5287 typename basic_format_arg<_Context>::handle
5288 basic_format_arg<_Context>::_M_handle_unrecognized() const
5289 {
5290 // If _M_type corresponds to a new value of _Arg_t introduced after
5291 // GCC 16, this function should return a handle that refers to the
5292 // union member of _M_val corresponding to that _Arg_t value.
5293 __throw_format_error("format error: unrecognized argument type");
5294 }
5295#endif
5296
5297/// @cond undocumented
5298namespace __format
5299{
5300 // Abstract base class defining an interface for scanning format strings.
5301 // Scan the characters in a format string, dividing it up into strings of
5302 // ordinary characters, escape sequences, and replacement fields.
5303 // Call virtual functions for derived classes to parse format-specifiers
5304 // or write formatted output.
5305 template<typename _CharT>
5306 struct _Scanner
5307 {
5308 using iterator = typename basic_format_parse_context<_CharT>::iterator;
5309
5310 typename basic_format_parse_context<_CharT>::_Scan_parse_context _M_pc;
5311
5312 constexpr explicit
5313 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
5314 : _M_pc(__str, __nargs)
5315 { }
5316
5317 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
5318 constexpr iterator end() const noexcept { return _M_pc.end(); }
5319
5320 constexpr void
5321 _M_scan()
5322 {
5323 basic_string_view<_CharT> __fmt = _M_fmt_str();
5324
5325 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5326 {
5327 _M_pc.advance_to(begin() + 1);
5328 _M_format_arg(_M_pc.next_arg_id());
5329 return;
5330 }
5331
5332 size_t __lbr = __fmt.find('{');
5333 size_t __rbr = __fmt.find('}');
5334
5335 while (__fmt.size())
5336 {
5337 auto __cmp = __lbr <=> __rbr;
5338 if (__cmp == 0)
5339 {
5340 _M_on_chars(end());
5341 _M_pc.advance_to(end());
5342 return;
5343 }
5344 else if (__cmp < 0)
5345 {
5346 if (__lbr + 1 == __fmt.size()
5347 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
5348 __format::__unmatched_left_brace_in_format_string();
5349 const bool __is_escape = __fmt[__lbr + 1] == '{';
5350 iterator __last = begin() + __lbr + int(__is_escape);
5351 _M_on_chars(__last);
5352 _M_pc.advance_to(__last + 1);
5353 __fmt = _M_fmt_str();
5354 if (__is_escape)
5355 {
5356 if (__rbr != __fmt.npos)
5357 __rbr -= __lbr + 2;
5358 __lbr = __fmt.find('{');
5359 }
5360 else
5361 {
5362 _M_on_replacement_field();
5363 __fmt = _M_fmt_str();
5364 __lbr = __fmt.find('{');
5365 __rbr = __fmt.find('}');
5366 }
5367 }
5368 else
5369 {
5370 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
5371 __format::__unmatched_right_brace_in_format_string();
5372 iterator __last = begin() + __rbr;
5373 _M_on_chars(__last);
5374 _M_pc.advance_to(__last + 1);
5375 __fmt = _M_fmt_str();
5376 if (__lbr != __fmt.npos)
5377 __lbr -= __rbr + 1;
5378 __rbr = __fmt.find('}');
5379 }
5380 }
5381 }
5382
5383 constexpr basic_string_view<_CharT>
5384 _M_fmt_str() const noexcept
5385 { return {begin(), end()}; }
5386
5387 constexpr virtual void _M_on_chars(iterator) { }
5388
5389 constexpr void _M_on_replacement_field()
5390 {
5391 auto __next = begin();
5392
5393 size_t __id;
5394 if (*__next == '}')
5395 __id = _M_pc.next_arg_id();
5396 else if (*__next == ':')
5397 {
5398 __id = _M_pc.next_arg_id();
5399 _M_pc.advance_to(++__next);
5400 }
5401 else
5402 {
5403 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5404 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5405 __format::__invalid_arg_id_in_format_string();
5406 _M_pc.check_arg_id(__id = __i);
5407 if (*__ptr == ':')
5408 {
5409 _M_pc.advance_to(++__ptr);
5410 }
5411 else
5412 _M_pc.advance_to(__ptr);
5413 }
5414 _M_format_arg(__id);
5415 if (begin() == end() || *begin() != '}')
5416 __format::__unmatched_left_brace_in_format_string();
5417 _M_pc.advance_to(begin() + 1); // Move past '}'
5418 }
5419
5420 constexpr virtual void _M_format_arg(size_t __id) = 0;
5421 };
5422
5423 // Process a format string and format the arguments in the context.
5424 template<typename _Out, typename _CharT>
5425 class _Formatting_scanner : public _Scanner<_CharT>
5426 {
5427 public:
5428 _GLIBCXX_CONSTEXPR_FORMAT
5429 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5430 basic_string_view<_CharT> __str)
5431 : _Scanner<_CharT>(__str), _M_fc(__fc)
5432 { }
5433
5434 private:
5435 basic_format_context<_Out, _CharT>& _M_fc;
5436
5437 using iterator = typename _Scanner<_CharT>::iterator;
5438
5439 constexpr void
5440 _M_on_chars(iterator __last) override
5441 {
5442 basic_string_view<_CharT> __str(this->begin(), __last);
5443 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5444 }
5445
5446 constexpr void
5447 _M_format_arg(size_t __id) override
5448 {
5449 using _Context = basic_format_context<_Out, _CharT>;
5450 using handle = typename basic_format_arg<_Context>::handle;
5451
5452 __format::__visit_format_arg([this](auto& __arg) {
5453 using _Type = remove_reference_t<decltype(__arg)>;
5454 using _Formatter = typename _Context::template formatter_type<_Type>;
5455 if constexpr (is_same_v<_Type, monostate>)
5456 __format::__invalid_arg_id_in_format_string();
5457 else if constexpr (is_same_v<_Type, handle>)
5458 __arg.format(this->_M_pc, this->_M_fc);
5459 else if constexpr (is_default_constructible_v<_Formatter>)
5460 {
5461 _Formatter __f;
5462 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5463 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5464 }
5465 else
5466 static_assert(__format::__formattable_with<_Type, _Context>);
5467 }, _M_fc.arg(__id));
5468 }
5469 };
5470
5471 template<typename _CharT, typename _Tp>
5472 consteval _Arg_t
5473 __to_arg_t_enum() noexcept
5474 {
5475 using _Context = __format::__format_context<_CharT>;
5476 using _Fmt_arg = basic_format_arg<_Context>;
5477 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5478 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5479 }
5480
5481 // Validate a format string for Args.
5482 template<typename _CharT, typename... _Args>
5483 class _Checking_scanner : public _Scanner<_CharT>
5484 {
5485 static_assert(
5486 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5487 "std::formatter must be specialized for each type being formatted");
5488
5489 public:
5490 consteval
5491 _Checking_scanner(basic_string_view<_CharT> __str)
5492 : _Scanner<_CharT>(__str, sizeof...(_Args))
5493 {
5494#if __cpp_lib_format >= 202305L
5495 this->_M_pc._M_types = _M_types.data();
5496#endif
5497 }
5498
5499 private:
5500 constexpr void
5501 _M_format_arg(size_t __id) override
5502 {
5503 if constexpr (sizeof...(_Args) != 0)
5504 {
5505 if (__id < sizeof...(_Args))
5506 {
5507 _M_parse_format_spec<_Args...>(__id);
5508 return;
5509 }
5510 }
5511 __builtin_unreachable();
5512 }
5513
5514 template<typename _Tp, typename... _OtherArgs>
5515 constexpr void
5516 _M_parse_format_spec(size_t __id)
5517 {
5518 if (__id == 0)
5519 {
5520 formatter<_Tp, _CharT> __f;
5521 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5522 }
5523 else if constexpr (sizeof...(_OtherArgs) != 0)
5524 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5525 else
5526 __builtin_unreachable();
5527 }
5528
5529#if __cpp_lib_format >= 202305L
5530 array<_Arg_t, sizeof...(_Args)>
5531 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5532#endif
5533 };
5534
5535 template<typename _CharT, unsigned = __unicode::__literal_encoding_is_unicode<_CharT>()>
5536 _GLIBCXX_CONSTEXPR_FORMAT _Sink_iter<_CharT>
5537 __do_vformat_to(_Sink_iter<_CharT> __out, basic_string_view<_CharT> __fmt,
5538 __format_context<_CharT>& __ctx)
5539 {
5540 if constexpr (is_same_v<_CharT, char>)
5541 // Fast path for "{}" format strings and simple format arg types.
5542 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5543 {
5544 bool __done = false;
5545 __format::__visit_format_arg([&](auto& __arg) {
5546 using _Tp = remove_cvref_t<decltype(__arg)>;
5547 if constexpr (is_same_v<_Tp, bool>)
5548 {
5549 size_t __len = 4 + !__arg;
5550 const char* __chars[] = { "false", "true" };
5551 if (auto __res = __out._M_reserve(__len))
5552 {
5553 ranges::copy_n(__chars[__arg], __len, __res.get());
5554 __res._M_bump(__len);
5555 __done = true;
5556 }
5557 }
5558 else if constexpr (is_same_v<_Tp, char>)
5559 {
5560 if (auto __res = __out._M_reserve(1))
5561 {
5562 *__res.get() = __arg;
5563 __res._M_bump(1);
5564 __done = true;
5565 }
5566 }
5567 else if constexpr (is_integral_v<_Tp>)
5568 {
5569 make_unsigned_t<_Tp> __uval;
5570 const bool __neg = __arg < 0;
5571 if (__neg)
5572 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5573 else
5574 __uval = __arg;
5575 const auto __n = __detail::__to_chars_len(__uval);
5576 if (auto __res = __out._M_reserve(__n + __neg))
5577 {
5578 auto __ptr = __res.get();
5579 *__ptr = '-';
5580 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5581 __uval);
5582 __res._M_bump(__n + __neg);
5583 __done = true;
5584 }
5585 }
5586 else if constexpr (is_convertible_v<_Tp, string_view>)
5587 {
5588 string_view __sv = __arg;
5589 if (auto __res = __out._M_reserve(__sv.size()))
5590 {
5591 ranges::copy(__sv, __res.get());
5592 __res._M_bump(__sv.size());
5593 __done = true;
5594 }
5595 }
5596 }, __ctx.arg(0));
5597
5598 if (__done)
5599 return __out;
5600 }
5601
5602 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5603 __scanner._M_scan();
5604 return __out;
5605 }
5606
5607// The behavior of the formatters (interpretation of fill character) depends
5608// on the literal encoding. As explicit instantiation of __do_vformat_to
5609// instantiates formatters for types stored in basic_format_arg, we can
5610// support only single encoding, in this case unicode. This should cover
5611// most common use cases.
5612#if __cplusplus <= 202002L && _GLIBCXX_EXTERN_TEMPLATE
5613 extern template _Sink_iter<char>
5614 __do_vformat_to<char, 1>(_Sink_iter<char>, string_view,
5615 format_context&);
5616# ifdef _GLIBCXX_USE_WCHAR_T
5617 extern template _Sink_iter<wchar_t>
5618 __do_vformat_to<wchar_t, 1>(_Sink_iter<wchar_t>, wstring_view,
5619 wformat_context&);
5620# endif
5621#endif
5622
5623 template<typename _Out, typename _CharT, typename _Context>
5624 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5625 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5626 const basic_format_args<_Context>& __args,
5627 const locale* __loc)
5628 {
5629 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5630 {
5631 auto __ctx = __loc == nullptr
5632 ? _Context(__args, __out)
5633 : _Context(__args, __out, *__loc);
5634 return __format::__do_vformat_to(__out, __fmt, __ctx);
5635 }
5636 else if constexpr (__contiguous_char_iter<_CharT, _Out>)
5637 {
5638 _Ptr_sink<_CharT> __sink(__out);
5639 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5640 return std::move(__sink)._M_finish(__out).out;
5641 }
5642 else
5643 {
5644 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5645 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5646 return std::move(__sink)._M_finish().out;
5647 }
5648 }
5649
5650 template<typename _Out, typename _CharT>
5651 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5652 __do_vformat_to_n(_Out __out, iter_difference_t<_Out> __n,
5653 basic_string_view<_CharT> __fmt,
5654 const type_identity_t<
5655 basic_format_args<__format_context<_CharT>>>& __args,
5656 const locale* __loc = nullptr)
5657 {
5658 if constexpr (__contiguous_char_iter<_CharT, _Out>)
5659 {
5660 _Ptr_sink<_CharT> __sink(__out, __n);
5661 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5662 return std::move(__sink)._M_finish(__out);
5663 }
5664 else
5665 {
5666 _Iter_sink<_CharT, _Out> __sink(std::move(__out), __n);
5667 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5668 return std::move(__sink)._M_finish();
5669 }
5670 }
5671
5672#pragma GCC diagnostic pop
5673
5674} // namespace __format
5675/// @endcond
5676
5677 template<typename _CharT, typename... _Args>
5678 template<typename _Tp>
5679 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5680 consteval
5681 basic_format_string<_CharT, _Args...>::
5682 basic_format_string(const _Tp& __s) noexcept
5683 : _M_str(__s)
5684 {
5685 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5686 __scanner(_M_str);
5687 __scanner._M_scan();
5688 }
5689
5690 // [format.functions], formatting functions
5691
5692 template<typename _Out> requires output_iterator<_Out, const char&>
5693 [[__gnu__::__always_inline__]]
5694 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5695 vformat_to(_Out __out, string_view __fmt, format_args __args)
5696 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5697
5698#ifdef _GLIBCXX_USE_WCHAR_T
5699 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5700 [[__gnu__::__always_inline__]]
5701 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5702 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5703 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5704#endif
5705
5706 template<typename _Out> requires output_iterator<_Out, const char&>
5707 [[__gnu__::__always_inline__]]
5708 inline _Out
5709 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5710 format_args __args)
5711 {
5712 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5713 }
5714
5715#ifdef _GLIBCXX_USE_WCHAR_T
5716 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5717 [[__gnu__::__always_inline__]]
5718 inline _Out
5719 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5720 wformat_args __args)
5721 {
5722 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5723 }
5724#endif
5725
5726 [[nodiscard]]
5727 inline _GLIBCXX_CONSTEXPR_FORMAT string
5728 vformat(string_view __fmt, format_args __args)
5729 {
5730 __format::_Str_sink<char> __buf;
5731 std::vformat_to(__buf.out(), __fmt, __args);
5732 return std::move(__buf).get();
5733 }
5734
5735#ifdef _GLIBCXX_USE_WCHAR_T
5736 [[nodiscard]]
5737 inline _GLIBCXX_CONSTEXPR_FORMAT wstring
5738 vformat(wstring_view __fmt, wformat_args __args)
5739 {
5740 __format::_Str_sink<wchar_t> __buf;
5741 std::vformat_to(__buf.out(), __fmt, __args);
5742 return std::move(__buf).get();
5743 }
5744#endif
5745
5746 [[nodiscard]]
5747 inline string
5748 vformat(const locale& __loc, string_view __fmt, format_args __args)
5749 {
5750 __format::_Str_sink<char> __buf;
5751 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5752 return std::move(__buf).get();
5753 }
5754
5755#ifdef _GLIBCXX_USE_WCHAR_T
5756 [[nodiscard]]
5757 inline wstring
5758 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5759 {
5760 __format::_Str_sink<wchar_t> __buf;
5761 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5762 return std::move(__buf).get();
5763 }
5764#endif
5765
5766 template<typename... _Args>
5767 [[nodiscard]]
5768 inline _GLIBCXX_CONSTEXPR_FORMAT string
5769 format(format_string<_Args...> __fmt, _Args&&... __args)
5770 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5771
5772#ifdef _GLIBCXX_USE_WCHAR_T
5773 template<typename... _Args>
5774 [[nodiscard]]
5775 inline _GLIBCXX_CONSTEXPR_FORMAT wstring
5776 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5777 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5778#endif
5779
5780 template<typename... _Args>
5781 [[nodiscard]]
5782 inline string
5783 format(const locale& __loc, format_string<_Args...> __fmt,
5784 _Args&&... __args)
5785 {
5786 return std::vformat(__loc, __fmt.get(),
5787 std::make_format_args(__args...));
5788 }
5789
5790#ifdef _GLIBCXX_USE_WCHAR_T
5791 template<typename... _Args>
5792 [[nodiscard]]
5793 inline wstring
5794 format(const locale& __loc, wformat_string<_Args...> __fmt,
5795 _Args&&... __args)
5796 {
5797 return std::vformat(__loc, __fmt.get(),
5798 std::make_wformat_args(__args...));
5799 }
5800#endif
5801
5802 template<typename _Out, typename... _Args>
5803 requires output_iterator<_Out, const char&>
5804 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5805 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5806 {
5807 return std::vformat_to(std::move(__out), __fmt.get(),
5808 std::make_format_args(__args...));
5809 }
5810
5811#ifdef _GLIBCXX_USE_WCHAR_T
5812 template<typename _Out, typename... _Args>
5813 requires output_iterator<_Out, const wchar_t&>
5814 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5815 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5816 {
5817 return std::vformat_to(std::move(__out), __fmt.get(),
5818 std::make_wformat_args(__args...));
5819 }
5820#endif
5821
5822 template<typename _Out, typename... _Args>
5823 requires output_iterator<_Out, const char&>
5824 inline _Out
5825 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5826 _Args&&... __args)
5827 {
5828 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5829 std::make_format_args(__args...));
5830 }
5831
5832#ifdef _GLIBCXX_USE_WCHAR_T
5833 template<typename _Out, typename... _Args>
5834 requires output_iterator<_Out, const wchar_t&>
5835 inline _Out
5836 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5837 _Args&&... __args)
5838 {
5839 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5840 std::make_wformat_args(__args...));
5841 }
5842#endif
5843
5844 template<typename _Out, typename... _Args>
5845 requires output_iterator<_Out, const char&>
5846 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5847 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5848 format_string<_Args...> __fmt, _Args&&... __args)
5849 {
5850 return __format::__do_vformat_to_n(
5851 std::move(__out), __n, __fmt.get(),
5852 std::make_format_args(__args...));
5853 }
5854
5855#ifdef _GLIBCXX_USE_WCHAR_T
5856 template<typename _Out, typename... _Args>
5857 requires output_iterator<_Out, const wchar_t&>
5858 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5859 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5860 wformat_string<_Args...> __fmt, _Args&&... __args)
5861 {
5862 return __format::__do_vformat_to_n(
5863 std::move(__out), __n, __fmt.get(),
5864 std::make_wformat_args(__args...));
5865 }
5866#endif
5867
5868 template<typename _Out, typename... _Args>
5869 requires output_iterator<_Out, const char&>
5870 inline format_to_n_result<_Out>
5871 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5872 format_string<_Args...> __fmt, _Args&&... __args)
5873 {
5874 return __format::__do_vformat_to_n(
5875 std::move(__out), __n, __fmt.get(),
5876 std::make_format_args(__args...), &__loc);
5877 }
5878
5879#ifdef _GLIBCXX_USE_WCHAR_T
5880 template<typename _Out, typename... _Args>
5881 requires output_iterator<_Out, const wchar_t&>
5882 inline format_to_n_result<_Out>
5883 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5884 wformat_string<_Args...> __fmt, _Args&&... __args)
5885 {
5886 return __format::__do_vformat_to_n(
5887 std::move(__out), __n, __fmt.get(),
5888 std::make_wformat_args(__args...), &__loc);
5889 }
5890#endif
5891
5892/// @cond undocumented
5893namespace __format
5894{
5895#if 1
5896 template<typename _CharT>
5897 class _Counting_sink final : public _Ptr_sink<_CharT>
5898 {
5899 public:
5900 _GLIBCXX_CONSTEXPR_FORMAT
5901 _Counting_sink() : _Ptr_sink<_CharT>(nullptr, 0) { }
5902
5903 [[__gnu__::__always_inline__]]
5904 _GLIBCXX_CONSTEXPR_FORMAT size_t
5905 count() const
5906 { return this->_M_count + this->_M_used().size(); }
5907 };
5908#else
5909 template<typename _CharT>
5910 class _Counting_sink : public _Buf_sink<_CharT>
5911 {
5912 size_t _M_count = 0;
5913
5914 void
5915 _M_overflow() override
5916 {
5917 if (!std::is_constant_evaluated())
5918 _M_count += this->_M_used().size();
5919 this->_M_rewind();
5920 }
5921
5922 public:
5923 _Counting_sink() = default;
5924
5925 [[__gnu__::__always_inline__]]
5926 size_t
5927 count() noexcept
5928 {
5929 _Counting_sink::_M_overflow();
5930 return _M_count;
5931 }
5932 };
5933#endif
5934} // namespace __format
5935/// @endcond
5936
5937 template<typename... _Args>
5938 [[nodiscard]]
5939 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
5940 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5941 {
5942 __format::_Counting_sink<char> __buf;
5943 std::vformat_to(__buf.out(), __fmt.get(),
5944 std::make_format_args(__args...));
5945 return __buf.count();
5946 }
5947
5948#ifdef _GLIBCXX_USE_WCHAR_T
5949 template<typename... _Args>
5950 [[nodiscard]]
5951 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
5952 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5953 {
5954 __format::_Counting_sink<wchar_t> __buf;
5955 std::vformat_to(__buf.out(), __fmt.get(),
5956 std::make_wformat_args(__args...));
5957 return __buf.count();
5958 }
5959#endif
5960
5961 template<typename... _Args>
5962 [[nodiscard]]
5963 inline size_t
5964 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5965 _Args&&... __args)
5966 {
5967 __format::_Counting_sink<char> __buf;
5968 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5969 std::make_format_args(__args...));
5970 return __buf.count();
5971 }
5972
5973#ifdef _GLIBCXX_USE_WCHAR_T
5974 template<typename... _Args>
5975 [[nodiscard]]
5976 inline size_t
5977 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5978 _Args&&... __args)
5979 {
5980 __format::_Counting_sink<wchar_t> __buf;
5981 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5982 std::make_wformat_args(__args...));
5983 return __buf.count();
5984 }
5985#endif
5986
5987#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5988 /// @cond undocumented
5989 template<typename _Tp>
5990 consteval range_format
5991 __fmt_kind()
5992 {
5993 using _Ref = ranges::range_reference_t<_Tp>;
5994 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5995 return range_format::disabled;
5996 else if constexpr (requires { typename _Tp::key_type; })
5997 {
5998 if constexpr (requires { typename _Tp::mapped_type; })
5999 {
6000 using _Up = remove_cvref_t<_Ref>;
6001 if constexpr (__is_pair<_Up>)
6002 return range_format::map;
6003 else if constexpr (__is_specialization_of<_Up, tuple>)
6004 if constexpr (tuple_size_v<_Up> == 2)
6005 return range_format::map;
6006 }
6007 return range_format::set;
6008 }
6009 else
6010 return range_format::sequence;
6011 }
6012 /// @endcond
6013
6014 /// A constant determining how a range should be formatted.
6015 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
6016 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
6017
6018/// @cond undocumented
6019namespace __format
6020{
6021 template<typename _CharT, typename _Out, typename _Callback>
6022 _GLIBCXX_CONSTEXPR_FORMAT
6023 typename basic_format_context<_Out, _CharT>::iterator
6024 __format_padded(basic_format_context<_Out, _CharT>& __fc,
6025 const _Spec<_CharT>& __spec,
6026 _Callback&& __call)
6027 {
6028 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
6029 return __fc.out();
6030 else
6031 {
6032 // This is required to implement formatting with padding,
6033 // as we need to format to temporary buffer, using the same iterator.
6034 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
6035
6036 const size_t __padwidth = __spec._M_get_width(__fc);
6037 if (__padwidth == 0)
6038 return __call(__fc);
6039
6040 struct _Restore_out
6041 {
6042 _GLIBCXX_CONSTEXPR_FORMAT
6043 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
6044 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
6045 { }
6046
6047 _GLIBCXX_CONSTEXPR_FORMAT void
6048 _M_disarm()
6049 { _M_ctx = nullptr; }
6050
6051 _GLIBCXX_CONSTEXPR_FORMAT
6052 ~_Restore_out()
6053 {
6054 if (_M_ctx)
6055 _M_ctx->advance_to(_M_out);
6056 }
6057
6058 private:
6059 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
6060 _Sink_iter<_CharT> _M_out;
6061 };
6062
6063 _Restore_out __restore(__fc);
6064 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
6065 __fc.advance_to(__sink.out());
6066 __call(__fc);
6067 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
6068 __restore._M_disarm();
6069 return __fc.out();
6070 }
6071 }
6072
6073 template<size_t _Pos, typename _Tp, typename _CharT>
6074 struct __indexed_formatter_storage
6075 {
6076 constexpr void
6077 _M_parse()
6078 {
6079 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6080 // 3892. Incorrect formatting of nested ranges and tuples
6081 basic_format_parse_context<_CharT> __pc({});
6082 if (_M_formatter.parse(__pc) != __pc.end())
6083 __format::__failed_to_parse_format_spec();
6084 }
6085
6086 template<typename _Out>
6087 _GLIBCXX_CONSTEXPR_FORMAT void
6088 _M_format(__maybe_const<_Tp, _CharT>& __elem,
6089 basic_format_context<_Out, _CharT>& __fc,
6090 basic_string_view<_CharT> __sep) const
6091 {
6092 if constexpr (_Pos != 0)
6093 __fc.advance_to(__format::__write(__fc.out(), __sep));
6094 __fc.advance_to(_M_formatter.format(__elem, __fc));
6095 }
6096
6097 [[__gnu__::__always_inline__]]
6098 constexpr void
6099 set_debug_format()
6100 {
6101 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
6102 _M_formatter.set_debug_format();
6103 }
6104
6105 private:
6106 formatter<_Tp, _CharT> _M_formatter;
6107 };
6108
6109 template<typename _CharT, typename... _Tps>
6110 class __tuple_formatter
6111 {
6112 using _String_view = basic_string_view<_CharT>;
6113 using _Seps = __format::_Separators<_CharT>;
6114
6115 public:
6116 constexpr void
6117 set_separator(basic_string_view<_CharT> __sep) noexcept
6118 { _M_sep = __sep; }
6119
6120 constexpr void
6121 set_brackets(basic_string_view<_CharT> __open,
6122 basic_string_view<_CharT> __close) noexcept
6123 {
6124 _M_open = __open;
6125 _M_close = __close;
6126 }
6127
6128 // We deviate from standard, that declares this as template accepting
6129 // unconstrained ParseContext type, which seems unimplementable.
6130 constexpr typename basic_format_parse_context<_CharT>::iterator
6131 parse(basic_format_parse_context<_CharT>& __pc)
6132 {
6133 auto __first = __pc.begin();
6134 const auto __last = __pc.end();
6135 __format::_Spec<_CharT> __spec{};
6136
6137 auto __finished = [&]
6138 {
6139 if (__first != __last && *__first != '}')
6140 return false;
6141
6142 _M_spec = __spec;
6143 _M_felems._M_parse();
6144 _M_felems.set_debug_format();
6145 return true;
6146 };
6147
6148 if (__finished())
6149 return __first;
6150
6151 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6152 if (__finished())
6153 return __first;
6154
6155 __first = __spec._M_parse_width(__first, __last, __pc);
6156 if (__finished())
6157 return __first;
6158
6159 if (*__first == 'n')
6160 {
6161 ++__first;
6162 _M_open = _M_close = _String_view();
6163 }
6164 else if (*__first == 'm')
6165 {
6166 ++__first;
6167 if constexpr (sizeof...(_Tps) == 2)
6168 {
6169 _M_sep = _Seps::_S_colon();
6170 _M_open = _M_close = _String_view();
6171 }
6172 else
6173 __throw_format_error("format error: 'm' specifier requires range"
6174 " of pair or tuple of two elements");
6175 }
6176
6177 if (__finished())
6178 return __first;
6179
6180 __format::__failed_to_parse_format_spec();
6181 }
6182
6183 protected:
6184 template<typename _Tuple, typename _Out, size_t... _Ids>
6185 _GLIBCXX_CONSTEXPR_FORMAT
6186 typename basic_format_context<_Out, _CharT>::iterator
6187 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
6188 basic_format_context<_Out, _CharT>& __fc) const
6189 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
6190
6191 template<typename _Out>
6192 _GLIBCXX_CONSTEXPR_FORMAT
6193 typename basic_format_context<_Out, _CharT>::iterator
6194 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
6195 basic_format_context<_Out, _CharT>& __fc) const
6196 {
6197 return __format::__format_padded(
6198 __fc, _M_spec,
6199 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
6200 {
6201 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
6202 _M_felems._M_format(__elems..., __nfc, _M_sep);
6203 return __format::__write(__nfc.out(), _M_close);
6204 });
6205 }
6206
6207 private:
6208 template<size_t... _Ids>
6209 struct __formatters_storage
6210 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
6211 {
6212 template<size_t _Id, typename _Up>
6213 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
6214
6215 constexpr void
6216 _M_parse()
6217 {
6218 (_Base<_Ids, _Tps>::_M_parse(), ...);
6219 }
6220
6221 template<typename _Out>
6222 _GLIBCXX_CONSTEXPR_FORMAT void
6223 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
6224 basic_format_context<_Out, _CharT>& __fc,
6225 _String_view __sep) const
6226 {
6227 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
6228 }
6229
6230 constexpr void
6231 set_debug_format()
6232 {
6233 (_Base<_Ids, _Tps>::set_debug_format(), ...);
6234 }
6235 };
6236
6237 template<size_t... _Ids>
6238 static _GLIBCXX_CONSTEXPR_FORMAT auto
6239 _S_create_storage(index_sequence<_Ids...>)
6240 -> __formatters_storage<_Ids...>;
6241 using _Formatters
6242 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
6243
6244 _Spec<_CharT> _M_spec{};
6245 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
6246 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
6247 _String_view _M_sep = _Seps::_S_comma();
6248 _Formatters _M_felems;
6249 };
6250
6251 template<typename _Tp>
6252 concept __is_map_formattable
6253 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
6254
6255} // namespace __format
6256/// @endcond
6257
6258 // [format.tuple] Tuple formatter
6259 template<__format::__char _CharT, formattable<_CharT> _Fp,
6260 formattable<_CharT> _Sp>
6261 struct formatter<pair<_Fp, _Sp>, _CharT>
6262 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
6263 remove_cvref_t<_Sp>>
6264 {
6265 private:
6266 using __maybe_const_pair
6267 = __conditional_t<formattable<const _Fp, _CharT>
6268 && formattable<const _Sp, _CharT>,
6269 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
6270 public:
6271 // We deviate from standard, that declares this as template accepting
6272 // unconstrained FormatContext type, which seems unimplementable.
6273 template<typename _Out>
6274 _GLIBCXX_CONSTEXPR_FORMAT
6275 typename basic_format_context<_Out, _CharT>::iterator
6276 format(__maybe_const_pair& __p,
6277 basic_format_context<_Out, _CharT>& __fc) const
6278 { return this->_M_format_elems(__p.first, __p.second, __fc); }
6279 };
6280
6281#if __glibcxx_print >= 202406L
6282 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6283 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6284 template<typename _Fp, typename _Sp>
6285 constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
6286 = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
6287 && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
6288#endif
6289
6290 template<__format::__char _CharT, formattable<_CharT>... _Tps>
6291 struct formatter<tuple<_Tps...>, _CharT>
6292 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
6293 {
6294 private:
6295 using __maybe_const_tuple
6296 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
6297 const tuple<_Tps...>, tuple<_Tps...>>;
6298 public:
6299 // We deviate from standard, that declares this as template accepting
6300 // unconstrained FormatContext type, which seems unimplementable.
6301 template<typename _Out>
6302 _GLIBCXX_CONSTEXPR_FORMAT
6303 typename basic_format_context<_Out, _CharT>::iterator
6304 format(__maybe_const_tuple& __t,
6305 basic_format_context<_Out, _CharT>& __fc) const
6306 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
6307 };
6308
6309#if __glibcxx_print >= 202406L
6310 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6311 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6312 template<typename... _Tps>
6313 constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
6314 = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
6315#endif
6316
6317 // [format.range.formatter], class template range_formatter
6318 template<typename _Tp, __format::__char _CharT>
6319 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
6320 class range_formatter
6321 {
6322 using _String_view = basic_string_view<_CharT>;
6323 using _Seps = __format::_Separators<_CharT>;
6324
6325 public:
6326 constexpr void
6327 set_separator(basic_string_view<_CharT> __sep) noexcept
6328 { _M_sep = __sep; }
6329
6330 constexpr void
6331 set_brackets(basic_string_view<_CharT> __open,
6332 basic_string_view<_CharT> __close) noexcept
6333 {
6334 _M_open = __open;
6335 _M_close = __close;
6336 }
6337
6338 constexpr formatter<_Tp, _CharT>&
6339 underlying() noexcept
6340 { return _M_fval; }
6341
6342 constexpr const formatter<_Tp, _CharT>&
6343 underlying() const noexcept
6344 { return _M_fval; }
6345
6346 // We deviate from standard, that declares this as template accepting
6347 // unconstrained ParseContext type, which seems unimplementable.
6348 constexpr typename basic_format_parse_context<_CharT>::iterator
6349 parse(basic_format_parse_context<_CharT>& __pc)
6350 {
6351 auto __first = __pc.begin();
6352 const auto __last = __pc.end();
6353 __format::_Spec<_CharT> __spec{};
6354 bool __no_brace = false;
6355
6356 auto __finished = [&]
6357 { return __first == __last || *__first == '}'; };
6358
6359 auto __finalize = [&]
6360 {
6361 _M_spec = __spec;
6362 return __first;
6363 };
6364
6365 auto __parse_val = [&](_String_view __nfs = _String_view())
6366 {
6367 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6368 // 3892. Incorrect formatting of nested ranges and tuples
6369 basic_format_parse_context<_CharT> __npc(__nfs);
6370 if (_M_fval.parse(__npc) != __npc.end())
6371 __format::__failed_to_parse_format_spec();
6372 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
6373 _M_fval.set_debug_format();
6374 return __finalize();
6375 };
6376
6377 if (__finished())
6378 return __parse_val();
6379
6380 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6381 if (__finished())
6382 return __parse_val();
6383
6384 __first = __spec._M_parse_width(__first, __last, __pc);
6385 if (__finished())
6386 return __parse_val();
6387
6388 if (*__first == '?')
6389 {
6390 ++__first;
6391 __spec._M_debug = true;
6392 if (__finished() || *__first != 's')
6393 __throw_format_error("format error: '?' is allowed only in"
6394 " combination with 's'");
6395 }
6396
6397 if (*__first == 's')
6398 {
6399 ++__first;
6400 if constexpr (same_as<_Tp, _CharT>)
6401 {
6402 __spec._M_type = __format::_Pres_s;
6403 if (__finished())
6404 return __finalize();
6405 __throw_format_error("format error: element format specifier"
6406 " cannot be provided when 's' specifier is used");
6407 }
6408 else
6409 __throw_format_error("format error: 's' specifier requires"
6410 " range of character types");
6411 }
6412
6413 if (__finished())
6414 return __parse_val();
6415
6416 if (*__first == 'n')
6417 {
6418 ++__first;
6419 _M_open = _M_close = _String_view();
6420 __no_brace = true;
6421 }
6422
6423 if (__finished())
6424 return __parse_val();
6425
6426 if (*__first == 'm')
6427 {
6428 _String_view __m(__first, 1);
6429 ++__first;
6430 if constexpr (__format::__is_map_formattable<_Tp>)
6431 {
6432 _M_sep = _Seps::_S_comma();
6433 if (!__no_brace)
6434 {
6435 _M_open = _Seps::_S_braces().substr(0, 1);
6436 _M_close = _Seps::_S_braces().substr(1, 1);
6437 }
6438 if (__finished())
6439 return __parse_val(__m);
6440 __throw_format_error("format error: element format specifier"
6441 " cannot be provided when 'm' specifier is used");
6442 }
6443 else
6444 __throw_format_error("format error: 'm' specifier requires"
6445 " range of pairs or tuples of two elements");
6446 }
6447
6448 if (__finished())
6449 return __parse_val();
6450
6451 if (*__first == ':')
6452 {
6453 __pc.advance_to(++__first);
6454 __first = _M_fval.parse(__pc);
6455 }
6456
6457 if (__finished())
6458 return __finalize();
6459
6460 __format::__failed_to_parse_format_spec();
6461 }
6462
6463 // We deviate from standard, that declares this as template accepting
6464 // unconstrained FormatContext type, which seems unimplementable.
6465 template<ranges::input_range _Rg, typename _Out>
6466 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6467 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6468 _GLIBCXX_CONSTEXPR_FORMAT
6469 typename basic_format_context<_Out, _CharT>::iterator
6470 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6471 {
6472 using _Range = remove_reference_t<_Rg>;
6473 if constexpr (ranges::contiguous_range<_Rg>)
6474 {
6475 const span<__format::__maybe_const<_Tp, _CharT>>
6476 __spn(ranges::data(__rg), size_t(ranges::distance(__rg)));
6477 return _M_format(__spn, __fc);
6478 }
6479 else if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6480 return _M_format<const _Range>(__rg, __fc);
6481 else
6482 return _M_format(__rg, __fc);
6483 }
6484
6485 private:
6486 template<ranges::input_range _Rg, typename _Out>
6487 _GLIBCXX_CONSTEXPR_FORMAT
6488 typename basic_format_context<_Out, _CharT>::iterator
6489 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6490 {
6491 if constexpr (same_as<_Tp, _CharT>)
6492 if (_M_spec._M_type == __format::_Pres_s)
6493 {
6494 __format::__formatter_str __fstr(_M_spec);
6495 return __fstr._M_format_range(__rg, __fc);
6496 }
6497 return __format::__format_padded(
6498 __fc, _M_spec,
6499 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6500 { return _M_format_elems(__rg, __nfc); });
6501 }
6502
6503
6504 template<ranges::input_range _Rg, typename _Out>
6505 _GLIBCXX_CONSTEXPR_FORMAT
6506 typename basic_format_context<_Out, _CharT>::iterator
6507 _M_format_elems(_Rg& __rg,
6508 basic_format_context<_Out, _CharT>& __fc) const
6509 {
6510 auto __out = __format::__write(__fc.out(), _M_open);
6511
6512 auto __first = ranges::begin(__rg);
6513 auto const __last = ranges::end(__rg);
6514 if (__first == __last)
6515 return __format::__write(__out, _M_close);
6516
6517 __fc.advance_to(__out);
6518 __out = _M_fval.format(*__first, __fc);
6519 for (++__first; __first != __last; ++__first)
6520 {
6521 __out = __format::__write(__out, _M_sep);
6522 __fc.advance_to(__out);
6523 __out = _M_fval.format(*__first, __fc);
6524 }
6525
6526 return __format::__write(__out, _M_close);
6527 }
6528
6529 __format::_Spec<_CharT> _M_spec{};
6530 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6531 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6532 _String_view _M_sep = _Seps::_S_comma();
6533 formatter<_Tp, _CharT> _M_fval;
6534 };
6535
6536 // In standard this is shown as inheriting from specialization of
6537 // exposition only specialization for range-default-formatter for
6538 // each range_format. We opt for simpler implementation.
6539 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6540 // specializations for maps, sets, and strings
6541 template<ranges::input_range _Rg, __format::__char _CharT>
6542 requires (format_kind<_Rg> != range_format::disabled)
6543 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6544 struct formatter<_Rg, _CharT>
6545 {
6546 private:
6547 static const bool _S_range_format_is_string =
6548 (format_kind<_Rg> == range_format::string)
6549 || (format_kind<_Rg> == range_format::debug_string);
6550 using _Vt = remove_cvref_t<
6551 ranges::range_reference_t<
6552 __format::__maybe_const_range<_Rg, _CharT>>>;
6553
6554 static consteval bool _S_is_correct()
6555 {
6556 if constexpr (_S_range_format_is_string)
6557 static_assert(same_as<_Vt, _CharT>);
6558 return true;
6559 }
6560
6561 static_assert(_S_is_correct());
6562
6563 public:
6564 constexpr formatter() noexcept
6565 {
6566 using _Seps = __format::_Separators<_CharT>;
6567 if constexpr (format_kind<_Rg> == range_format::map)
6568 {
6569 static_assert(__format::__is_map_formattable<_Vt>);
6570 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6571 _Seps::_S_braces().substr(1, 1));
6572 _M_under.underlying().set_brackets({}, {});
6573 _M_under.underlying().set_separator(_Seps::_S_colon());
6574 }
6575 else if constexpr (format_kind<_Rg> == range_format::set)
6576 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6577 _Seps::_S_braces().substr(1, 1));
6578 }
6579
6580 constexpr void
6581 set_separator(basic_string_view<_CharT> __sep) noexcept
6582 requires (format_kind<_Rg> == range_format::sequence)
6583 { _M_under.set_separator(__sep); }
6584
6585 constexpr void
6586 set_brackets(basic_string_view<_CharT> __open,
6587 basic_string_view<_CharT> __close) noexcept
6588 requires (format_kind<_Rg> == range_format::sequence)
6589 { _M_under.set_brackets(__open, __close); }
6590
6591 // We deviate from standard, that declares this as template accepting
6592 // unconstrained ParseContext type, which seems unimplementable.
6593 constexpr typename basic_format_parse_context<_CharT>::iterator
6594 parse(basic_format_parse_context<_CharT>& __pc)
6595 {
6596 auto __res = _M_under.parse(__pc);
6597 if constexpr (format_kind<_Rg> == range_format::debug_string)
6598 _M_under.set_debug_format();
6599 return __res;
6600 }
6601
6602 // We deviate from standard, that declares this as template accepting
6603 // unconstrained FormatContext type, which seems unimplementable.
6604 template<typename _Out>
6605 _GLIBCXX_CONSTEXPR_FORMAT
6606 typename basic_format_context<_Out, _CharT>::iterator
6607 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6608 basic_format_context<_Out, _CharT>& __fc) const
6609 {
6610 if constexpr (_S_range_format_is_string)
6611 return _M_under._M_format_range(__rg, __fc);
6612 else
6613 return _M_under.format(__rg, __fc);
6614 }
6615
6616 private:
6617 using _Formatter_under
6618 = __conditional_t<_S_range_format_is_string,
6619 __format::__formatter_str<_CharT>,
6620 range_formatter<_Vt, _CharT>>;
6621 _Formatter_under _M_under;
6622 };
6623
6624#if __glibcxx_print >= 202406L
6625 template<ranges::input_range _Rg>
6626 requires (format_kind<_Rg> != range_format::disabled)
6627 constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6628#endif
6629
6630#endif // C++23 formatting ranges
6631#undef _GLIBCXX_WIDEN
6632#undef _GLIBCXX_CONSTEXPR_FORMAT
6633
6634_GLIBCXX_END_NAMESPACE_VERSION
6635} // namespace std
6636#endif // __cpp_lib_format
6637#pragma GCC diagnostic pop
6638#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.
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:73
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.