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