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 <variant> // monostate (TODO: move to bits/utility.h?)
55#include <bits/ranges_base.h> // input_range, range_reference_t
56#include <bits/ranges_util.h> // subrange
57#include <bits/ranges_algobase.h> // ranges::copy
58#include <bits/stl_iterator.h> // back_insert_iterator
59#include <bits/stl_pair.h> // __is_pair
60#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
61#include <bits/utility.h> // tuple_size_v
62#include <ext/numeric_traits.h> // __int_traits
63
64#if !__has_builtin(__builtin_toupper)
65# include <cctype>
66#endif
67
68#pragma GCC diagnostic push
69#pragma GCC diagnostic ignored "-Wpedantic" // __int128
70#pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
71
72namespace std _GLIBCXX_VISIBILITY(default)
73{
74_GLIBCXX_BEGIN_NAMESPACE_VERSION
75
76 // [format.context], class template basic_format_context
77 template<typename _Out, typename _CharT> class basic_format_context;
78
79 // [format.fmt.string], class template basic_format_string
80 template<typename _CharT, typename... _Args> struct basic_format_string;
81
82/// @cond undocumented
83namespace __format
84{
85 // Type-erased character sink.
86 template<typename _CharT> class _Sink;
87 // Output iterator that writes to a type-erase character sink.
88 template<typename _CharT>
89 class _Sink_iter;
90
91 template<typename _CharT>
92 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
93
94 template<typename _CharT>
95 struct _Runtime_format_string
96 {
97 [[__gnu__::__always_inline__]]
98 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
99 : _M_str(__s) { }
100
101 _Runtime_format_string(const _Runtime_format_string&) = delete;
102 void operator=(const _Runtime_format_string&) = delete;
103
104 private:
105 basic_string_view<_CharT> _M_str;
106
107 template<typename, typename...> friend struct std::basic_format_string;
108 };
109} // namespace __format
110/// @endcond
111
112 using format_context = __format::__format_context<char>;
113#ifdef _GLIBCXX_USE_WCHAR_T
114 using wformat_context = __format::__format_context<wchar_t>;
115#endif
116
117 // [format.args], class template basic_format_args
118 template<typename _Context> class basic_format_args;
119 using format_args = basic_format_args<format_context>;
120#ifdef _GLIBCXX_USE_WCHAR_T
121 using wformat_args = basic_format_args<wformat_context>;
122#endif
123
124 // [format.arguments], arguments
125 // [format.arg], class template basic_format_arg
126 template<typename _Context>
127 class basic_format_arg;
128
129 /** A compile-time checked format string for the specified argument types.
130 *
131 * @since C++23 but available as an extension in C++20.
132 */
133 template<typename _CharT, typename... _Args>
134 struct basic_format_string
135 {
136 template<typename _Tp>
137 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
138 consteval
139 basic_format_string(const _Tp& __s);
140
141 [[__gnu__::__always_inline__]]
142 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
143 : _M_str(__s._M_str)
144 { }
145
146 [[__gnu__::__always_inline__]]
147 constexpr basic_string_view<_CharT>
148 get() const noexcept
149 { return _M_str; }
150
151 private:
152 basic_string_view<_CharT> _M_str;
153 };
154
155 template<typename... _Args>
156 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
157
158#ifdef _GLIBCXX_USE_WCHAR_T
159 template<typename... _Args>
160 using wformat_string
161 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
162#endif
163
164#if __cpp_lib_format >= 202311L // >= C++26
165 [[__gnu__::__always_inline__]]
166 inline __format::_Runtime_format_string<char>
167 runtime_format(string_view __fmt) noexcept
168 { return __fmt; }
169
170#ifdef _GLIBCXX_USE_WCHAR_T
171 [[__gnu__::__always_inline__]]
172 inline __format::_Runtime_format_string<wchar_t>
173 runtime_format(wstring_view __fmt) noexcept
174 { return __fmt; }
175#endif
176#endif // C++26
177
178 // [format.formatter], formatter
179
180 /// The primary template of std::formatter is disabled.
181 template<typename _Tp, typename _CharT = char>
182 struct formatter
183 {
184 formatter() = delete; // No std::formatter specialization for this type.
185 formatter(const formatter&) = delete;
186 formatter& operator=(const formatter&) = delete;
187 };
188
189 // [format.error], class format_error
190 class format_error : public runtime_error
191 {
192 public:
193 explicit format_error(const string& __what) : runtime_error(__what) { }
194 explicit format_error(const char* __what) : runtime_error(__what) { }
195 };
196
197 /// @cond undocumented
198 [[noreturn]]
199 inline void
200 __throw_format_error(const char* __what)
201 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
202
203namespace __format
204{
205 // XXX use named functions for each constexpr error?
206
207 [[noreturn]]
208 inline void
209 __unmatched_left_brace_in_format_string()
210 { __throw_format_error("format error: unmatched '{' in format string"); }
211
212 [[noreturn]]
213 inline void
214 __unmatched_right_brace_in_format_string()
215 { __throw_format_error("format error: unmatched '}' in format string"); }
216
217 [[noreturn]]
218 inline void
219 __conflicting_indexing_in_format_string()
220 { __throw_format_error("format error: conflicting indexing style in format string"); }
221
222 [[noreturn]]
223 inline void
224 __invalid_arg_id_in_format_string()
225 { __throw_format_error("format error: invalid arg-id in format string"); }
226
227 [[noreturn]]
228 inline void
229 __failed_to_parse_format_spec()
230 { __throw_format_error("format error: failed to parse format-spec"); }
231
232 template<typename _CharT> class _Scanner;
233
234} // namespace __format
235 /// @endcond
236
237 // [format.parse.ctx], class template basic_format_parse_context
238 template<typename _CharT> class basic_format_parse_context;
239 using format_parse_context = basic_format_parse_context<char>;
240#ifdef _GLIBCXX_USE_WCHAR_T
241 using wformat_parse_context = basic_format_parse_context<wchar_t>;
242#endif
243
244 template<typename _CharT>
245 class basic_format_parse_context
246 {
247 public:
248 using char_type = _CharT;
249 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
250 using iterator = const_iterator;
251
252 constexpr explicit
253 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
254 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
255 { }
256
257 basic_format_parse_context(const basic_format_parse_context&) = delete;
258 void operator=(const basic_format_parse_context&) = delete;
259
260 constexpr const_iterator begin() const noexcept { return _M_begin; }
261 constexpr const_iterator end() const noexcept { return _M_end; }
262
263 constexpr void
264 advance_to(const_iterator __it) noexcept
265 { _M_begin = __it; }
266
267 constexpr size_t
268 next_arg_id()
269 {
270 if (_M_indexing == _Manual)
271 __format::__conflicting_indexing_in_format_string();
272 _M_indexing = _Auto;
273
274 // _GLIBCXX_RESOLVE_LIB_DEFECTS
275 // 3825. Missing compile-time argument id check in next_arg_id
276 if (std::is_constant_evaluated())
277 if (_M_next_arg_id == _M_num_args)
278 __format::__invalid_arg_id_in_format_string();
279 return _M_next_arg_id++;
280 }
281
282 constexpr void
283 check_arg_id(size_t __id)
284 {
285 if (_M_indexing == _Auto)
286 __format::__conflicting_indexing_in_format_string();
287 _M_indexing = _Manual;
288
289 if (std::is_constant_evaluated())
290 if (__id >= _M_num_args)
291 __format::__invalid_arg_id_in_format_string();
292 }
293
294#if __cpp_lib_format >= 202305L
295 template<typename... _Ts>
296 constexpr void
297 check_dynamic_spec(size_t __id) noexcept;
298
299 constexpr void
300 check_dynamic_spec_integral(size_t __id) noexcept
301 {
302 check_dynamic_spec<int, unsigned, long long, unsigned long long>(__id);
303 }
304
305 constexpr void
306 check_dynamic_spec_string(size_t __id) noexcept
307 {
308 check_dynamic_spec<const char_type*, basic_string_view<_CharT>>(__id);
309 }
310
311 private:
312 // Check the Mandates: condition for check_dynamic_spec<Ts...>(n)
313 template<typename... _Ts>
314 static consteval bool
315 __check_dynamic_spec_types()
316 {
317 if constexpr (sizeof...(_Ts))
318 {
319 int __counts[] = {
320 (is_same_v<bool, _Ts> + ...),
321 (is_same_v<_CharT, _Ts> + ...),
322 (is_same_v<int, _Ts> + ...),
323 (is_same_v<unsigned, _Ts> + ...),
324 (is_same_v<long long, _Ts> + ...),
325 (is_same_v<unsigned long long, _Ts> + ...),
326 (is_same_v<float, _Ts> + ...),
327 (is_same_v<double, _Ts> + ...),
328 (is_same_v<long double, _Ts> + ...),
329 (is_same_v<const _CharT*, _Ts> + ...),
330 (is_same_v<basic_string_view<_CharT>, _Ts> + ...),
331 (is_same_v<const void*, _Ts> + ...)
332 };
333 int __sum = 0;
334 for (int __c : __counts)
335 {
336 __sum += __c;
337 if (__c > 1)
338 __invalid_dynamic_spec("non-unique template argument type");
339 }
340 if (__sum != sizeof...(_Ts))
341 __invalid_dynamic_spec("disallowed template argument type");
342 }
343 return true;
344 }
345
346 // This must not be constexpr.
347 static void __invalid_dynamic_spec(const char*);
348
349 friend __format::_Scanner<_CharT>;
350#endif
351
352 // This constructor should only be used by the implementation.
353 constexpr explicit
354 basic_format_parse_context(basic_string_view<_CharT> __fmt,
355 size_t __num_args) noexcept
356 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
357 { }
358
359 private:
360 iterator _M_begin;
361 iterator _M_end;
362 enum _Indexing { _Unknown, _Manual, _Auto };
363 _Indexing _M_indexing = _Unknown;
364 size_t _M_next_arg_id = 0;
365 size_t _M_num_args = 0;
366 };
367
368/// @cond undocumented
369 template<typename _Tp, template<typename...> class _Class>
370 constexpr bool __is_specialization_of = false;
371 template<template<typename...> class _Class, typename... _Args>
372 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
373
374namespace __format
375{
376 // pre: first != last
377 template<typename _CharT>
378 constexpr pair<unsigned short, const _CharT*>
379 __parse_integer(const _CharT* __first, const _CharT* __last)
380 {
381 if (__first == __last)
382 __builtin_unreachable();
383
384 if constexpr (is_same_v<_CharT, char>)
385 {
386 const auto __start = __first;
387 unsigned short __val = 0;
388 // N.B. std::from_chars is not constexpr in C++20.
389 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
390 && __first != __start) [[likely]]
391 return {__val, __first};
392 }
393 else
394 {
395 constexpr int __n = 32;
396 char __buf[__n]{};
397 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
398 __buf[__i] = __first[__i];
399 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
400 if (__ptr) [[likely]]
401 return {__v, __first + (__ptr - __buf)};
402 }
403 return {0, nullptr};
404 }
405
406 template<typename _CharT>
407 constexpr pair<unsigned short, const _CharT*>
408 __parse_arg_id(const _CharT* __first, const _CharT* __last)
409 {
410 if (__first == __last)
411 __builtin_unreachable();
412
413 if (*__first == '0')
414 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
415
416 if ('1' <= *__first && *__first <= '9')
417 {
418 const unsigned short __id = *__first - '0';
419 const auto __next = __first + 1;
420 // Optimize for most likely case of single digit arg-id.
421 if (__next == __last || !('0' <= *__next && *__next <= '9'))
422 return {__id, __next};
423 else
424 return __format::__parse_integer(__first, __last);
425 }
426 return {0, nullptr};
427 }
428
429 enum _Pres_type {
430 _Pres_none = 0, // Default type (not valid for integer presentation types).
431 // Presentation types for integral types (including bool and charT).
432 _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
433 // Presentation types for floating-point types.
434 _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
435 _Pres_p = 0, _Pres_P, // For pointers.
436 _Pres_s = 0, // For strings and bool.
437 _Pres_esc = 0xf, // For strings and charT.
438 };
439
440 enum _Align {
441 _Align_default,
442 _Align_left,
443 _Align_right,
444 _Align_centre,
445 };
446
447 enum _Sign {
448 _Sign_default,
449 _Sign_plus,
450 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
451 _Sign_space,
452 };
453
454 enum _WidthPrec {
455 _WP_none, // No width/prec specified.
456 _WP_value, // Fixed width/prec specified.
457 _WP_from_arg // Use a formatting argument for width/prec.
458 };
459
460 template<typename _Context>
461 size_t
462 __int_from_arg(const basic_format_arg<_Context>& __arg);
463
464 constexpr bool __is_digit(char __c)
465 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
466
467 constexpr bool __is_xdigit(char __c)
468 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
469
470 template<typename _CharT>
471 struct _Spec
472 {
473 _Align _M_align : 2;
474 _Sign _M_sign : 2;
475 unsigned _M_alt : 1;
476 unsigned _M_localized : 1;
477 unsigned _M_zero_fill : 1;
478 _WidthPrec _M_width_kind : 2;
479 _WidthPrec _M_prec_kind : 2;
480 _Pres_type _M_type : 4;
481 unsigned _M_reserved : 1;
482 unsigned _M_reserved2 : 16;
483 unsigned short _M_width;
484 unsigned short _M_prec;
485 char32_t _M_fill = ' ';
486
487 using iterator = typename basic_string_view<_CharT>::iterator;
488
489 static constexpr _Align
490 _S_align(_CharT __c) noexcept
491 {
492 switch (__c)
493 {
494 case '<': return _Align_left;
495 case '>': return _Align_right;
496 case '^': return _Align_centre;
497 default: return _Align_default;
498 }
499 }
500
501 // pre: __first != __last
502 constexpr iterator
503 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
504 {
505 if (*__first != '{')
506 {
507 using namespace __unicode;
508 if constexpr (__literal_encoding_is_unicode<_CharT>())
509 {
510 // Accept any UCS scalar value as fill character.
511 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
512 if (!__uv.empty())
513 {
514 auto __beg = __uv.begin();
515 char32_t __c = *__beg++;
516 if (__is_scalar_value(__c))
517 if (auto __next = __beg.base(); __next != __last)
518 if (_Align __align = _S_align(*__next))
519 {
520 _M_fill = __c;
521 _M_align = __align;
522 return ++__next;
523 }
524 }
525 }
526 else if (__last - __first >= 2)
527 if (_Align __align = _S_align(__first[1]))
528 {
529 _M_fill = *__first;
530 _M_align = __align;
531 return __first + 2;
532 }
533
534 if (_Align __align = _S_align(__first[0]))
535 {
536 _M_fill = ' ';
537 _M_align = __align;
538 return __first + 1;
539 }
540 }
541 return __first;
542 }
543
544 static constexpr _Sign
545 _S_sign(_CharT __c) noexcept
546 {
547 switch (__c)
548 {
549 case '+': return _Sign_plus;
550 case '-': return _Sign_minus;
551 case ' ': return _Sign_space;
552 default: return _Sign_default;
553 }
554 }
555
556 // pre: __first != __last
557 constexpr iterator
558 _M_parse_sign(iterator __first, iterator) noexcept
559 {
560 if (_Sign __sign = _S_sign(*__first))
561 {
562 _M_sign = __sign;
563 return __first + 1;
564 }
565 return __first;
566 }
567
568 // pre: *__first is valid
569 constexpr iterator
570 _M_parse_alternate_form(iterator __first, iterator) noexcept
571 {
572 if (*__first == '#')
573 {
574 _M_alt = true;
575 ++__first;
576 }
577 return __first;
578 }
579
580 // pre: __first != __last
581 constexpr iterator
582 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
583 {
584 if (*__first == '0')
585 {
586 _M_zero_fill = true;
587 ++__first;
588 }
589 return __first;
590 }
591
592 // pre: __first != __last
593 static constexpr iterator
594 _S_parse_width_or_precision(iterator __first, iterator __last,
595 unsigned short& __val, bool& __arg_id,
596 basic_format_parse_context<_CharT>& __pc)
597 {
598 if (__format::__is_digit(*__first))
599 {
600 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
601 if (!__ptr)
602 __throw_format_error("format error: invalid width or precision "
603 "in format-spec");
604 __first = __ptr;
605 __val = __v;
606 }
607 else if (*__first == '{')
608 {
609 __arg_id = true;
610 ++__first;
611 if (__first == __last)
612 __format::__unmatched_left_brace_in_format_string();
613 if (*__first == '}')
614 __val = __pc.next_arg_id();
615 else
616 {
617 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
618 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
619 __format::__invalid_arg_id_in_format_string();
620 __first = __ptr;
621 __pc.check_arg_id(__v);
622 __val = __v;
623 }
624#if __cpp_lib_format >= 202305L
625 __pc.check_dynamic_spec_integral(__val);
626#endif
627 ++__first; // past the '}'
628 }
629 return __first;
630 }
631
632 // pre: __first != __last
633 constexpr iterator
634 _M_parse_width(iterator __first, iterator __last,
635 basic_format_parse_context<_CharT>& __pc)
636 {
637 bool __arg_id = false;
638 if (*__first == '0')
639 __throw_format_error("format error: width must be non-zero in "
640 "format string");
641 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
642 __arg_id, __pc);
643 if (__next != __first)
644 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
645 return __next;
646 }
647
648 // pre: __first != __last
649 constexpr iterator
650 _M_parse_precision(iterator __first, iterator __last,
651 basic_format_parse_context<_CharT>& __pc)
652 {
653 if (__first[0] != '.')
654 return __first;
655
656 iterator __next = ++__first;
657 bool __arg_id = false;
658 if (__next != __last)
659 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
660 __arg_id, __pc);
661 if (__next == __first)
662 __throw_format_error("format error: missing precision after '.' in "
663 "format string");
664 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
665 return __next;
666 }
667
668 // pre: __first != __last
669 constexpr iterator
670 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
671 {
672 if (*__first == 'L')
673 {
674 _M_localized = true;
675 ++__first;
676 }
677 return __first;
678 }
679
680 template<typename _Context>
681 size_t
682 _M_get_width(_Context& __ctx) const
683 {
684 size_t __width = 0;
685 if (_M_width_kind == _WP_value)
686 __width = _M_width;
687 else if (_M_width_kind == _WP_from_arg)
688 __width = __format::__int_from_arg(__ctx.arg(_M_width));
689 return __width;
690 }
691
692 template<typename _Context>
693 size_t
694 _M_get_precision(_Context& __ctx) const
695 {
696 size_t __prec = -1;
697 if (_M_prec_kind == _WP_value)
698 __prec = _M_prec;
699 else if (_M_prec_kind == _WP_from_arg)
700 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
701 return __prec;
702 }
703 };
704
705 template<typename _Int>
706 inline char*
707 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
708 {
709 if (__i < 0)
710 *__dest = '-';
711 else if (__sign == _Sign_plus)
712 *__dest = '+';
713 else if (__sign == _Sign_space)
714 *__dest = ' ';
715 else
716 ++__dest;
717 return __dest;
718 }
719
720 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
721 template<typename _Out, typename _CharT>
722 requires output_iterator<_Out, const _CharT&>
723 inline _Out
724 __write(_Out __out, basic_string_view<_CharT> __str)
725 {
726 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
727 {
728 if (__str.size())
729 __out = __str;
730 }
731 else
732 for (_CharT __c : __str)
733 *__out++ = __c;
734 return __out;
735 }
736
737 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
738 // pre: __align != _Align_default
739 template<typename _Out, typename _CharT>
740 _Out
741 __write_padded(_Out __out, basic_string_view<_CharT> __str,
742 _Align __align, size_t __nfill, char32_t __fill_char)
743 {
744 const size_t __buflen = 0x20;
745 _CharT __padding_chars[__buflen];
746 __padding_chars[0] = _CharT();
747 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
748
749 auto __pad = [&__padding] (size_t __n, _Out& __o) {
750 if (__n == 0)
751 return;
752 while (__n > __padding.size())
753 {
754 __o = __format::__write(std::move(__o), __padding);
755 __n -= __padding.size();
756 }
757 if (__n != 0)
758 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
759 };
760
761 size_t __l, __r, __max;
762 if (__align == _Align_centre)
763 {
764 __l = __nfill / 2;
765 __r = __l + (__nfill & 1);
766 __max = __r;
767 }
768 else if (__align == _Align_right)
769 {
770 __l = __nfill;
771 __r = 0;
772 __max = __l;
773 }
774 else
775 {
776 __l = 0;
777 __r = __nfill;
778 __max = __r;
779 }
780
781 using namespace __unicode;
782 if constexpr (__literal_encoding_is_unicode<_CharT>())
783 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
784 {
785 // Encode fill char as multiple code units of type _CharT.
786 const char32_t __arr[1]{ __fill_char };
787 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
788 basic_string<_CharT> __padstr(__v.begin(), __v.end());
789 __padding = __padstr;
790 while (__l-- > 0)
791 __out = __format::__write(std::move(__out), __padding);
792 __out = __format::__write(std::move(__out), __str);
793 while (__r-- > 0)
794 __out = __format::__write(std::move(__out), __padding);
795 return __out;
796 }
797
798 if (__max < __buflen)
799 __padding.remove_suffix(__buflen - __max);
800 else
801 __max = __buflen;
802
803 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
804 __pad(__l, __out);
805 __out = __format::__write(std::move(__out), __str);
806 __pad(__r, __out);
807
808 return __out;
809 }
810
811 // Write STR to OUT, with alignment and padding as determined by SPEC.
812 // pre: __spec._M_align != _Align_default || __align != _Align_default
813 template<typename _CharT, typename _Out>
814 _Out
815 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
816 size_t __estimated_width,
817 basic_format_context<_Out, _CharT>& __fc,
818 const _Spec<_CharT>& __spec,
819 _Align __align = _Align_left)
820 {
821 size_t __width = __spec._M_get_width(__fc);
822
823 if (__width <= __estimated_width)
824 return __format::__write(__fc.out(), __str);
825
826 const size_t __nfill = __width - __estimated_width;
827
828 if (__spec._M_align)
829 __align = __spec._M_align;
830
831 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
832 __spec._M_fill);
833 }
834
835 // A lightweight optional<locale>.
836 struct _Optional_locale
837 {
838 [[__gnu__::__always_inline__]]
839 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
840
841 _Optional_locale(const locale& __loc) noexcept
842 : _M_loc(__loc), _M_hasval(true)
843 { }
844
845 _Optional_locale(const _Optional_locale& __l) noexcept
846 : _M_dummy(), _M_hasval(__l._M_hasval)
847 {
848 if (_M_hasval)
849 std::construct_at(&_M_loc, __l._M_loc);
850 }
851
852 _Optional_locale&
853 operator=(const _Optional_locale& __l) noexcept
854 {
855 if (_M_hasval)
856 {
857 if (__l._M_hasval)
858 _M_loc = __l._M_loc;
859 else
860 {
861 _M_loc.~locale();
862 _M_hasval = false;
863 }
864 }
865 else if (__l._M_hasval)
866 {
867 std::construct_at(&_M_loc, __l._M_loc);
868 _M_hasval = true;
869 }
870 return *this;
871 }
872
873 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
874
875 _Optional_locale&
876 operator=(locale&& __loc) noexcept
877 {
878 if (_M_hasval)
879 _M_loc = std::move(__loc);
880 else
881 {
882 std::construct_at(&_M_loc, std::move(__loc));
883 _M_hasval = true;
884 }
885 return *this;
886 }
887
888 const locale&
889 value() noexcept
890 {
891 if (!_M_hasval)
892 {
893 std::construct_at(&_M_loc);
894 _M_hasval = true;
895 }
896 return _M_loc;
897 }
898
899 bool has_value() const noexcept { return _M_hasval; }
900
901 union {
902 char _M_dummy = '\0';
903 std::locale _M_loc;
904 };
905 bool _M_hasval = false;
906 };
907
908#ifdef _GLIBCXX_USE_WCHAR_T
909 template<typename _CharT>
910 concept __char = same_as<_CharT, char> || same_as<_CharT, wchar_t>;
911#else
912 template<typename _CharT>
913 concept __char = same_as<_CharT, char>;
914#endif
915
916 template<__char _CharT>
917 struct __formatter_str
918 {
919 constexpr typename basic_format_parse_context<_CharT>::iterator
920 parse(basic_format_parse_context<_CharT>& __pc)
921 {
922 auto __first = __pc.begin();
923 const auto __last = __pc.end();
924 _Spec<_CharT> __spec{};
925
926 auto __finalize = [this, &__spec] {
927 _M_spec = __spec;
928 };
929
930 auto __finished = [&] {
931 if (__first == __last || *__first == '}')
932 {
933 __finalize();
934 return true;
935 }
936 return false;
937 };
938
939 if (__finished())
940 return __first;
941
942 __first = __spec._M_parse_fill_and_align(__first, __last);
943 if (__finished())
944 return __first;
945
946 __first = __spec._M_parse_width(__first, __last, __pc);
947 if (__finished())
948 return __first;
949
950 __first = __spec._M_parse_precision(__first, __last, __pc);
951 if (__finished())
952 return __first;
953
954 if (*__first == 's')
955 ++__first;
956#if __cpp_lib_format_ranges
957 else if (*__first == '?')
958 {
959 __spec._M_type = _Pres_esc;
960 ++__first;
961 }
962#endif
963
964 if (__finished())
965 return __first;
966
967 __format::__failed_to_parse_format_spec();
968 }
969
970 template<typename _Out>
971 _Out
972 format(basic_string_view<_CharT> __s,
973 basic_format_context<_Out, _CharT>& __fc) const
974 {
975 if (_M_spec._M_type == _Pres_esc)
976 {
977 // TODO: C++23 escaped string presentation
978 }
979
980 if (_M_spec._M_width_kind == _WP_none
981 && _M_spec._M_prec_kind == _WP_none)
982 return __format::__write(__fc.out(), __s);
983
984 size_t __estimated_width;
985 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
986 {
987 if (_M_spec._M_prec_kind != _WP_none)
988 {
989 size_t __prec = _M_spec._M_get_precision(__fc);
990 __estimated_width = __unicode::__truncate(__s, __prec);
991 }
992 else
993 __estimated_width = __unicode::__field_width(__s);
994 }
995 else
996 {
997 __s = __s.substr(0, _M_spec._M_get_precision(__fc));
998 __estimated_width = __s.size();
999 }
1000
1001 return __format::__write_padded_as_spec(__s, __estimated_width,
1002 __fc, _M_spec);
1003 }
1004
1005#if __cpp_lib_format_ranges
1006 constexpr void
1007 set_debug_format() noexcept
1008 { _M_spec._M_type = _Pres_esc; }
1009#endif
1010
1011 private:
1012 _Spec<_CharT> _M_spec{};
1013 };
1014
1015 template<__char _CharT>
1016 struct __formatter_int
1017 {
1018 // If no presentation type is specified, meaning of "none" depends
1019 // whether we are formatting an integer or a char or a bool.
1020 static constexpr _Pres_type _AsInteger = _Pres_d;
1021 static constexpr _Pres_type _AsBool = _Pres_s;
1022 static constexpr _Pres_type _AsChar = _Pres_c;
1023
1024 constexpr typename basic_format_parse_context<_CharT>::iterator
1025 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1026 {
1027 _Spec<_CharT> __spec{};
1028 __spec._M_type = __type;
1029
1030 const auto __last = __pc.end();
1031 auto __first = __pc.begin();
1032
1033 auto __finalize = [this, &__spec] {
1034 _M_spec = __spec;
1035 };
1036
1037 auto __finished = [&] {
1038 if (__first == __last || *__first == '}')
1039 {
1040 __finalize();
1041 return true;
1042 }
1043 return false;
1044 };
1045
1046 if (__finished())
1047 return __first;
1048
1049 __first = __spec._M_parse_fill_and_align(__first, __last);
1050 if (__finished())
1051 return __first;
1052
1053 __first = __spec._M_parse_sign(__first, __last);
1054 if (__finished())
1055 return __first;
1056
1057 __first = __spec._M_parse_alternate_form(__first, __last);
1058 if (__finished())
1059 return __first;
1060
1061 __first = __spec._M_parse_zero_fill(__first, __last);
1062 if (__finished())
1063 return __first;
1064
1065 __first = __spec._M_parse_width(__first, __last, __pc);
1066 if (__finished())
1067 return __first;
1068
1069 __first = __spec._M_parse_locale(__first, __last);
1070 if (__finished())
1071 return __first;
1072
1073 switch (*__first)
1074 {
1075 case 'b':
1076 __spec._M_type = _Pres_b;
1077 ++__first;
1078 break;
1079 case 'B':
1080 __spec._M_type = _Pres_B;
1081 ++__first;
1082 break;
1083 case 'c':
1084 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1085 // 3586. format should not print bool with 'c'
1086 if (__type != _AsBool)
1087 {
1088 __spec._M_type = _Pres_c;
1089 ++__first;
1090 }
1091 break;
1092 case 'd':
1093 __spec._M_type = _Pres_d;
1094 ++__first;
1095 break;
1096 case 'o':
1097 __spec._M_type = _Pres_o;
1098 ++__first;
1099 break;
1100 case 'x':
1101 __spec._M_type = _Pres_x;
1102 ++__first;
1103 break;
1104 case 'X':
1105 __spec._M_type = _Pres_X;
1106 ++__first;
1107 break;
1108 case 's':
1109 if (__type == _AsBool)
1110 {
1111 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1112 ++__first;
1113 }
1114 break;
1115#if __cpp_lib_format_ranges
1116 case '?':
1117 if (__type == _AsChar)
1118 {
1119 __spec._M_type = _Pres_esc;
1120 ++__first;
1121 }
1122#endif
1123 break;
1124 }
1125
1126 if (__finished())
1127 return __first;
1128
1129 __format::__failed_to_parse_format_spec();
1130 }
1131
1132 template<typename _Tp>
1133 constexpr typename basic_format_parse_context<_CharT>::iterator
1134 _M_parse(basic_format_parse_context<_CharT>& __pc)
1135 {
1136 if constexpr (is_same_v<_Tp, bool>)
1137 {
1138 auto __end = _M_do_parse(__pc, _AsBool);
1139 if (_M_spec._M_type == _Pres_s)
1140 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1141 __throw_format_error("format error: format-spec contains "
1142 "invalid formatting options for "
1143 "'bool'");
1144 return __end;
1145 }
1146 else if constexpr (__char<_Tp>)
1147 {
1148 auto __end = _M_do_parse(__pc, _AsChar);
1149 if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1150 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1151 /* XXX should be invalid? || _M_spec._M_localized */)
1152 __throw_format_error("format error: format-spec contains "
1153 "invalid formatting options for "
1154 "'charT'");
1155 return __end;
1156 }
1157 else
1158 return _M_do_parse(__pc, _AsInteger);
1159 }
1160
1161 template<typename _Int, typename _Out>
1162 typename basic_format_context<_Out, _CharT>::iterator
1163 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1164 {
1165 if (_M_spec._M_type == _Pres_c)
1166 return _M_format_character(_S_to_character(__i), __fc);
1167
1168 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1169 to_chars_result __res{};
1170
1171 string_view __base_prefix;
1172 make_unsigned_t<_Int> __u;
1173 if (__i < 0)
1174 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1175 else
1176 __u = __i;
1177
1178 char* __start = __buf + 3;
1179 char* const __end = __buf + sizeof(__buf);
1180 char* const __start_digits = __start;
1181
1182 switch (_M_spec._M_type)
1183 {
1184 case _Pres_b:
1185 case _Pres_B:
1186 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1187 __res = to_chars(__start, __end, __u, 2);
1188 break;
1189#if 0
1190 case _Pres_c:
1191 return _M_format_character(_S_to_character(__i), __fc);
1192#endif
1193 case _Pres_none:
1194 // Should not reach here with _Pres_none for bool or charT, so:
1195 [[fallthrough]];
1196 case _Pres_d:
1197 __res = to_chars(__start, __end, __u, 10);
1198 break;
1199 case _Pres_o:
1200 if (__i != 0)
1201 __base_prefix = "0";
1202 __res = to_chars(__start, __end, __u, 8);
1203 break;
1204 case _Pres_x:
1205 case _Pres_X:
1206 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1207 __res = to_chars(__start, __end, __u, 16);
1208 if (_M_spec._M_type == _Pres_X)
1209 for (auto __p = __start; __p != __res.ptr; ++__p)
1210#if __has_builtin(__builtin_toupper)
1211 *__p = __builtin_toupper(*__p);
1212#else
1213 *__p = std::toupper(*__p);
1214#endif
1215 break;
1216 default:
1217 __builtin_unreachable();
1218 }
1219
1220 if (_M_spec._M_alt && __base_prefix.size())
1221 {
1222 __start -= __base_prefix.size();
1223 __builtin_memcpy(__start, __base_prefix.data(),
1224 __base_prefix.size());
1225 }
1226 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1227
1228 return _M_format_int(string_view(__start, __res.ptr - __start),
1229 __start_digits - __start, __fc);
1230 }
1231
1232 template<typename _Out>
1233 typename basic_format_context<_Out, _CharT>::iterator
1234 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1235 {
1236 if (_M_spec._M_type == _Pres_c)
1237 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1238 if (_M_spec._M_type != _Pres_s)
1239 return format(static_cast<unsigned char>(__i), __fc);
1240
1241 basic_string<_CharT> __s;
1242 size_t __est_width;
1243 if (_M_spec._M_localized) [[unlikely]]
1244 {
1245 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1246 __s = __i ? __np.truename() : __np.falsename();
1247 __est_width = __s.size(); // TODO Unicode-aware estimate
1248 }
1249 else
1250 {
1251 if constexpr (is_same_v<char, _CharT>)
1252 __s = __i ? "true" : "false";
1253 else
1254 __s = __i ? L"true" : L"false";
1255 __est_width = __s.size();
1256 }
1257
1258 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1259 _M_spec);
1260 }
1261
1262 template<typename _Out>
1263 typename basic_format_context<_Out, _CharT>::iterator
1264 _M_format_character(_CharT __c,
1265 basic_format_context<_Out, _CharT>& __fc) const
1266 {
1267 return __format::__write_padded_as_spec({&__c, 1u}, 1, __fc, _M_spec);
1268 }
1269
1270 template<typename _Int>
1271 static _CharT
1272 _S_to_character(_Int __i)
1273 {
1274 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1275 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1276 {
1277 if (_Traits::__min <= __i && __i <= _Traits::__max)
1278 return static_cast<_CharT>(__i);
1279 }
1280 else if constexpr (is_signed_v<_Int>)
1281 {
1282 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1283 return static_cast<_CharT>(__i);
1284 }
1285 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1286 return static_cast<_CharT>(__i);
1287 __throw_format_error("format error: integer not representable as "
1288 "character");
1289 }
1290
1291 template<typename _Out>
1292 typename basic_format_context<_Out, _CharT>::iterator
1293 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1294 basic_format_context<_Out, _CharT>& __fc) const
1295 {
1296 size_t __width = _M_spec._M_get_width(__fc);
1297
1298 basic_string_view<_CharT> __str;
1299 if constexpr (is_same_v<char, _CharT>)
1300 __str = __narrow_str;
1301#ifdef _GLIBCXX_USE_WCHAR_T
1302 else
1303 {
1304 size_t __n = __narrow_str.size();
1305 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1306 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1307 __str = {__p, __n};
1308 }
1309#endif
1310
1311 if (_M_spec._M_localized)
1312 {
1313 const auto& __l = __fc.locale();
1314 if (__l.name() != "C")
1315 {
1316 auto& __np = use_facet<numpunct<_CharT>>(__l);
1317 string __grp = __np.grouping();
1318 if (!__grp.empty())
1319 {
1320 size_t __n = __str.size() - __prefix_len;
1321 auto __p = (_CharT*)__builtin_alloca(2 * __n
1322 * sizeof(_CharT)
1323 + __prefix_len);
1324 auto __s = __str.data();
1325 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1326 __s += __prefix_len;
1327 auto __end = std::__add_grouping(__p + __prefix_len,
1328 __np.thousands_sep(),
1329 __grp.data(),
1330 __grp.size(),
1331 __s, __s + __n);
1332 __str = {__p, size_t(__end - __p)};
1333 }
1334 }
1335 }
1336
1337 if (__width <= __str.size())
1338 return __format::__write(__fc.out(), __str);
1339
1340 char32_t __fill_char = _M_spec._M_fill;
1341 _Align __align = _M_spec._M_align;
1342
1343 size_t __nfill = __width - __str.size();
1344 auto __out = __fc.out();
1345 if (__align == _Align_default)
1346 {
1347 __align = _Align_right;
1348 if (_M_spec._M_zero_fill)
1349 {
1350 __fill_char = _CharT('0');
1351 // Write sign and base prefix before zero filling.
1352 if (__prefix_len != 0)
1353 {
1354 __out = __format::__write(std::move(__out),
1355 __str.substr(0, __prefix_len));
1356 __str.remove_prefix(__prefix_len);
1357 }
1358 }
1359 else
1360 __fill_char = _CharT(' ');
1361 }
1362 return __format::__write_padded(std::move(__out), __str,
1363 __align, __nfill, __fill_char);
1364 }
1365
1366#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1367 template<typename _Tp>
1368 using make_unsigned_t
1369 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1371 type_identity<unsigned __int128>>::type;
1372
1373 // std::to_chars is not overloaded for int128 in strict mode.
1374 template<typename _Int>
1375 static to_chars_result
1376 to_chars(char* __first, char* __last, _Int __value, int __base)
1377 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1378#endif
1379
1380 _Spec<_CharT> _M_spec{};
1381 };
1382
1383 // Decide how 128-bit floating-point types should be formatted (or not).
1384 // When supported, the typedef __format::__float128_t is the type that
1385 // format arguments should be converted to for storage in basic_format_arg.
1386 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1387 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1388 // by converting them to long double (or __ieee128 for powerpc64le).
1389 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1390 // support for _Float128, rather than formatting it as another type.
1391#undef _GLIBCXX_FORMAT_F128
1392
1393#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1394
1395 // Format 128-bit floating-point types using __ieee128.
1396 using __float128_t = __ieee128;
1397# define _GLIBCXX_FORMAT_F128 1
1398
1399#ifdef __LONG_DOUBLE_IEEE128__
1400 // These overloads exist in the library, but are not declared.
1401 // Make them available as std::__format::to_chars.
1402 to_chars_result
1403 to_chars(char*, char*, __ibm128) noexcept
1404 __asm("_ZSt8to_charsPcS_e");
1405
1406 to_chars_result
1407 to_chars(char*, char*, __ibm128, chars_format) noexcept
1408 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1409
1410 to_chars_result
1411 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1412 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1413#elif __cplusplus == 202002L
1414 to_chars_result
1415 to_chars(char*, char*, __ieee128) noexcept
1416 __asm("_ZSt8to_charsPcS_u9__ieee128");
1417
1418 to_chars_result
1419 to_chars(char*, char*, __ieee128, chars_format) noexcept
1420 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1421
1422 to_chars_result
1423 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1424 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1425#endif
1426
1427#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1428
1429 // Format 128-bit floating-point types using long double.
1430 using __float128_t = long double;
1431# define _GLIBCXX_FORMAT_F128 1
1432
1433#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1434
1435 // Format 128-bit floating-point types using _Float128.
1436 using __float128_t = _Float128;
1437# define _GLIBCXX_FORMAT_F128 2
1438
1439# if __cplusplus == 202002L
1440 // These overloads exist in the library, but are not declared for C++20.
1441 // Make them available as std::__format::to_chars.
1442 to_chars_result
1443 to_chars(char*, char*, _Float128) noexcept
1444# if _GLIBCXX_INLINE_VERSION
1445 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1446# else
1447 __asm("_ZSt8to_charsPcS_DF128_");
1448# endif
1449
1450 to_chars_result
1451 to_chars(char*, char*, _Float128, chars_format) noexcept
1452# if _GLIBCXX_INLINE_VERSION
1453 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1454# else
1455 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1456# endif
1457
1458 to_chars_result
1459 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1460# if _GLIBCXX_INLINE_VERSION
1461 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1462# else
1463 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1464# endif
1465# endif
1466#endif
1467
1468 using std::to_chars;
1469
1470 // We can format a floating-point type iff it is usable with to_chars.
1471 template<typename _Tp>
1472 concept __formattable_float
1473 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1474 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1475
1476 template<__char _CharT>
1477 struct __formatter_fp
1478 {
1479 constexpr typename basic_format_parse_context<_CharT>::iterator
1480 parse(basic_format_parse_context<_CharT>& __pc)
1481 {
1482 _Spec<_CharT> __spec{};
1483 const auto __last = __pc.end();
1484 auto __first = __pc.begin();
1485
1486 auto __finalize = [this, &__spec] {
1487 _M_spec = __spec;
1488 };
1489
1490 auto __finished = [&] {
1491 if (__first == __last || *__first == '}')
1492 {
1493 __finalize();
1494 return true;
1495 }
1496 return false;
1497 };
1498
1499 if (__finished())
1500 return __first;
1501
1502 __first = __spec._M_parse_fill_and_align(__first, __last);
1503 if (__finished())
1504 return __first;
1505
1506 __first = __spec._M_parse_sign(__first, __last);
1507 if (__finished())
1508 return __first;
1509
1510 __first = __spec._M_parse_alternate_form(__first, __last);
1511 if (__finished())
1512 return __first;
1513
1514 __first = __spec._M_parse_zero_fill(__first, __last);
1515 if (__finished())
1516 return __first;
1517
1518 if (__first[0] != '.')
1519 {
1520 __first = __spec._M_parse_width(__first, __last, __pc);
1521 if (__finished())
1522 return __first;
1523 }
1524
1525 __first = __spec._M_parse_precision(__first, __last, __pc);
1526 if (__finished())
1527 return __first;
1528
1529 __first = __spec._M_parse_locale(__first, __last);
1530 if (__finished())
1531 return __first;
1532
1533 switch (*__first)
1534 {
1535 case 'a':
1536 __spec._M_type = _Pres_a;
1537 ++__first;
1538 break;
1539 case 'A':
1540 __spec._M_type = _Pres_A;
1541 ++__first;
1542 break;
1543 case 'e':
1544 __spec._M_type = _Pres_e;
1545 ++__first;
1546 break;
1547 case 'E':
1548 __spec._M_type = _Pres_E;
1549 ++__first;
1550 break;
1551 case 'f':
1552 __spec._M_type = _Pres_f;
1553 ++__first;
1554 break;
1555 case 'F':
1556 __spec._M_type = _Pres_F;
1557 ++__first;
1558 break;
1559 case 'g':
1560 __spec._M_type = _Pres_g;
1561 ++__first;
1562 break;
1563 case 'G':
1564 __spec._M_type = _Pres_G;
1565 ++__first;
1566 break;
1567 }
1568
1569 if (__finished())
1570 return __first;
1571
1572 __format::__failed_to_parse_format_spec();
1573 }
1574
1575 template<typename _Fp, typename _Out>
1576 typename basic_format_context<_Out, _CharT>::iterator
1577 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
1578 {
1579 std::string __dynbuf;
1580 char __buf[128];
1581 to_chars_result __res{};
1582
1583 size_t __prec = 6;
1584 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
1585 if (__use_prec)
1586 __prec = _M_spec._M_get_precision(__fc);
1587
1588 char* __start = __buf + 1; // reserve space for sign
1589 char* __end = __buf + sizeof(__buf);
1590
1591 chars_format __fmt{};
1592 bool __upper = false;
1593 bool __trailing_zeros = false;
1594 char __expc = 'e';
1595
1596 switch (_M_spec._M_type)
1597 {
1598 case _Pres_A:
1599 __upper = true;
1600 __expc = 'P';
1601 [[fallthrough]];
1602 case _Pres_a:
1603 if (_M_spec._M_type != _Pres_A)
1604 __expc = 'p';
1605 __fmt = chars_format::hex;
1606 break;
1607 case _Pres_E:
1608 __upper = true;
1609 __expc = 'E';
1610 [[fallthrough]];
1611 case _Pres_e:
1612 __use_prec = true;
1613 __fmt = chars_format::scientific;
1614 break;
1615 case _Pres_F:
1616 __upper = true;
1617 [[fallthrough]];
1618 case _Pres_f:
1619 __use_prec = true;
1620 __fmt = chars_format::fixed;
1621 break;
1622 case _Pres_G:
1623 __upper = true;
1624 __expc = 'E';
1625 [[fallthrough]];
1626 case _Pres_g:
1627 __trailing_zeros = true;
1628 __use_prec = true;
1629 __fmt = chars_format::general;
1630 break;
1631 case _Pres_none:
1632 if (__use_prec)
1633 __fmt = chars_format::general;
1634 break;
1635 default:
1636 __builtin_unreachable();
1637 }
1638
1639 // Write value into buffer using std::to_chars.
1640 auto __to_chars = [&](char* __b, char* __e) {
1641 if (__use_prec)
1642 return __format::to_chars(__b, __e, __v, __fmt, __prec);
1643 else if (__fmt != chars_format{})
1644 return __format::to_chars(__b, __e, __v, __fmt);
1645 else
1646 return __format::to_chars(__b, __e, __v);
1647 };
1648
1649 // First try using stack buffer.
1650 __res = __to_chars(__start, __end);
1651
1652 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
1653 {
1654 // If the buffer is too small it's probably because of a large
1655 // precision, or a very large value in fixed format.
1656 size_t __guess = 8 + __prec;
1657 if (__fmt == chars_format::fixed) // +ddd.prec
1658 {
1659 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
1660 || is_same_v<_Fp, long double>)
1661 {
1662 // The number of digits to the left of the decimal point
1663 // is floor(log10(max(abs(__v),1)))+1
1664 int __exp{};
1665 if constexpr (is_same_v<_Fp, float>)
1666 __builtin_frexpf(__v, &__exp);
1667 else if constexpr (is_same_v<_Fp, double>)
1668 __builtin_frexp(__v, &__exp);
1669 else if constexpr (is_same_v<_Fp, long double>)
1670 __builtin_frexpl(__v, &__exp);
1671 if (__exp > 0)
1672 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
1673 }
1674 else
1675 __guess += numeric_limits<_Fp>::max_exponent10;
1676 }
1677 if (__guess <= sizeof(__buf)) [[unlikely]]
1678 __guess = sizeof(__buf) * 2;
1679 __dynbuf.reserve(__guess);
1680
1681 do
1682 {
1683 // Mangling of this lambda, and thus resize_and_overwrite
1684 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
1685 // <format> was new in G++ 13, and is experimental, that
1686 // isn't a problem.
1687 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
1688 {
1689 __res = __to_chars(__p + 1, __p + __n - 1);
1690 return __res.ec == errc{} ? __res.ptr - __p : 0;
1691 };
1692
1693 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
1694 __overwrite);
1695 __start = __dynbuf.data() + 1; // reserve space for sign
1696 __end = __dynbuf.data() + __dynbuf.size();
1697 }
1698 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
1699 }
1700
1701 // Use uppercase for 'A', 'E', and 'G' formats.
1702 if (__upper)
1703 {
1704 for (char* __p = __start; __p != __res.ptr; ++__p)
1705 *__p = std::toupper(*__p);
1706 }
1707
1708 bool __have_sign = true;
1709 // Add sign for non-negative values.
1710 if (!__builtin_signbit(__v))
1711 {
1712 if (_M_spec._M_sign == _Sign_plus)
1713 *--__start = '+';
1714 else if (_M_spec._M_sign == _Sign_space)
1715 *--__start = ' ';
1716 else
1717 __have_sign = false;
1718 }
1719
1720 string_view __narrow_str(__start, __res.ptr - __start);
1721
1722 // Use alternate form. Ensure decimal point is always present,
1723 // and add trailing zeros (up to precision) for g and G forms.
1724 if (_M_spec._M_alt && __builtin_isfinite(__v))
1725 {
1726 string_view __s = __narrow_str;
1727 size_t __sigfigs; // Number of significant figures.
1728 size_t __z = 0; // Number of trailing zeros to add.
1729 size_t __p; // Position of the exponent character (if any).
1730 size_t __d = __s.find('.'); // Position of decimal point.
1731 if (__d != __s.npos) // Found decimal point.
1732 {
1733 __p = __s.find(__expc, __d + 1);
1734 if (__p == __s.npos)
1735 __p = __s.size();
1736
1737 // If presentation type is g or G we might need to add zeros.
1738 if (__trailing_zeros)
1739 {
1740 // Find number of digits after first significant figure.
1741 if (__s[__have_sign] != '0')
1742 // A string like "D.D" or "-D.DDD"
1743 __sigfigs = __p - __have_sign - 1;
1744 else
1745 // A string like "0.D" or "-0.0DD".
1746 // Safe to assume there is a non-zero digit, because
1747 // otherwise there would be no decimal point.
1748 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
1749 }
1750 }
1751 else // No decimal point, we need to insert one.
1752 {
1753 __p = __s.find(__expc); // Find the exponent, if present.
1754 if (__p == __s.npos)
1755 __p = __s.size();
1756 __d = __p; // Position where '.' should be inserted.
1757 __sigfigs = __d - __have_sign;
1758 }
1759
1760 if (__trailing_zeros && __prec != 0)
1761 {
1762 // For g and G presentation types std::to_chars produces
1763 // no more than prec significant figures. Insert this many
1764 // zeros so the result has exactly prec significant figures.
1765 __z = __prec - __sigfigs;
1766 }
1767
1768 if (size_t __extras = int(__d == __p) + __z) // How many to add.
1769 {
1770 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
1771 {
1772 // The stack buffer is large enough for the result.
1773 // Move exponent to make space for extra chars.
1774 __builtin_memmove(__start + __p + __extras,
1775 __start + __p,
1776 __s.size() - __p);
1777 if (__d == __p)
1778 __start[__p++] = '.';
1779 __builtin_memset(__start + __p, '0', __z);
1780 __narrow_str = {__s.data(), __s.size() + __extras};
1781 }
1782 else // Need to switch to the dynamic buffer.
1783 {
1784 __dynbuf.reserve(__s.size() + __extras);
1785 if (__dynbuf.empty())
1786 {
1787 __dynbuf = __s.substr(0, __p);
1788 if (__d == __p)
1789 __dynbuf += '.';
1790 if (__z)
1791 __dynbuf.append(__z, '0');
1792 __dynbuf.append(__s.substr(__p));
1793 }
1794 else
1795 {
1796 __dynbuf.insert(__p, __extras, '0');
1797 if (__d == __p)
1798 __dynbuf[__p] = '.';
1799 }
1800 __narrow_str = __dynbuf;
1801 }
1802 }
1803 }
1804
1805 basic_string<_CharT> __wstr;
1806 basic_string_view<_CharT> __str;
1807 if constexpr (is_same_v<_CharT, char>)
1808 __str = __narrow_str;
1809#ifdef _GLIBCXX_USE_WCHAR_T
1810 else
1811 {
1812 __wstr = std::__to_wstring_numeric(__narrow_str);
1813 __str = __wstr;
1814 }
1815#endif
1816
1817 if (_M_spec._M_localized && __builtin_isfinite(__v))
1818 {
1819 __wstr = _M_localize(__str, __expc, __fc.locale());
1820 if (!__wstr.empty())
1821 __str = __wstr;
1822 }
1823
1824 size_t __width = _M_spec._M_get_width(__fc);
1825
1826 if (__width <= __str.size())
1827 return __format::__write(__fc.out(), __str);
1828
1829 char32_t __fill_char = _M_spec._M_fill;
1830 _Align __align = _M_spec._M_align;
1831
1832 size_t __nfill = __width - __str.size();
1833 auto __out = __fc.out();
1834 if (__align == _Align_default)
1835 {
1836 __align = _Align_right;
1837 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
1838 {
1839 __fill_char = _CharT('0');
1840 // Write sign before zero filling.
1841 if (!__format::__is_xdigit(__narrow_str[0]))
1842 {
1843 *__out++ = __str[0];
1844 __str.remove_prefix(1);
1845 }
1846 }
1847 else
1848 __fill_char = _CharT(' ');
1849 }
1850 return __format::__write_padded(std::move(__out), __str,
1851 __align, __nfill, __fill_char);
1852 }
1853
1854 // Locale-specific format.
1855 basic_string<_CharT>
1856 _M_localize(basic_string_view<_CharT> __str, char __expc,
1857 const locale& __loc) const
1858 {
1859 basic_string<_CharT> __lstr;
1860
1861 if (__loc == locale::classic())
1862 return __lstr; // Nothing to do.
1863
1864 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1865 const _CharT __point = __np.decimal_point();
1866 const string __grp = __np.grouping();
1867
1868 _CharT __dot, __exp;
1869 if constexpr (is_same_v<_CharT, char>)
1870 {
1871 __dot = '.';
1872 __exp = __expc;
1873 }
1874 else
1875 {
1876 __dot = L'.';
1877 switch (__expc)
1878 {
1879 case 'e':
1880 __exp = L'e';
1881 break;
1882 case 'E':
1883 __exp = L'E';
1884 break;
1885 case 'p':
1886 __exp = L'p';
1887 break;
1888 case 'P':
1889 __exp = L'P';
1890 break;
1891 default:
1892 __builtin_unreachable();
1893 }
1894 }
1895
1896 if (__grp.empty() && __point == __dot)
1897 return __lstr; // Locale uses '.' and no grouping.
1898
1899 size_t __d = __str.find(__dot); // Index of radix character (if any).
1900 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
1901 if (__e == __str.npos)
1902 __e = __str.size();
1903 const size_t __r = __str.size() - __e; // Length of remainder.
1904 auto __overwrite = [&](_CharT* __p, size_t) {
1905 // Apply grouping to the digits before the radix or exponent.
1906 auto __end = std::__add_grouping(__p, __np.thousands_sep(),
1907 __grp.data(), __grp.size(),
1908 __str.data(), __str.data() + __e);
1909 if (__r) // If there's a fractional part or exponent
1910 {
1911 if (__d != __str.npos)
1912 {
1913 *__end = __point; // Add the locale's radix character.
1914 ++__end;
1915 ++__e;
1916 }
1917 const size_t __rlen = __str.size() - __e;
1918 // Append fractional digits and/or exponent:
1919 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
1920 __end += __rlen;
1921 }
1922 return (__end - __p);
1923 };
1924 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
1925 return __lstr;
1926 }
1927
1928 _Spec<_CharT> _M_spec{};
1929 };
1930
1931} // namespace __format
1932/// @endcond
1933
1934 /// Format a character.
1935 template<__format::__char _CharT>
1936 struct formatter<_CharT, _CharT>
1937 {
1938 formatter() = default;
1939
1940 constexpr typename basic_format_parse_context<_CharT>::iterator
1941 parse(basic_format_parse_context<_CharT>& __pc)
1942 {
1943 return _M_f.template _M_parse<_CharT>(__pc);
1944 }
1945
1946 template<typename _Out>
1947 typename basic_format_context<_Out, _CharT>::iterator
1948 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
1949 {
1950 if (_M_f._M_spec._M_type == __format::_Pres_none
1951 || _M_f._M_spec._M_type == __format::_Pres_c)
1952 return _M_f._M_format_character(__u, __fc);
1953 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1954 {
1955 // TODO
1956 return __fc.out();
1957 }
1958 else
1959 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
1960 }
1961
1962#if __cpp_lib_format_ranges
1963 constexpr void
1964 set_debug_format() noexcept
1965 { _M_f._M_spec._M_type = __format::_Pres_esc; }
1966#endif
1967
1968 private:
1969 __format::__formatter_int<_CharT> _M_f;
1970 };
1971
1972#ifdef _GLIBCXX_USE_WCHAR_T
1973 /// Format a char value for wide character output.
1974 template<>
1975 struct formatter<char, wchar_t>
1976 {
1977 formatter() = default;
1978
1979 constexpr typename basic_format_parse_context<wchar_t>::iterator
1980 parse(basic_format_parse_context<wchar_t>& __pc)
1981 {
1982 return _M_f._M_parse<char>(__pc);
1983 }
1984
1985 template<typename _Out>
1986 typename basic_format_context<_Out, wchar_t>::iterator
1987 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
1988 {
1989 if (_M_f._M_spec._M_type == __format::_Pres_none
1990 || _M_f._M_spec._M_type == __format::_Pres_c)
1991 return _M_f._M_format_character(__u, __fc);
1992 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1993 {
1994 // TODO
1995 return __fc.out();
1996 }
1997 else
1998 return _M_f.format(static_cast<unsigned char>(__u), __fc);
1999 }
2000
2001#if __cpp_lib_format_ranges
2002 constexpr void
2003 set_debug_format() noexcept
2004 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2005#endif
2006
2007 private:
2008 __format::__formatter_int<wchar_t> _M_f;
2009 };
2010#endif // USE_WCHAR_T
2011
2012 /** Format a string.
2013 * @{
2014 */
2015 template<__format::__char _CharT>
2016 struct formatter<_CharT*, _CharT>
2017 {
2018 formatter() = default;
2019
2020 [[__gnu__::__always_inline__]]
2021 constexpr typename basic_format_parse_context<_CharT>::iterator
2022 parse(basic_format_parse_context<_CharT>& __pc)
2023 { return _M_f.parse(__pc); }
2024
2025 template<typename _Out>
2026 [[__gnu__::__nonnull__]]
2027 typename basic_format_context<_Out, _CharT>::iterator
2028 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2029 { return _M_f.format(__u, __fc); }
2030
2031#if __cpp_lib_format_ranges
2032 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2033#endif
2034
2035 private:
2036 __format::__formatter_str<_CharT> _M_f;
2037 };
2038
2039 template<__format::__char _CharT>
2040 struct formatter<const _CharT*, _CharT>
2041 {
2042 formatter() = default;
2043
2044 [[__gnu__::__always_inline__]]
2045 constexpr typename basic_format_parse_context<_CharT>::iterator
2046 parse(basic_format_parse_context<_CharT>& __pc)
2047 { return _M_f.parse(__pc); }
2048
2049 template<typename _Out>
2050 [[__gnu__::__nonnull__]]
2051 typename basic_format_context<_Out, _CharT>::iterator
2052 format(const _CharT* __u,
2053 basic_format_context<_Out, _CharT>& __fc) const
2054 { return _M_f.format(__u, __fc); }
2055
2056#if __cpp_lib_format_ranges
2057 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2058#endif
2059
2060 private:
2061 __format::__formatter_str<_CharT> _M_f;
2062 };
2063
2064 template<__format::__char _CharT, size_t _Nm>
2065 struct formatter<_CharT[_Nm], _CharT>
2066 {
2067 formatter() = default;
2068
2069 [[__gnu__::__always_inline__]]
2070 constexpr typename basic_format_parse_context<_CharT>::iterator
2071 parse(basic_format_parse_context<_CharT>& __pc)
2072 { return _M_f.parse(__pc); }
2073
2074 template<typename _Out>
2075 typename basic_format_context<_Out, _CharT>::iterator
2076 format(const _CharT (&__u)[_Nm],
2077 basic_format_context<_Out, _CharT>& __fc) const
2078 { return _M_f.format({__u, _Nm}, __fc); }
2079
2080#if __cpp_lib_format_ranges
2081 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2082#endif
2083
2084 private:
2085 __format::__formatter_str<_CharT> _M_f;
2086 };
2087
2088 template<typename _Traits, typename _Alloc>
2089 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2090 {
2091 formatter() = default;
2092
2093 [[__gnu__::__always_inline__]]
2094 constexpr typename basic_format_parse_context<char>::iterator
2095 parse(basic_format_parse_context<char>& __pc)
2096 { return _M_f.parse(__pc); }
2097
2098 template<typename _Out>
2099 typename basic_format_context<_Out, char>::iterator
2100 format(const basic_string<char, _Traits, _Alloc>& __u,
2101 basic_format_context<_Out, char>& __fc) const
2102 { return _M_f.format(__u, __fc); }
2103
2104#if __cpp_lib_format_ranges
2105 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2106#endif
2107
2108 private:
2109 __format::__formatter_str<char> _M_f;
2110 };
2111
2112#ifdef _GLIBCXX_USE_WCHAR_T
2113 template<typename _Traits, typename _Alloc>
2114 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2115 {
2116 formatter() = default;
2117
2118 [[__gnu__::__always_inline__]]
2119 constexpr typename basic_format_parse_context<wchar_t>::iterator
2120 parse(basic_format_parse_context<wchar_t>& __pc)
2121 { return _M_f.parse(__pc); }
2122
2123 template<typename _Out>
2124 typename basic_format_context<_Out, wchar_t>::iterator
2125 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2126 basic_format_context<_Out, wchar_t>& __fc) const
2127 { return _M_f.format(__u, __fc); }
2128
2129#if __cpp_lib_format_ranges
2130 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2131#endif
2132
2133 private:
2134 __format::__formatter_str<wchar_t> _M_f;
2135 };
2136#endif // USE_WCHAR_T
2137
2138 template<typename _Traits>
2139 struct formatter<basic_string_view<char, _Traits>, char>
2140 {
2141 formatter() = default;
2142
2143 [[__gnu__::__always_inline__]]
2144 constexpr typename basic_format_parse_context<char>::iterator
2145 parse(basic_format_parse_context<char>& __pc)
2146 { return _M_f.parse(__pc); }
2147
2148 template<typename _Out>
2149 typename basic_format_context<_Out, char>::iterator
2150 format(basic_string_view<char, _Traits> __u,
2151 basic_format_context<_Out, char>& __fc) const
2152 { return _M_f.format(__u, __fc); }
2153
2154#if __cpp_lib_format_ranges
2155 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2156#endif
2157
2158 private:
2159 __format::__formatter_str<char> _M_f;
2160 };
2161
2162#ifdef _GLIBCXX_USE_WCHAR_T
2163 template<typename _Traits>
2164 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2165 {
2166 formatter() = default;
2167
2168 [[__gnu__::__always_inline__]]
2169 constexpr typename basic_format_parse_context<wchar_t>::iterator
2170 parse(basic_format_parse_context<wchar_t>& __pc)
2171 { return _M_f.parse(__pc); }
2172
2173 template<typename _Out>
2174 typename basic_format_context<_Out, wchar_t>::iterator
2175 format(basic_string_view<wchar_t, _Traits> __u,
2176 basic_format_context<_Out, wchar_t>& __fc) const
2177 { return _M_f.format(__u, __fc); }
2178
2179#if __cpp_lib_format_ranges
2180 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2181#endif
2182
2183 private:
2184 __format::__formatter_str<wchar_t> _M_f;
2185 };
2186#endif // USE_WCHAR_T
2187 /// @}
2188
2189/// @cond undocumented
2190namespace __format
2191{
2192 // each cv-unqualified arithmetic type ArithmeticT other than
2193 // char, wchar_t, char8_t, char16_t, or char32_t
2194 template<typename _Tp>
2195 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2196
2197#if defined __SIZEOF_INT128__
2198 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2199 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2200 = true;
2201#endif
2202
2203 template<> inline constexpr bool __is_formattable_integer<char> = false;
2204 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2205#ifdef _GLIBCXX_USE_CHAR8_T
2206 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2207#endif
2208 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2209 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2210}
2211/// @endcond
2212
2213 /// Format an integer.
2214 template<typename _Tp, __format::__char _CharT>
2215 requires __format::__is_formattable_integer<_Tp>
2216 struct formatter<_Tp, _CharT>
2217 {
2218 formatter() = default;
2219
2220 [[__gnu__::__always_inline__]]
2221 constexpr typename basic_format_parse_context<_CharT>::iterator
2222 parse(basic_format_parse_context<_CharT>& __pc)
2223 {
2224 return _M_f.template _M_parse<_Tp>(__pc);
2225 }
2226
2227 template<typename _Out>
2228 typename basic_format_context<_Out, _CharT>::iterator
2229 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2230 { return _M_f.format(__u, __fc); }
2231
2232 private:
2233 __format::__formatter_int<_CharT> _M_f;
2234 };
2235
2236#if defined __glibcxx_to_chars
2237 /// Format a floating-point value.
2238 template<__format::__formattable_float _Tp, __format::__char _CharT>
2239 struct formatter<_Tp, _CharT>
2240 {
2241 formatter() = default;
2242
2243 [[__gnu__::__always_inline__]]
2244 constexpr typename basic_format_parse_context<_CharT>::iterator
2245 parse(basic_format_parse_context<_CharT>& __pc)
2246 { return _M_f.parse(__pc); }
2247
2248 template<typename _Out>
2249 typename basic_format_context<_Out, _CharT>::iterator
2250 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2251 { return _M_f.format(__u, __fc); }
2252
2253 private:
2254 __format::__formatter_fp<_CharT> _M_f;
2255 };
2256
2257#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2258 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2259 template<__format::__char _CharT>
2260 struct formatter<long double, _CharT>
2261 {
2262 formatter() = default;
2263
2264 [[__gnu__::__always_inline__]]
2265 constexpr typename basic_format_parse_context<_CharT>::iterator
2266 parse(basic_format_parse_context<_CharT>& __pc)
2267 { return _M_f.parse(__pc); }
2268
2269 template<typename _Out>
2270 typename basic_format_context<_Out, _CharT>::iterator
2271 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2272 { return _M_f.format((double)__u, __fc); }
2273
2274 private:
2275 __format::__formatter_fp<_CharT> _M_f;
2276 };
2277#endif
2278
2279#ifdef __STDCPP_FLOAT16_T__
2280 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2281 template<__format::__char _CharT>
2282 struct formatter<_Float16, _CharT>
2283 {
2284 formatter() = default;
2285
2286 [[__gnu__::__always_inline__]]
2287 constexpr typename basic_format_parse_context<_CharT>::iterator
2288 parse(basic_format_parse_context<_CharT>& __pc)
2289 { return _M_f.parse(__pc); }
2290
2291 template<typename _Out>
2292 typename basic_format_context<_Out, _CharT>::iterator
2293 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2294 { return _M_f.format((float)__u, __fc); }
2295
2296 private:
2297 __format::__formatter_fp<_CharT> _M_f;
2298 };
2299#endif
2300
2301#if defined(__FLT32_DIG__)
2302 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2303 template<__format::__char _CharT>
2304 struct formatter<_Float32, _CharT>
2305 {
2306 formatter() = default;
2307
2308 [[__gnu__::__always_inline__]]
2309 constexpr typename basic_format_parse_context<_CharT>::iterator
2310 parse(basic_format_parse_context<_CharT>& __pc)
2311 { return _M_f.parse(__pc); }
2312
2313 template<typename _Out>
2314 typename basic_format_context<_Out, _CharT>::iterator
2315 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2316 { return _M_f.format((float)__u, __fc); }
2317
2318 private:
2319 __format::__formatter_fp<_CharT> _M_f;
2320 };
2321#endif
2322
2323#if defined(__FLT64_DIG__)
2324 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2325 template<__format::__char _CharT>
2326 struct formatter<_Float64, _CharT>
2327 {
2328 formatter() = default;
2329
2330 [[__gnu__::__always_inline__]]
2331 constexpr typename basic_format_parse_context<_CharT>::iterator
2332 parse(basic_format_parse_context<_CharT>& __pc)
2333 { return _M_f.parse(__pc); }
2334
2335 template<typename _Out>
2336 typename basic_format_context<_Out, _CharT>::iterator
2337 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2338 { return _M_f.format((double)__u, __fc); }
2339
2340 private:
2341 __format::__formatter_fp<_CharT> _M_f;
2342 };
2343#endif
2344
2345#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2346 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2347 template<__format::__char _CharT>
2348 struct formatter<_Float128, _CharT>
2349 {
2350 formatter() = default;
2351
2352 [[__gnu__::__always_inline__]]
2353 constexpr typename basic_format_parse_context<_CharT>::iterator
2354 parse(basic_format_parse_context<_CharT>& __pc)
2355 { return _M_f.parse(__pc); }
2356
2357 template<typename _Out>
2358 typename basic_format_context<_Out, _CharT>::iterator
2359 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2360 { return _M_f.format((__format::__float128_t)__u, __fc); }
2361
2362 private:
2363 __format::__formatter_fp<_CharT> _M_f;
2364 };
2365#endif
2366
2367#ifdef __STDCPP_BFLOAT16_T__
2368 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2369 template<__format::__char _CharT>
2370 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2371 {
2372 formatter() = default;
2373
2374 [[__gnu__::__always_inline__]]
2375 constexpr typename basic_format_parse_context<_CharT>::iterator
2376 parse(basic_format_parse_context<_CharT>& __pc)
2377 { return _M_f.parse(__pc); }
2378
2379 template<typename _Out>
2380 typename basic_format_context<_Out, _CharT>::iterator
2381 format(__gnu_cxx::__bfloat16_t __u,
2382 basic_format_context<_Out, _CharT>& __fc) const
2383 { return _M_f.format((float)__u, __fc); }
2384
2385 private:
2386 __format::__formatter_fp<_CharT> _M_f;
2387 };
2388#endif
2389#endif // __cpp_lib_to_chars
2390
2391 /** Format a pointer.
2392 * @{
2393 */
2394 template<__format::__char _CharT>
2395 struct formatter<const void*, _CharT>
2396 {
2397 formatter() = default;
2398
2399 constexpr typename basic_format_parse_context<_CharT>::iterator
2400 parse(basic_format_parse_context<_CharT>& __pc)
2401 {
2402 __format::_Spec<_CharT> __spec{};
2403 const auto __last = __pc.end();
2404 auto __first = __pc.begin();
2405
2406 auto __finalize = [this, &__spec] {
2407 _M_spec = __spec;
2408 };
2409
2410 auto __finished = [&] {
2411 if (__first == __last || *__first == '}')
2412 {
2413 __finalize();
2414 return true;
2415 }
2416 return false;
2417 };
2418
2419 if (__finished())
2420 return __first;
2421
2422 __first = __spec._M_parse_fill_and_align(__first, __last);
2423 if (__finished())
2424 return __first;
2425
2426// _GLIBCXX_RESOLVE_LIB_DEFECTS
2427// P2510R3 Formatting pointers
2428#if __glibcxx_format >= 202304L
2429 __first = __spec._M_parse_zero_fill(__first, __last);
2430 if (__finished())
2431 return __first;
2432#endif
2433
2434 __first = __spec._M_parse_width(__first, __last, __pc);
2435
2436 if (__first != __last)
2437 {
2438 if (*__first == 'p')
2439 ++__first;
2440#if __glibcxx_format >= 202304L
2441 else if (*__first == 'P')
2442 {
2443 __spec._M_type = __format::_Pres_P;
2444 ++__first;
2445 }
2446#endif
2447 }
2448
2449 if (__finished())
2450 return __first;
2451
2452 __format::__failed_to_parse_format_spec();
2453 }
2454
2455 template<typename _Out>
2456 typename basic_format_context<_Out, _CharT>::iterator
2457 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2458 {
2459 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2460 char __buf[2 + sizeof(__v) * 2];
2461 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2462 __u, 16);
2463 int __n = __ptr - __buf;
2464 __buf[0] = '0';
2465 __buf[1] = 'x';
2466#if __glibcxx_format >= 202304L
2467 if (_M_spec._M_type == __format::_Pres_P)
2468 {
2469 __buf[1] = 'X';
2470 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2471#if __has_builtin(__builtin_toupper)
2472 *__p = __builtin_toupper(*__p);
2473#else
2474 *__p = std::toupper(*__p);
2475#endif
2476 }
2477#endif
2478
2479 basic_string_view<_CharT> __str;
2480 if constexpr (is_same_v<_CharT, char>)
2481 __str = string_view(__buf, __n);
2482#ifdef _GLIBCXX_USE_WCHAR_T
2483 else
2484 {
2485 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2486 std::__to_wstring_numeric(__buf, __n, __p);
2487 __str = wstring_view(__p, __n);
2488 }
2489#endif
2490
2491#if __glibcxx_format >= 202304L
2492 if (_M_spec._M_zero_fill)
2493 {
2494 size_t __width = _M_spec._M_get_width(__fc);
2495 if (__width <= __str.size())
2496 return __format::__write(__fc.out(), __str);
2497
2498 auto __out = __fc.out();
2499 // Write "0x" or "0X" prefix before zero-filling.
2500 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2501 __str.remove_prefix(2);
2502 size_t __nfill = __width - __n;
2503 return __format::__write_padded(std::move(__out), __str,
2504 __format::_Align_right,
2505 __nfill, _CharT('0'));
2506 }
2507#endif
2508
2509 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2510 __format::_Align_right);
2511 }
2512
2513 private:
2514 __format::_Spec<_CharT> _M_spec{};
2515 };
2516
2517 template<__format::__char _CharT>
2518 struct formatter<void*, _CharT>
2519 {
2520 formatter() = default;
2521
2522 [[__gnu__::__always_inline__]]
2523 constexpr typename basic_format_parse_context<_CharT>::iterator
2524 parse(basic_format_parse_context<_CharT>& __pc)
2525 { return _M_f.parse(__pc); }
2526
2527 template<typename _Out>
2528 typename basic_format_context<_Out, _CharT>::iterator
2529 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2530 { return _M_f.format(__v, __fc); }
2531
2532 private:
2533 formatter<const void*, _CharT> _M_f;
2534 };
2535
2536 template<__format::__char _CharT>
2537 struct formatter<nullptr_t, _CharT>
2538 {
2539 formatter() = default;
2540
2541 [[__gnu__::__always_inline__]]
2542 constexpr typename basic_format_parse_context<_CharT>::iterator
2543 parse(basic_format_parse_context<_CharT>& __pc)
2544 { return _M_f.parse(__pc); }
2545
2546 template<typename _Out>
2547 typename basic_format_context<_Out, _CharT>::iterator
2548 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2549 { return _M_f.format(nullptr, __fc); }
2550
2551 private:
2552 formatter<const void*, _CharT> _M_f;
2553 };
2554 /// @}
2555
2556#if defined _GLIBCXX_USE_WCHAR_T && __cpp_lib_format_ranges
2557 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2558 // 3944. Formatters converting sequences of char to sequences of wchar_t
2559
2560 namespace __format { struct __disabled; }
2561
2562 // std::formatter<__disabled, C> uses the primary template, which is disabled.
2563 template<>
2564 struct formatter<char*, wchar_t>
2565 : private formatter<__format::__disabled, wchar_t> { };
2566 template<>
2567 struct formatter<const char*, wchar_t>
2568 : private formatter<__format::__disabled, wchar_t> { };
2569 template<size_t _Nm>
2570 struct formatter<char[_Nm], wchar_t>
2571 : private formatter<__format::__disabled, wchar_t> { };
2572 template<class _Traits, class _Allocator>
2573 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
2574 : private formatter<__format::__disabled, wchar_t> { };
2575 template<class _Traits>
2576 struct formatter<basic_string_view<char, _Traits>, wchar_t>
2577 : private formatter<__format::__disabled, wchar_t> { };
2578#endif
2579
2580/// @cond undocumented
2581namespace __format
2582{
2583 template<typename _Tp, typename _Context,
2584 typename _Formatter
2585 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2586 typename _ParseContext
2587 = basic_format_parse_context<typename _Context::char_type>>
2588 concept __parsable_with
2589 = semiregular<_Formatter>
2590 && requires (_Formatter __f, _ParseContext __pc)
2591 {
2592 { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
2593 };
2594
2595 template<typename _Tp, typename _Context,
2596 typename _Formatter
2597 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2598 typename _ParseContext
2599 = basic_format_parse_context<typename _Context::char_type>>
2600 concept __formattable_with
2601 = semiregular<_Formatter>
2602 && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
2603 {
2604 { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
2605 };
2606
2607 // An unspecified output iterator type used in the `formattable` concept.
2608 template<typename _CharT>
2609 using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
2610
2611 template<typename _Tp, typename _CharT,
2612 typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
2613 concept __formattable_impl
2614 = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
2615
2616} // namespace __format
2617/// @endcond
2618
2619// Concept std::formattable was introduced by P2286R8 "Formatting Ranges",
2620// but we can't guard it with __cpp_lib_format_ranges until we define that!
2621#if __cplusplus > 202002L
2622 // [format.formattable], concept formattable
2623 template<typename _Tp, typename _CharT>
2624 concept formattable
2625 = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
2626#endif
2627
2628#if __cpp_lib_format_ranges
2629 /// @cond undocumented
2630namespace __format
2631{
2632 template<typename _Rg, typename _CharT>
2633 concept __const_formattable_range
2634 = ranges::input_range<const _Rg>
2635 && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
2636
2637 template<typename _Rg, typename _CharT>
2638 using __maybe_const_range
2639 = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
2640} // namespace __format
2641 /// @endcond
2642#endif // format_ranges
2643
2644 /// An iterator after the last character written, and the number of
2645 /// characters that would have been written.
2646 template<typename _Out>
2647 struct format_to_n_result
2648 {
2649 _Out out;
2650 iter_difference_t<_Out> size;
2651 };
2652
2653_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
2654template<typename, typename> class vector;
2655_GLIBCXX_END_NAMESPACE_CONTAINER
2656
2657/// @cond undocumented
2658namespace __format
2659{
2660 template<typename _CharT>
2661 class _Sink_iter
2662 {
2663 _Sink<_CharT>* _M_sink = nullptr;
2664
2665 public:
2666 using iterator_category = output_iterator_tag;
2667 using value_type = void;
2668 using difference_type = ptrdiff_t;
2669 using pointer = void;
2670 using reference = void;
2671
2672 _Sink_iter() = default;
2673 _Sink_iter(const _Sink_iter&) = default;
2674 _Sink_iter& operator=(const _Sink_iter&) = default;
2675
2676 [[__gnu__::__always_inline__]]
2677 explicit constexpr
2678 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
2679
2680 [[__gnu__::__always_inline__]]
2681 constexpr _Sink_iter&
2682 operator=(_CharT __c)
2683 {
2684 _M_sink->_M_write(__c);
2685 return *this;
2686 }
2687
2688 [[__gnu__::__always_inline__]]
2689 constexpr _Sink_iter&
2690 operator=(basic_string_view<_CharT> __s)
2691 {
2692 _M_sink->_M_write(__s);
2693 return *this;
2694 }
2695
2696 [[__gnu__::__always_inline__]]
2697 constexpr _Sink_iter&
2698 operator*() { return *this; }
2699
2700 [[__gnu__::__always_inline__]]
2701 constexpr _Sink_iter&
2702 operator++() { return *this; }
2703
2704 [[__gnu__::__always_inline__]]
2705 constexpr _Sink_iter
2706 operator++(int) { return *this; }
2707
2708 auto
2709 _M_reserve(size_t __n) const
2710 { return _M_sink->_M_reserve(__n); }
2711 };
2712
2713 // Abstract base class for type-erased character sinks.
2714 // All formatting and output is done via this type's iterator,
2715 // to reduce the number of different template instantiations.
2716 template<typename _CharT>
2717 class _Sink
2718 {
2719 friend class _Sink_iter<_CharT>;
2720
2721 span<_CharT> _M_span;
2722 typename span<_CharT>::iterator _M_next;
2723
2724 // Called when the span is full, to make more space available.
2725 // Precondition: _M_next != _M_span.begin()
2726 // Postcondition: _M_next != _M_span.end()
2727 // TODO: remove the precondition? could make overflow handle it.
2728 virtual void _M_overflow() = 0;
2729
2730 protected:
2731 // Precondition: __span.size() != 0
2732 [[__gnu__::__always_inline__]]
2733 explicit constexpr
2734 _Sink(span<_CharT> __span) noexcept
2735 : _M_span(__span), _M_next(__span.begin())
2736 { }
2737
2738 // The portion of the span that has been written to.
2739 [[__gnu__::__always_inline__]]
2740 span<_CharT>
2741 _M_used() const noexcept
2742 { return _M_span.first(_M_next - _M_span.begin()); }
2743
2744 // The portion of the span that has not been written to.
2745 [[__gnu__::__always_inline__]]
2746 constexpr span<_CharT>
2747 _M_unused() const noexcept
2748 { return _M_span.subspan(_M_next - _M_span.begin()); }
2749
2750 // Use the start of the span as the next write position.
2751 [[__gnu__::__always_inline__]]
2752 constexpr void
2753 _M_rewind() noexcept
2754 { _M_next = _M_span.begin(); }
2755
2756 // Replace the current output range.
2757 void
2758 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
2759 {
2760 _M_span = __s;
2761 _M_next = __s.begin() + __pos;
2762 }
2763
2764 // Called by the iterator for *it++ = c
2765 constexpr void
2766 _M_write(_CharT __c)
2767 {
2768 *_M_next++ = __c;
2769 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
2770 _M_overflow();
2771 }
2772
2773 constexpr void
2774 _M_write(basic_string_view<_CharT> __s)
2775 {
2776 span __to = _M_unused();
2777 while (__to.size() <= __s.size())
2778 {
2779 __s.copy(__to.data(), __to.size());
2780 _M_next += __to.size();
2781 __s.remove_prefix(__to.size());
2782 _M_overflow();
2783 __to = _M_unused();
2784 }
2785 if (__s.size())
2786 {
2787 __s.copy(__to.data(), __s.size());
2788 _M_next += __s.size();
2789 }
2790 }
2791
2792 // A successful _Reservation can be used to directly write
2793 // up to N characters to the sink to avoid unwanted buffering.
2794 struct _Reservation
2795 {
2796 // True if the reservation was successful, false otherwise.
2797 explicit operator bool() const noexcept { return _M_sink; }
2798 // A pointer to write directly to the sink.
2799 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
2800 // Add n to the _M_next iterator for the sink.
2801 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
2802 _Sink* _M_sink;
2803 };
2804
2805 // Attempt to reserve space to write n characters to the sink.
2806 // If anything is written to the reservation then there must be a call
2807 // to _M_bump(N2) before any call to another member function of *this,
2808 // where N2 is the number of characters written.
2809 virtual _Reservation
2810 _M_reserve(size_t __n)
2811 {
2812 if (__n <= _M_unused().size())
2813 return { this };
2814
2815 if (__n <= _M_span.size()) // Cannot meet the request.
2816 {
2817 _M_overflow(); // Make more space available.
2818 if (__n <= _M_unused().size())
2819 return { this };
2820 }
2821 return { nullptr };
2822 }
2823
2824 // Update the next output position after writing directly to the sink.
2825 // pre: no calls to _M_write or _M_overflow since _M_reserve.
2826 virtual void
2827 _M_bump(size_t __n)
2828 { _M_next += __n; }
2829
2830 public:
2831 _Sink(const _Sink&) = delete;
2832 _Sink& operator=(const _Sink&) = delete;
2833
2834 [[__gnu__::__always_inline__]]
2835 constexpr _Sink_iter<_CharT>
2836 out() noexcept
2837 { return _Sink_iter<_CharT>(*this); }
2838 };
2839
2840 // A sink with an internal buffer. This is used to implement concrete sinks.
2841 template<typename _CharT>
2842 class _Buf_sink : public _Sink<_CharT>
2843 {
2844 protected:
2845 _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
2846
2847 [[__gnu__::__always_inline__]]
2848 constexpr
2849 _Buf_sink() noexcept
2850 : _Sink<_CharT>(_M_buf)
2851 { }
2852 };
2853
2854 using _GLIBCXX_STD_C::vector;
2855
2856 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
2857 // Writes to a buffer then appends that to the sequence when it fills up.
2858 template<typename _Seq>
2859 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
2860 {
2861 using _CharT = typename _Seq::value_type;
2862
2863 _Seq _M_seq;
2864
2865 // Transfer buffer contents to the sequence, so buffer can be refilled.
2866 void
2867 _M_overflow() override
2868 {
2869 auto __s = this->_M_used();
2870 if (__s.empty()) [[unlikely]]
2871 return; // Nothing in the buffer to transfer to _M_seq.
2872
2873 // If _M_reserve was called then _M_bump must have been called too.
2874 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
2875
2876 if constexpr (__is_specialization_of<_Seq, basic_string>)
2877 _M_seq.append(__s.data(), __s.size());
2878 else
2879 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
2880
2881 // Make the whole of _M_buf available for the next write:
2882 this->_M_rewind();
2883 }
2884
2885 typename _Sink<_CharT>::_Reservation
2886 _M_reserve(size_t __n) override
2887 {
2888 // We might already have n characters available in this->_M_unused(),
2889 // but the whole point of this function is to be an optimization for
2890 // the std::format("{}", x) case. We want to avoid writing to _M_buf
2891 // and then copying that into a basic_string if possible, so this
2892 // function prefers to create space directly in _M_seq rather than
2893 // using _M_buf.
2894
2895 if constexpr (__is_specialization_of<_Seq, basic_string>
2896 || __is_specialization_of<_Seq, vector>)
2897 {
2898 // Flush the buffer to _M_seq first (should not be needed).
2899 if (this->_M_used().size()) [[unlikely]]
2900 _Seq_sink::_M_overflow();
2901
2902 // Expand _M_seq to make __n new characters available:
2903 const auto __sz = _M_seq.size();
2904 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
2905 _M_seq.__resize_and_overwrite(__sz + __n,
2906 [](auto, auto __n2) {
2907 return __n2;
2908 });
2909 else
2910 _M_seq.resize(__sz + __n);
2911
2912 // Set _M_used() to be a span over the original part of _M_seq
2913 // and _M_unused() to be the extra capacity we just created:
2914 this->_M_reset(_M_seq, __sz);
2915 return { this };
2916 }
2917 else // Try to use the base class' buffer.
2918 return _Sink<_CharT>::_M_reserve(__n);
2919 }
2920
2921 void
2922 _M_bump(size_t __n) override
2923 {
2924 if constexpr (__is_specialization_of<_Seq, basic_string>
2925 || __is_specialization_of<_Seq, vector>)
2926 {
2927 auto __s = this->_M_used();
2928 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
2929 // Truncate the sequence to the part that was actually written to:
2930 _M_seq.resize(__s.size() + __n);
2931 // Switch back to using buffer:
2932 this->_M_reset(this->_M_buf);
2933 }
2934 }
2935
2936 public:
2937 // TODO: for SSO string, use SSO buffer as initial span, then switch
2938 // to _M_buf if it overflows? Or even do that for all unused capacity?
2939
2940 [[__gnu__::__always_inline__]]
2941 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
2942 { }
2943
2944 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
2945 : _M_seq(std::move(__s))
2946 { }
2947
2948 using _Sink<_CharT>::out;
2949
2950 _Seq
2951 get() &&
2952 {
2953 if (this->_M_used().size() != 0)
2954 _Seq_sink::_M_overflow();
2955 return std::move(_M_seq);
2956 }
2957
2958 // A writable span that views everything written to the sink.
2959 // Will be either a view over _M_seq or the used part of _M_buf.
2960 span<_CharT>
2961 view()
2962 {
2963 auto __s = this->_M_used();
2964 if (_M_seq.size())
2965 {
2966 if (__s.size() != 0)
2967 _Seq_sink::_M_overflow();
2968 return _M_seq;
2969 }
2970 return __s;
2971 }
2972 };
2973
2974 template<typename _CharT, typename _Alloc = allocator<_CharT>>
2975 using _Str_sink
2976 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
2977
2978 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
2979 // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
2980
2981 // A sink that writes to an output iterator.
2982 // Writes to a fixed-size buffer and then flushes to the output iterator
2983 // when the buffer fills up.
2984 template<typename _CharT, typename _OutIter>
2985 class _Iter_sink : public _Buf_sink<_CharT>
2986 {
2987 _OutIter _M_out;
2988 iter_difference_t<_OutIter> _M_max;
2989
2990 protected:
2991 size_t _M_count = 0;
2992
2993 void
2994 _M_overflow() override
2995 {
2996 auto __s = this->_M_used();
2997 if (_M_max < 0) // No maximum.
2998 _M_out = ranges::copy(__s, std::move(_M_out)).out;
2999 else if (_M_count < static_cast<size_t>(_M_max))
3000 {
3001 auto __max = _M_max - _M_count;
3002 span<_CharT> __first;
3003 if (__max < __s.size())
3004 __first = __s.first(static_cast<size_t>(__max));
3005 else
3006 __first = __s;
3007 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3008 }
3009 this->_M_rewind();
3010 _M_count += __s.size();
3011 }
3012
3013 public:
3014 [[__gnu__::__always_inline__]]
3015 explicit
3016 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3017 : _M_out(std::move(__out)), _M_max(__max)
3018 { }
3019
3020 using _Sink<_CharT>::out;
3021
3022 format_to_n_result<_OutIter>
3023 _M_finish() &&
3024 {
3025 if (this->_M_used().size() != 0)
3026 _Iter_sink::_M_overflow();
3027 iter_difference_t<_OutIter> __count(_M_count);
3028 return { std::move(_M_out), __count };
3029 }
3030 };
3031
3032 // Partial specialization for contiguous iterators.
3033 // No buffer is used, characters are written straight to the iterator.
3034 // We do not know the size of the output range, so the span size just grows
3035 // as needed. The end of the span might be an invalid pointer outside the
3036 // valid range, but we never actually call _M_span.end(). This class does
3037 // not introduce any invalid pointer arithmetic or overflows that would not
3038 // have happened anyway.
3039 template<typename _CharT, contiguous_iterator _OutIter>
3040 requires same_as<iter_value_t<_OutIter>, _CharT>
3041 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3042 {
3043 _OutIter _M_first;
3044 iter_difference_t<_OutIter> _M_max = -1;
3045 protected:
3046 size_t _M_count = 0;
3047 private:
3048 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3049
3050 protected:
3051 void
3052 _M_overflow() override
3053 {
3054 if (this->_M_unused().size() != 0)
3055 return; // No need to switch to internal buffer yet.
3056
3057 auto __s = this->_M_used();
3058
3059 if (_M_max >= 0)
3060 {
3061 _M_count += __s.size();
3062 // Span was already sized for the maximum character count,
3063 // if it overflows then any further output must go to the
3064 // internal buffer, to be discarded.
3065 this->_M_reset(this->_M_buf);
3066 }
3067 else
3068 {
3069 // No maximum character count. Just extend the span to allow
3070 // writing more characters to it.
3071 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3072 }
3073 }
3074
3075 typename _Sink<_CharT>::_Reservation
3076 _M_reserve(size_t __n) final
3077 {
3078 auto __avail = this->_M_unused();
3079 if (__n > __avail.size())
3080 {
3081 if (_M_max >= 0)
3082 return {}; // cannot grow
3083
3084 auto __s = this->_M_used();
3085 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3086 }
3087 return { this };
3088 }
3089
3090 private:
3091 static span<_CharT>
3092 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3093 span<_CharT> __buf) noexcept
3094 {
3095 if (__n == 0)
3096 return __buf; // Only write to the internal buffer.
3097
3098 if (__n > 0)
3099 {
3100 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3101 || sizeof(__n) > sizeof(size_t))
3102 {
3103 // __int128 or __detail::__max_diff_type
3104 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3105 if (__n > __m)
3106 __n = __m;
3107 }
3108 return {__ptr, (size_t)__n};
3109 }
3110
3111#if __has_builtin(__builtin_dynamic_object_size)
3112 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3113 return {__ptr, __bytes / sizeof(_CharT)};
3114#endif
3115 // Avoid forming a pointer to a different memory page.
3116 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3117 __n = (1024 - __off) / sizeof(_CharT);
3118 if (__n > 0) [[likely]]
3119 return {__ptr, static_cast<size_t>(__n)};
3120 else // Misaligned/packed buffer of wchar_t?
3121 return {__ptr, 1};
3122 }
3123
3124 public:
3125 explicit
3126 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3127 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3128 _M_first(__out), _M_max(__n)
3129 { }
3130
3131 format_to_n_result<_OutIter>
3132 _M_finish() &&
3133 {
3134 auto __s = this->_M_used();
3135 if (__s.data() == _M_buf)
3136 {
3137 // Switched to internal buffer, so must have written _M_max.
3138 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3139 return { _M_first + _M_max, __count };
3140 }
3141 else // Not using internal buffer yet
3142 {
3143 iter_difference_t<_OutIter> __count(__s.size());
3144 return { _M_first + __count, __count };
3145 }
3146 }
3147 };
3148
3149 enum _Arg_t : unsigned char {
3150 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3151 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3152 _Arg_i128, _Arg_u128,
3153 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3154#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3155 _Arg_next_value_,
3156 _Arg_f128 = _Arg_ldbl,
3157 _Arg_ibm128 = _Arg_next_value_,
3158#else
3159 _Arg_f128,
3160#endif
3161 _Arg_max_
3162 };
3163
3164 template<typename _Context>
3165 struct _Arg_value
3166 {
3167 using _CharT = typename _Context::char_type;
3168
3169 struct _HandleBase
3170 {
3171 const void* _M_ptr;
3172 void (*_M_func)();
3173 };
3174
3175 union
3176 {
3177 monostate _M_none;
3178 bool _M_bool;
3179 _CharT _M_c;
3180 int _M_i;
3181 unsigned _M_u;
3182 long long _M_ll;
3183 unsigned long long _M_ull;
3184 float _M_flt;
3185 double _M_dbl;
3186#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3187 long double _M_ldbl;
3188#endif
3189 const _CharT* _M_str;
3190 basic_string_view<_CharT> _M_sv;
3191 const void* _M_ptr;
3192 _HandleBase _M_handle;
3193#ifdef __SIZEOF_INT128__
3194 __int128 _M_i128;
3195 unsigned __int128 _M_u128;
3196#endif
3197#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3198 __ieee128 _M_f128;
3199 __ibm128 _M_ibm128;
3200#elif _GLIBCXX_FORMAT_F128 == 2
3201 __float128_t _M_f128;
3202#endif
3203 };
3204
3205 [[__gnu__::__always_inline__]]
3206 _Arg_value() : _M_none() { }
3207
3208#if 0
3209 template<typename _Tp>
3210 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3211 { _S_get<_Tp>() = __val; }
3212#endif
3213
3214 template<typename _Tp, typename _Self>
3215 [[__gnu__::__always_inline__]]
3216 static auto&
3217 _S_get(_Self& __u) noexcept
3218 {
3219 if constexpr (is_same_v<_Tp, bool>)
3220 return __u._M_bool;
3221 else if constexpr (is_same_v<_Tp, _CharT>)
3222 return __u._M_c;
3223 else if constexpr (is_same_v<_Tp, int>)
3224 return __u._M_i;
3225 else if constexpr (is_same_v<_Tp, unsigned>)
3226 return __u._M_u;
3227 else if constexpr (is_same_v<_Tp, long long>)
3228 return __u._M_ll;
3229 else if constexpr (is_same_v<_Tp, unsigned long long>)
3230 return __u._M_ull;
3231 else if constexpr (is_same_v<_Tp, float>)
3232 return __u._M_flt;
3233 else if constexpr (is_same_v<_Tp, double>)
3234 return __u._M_dbl;
3235#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3236 else if constexpr (is_same_v<_Tp, long double>)
3237 return __u._M_ldbl;
3238#else
3239 else if constexpr (is_same_v<_Tp, __ieee128>)
3240 return __u._M_f128;
3241 else if constexpr (is_same_v<_Tp, __ibm128>)
3242 return __u._M_ibm128;
3243#endif
3244 else if constexpr (is_same_v<_Tp, const _CharT*>)
3245 return __u._M_str;
3246 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3247 return __u._M_sv;
3248 else if constexpr (is_same_v<_Tp, const void*>)
3249 return __u._M_ptr;
3250#ifdef __SIZEOF_INT128__
3251 else if constexpr (is_same_v<_Tp, __int128>)
3252 return __u._M_i128;
3253 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3254 return __u._M_u128;
3255#endif
3256#if _GLIBCXX_FORMAT_F128 == 2
3257 else if constexpr (is_same_v<_Tp, __float128_t>)
3258 return __u._M_f128;
3259#endif
3260 else if constexpr (derived_from<_Tp, _HandleBase>)
3261 return static_cast<_Tp&>(__u._M_handle);
3262 // Otherwise, ill-formed.
3263 }
3264
3265 template<typename _Tp>
3266 [[__gnu__::__always_inline__]]
3267 auto&
3268 _M_get() noexcept
3269 { return _S_get<_Tp>(*this); }
3270
3271 template<typename _Tp>
3272 [[__gnu__::__always_inline__]]
3273 const auto&
3274 _M_get() const noexcept
3275 { return _S_get<_Tp>(*this); }
3276
3277 template<typename _Tp>
3278 [[__gnu__::__always_inline__]]
3279 void
3280 _M_set(_Tp __v) noexcept
3281 {
3282 if constexpr (derived_from<_Tp, _HandleBase>)
3283 std::construct_at(&_M_handle, __v);
3284 else
3285 _S_get<_Tp>(*this) = __v;
3286 }
3287 };
3288
3289 // [format.arg.store], class template format-arg-store
3290 template<typename _Context, typename... _Args>
3291 class _Arg_store;
3292
3293 template<typename _Ch, typename _Tp>
3294 consteval _Arg_t
3295 __to_arg_t_enum() noexcept;
3296
3297} // namespace __format
3298/// @endcond
3299
3300 template<typename _Context>
3301 class basic_format_arg
3302 {
3303 using _CharT = typename _Context::char_type;
3304
3305 template<typename _Tp>
3306 static constexpr bool __formattable
3307 = __format::__formattable_with<_Tp, _Context>;
3308
3309 public:
3310 class handle : public __format::_Arg_value<_Context>::_HandleBase
3311 {
3312 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3313
3314 // Format as const if possible, to reduce instantiations.
3315 template<typename _Tp>
3316 using __maybe_const_t
3317 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3318
3319 template<typename _Tq>
3320 static void
3321 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3322 _Context& __format_ctx, const void* __ptr)
3323 {
3324 using _Td = remove_const_t<_Tq>;
3325 typename _Context::template formatter_type<_Td> __f;
3326 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3327 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3328 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3329 }
3330
3331 template<typename _Tp>
3332 explicit
3333 handle(_Tp& __val) noexcept
3334 {
3335 this->_M_ptr = __builtin_addressof(__val);
3336 auto __func = _S_format<__maybe_const_t<_Tp>>;
3337 this->_M_func = reinterpret_cast<void(*)()>(__func);
3338 }
3339
3340 friend class basic_format_arg<_Context>;
3341
3342 public:
3343 handle(const handle&) = default;
3344 handle& operator=(const handle&) = default;
3345
3346 [[__gnu__::__always_inline__]]
3347 void
3348 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3349 {
3350 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3351 _Context&, const void*);
3352 auto __f = reinterpret_cast<_Func>(this->_M_func);
3353 __f(__pc, __fc, this->_M_ptr);
3354 }
3355 };
3356
3357 [[__gnu__::__always_inline__]]
3358 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3359
3360 [[nodiscard,__gnu__::__always_inline__]]
3361 explicit operator bool() const noexcept
3362 { return _M_type != __format::_Arg_none; }
3363
3364#if __cpp_lib_format >= 202306L // >= C++26
3365 template<typename _Visitor>
3366 decltype(auto)
3367 visit(this basic_format_arg __arg, _Visitor&& __vis)
3368 { return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type); }
3369
3370 template<typename _Res, typename _Visitor>
3371 _Res
3372 visit(this basic_format_arg __arg, _Visitor&& __vis)
3373 { return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type); }
3374#endif
3375
3376 private:
3377 template<typename _Ctx>
3378 friend class basic_format_args;
3379
3380 template<typename _Ctx, typename... _Args>
3381 friend class __format::_Arg_store;
3382
3383 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3384
3385 __format::_Arg_value<_Context> _M_val;
3386 __format::_Arg_t _M_type;
3387
3388 // Transform incoming argument type to the type stored in _Arg_value.
3389 // e.g. short -> int, std::string -> std::string_view,
3390 // char[3] -> const char*.
3391 template<typename _Tp>
3392 static consteval auto
3393 _S_to_arg_type()
3394 {
3395 using _Td = remove_const_t<_Tp>;
3396 if constexpr (is_same_v<_Td, bool>)
3397 return type_identity<bool>();
3398 else if constexpr (is_same_v<_Td, _CharT>)
3399 return type_identity<_CharT>();
3400 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3401 return type_identity<_CharT>();
3402#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3403 else if constexpr (is_same_v<_Td, __int128>)
3404 return type_identity<__int128>();
3405 else if constexpr (is_same_v<_Td, unsigned __int128>)
3406 return type_identity<unsigned __int128>();
3407#endif
3408 else if constexpr (__is_signed_integer<_Td>::value)
3409 {
3410 if constexpr (sizeof(_Td) <= sizeof(int))
3411 return type_identity<int>();
3412 else if constexpr (sizeof(_Td) <= sizeof(long long))
3413 return type_identity<long long>();
3414 }
3415 else if constexpr (__is_unsigned_integer<_Td>::value)
3416 {
3417 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3418 return type_identity<unsigned>();
3419 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3420 return type_identity<unsigned long long>();
3421 }
3422 else if constexpr (is_same_v<_Td, float>)
3423 return type_identity<float>();
3424 else if constexpr (is_same_v<_Td, double>)
3425 return type_identity<double>();
3426#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3427 else if constexpr (is_same_v<_Td, long double>)
3428 return type_identity<long double>();
3429#else
3430 else if constexpr (is_same_v<_Td, __ibm128>)
3431 return type_identity<__ibm128>();
3432 else if constexpr (is_same_v<_Td, __ieee128>)
3433 return type_identity<__ieee128>();
3434#endif
3435
3436#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3437 else if constexpr (is_same_v<_Td, _Float16>)
3438 return type_identity<float>();
3439#endif
3440
3441#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3442 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3443 return type_identity<float>();
3444#endif
3445
3446#ifdef __FLT32_DIG__
3447 else if constexpr (is_same_v<_Td, _Float32>)
3448# ifdef _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3449 return type_identity<float>();
3450# else
3451 return type_identity<_Float32>();
3452# endif
3453#endif
3454#ifdef __FLT64_DIG__
3455 else if constexpr (is_same_v<_Td, _Float64>)
3456# ifdef _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3457 return type_identity<double>();
3458# else
3459 return type_identity<_Float64>();
3460# endif
3461#endif
3462#if _GLIBCXX_FORMAT_F128
3463# if __FLT128_DIG__
3464 else if constexpr (is_same_v<_Td, _Float128>)
3465 return type_identity<__format::__float128_t>();
3466# endif
3467# if __SIZEOF_FLOAT128__
3468 else if constexpr (is_same_v<_Td, __float128>)
3469 return type_identity<__format::__float128_t>();
3470# endif
3471#endif
3472 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3473 || __is_specialization_of<_Td, basic_string>)
3474 {
3475 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3476 return type_identity<basic_string_view<_CharT>>();
3477 else
3478 return type_identity<handle>();
3479 }
3480 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3481 return type_identity<const _CharT*>();
3482 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3483 return type_identity<const _CharT*>();
3484 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3485 return type_identity<const void*>();
3486 else if constexpr (is_same_v<_Td, nullptr_t>)
3487 return type_identity<const void*>();
3488 else
3489 return type_identity<handle>();
3490 }
3491
3492 // Transform a formattable type to the appropriate storage type.
3493 template<typename _Tp>
3494 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3495
3496 // Get the _Arg_t value corresponding to a normalized type.
3497 template<typename _Tp>
3498 static consteval __format::_Arg_t
3499 _S_to_enum()
3500 {
3501 using namespace __format;
3502 if constexpr (is_same_v<_Tp, bool>)
3503 return _Arg_bool;
3504 else if constexpr (is_same_v<_Tp, _CharT>)
3505 return _Arg_c;
3506 else if constexpr (is_same_v<_Tp, int>)
3507 return _Arg_i;
3508 else if constexpr (is_same_v<_Tp, unsigned>)
3509 return _Arg_u;
3510 else if constexpr (is_same_v<_Tp, long long>)
3511 return _Arg_ll;
3512 else if constexpr (is_same_v<_Tp, unsigned long long>)
3513 return _Arg_ull;
3514 else if constexpr (is_same_v<_Tp, float>)
3515 return _Arg_flt;
3516 else if constexpr (is_same_v<_Tp, double>)
3517 return _Arg_dbl;
3518#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3519 else if constexpr (is_same_v<_Tp, long double>)
3520 return _Arg_ldbl;
3521#else
3522 // Don't use _Arg_ldbl for this target, it's ambiguous.
3523 else if constexpr (is_same_v<_Tp, __ibm128>)
3524 return _Arg_ibm128;
3525 else if constexpr (is_same_v<_Tp, __ieee128>)
3526 return _Arg_f128;
3527#endif
3528 else if constexpr (is_same_v<_Tp, const _CharT*>)
3529 return _Arg_str;
3530 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3531 return _Arg_sv;
3532 else if constexpr (is_same_v<_Tp, const void*>)
3533 return _Arg_ptr;
3534#ifdef __SIZEOF_INT128__
3535 else if constexpr (is_same_v<_Tp, __int128>)
3536 return _Arg_i128;
3537 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3538 return _Arg_u128;
3539#endif
3540
3541 // N.B. some of these types will never actually be used here,
3542 // because they get normalized to a standard floating-point type.
3543#if defined __FLT32_DIG__ && ! _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3544 else if constexpr (is_same_v<_Tp, _Float32>)
3545 return _Arg_f32;
3546#endif
3547#if defined __FLT64_DIG__ && ! _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3548 else if constexpr (is_same_v<_Tp, _Float64>)
3549 return _Arg_f64;
3550#endif
3551#if _GLIBCXX_FORMAT_F128 == 2
3552 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3553 return _Arg_f128;
3554#endif
3555 else if constexpr (is_same_v<_Tp, handle>)
3556 return _Arg_handle;
3557 }
3558
3559 template<typename _Tp>
3560 void
3561 _M_set(_Tp __v) noexcept
3562 {
3563 _M_type = _S_to_enum<_Tp>();
3564 _M_val._M_set(__v);
3565 }
3566
3567 template<typename _Tp>
3568 requires __format::__formattable_with<_Tp, _Context>
3569 explicit
3570 basic_format_arg(_Tp& __v) noexcept
3571 {
3572 using _Td = _Normalize<_Tp>;
3573 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3574 _M_set(_Td{__v.data(), __v.size()});
3575 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3576 && is_same_v<_CharT, wchar_t>)
3577 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3578 else
3579 _M_set(static_cast<_Td>(__v));
3580 }
3581
3582 template<typename _Ctx, typename... _Argz>
3583 friend auto
3584 make_format_args(_Argz&...) noexcept;
3585
3586 template<typename _Visitor, typename _Ctx>
3587 friend decltype(auto)
3588 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3589
3590 template<typename _Ch, typename _Tp>
3591 friend consteval __format::_Arg_t
3592 __format::__to_arg_t_enum() noexcept;
3593
3594 template<typename _Visitor>
3595 decltype(auto)
3596 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
3597 {
3598 using namespace __format;
3599 switch (__type)
3600 {
3601 case _Arg_none:
3602 return std::forward<_Visitor>(__vis)(_M_val._M_none);
3603 case _Arg_bool:
3604 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
3605 case _Arg_c:
3606 return std::forward<_Visitor>(__vis)(_M_val._M_c);
3607 case _Arg_i:
3608 return std::forward<_Visitor>(__vis)(_M_val._M_i);
3609 case _Arg_u:
3610 return std::forward<_Visitor>(__vis)(_M_val._M_u);
3611 case _Arg_ll:
3612 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
3613 case _Arg_ull:
3614 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
3615#if __glibcxx_to_chars // FIXME: need to be able to format these types!
3616 case _Arg_flt:
3617 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
3618 case _Arg_dbl:
3619 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
3620#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3621 case _Arg_ldbl:
3622 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
3623#else
3624 case _Arg_f128:
3625 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3626 case _Arg_ibm128:
3627 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
3628#endif
3629#endif
3630 case _Arg_str:
3631 return std::forward<_Visitor>(__vis)(_M_val._M_str);
3632 case _Arg_sv:
3633 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
3634 case _Arg_ptr:
3635 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
3636 case _Arg_handle:
3637 {
3638 auto& __h = static_cast<handle&>(_M_val._M_handle);
3639 return std::forward<_Visitor>(__vis)(__h);
3640 }
3641#ifdef __SIZEOF_INT128__
3642 case _Arg_i128:
3643 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
3644 case _Arg_u128:
3645 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
3646#endif
3647
3648#if _GLIBCXX_FORMAT_F128 == 2
3649 case _Arg_f128:
3650 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3651#endif
3652
3653 default:
3654 // _Arg_f16 etc.
3655 __builtin_unreachable();
3656 }
3657 }
3658 };
3659
3660 template<typename _Visitor, typename _Context>
3661 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
3662 inline decltype(auto)
3663 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
3664 {
3665 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
3666 }
3667
3668/// @cond undocumented
3669namespace __format
3670{
3671 struct _WidthPrecVisitor
3672 {
3673 template<typename _Tp>
3674 size_t
3675 operator()(_Tp& __arg) const
3676 {
3677 if constexpr (is_same_v<_Tp, monostate>)
3678 __format::__invalid_arg_id_in_format_string();
3679 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3680 // 3720. Restrict the valid types of arg-id for width and precision
3681 // 3721. Allow an arg-id with a value of zero for width
3682 else if constexpr (sizeof(_Tp) <= sizeof(long long))
3683 {
3684 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3685 // 3720. Restrict the valid types of arg-id for width and precision
3686 if constexpr (__is_unsigned_integer<_Tp>::value)
3687 return __arg;
3688 else if constexpr (__is_signed_integer<_Tp>::value)
3689 if (__arg >= 0)
3690 return __arg;
3691 }
3692 __throw_format_error("format error: argument used for width or "
3693 "precision must be a non-negative integer");
3694 }
3695 };
3696
3697#pragma GCC diagnostic push
3698#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
3699 template<typename _Context>
3700 inline size_t
3701 __int_from_arg(const basic_format_arg<_Context>& __arg)
3702 { return std::visit_format_arg(_WidthPrecVisitor(), __arg); }
3703
3704 // Pack _Arg_t enum values into a single 60-bit integer.
3705 template<int _Bits, size_t _Nm>
3706 constexpr auto
3707 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
3708 {
3709 __UINT64_TYPE__ __packed_types = 0;
3710 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
3711 __packed_types = (__packed_types << _Bits) | *__i;
3712 return __packed_types;
3713 }
3714} // namespace __format
3715/// @endcond
3716
3717 template<typename _Context>
3718 class basic_format_args
3719 {
3720 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
3721 static constexpr int _S_packed_type_mask = 0b11111;
3722 static constexpr int _S_max_packed_args = 12;
3723
3724 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
3725
3726 template<typename... _Args>
3727 using _Store = __format::_Arg_store<_Context, _Args...>;
3728
3729 template<typename _Ctx, typename... _Args>
3730 friend class __format::_Arg_store;
3731
3732 using uint64_t = __UINT64_TYPE__;
3733 using _Format_arg = basic_format_arg<_Context>;
3734 using _Format_arg_val = __format::_Arg_value<_Context>;
3735
3736 // If args are packed then the number of args is in _M_packed_size and
3737 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
3738 // If args are not packed then the number of args is in _M_unpacked_size
3739 // and _M_packed_size is zero.
3740 uint64_t _M_packed_size : 4;
3741 uint64_t _M_unpacked_size : 60;
3742
3743 union {
3744 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
3745 const _Format_arg* _M_args; // Active when _M_packed_size == 0
3746 };
3747
3748 size_t
3749 _M_size() const noexcept
3750 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
3751
3752 typename __format::_Arg_t
3753 _M_type(size_t __i) const noexcept
3754 {
3755 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
3756 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
3757 }
3758
3759 template<typename _Ctx, typename... _Args>
3760 friend auto
3761 make_format_args(_Args&...) noexcept;
3762
3763 // An array of _Arg_t enums corresponding to _Args...
3764 template<typename... _Args>
3765 static consteval array<__format::_Arg_t, sizeof...(_Args)>
3766 _S_types_to_pack()
3767 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
3768
3769 public:
3770 template<typename... _Args>
3771 basic_format_args(const _Store<_Args...>& __store) noexcept;
3772
3773 [[nodiscard,__gnu__::__always_inline__]]
3774 basic_format_arg<_Context>
3775 get(size_t __i) const noexcept
3776 {
3777 basic_format_arg<_Context> __arg;
3778 if (__i < _M_packed_size)
3779 {
3780 __arg._M_type = _M_type(__i);
3781 __arg._M_val = _M_values[__i];
3782 }
3783 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
3784 __arg = _M_args[__i];
3785 return __arg;
3786 }
3787 };
3788
3789 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3790 // 3810. CTAD for std::basic_format_args
3791 template<typename _Context, typename... _Args>
3792 basic_format_args(__format::_Arg_store<_Context, _Args...>)
3793 -> basic_format_args<_Context>;
3794
3795 template<typename _Context, typename... _Args>
3796 auto
3797 make_format_args(_Args&... __fmt_args) noexcept;
3798
3799 // An array of type-erased formatting arguments.
3800 template<typename _Context, typename... _Args>
3801 class __format::_Arg_store
3802 {
3803 friend std::basic_format_args<_Context>;
3804
3805 template<typename _Ctx, typename... _Argz>
3806 friend auto std::
3807#if _GLIBCXX_INLINE_VERSION
3808 __8:: // Needed for PR c++/59256
3809#endif
3810 make_format_args(_Argz&...) noexcept;
3811
3812 // For a sufficiently small number of arguments we only store values.
3813 // basic_format_args can get the types from the _Args pack.
3814 static constexpr bool _S_values_only
3815 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
3816
3817 using _Element_t
3818 = __conditional_t<_S_values_only,
3819 __format::_Arg_value<_Context>,
3820 basic_format_arg<_Context>>;
3821
3822 _Element_t _M_args[sizeof...(_Args)];
3823
3824 template<typename _Tp>
3825 static _Element_t
3826 _S_make_elt(_Tp& __v)
3827 {
3828 using _Tq = remove_const_t<_Tp>;
3829 using _CharT = typename _Context::char_type;
3830 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
3831 "std::formatter must be specialized for the type "
3832 "of each format arg");
3833 using __format::__formattable_with;
3834 if constexpr (is_const_v<_Tp>)
3835 if constexpr (!__formattable_with<_Tp, _Context>)
3836 if constexpr (__formattable_with<_Tq, _Context>)
3837 static_assert(__formattable_with<_Tp, _Context>,
3838 "format arg must be non-const because its "
3839 "std::formatter specialization has a "
3840 "non-const reference parameter");
3841 basic_format_arg<_Context> __arg(__v);
3842 if constexpr (_S_values_only)
3843 return __arg._M_val;
3844 else
3845 return __arg;
3846 }
3847
3848 template<typename... _Tp>
3849 requires (sizeof...(_Tp) == sizeof...(_Args))
3850 [[__gnu__::__always_inline__]]
3851 _Arg_store(_Tp&... __a) noexcept
3852 : _M_args{_S_make_elt(__a)...}
3853 { }
3854 };
3855
3856 template<typename _Context>
3857 class __format::_Arg_store<_Context>
3858 { };
3859
3860 template<typename _Context>
3861 template<typename... _Args>
3862 inline
3863 basic_format_args<_Context>::
3864 basic_format_args(const _Store<_Args...>& __store) noexcept
3865 {
3866 if constexpr (sizeof...(_Args) == 0)
3867 {
3868 _M_packed_size = 0;
3869 _M_unpacked_size = 0;
3870 _M_args = nullptr;
3871 }
3872 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
3873 {
3874 // The number of packed arguments:
3875 _M_packed_size = sizeof...(_Args);
3876 // The packed type enums:
3877 _M_unpacked_size
3878 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
3879 // The _Arg_value objects.
3880 _M_values = __store._M_args;
3881 }
3882 else
3883 {
3884 // No packed arguments:
3885 _M_packed_size = 0;
3886 // The number of unpacked arguments:
3887 _M_unpacked_size = sizeof...(_Args);
3888 // The basic_format_arg objects:
3889 _M_args = __store._M_args;
3890 }
3891 }
3892
3893 /// Capture formatting arguments for use by `std::vformat`.
3894 template<typename _Context = format_context, typename... _Args>
3895 [[nodiscard,__gnu__::__always_inline__]]
3896 inline auto
3897 make_format_args(_Args&... __fmt_args) noexcept
3898 {
3899 using _Fmt_arg = basic_format_arg<_Context>;
3900 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
3901 _Normalize<_Args>...>;
3902 return _Store(__fmt_args...);
3903 }
3904
3905#ifdef _GLIBCXX_USE_WCHAR_T
3906 /// Capture formatting arguments for use by `std::vformat` (for wide output).
3907 template<typename... _Args>
3908 [[nodiscard,__gnu__::__always_inline__]]
3909 inline auto
3910 make_wformat_args(_Args&... __args) noexcept
3911 { return std::make_format_args<wformat_context>(__args...); }
3912#endif
3913
3914/// @cond undocumented
3915namespace __format
3916{
3917 template<typename _Out, typename _CharT, typename _Context>
3918 _Out
3919 __do_vformat_to(_Out, basic_string_view<_CharT>,
3920 const basic_format_args<_Context>&,
3921 const locale* = nullptr);
3922
3923 template<typename _CharT> struct __formatter_chrono;
3924
3925} // namespace __format
3926/// @endcond
3927
3928 /** Context for std::format and similar functions.
3929 *
3930 * A formatting context contains an output iterator and locale to use
3931 * for the formatting operations. Most programs will never need to use
3932 * this class template explicitly. For typical uses of `std::format` the
3933 * library will use the specializations `std::format_context` (for `char`)
3934 * and `std::wformat_context` (for `wchar_t`).
3935 *
3936 * You are not allowed to define partial or explicit specializations of
3937 * this class template.
3938 *
3939 * @since C++20
3940 */
3941 template<typename _Out, typename _CharT>
3942 class basic_format_context
3943 {
3944 static_assert( output_iterator<_Out, const _CharT&> );
3945
3946 basic_format_args<basic_format_context> _M_args;
3947 _Out _M_out;
3948 __format::_Optional_locale _M_loc;
3949
3950 basic_format_context(basic_format_args<basic_format_context> __args,
3951 _Out __out)
3952 : _M_args(__args), _M_out(std::move(__out))
3953 { }
3954
3955 basic_format_context(basic_format_args<basic_format_context> __args,
3956 _Out __out, const std::locale& __loc)
3957 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
3958 { }
3959
3960 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3961 // 4061. Should std::basic_format_context be
3962 // default-constructible/copyable/movable?
3963 basic_format_context(const basic_format_context&) = delete;
3964 basic_format_context& operator=(const basic_format_context&) = delete;
3965
3966 template<typename _Out2, typename _CharT2, typename _Context2>
3967 friend _Out2
3968 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
3969 const basic_format_args<_Context2>&,
3970 const locale*);
3971
3972 friend __format::__formatter_chrono<_CharT>;
3973
3974 public:
3975 ~basic_format_context() = default;
3976
3977 using iterator = _Out;
3978 using char_type = _CharT;
3979 template<typename _Tp>
3980 using formatter_type = formatter<_Tp, _CharT>;
3981
3982 [[nodiscard]]
3983 basic_format_arg<basic_format_context>
3984 arg(size_t __id) const noexcept
3985 { return _M_args.get(__id); }
3986
3987 [[nodiscard]]
3988 std::locale locale() { return _M_loc.value(); }
3989
3990 [[nodiscard]]
3991 iterator out() { return std::move(_M_out); }
3992
3993 void advance_to(iterator __it) { _M_out = std::move(__it); }
3994 };
3995
3996
3997/// @cond undocumented
3998namespace __format
3999{
4000 // Abstract base class defining an interface for scanning format strings.
4001 // Scan the characters in a format string, dividing it up into strings of
4002 // ordinary characters, escape sequences, and replacement fields.
4003 // Call virtual functions for derived classes to parse format-specifiers
4004 // or write formatted output.
4005 template<typename _CharT>
4006 struct _Scanner
4007 {
4008 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4009
4010 struct _Parse_context : basic_format_parse_context<_CharT>
4011 {
4012 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4013 const _Arg_t* _M_types = nullptr;
4014 } _M_pc;
4015
4016 constexpr explicit
4017 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = -1)
4018 : _M_pc(__str, __nargs)
4019 { }
4020
4021 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4022 constexpr iterator end() const noexcept { return _M_pc.end(); }
4023
4024 constexpr void
4025 _M_scan()
4026 {
4027 basic_string_view<_CharT> __fmt = _M_fmt_str();
4028
4029 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4030 {
4031 _M_pc.advance_to(begin() + 1);
4032 _M_format_arg(_M_pc.next_arg_id());
4033 return;
4034 }
4035
4036 size_t __lbr = __fmt.find('{');
4037 size_t __rbr = __fmt.find('}');
4038
4039 while (__fmt.size())
4040 {
4041 auto __cmp = __lbr <=> __rbr;
4042 if (__cmp == 0)
4043 {
4044 _M_on_chars(end());
4045 _M_pc.advance_to(end());
4046 return;
4047 }
4048 else if (__cmp < 0)
4049 {
4050 if (__lbr + 1 == __fmt.size()
4051 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4052 __format::__unmatched_left_brace_in_format_string();
4053 const bool __is_escape = __fmt[__lbr + 1] == '{';
4054 iterator __last = begin() + __lbr + int(__is_escape);
4055 _M_on_chars(__last);
4056 _M_pc.advance_to(__last + 1);
4057 __fmt = _M_fmt_str();
4058 if (__is_escape)
4059 {
4060 if (__rbr != __fmt.npos)
4061 __rbr -= __lbr + 2;
4062 __lbr = __fmt.find('{');
4063 }
4064 else
4065 {
4066 _M_on_replacement_field();
4067 __fmt = _M_fmt_str();
4068 __lbr = __fmt.find('{');
4069 __rbr = __fmt.find('}');
4070 }
4071 }
4072 else
4073 {
4074 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4075 __format::__unmatched_right_brace_in_format_string();
4076 iterator __last = begin() + __rbr;
4077 _M_on_chars(__last);
4078 _M_pc.advance_to(__last + 1);
4079 __fmt = _M_fmt_str();
4080 if (__lbr != __fmt.npos)
4081 __lbr -= __rbr + 1;
4082 __rbr = __fmt.find('}');
4083 }
4084 }
4085 }
4086
4087 constexpr basic_string_view<_CharT>
4088 _M_fmt_str() const noexcept
4089 { return {begin(), end()}; }
4090
4091 constexpr virtual void _M_on_chars(iterator) { }
4092
4093 constexpr void _M_on_replacement_field()
4094 {
4095 auto __next = begin();
4096
4097 size_t __id;
4098 if (*__next == '}')
4099 __id = _M_pc.next_arg_id();
4100 else if (*__next == ':')
4101 {
4102 __id = _M_pc.next_arg_id();
4103 _M_pc.advance_to(++__next);
4104 }
4105 else
4106 {
4107 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4108 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4109 __format::__invalid_arg_id_in_format_string();
4110 _M_pc.check_arg_id(__id = __i);
4111 if (*__ptr == ':')
4112 {
4113 _M_pc.advance_to(++__ptr);
4114 }
4115 else
4116 _M_pc.advance_to(__ptr);
4117 }
4118 _M_format_arg(__id);
4119 if (begin() == end() || *begin() != '}')
4120 __format::__unmatched_left_brace_in_format_string();
4121 _M_pc.advance_to(begin() + 1); // Move past '}'
4122 }
4123
4124 constexpr virtual void _M_format_arg(size_t __id) = 0;
4125 };
4126
4127 // Process a format string and format the arguments in the context.
4128 template<typename _Out, typename _CharT>
4129 class _Formatting_scanner : public _Scanner<_CharT>
4130 {
4131 public:
4132 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4133 basic_string_view<_CharT> __str)
4134 : _Scanner<_CharT>(__str), _M_fc(__fc)
4135 { }
4136
4137 private:
4138 basic_format_context<_Out, _CharT>& _M_fc;
4139
4140 using iterator = typename _Scanner<_CharT>::iterator;
4141
4142 constexpr void
4143 _M_on_chars(iterator __last) override
4144 {
4145 basic_string_view<_CharT> __str(this->begin(), __last);
4146 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4147 }
4148
4149 constexpr void
4150 _M_format_arg(size_t __id) override
4151 {
4152 using _Context = basic_format_context<_Out, _CharT>;
4153 using handle = typename basic_format_arg<_Context>::handle;
4154
4155 std::visit_format_arg([this](auto& __arg) {
4156 using _Type = remove_reference_t<decltype(__arg)>;
4157 using _Formatter = typename _Context::template formatter_type<_Type>;
4158 if constexpr (is_same_v<_Type, monostate>)
4159 __format::__invalid_arg_id_in_format_string();
4160 else if constexpr (is_same_v<_Type, handle>)
4161 __arg.format(this->_M_pc, this->_M_fc);
4162 else if constexpr (is_default_constructible_v<_Formatter>)
4163 {
4164 _Formatter __f;
4165 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4166 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4167 }
4168 else
4169 static_assert(__format::__formattable_with<_Type, _Context>);
4170 }, _M_fc.arg(__id));
4171 }
4172 };
4173
4174 template<typename _CharT, typename _Tp>
4175 consteval _Arg_t
4176 __to_arg_t_enum() noexcept
4177 {
4178 using _Context = __format::__format_context<_CharT>;
4179 using _Fmt_arg = basic_format_arg<_Context>;
4180 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4181 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4182 }
4183
4184 // Validate a format string for Args.
4185 template<typename _CharT, typename... _Args>
4186 class _Checking_scanner : public _Scanner<_CharT>
4187 {
4188 static_assert(
4189 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4190 "std::formatter must be specialized for each type being formatted");
4191
4192 public:
4193 consteval
4194 _Checking_scanner(basic_string_view<_CharT> __str)
4195 : _Scanner<_CharT>(__str, sizeof...(_Args))
4196 {
4197#if __cpp_lib_format >= 202305L
4198 this->_M_pc._M_types = _M_types.data();
4199#endif
4200 }
4201
4202 private:
4203 constexpr void
4204 _M_format_arg(size_t __id) override
4205 {
4206 if constexpr (sizeof...(_Args) != 0)
4207 {
4208 if (__id < sizeof...(_Args))
4209 {
4210 _M_parse_format_spec<_Args...>(__id);
4211 return;
4212 }
4213 }
4214 __builtin_unreachable();
4215 }
4216
4217 template<typename _Tp, typename... _OtherArgs>
4218 constexpr void
4219 _M_parse_format_spec(size_t __id)
4220 {
4221 if (__id == 0)
4222 {
4223 formatter<_Tp, _CharT> __f;
4224 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4225 }
4226 else if constexpr (sizeof...(_OtherArgs) != 0)
4227 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4228 else
4229 __builtin_unreachable();
4230 }
4231
4232#if __cpp_lib_format >= 202305L
4233 array<_Arg_t, sizeof...(_Args)>
4234 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
4235#endif
4236 };
4237
4238 template<typename _Out, typename _CharT, typename _Context>
4239 inline _Out
4240 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4241 const basic_format_args<_Context>& __args,
4242 const locale* __loc)
4243 {
4244 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4245 _Sink_iter<_CharT> __sink_out;
4246
4247 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4248 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4249 else
4250 __sink_out = __sink.out();
4251
4252 if constexpr (is_same_v<_CharT, char>)
4253 // Fast path for "{}" format strings and simple format arg types.
4254 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4255 {
4256 bool __done = false;
4257 std::visit_format_arg([&](auto& __arg) {
4258 using _Tp = remove_cvref_t<decltype(__arg)>;
4259 if constexpr (is_same_v<_Tp, bool>)
4260 {
4261 size_t __len = 4 + !__arg;
4262 const char* __chars[] = { "false", "true" };
4263 if (auto __res = __sink_out._M_reserve(__len))
4264 {
4265 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4266 __res._M_bump(__len);
4267 __done = true;
4268 }
4269 }
4270 else if constexpr (is_same_v<_Tp, char>)
4271 {
4272 if (auto __res = __sink_out._M_reserve(1))
4273 {
4274 *__res.get() = __arg;
4275 __res._M_bump(1);
4276 __done = true;
4277 }
4278 }
4279 else if constexpr (is_integral_v<_Tp>)
4280 {
4281 make_unsigned_t<_Tp> __uval;
4282 const bool __neg = __arg < 0;
4283 if (__neg)
4284 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4285 else
4286 __uval = __arg;
4287 const auto __n = __detail::__to_chars_len(__uval);
4288 if (auto __res = __sink_out._M_reserve(__n + __neg))
4289 {
4290 auto __ptr = __res.get();
4291 *__ptr = '-';
4292 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4293 __uval);
4294 __res._M_bump(__n + __neg);
4295 __done = true;
4296 }
4297 }
4298 else if constexpr (is_convertible_v<_Tp, string_view>)
4299 {
4300 string_view __sv = __arg;
4301 if (auto __res = __sink_out._M_reserve(__sv.size()))
4302 {
4303 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4304 __res._M_bump(__sv.size());
4305 __done = true;
4306 }
4307 }
4308 }, __args.get(0));
4309
4310 if (__done)
4311 {
4312 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4313 return __sink_out;
4314 else
4315 return std::move(__sink)._M_finish().out;
4316 }
4317 }
4318
4319 auto __ctx = __loc == nullptr
4320 ? _Context(__args, __sink_out)
4321 : _Context(__args, __sink_out, *__loc);
4322 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4323 __scanner._M_scan();
4324
4325 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4326 return __ctx.out();
4327 else
4328 return std::move(__sink)._M_finish().out;
4329 }
4330#pragma GCC diagnostic pop
4331
4332} // namespace __format
4333/// @endcond
4334
4335#if __cpp_lib_format >= 202305L
4336 template<typename _CharT>
4337 template<typename... _Ts>
4338 constexpr void
4339 basic_format_parse_context<_CharT>::check_dynamic_spec(size_t __id) noexcept
4340 {
4341 // This call enforces the Mandates: condition that _Ts contains valid
4342 // types and each type appears at most once. It could be a static_assert
4343 // but this way failures give better diagnostics, due to calling the
4344 // non-constexpr __invalid_dynamic_spec function.
4345 [[maybe_unused]]
4346 constexpr bool __ok = __check_dynamic_spec_types<_Ts...>();
4347
4348 if consteval {
4349 if (__id >= _M_num_args)
4350 __format::__invalid_arg_id_in_format_string();
4351 if constexpr (sizeof...(_Ts) != 0)
4352 {
4353 using _Parse_context = __format::_Scanner<_CharT>::_Parse_context;
4354 auto __arg = static_cast<_Parse_context*>(this)->_M_types[__id];
4355 __format::_Arg_t __types[] = {
4356 __format::__to_arg_t_enum<_CharT, _Ts>()...
4357 };
4358 for (auto __t : __types)
4359 if (__arg == __t)
4360 return;
4361 }
4362 __invalid_dynamic_spec("arg(id) type does not match");
4363 }
4364 }
4365#endif
4366
4367 template<typename _CharT, typename... _Args>
4368 template<typename _Tp>
4369 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4370 consteval
4371 basic_format_string<_CharT, _Args...>::
4372 basic_format_string(const _Tp& __s)
4373 : _M_str(__s)
4374 {
4375 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4376 __scanner(_M_str);
4377 __scanner._M_scan();
4378 }
4379
4380 // [format.functions], formatting functions
4381
4382 template<typename _Out> requires output_iterator<_Out, const char&>
4383 [[__gnu__::__always_inline__]]
4384 inline _Out
4385 vformat_to(_Out __out, string_view __fmt, format_args __args)
4386 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4387
4388#ifdef _GLIBCXX_USE_WCHAR_T
4389 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4390 [[__gnu__::__always_inline__]]
4391 inline _Out
4392 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4393 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4394#endif
4395
4396 template<typename _Out> requires output_iterator<_Out, const char&>
4397 [[__gnu__::__always_inline__]]
4398 inline _Out
4399 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4400 format_args __args)
4401 {
4402 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4403 }
4404
4405#ifdef _GLIBCXX_USE_WCHAR_T
4406 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4407 [[__gnu__::__always_inline__]]
4408 inline _Out
4409 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4410 wformat_args __args)
4411 {
4412 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4413 }
4414#endif
4415
4416 [[nodiscard]]
4417 inline string
4418 vformat(string_view __fmt, format_args __args)
4419 {
4420 __format::_Str_sink<char> __buf;
4421 std::vformat_to(__buf.out(), __fmt, __args);
4422 return std::move(__buf).get();
4423 }
4424
4425#ifdef _GLIBCXX_USE_WCHAR_T
4426 [[nodiscard]]
4427 inline wstring
4428 vformat(wstring_view __fmt, wformat_args __args)
4429 {
4430 __format::_Str_sink<wchar_t> __buf;
4431 std::vformat_to(__buf.out(), __fmt, __args);
4432 return std::move(__buf).get();
4433 }
4434#endif
4435
4436 [[nodiscard]]
4437 inline string
4438 vformat(const locale& __loc, string_view __fmt, format_args __args)
4439 {
4440 __format::_Str_sink<char> __buf;
4441 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4442 return std::move(__buf).get();
4443 }
4444
4445#ifdef _GLIBCXX_USE_WCHAR_T
4446 [[nodiscard]]
4447 inline wstring
4448 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4449 {
4450 __format::_Str_sink<wchar_t> __buf;
4451 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4452 return std::move(__buf).get();
4453 }
4454#endif
4455
4456 template<typename... _Args>
4457 [[nodiscard]]
4458 inline string
4459 format(format_string<_Args...> __fmt, _Args&&... __args)
4460 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4461
4462#ifdef _GLIBCXX_USE_WCHAR_T
4463 template<typename... _Args>
4464 [[nodiscard]]
4465 inline wstring
4466 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4467 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4468#endif
4469
4470 template<typename... _Args>
4471 [[nodiscard]]
4472 inline string
4473 format(const locale& __loc, format_string<_Args...> __fmt,
4474 _Args&&... __args)
4475 {
4476 return std::vformat(__loc, __fmt.get(),
4477 std::make_format_args(__args...));
4478 }
4479
4480#ifdef _GLIBCXX_USE_WCHAR_T
4481 template<typename... _Args>
4482 [[nodiscard]]
4483 inline wstring
4484 format(const locale& __loc, wformat_string<_Args...> __fmt,
4485 _Args&&... __args)
4486 {
4487 return std::vformat(__loc, __fmt.get(),
4488 std::make_wformat_args(__args...));
4489 }
4490#endif
4491
4492 template<typename _Out, typename... _Args>
4493 requires output_iterator<_Out, const char&>
4494 inline _Out
4495 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4496 {
4497 return std::vformat_to(std::move(__out), __fmt.get(),
4498 std::make_format_args(__args...));
4499 }
4500
4501#ifdef _GLIBCXX_USE_WCHAR_T
4502 template<typename _Out, typename... _Args>
4503 requires output_iterator<_Out, const wchar_t&>
4504 inline _Out
4505 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4506 {
4507 return std::vformat_to(std::move(__out), __fmt.get(),
4508 std::make_wformat_args(__args...));
4509 }
4510#endif
4511
4512 template<typename _Out, typename... _Args>
4513 requires output_iterator<_Out, const char&>
4514 inline _Out
4515 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4516 _Args&&... __args)
4517 {
4518 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4519 std::make_format_args(__args...));
4520 }
4521
4522#ifdef _GLIBCXX_USE_WCHAR_T
4523 template<typename _Out, typename... _Args>
4524 requires output_iterator<_Out, const wchar_t&>
4525 inline _Out
4526 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4527 _Args&&... __args)
4528 {
4529 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4530 std::make_wformat_args(__args...));
4531 }
4532#endif
4533
4534 template<typename _Out, typename... _Args>
4535 requires output_iterator<_Out, const char&>
4536 inline format_to_n_result<_Out>
4537 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4538 format_string<_Args...> __fmt, _Args&&... __args)
4539 {
4540 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4541 std::vformat_to(__sink.out(), __fmt.get(),
4542 std::make_format_args(__args...));
4543 return std::move(__sink)._M_finish();
4544 }
4545
4546#ifdef _GLIBCXX_USE_WCHAR_T
4547 template<typename _Out, typename... _Args>
4548 requires output_iterator<_Out, const wchar_t&>
4549 inline format_to_n_result<_Out>
4550 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4551 wformat_string<_Args...> __fmt, _Args&&... __args)
4552 {
4553 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4554 std::vformat_to(__sink.out(), __fmt.get(),
4555 std::make_wformat_args(__args...));
4556 return std::move(__sink)._M_finish();
4557 }
4558#endif
4559
4560 template<typename _Out, typename... _Args>
4561 requires output_iterator<_Out, const char&>
4562 inline format_to_n_result<_Out>
4563 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4564 format_string<_Args...> __fmt, _Args&&... __args)
4565 {
4566 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4567 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4568 std::make_format_args(__args...));
4569 return std::move(__sink)._M_finish();
4570 }
4571
4572#ifdef _GLIBCXX_USE_WCHAR_T
4573 template<typename _Out, typename... _Args>
4574 requires output_iterator<_Out, const wchar_t&>
4575 inline format_to_n_result<_Out>
4576 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4577 wformat_string<_Args...> __fmt, _Args&&... __args)
4578 {
4579 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4580 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4581 std::make_wformat_args(__args...));
4582 return std::move(__sink)._M_finish();
4583 }
4584#endif
4585
4586/// @cond undocumented
4587namespace __format
4588{
4589#if 1
4590 template<typename _CharT>
4591 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
4592 {
4593 public:
4594 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
4595
4596 [[__gnu__::__always_inline__]]
4597 size_t
4598 count() const
4599 { return this->_M_count + this->_M_used().size(); }
4600 };
4601#else
4602 template<typename _CharT>
4603 class _Counting_sink : public _Buf_sink<_CharT>
4604 {
4605 size_t _M_count = 0;
4606
4607 void
4608 _M_overflow() override
4609 {
4610 if (!std::is_constant_evaluated())
4611 _M_count += this->_M_used().size();
4612 this->_M_rewind();
4613 }
4614
4615 public:
4616 _Counting_sink() = default;
4617
4618 [[__gnu__::__always_inline__]]
4619 size_t
4620 count() noexcept
4621 {
4622 _Counting_sink::_M_overflow();
4623 return _M_count;
4624 }
4625 };
4626#endif
4627} // namespace __format
4628/// @endcond
4629
4630 template<typename... _Args>
4631 [[nodiscard]]
4632 inline size_t
4633 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
4634 {
4635 __format::_Counting_sink<char> __buf;
4636 std::vformat_to(__buf.out(), __fmt.get(),
4637 std::make_format_args(__args...));
4638 return __buf.count();
4639 }
4640
4641#ifdef _GLIBCXX_USE_WCHAR_T
4642 template<typename... _Args>
4643 [[nodiscard]]
4644 inline size_t
4645 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
4646 {
4647 __format::_Counting_sink<wchar_t> __buf;
4648 std::vformat_to(__buf.out(), __fmt.get(),
4649 std::make_wformat_args(__args...));
4650 return __buf.count();
4651 }
4652#endif
4653
4654 template<typename... _Args>
4655 [[nodiscard]]
4656 inline size_t
4657 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
4658 _Args&&... __args)
4659 {
4660 __format::_Counting_sink<char> __buf;
4661 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4662 std::make_format_args(__args...));
4663 return __buf.count();
4664 }
4665
4666#ifdef _GLIBCXX_USE_WCHAR_T
4667 template<typename... _Args>
4668 [[nodiscard]]
4669 inline size_t
4670 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
4671 _Args&&... __args)
4672 {
4673 __format::_Counting_sink<wchar_t> __buf;
4674 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4675 std::make_wformat_args(__args...));
4676 return __buf.count();
4677 }
4678#endif
4679
4680#if __cpp_lib_format_ranges
4681 // [format.range], formatting of ranges
4682 // [format.range.fmtkind], variable template format_kind
4683 enum class range_format {
4684 disabled,
4685 map,
4686 set,
4687 sequence,
4688 string,
4689 debug_string
4690 };
4691
4692 /// @cond undocumented
4693 template<typename _Rg>
4694 constexpr auto format_kind = not defined(format_kind<_Rg>);
4695
4696 template<typename _Tp>
4697 consteval range_format
4698 __fmt_kind()
4699 {
4700 using _Ref = ranges::range_reference_t<_Tp>;
4701 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
4702 return range_format::disabled;
4703 else if constexpr (requires { typename _Tp::key_type; })
4704 {
4705 if constexpr (requires { typename _Tp::mapped_type; })
4706 {
4707 using _Up = remove_cvref_t<_Ref>;
4708 if constexpr (__is_pair<_Up>)
4709 return range_format::map;
4710 else if constexpr (__is_specialization_of<_Up, tuple>)
4711 if constexpr (tuple_size_v<_Up> == 2)
4712 return range_format::map;
4713 }
4714 return range_format::set;
4715 }
4716 else
4717 return range_format::sequence;
4718 }
4719 /// @endcond
4720
4721 /// A constant determining how a range should be formatted.
4722 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
4723 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
4724
4725 // [format.range.formatter], class template range_formatter
4726 template<typename _Tp, typename _CharT = char>
4727 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
4728 class range_formatter; // TODO
4729
4730/// @cond undocumented
4731namespace __format
4732{
4733 // [format.range.fmtdef], class template range-default-formatter
4734 template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
4735 struct __range_default_formatter; // TODO
4736} // namespace __format
4737/// @endcond
4738
4739 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
4740 // specializations for maps, sets, and strings
4741 template<ranges::input_range _Rg, typename _CharT>
4742 requires (format_kind<_Rg> != range_format::disabled)
4743 && formattable<ranges::range_reference_t<_Rg>, _CharT>
4744 struct formatter<_Rg, _CharT>
4745 : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
4746 { };
4747#endif // C++23 formatting ranges
4748
4749_GLIBCXX_END_NAMESPACE_VERSION
4750} // namespace std
4751#endif // __cpp_lib_format
4752#pragma GCC diagnostic pop
4753#endif // _GLIBCXX_FORMAT
constexpr complex< _Tp > operator*(const complex< _Tp > &__x, const complex< _Tp > &__y)
Return new complex value x times y.
Definition complex:405
_Tp arg(const complex< _Tp > &)
Return phase angle of z.
Definition complex:928
typename remove_reference< _Tp >::type remove_reference_t
Alias template for remove_reference.
Definition type_traits:1799
typename make_unsigned< _Tp >::type make_unsigned_t
Alias template for make_unsigned.
Definition type_traits:2142
constexpr _Tp * addressof(_Tp &__r) noexcept
Returns the actual address of the object or function referenced by r, even in the presence of an over...
Definition move.h:163
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:127
_Tp * end(valarray< _Tp > &__va) noexcept
Return an iterator pointing to one past the last element of the valarray.
Definition valarray:1251
_Tp * begin(valarray< _Tp > &__va) noexcept
Return an iterator pointing to the first element of the valarray.
Definition valarray:1229
basic_string< char > string
A string of char.
Definition stringfwd.h:79
basic_string< wchar_t > wstring
A string of wchar_t.
Definition stringfwd.h:82
ISO C++ entities toplevel namespace is std.
chars_format
floating-point format for primitive numerical conversion
Definition charconv:626
_CharT toupper(_CharT __c, const locale &__loc)
Convenience interface to ctype.toupper(__c).
constexpr auto size(const _Container &__cont) noexcept(noexcept(__cont.size())) -> decltype(__cont.size())
Return the size of a container.
GNU extensions for public use.
__numeric_traits_integer< _Tp > __int_traits
Convenience alias for __numeric_traits<integer-type>.
make_unsigned
Definition type_traits:1995
const _CharT * data() const noexcept
Return const pointer to contents.
void __resize_and_overwrite(size_type __n, _Operation __op)
Non-standard version of resize_and_overwrite for C++11 and above.
basic_string substr(size_type __pos=0, size_type __n=npos) const
Get a substring.
void reserve(size_type __res_arg)
Attempt to preallocate enough memory for specified number of characters.
void insert(iterator __p, size_type __n, _CharT __c)
Insert multiple characters.
size_type size() const noexcept
Returns the number of characters in the string, not including any null-termination.
Definition cow_string.h:913
basic_string & append(const basic_string &__str)
Append a string to this string.
bool empty() const noexcept
size_type capacity() const noexcept
Container class for localization functionality.