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