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 [[__gnu__::__always_inline__]]
1281 static size_t
1282 _S_character_width(_CharT __c)
1283 {
1284 // N.B. single byte cannot encode charcter of width greater than 1
1285 if constexpr (sizeof(_CharT) > 1u &&
1286 __unicode::__literal_encoding_is_unicode<_CharT>())
1287 return __unicode::__field_width(__c);
1288 else
1289 return 1u;
1290 }
1291
1292 template<typename _Out>
1293 typename basic_format_context<_Out, _CharT>::iterator
1294 _M_format_character(_CharT __c,
1295 basic_format_context<_Out, _CharT>& __fc) const
1296 {
1297 return __format::__write_padded_as_spec({&__c, 1u},
1298 _S_character_width(__c),
1299 __fc, _M_spec);
1300 }
1301
1302 template<typename _Int>
1303 static _CharT
1304 _S_to_character(_Int __i)
1305 {
1306 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1307 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1308 {
1309 if (_Traits::__min <= __i && __i <= _Traits::__max)
1310 return static_cast<_CharT>(__i);
1311 }
1312 else if constexpr (is_signed_v<_Int>)
1313 {
1314 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1315 return static_cast<_CharT>(__i);
1316 }
1317 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1318 return static_cast<_CharT>(__i);
1319 __throw_format_error("format error: integer not representable as "
1320 "character");
1321 }
1322
1323 template<typename _Out>
1324 typename basic_format_context<_Out, _CharT>::iterator
1325 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1326 basic_format_context<_Out, _CharT>& __fc) const
1327 {
1328 size_t __width = _M_spec._M_get_width(__fc);
1329
1330 basic_string_view<_CharT> __str;
1331 if constexpr (is_same_v<char, _CharT>)
1332 __str = __narrow_str;
1333#ifdef _GLIBCXX_USE_WCHAR_T
1334 else
1335 {
1336 size_t __n = __narrow_str.size();
1337 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1338 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1339 __str = {__p, __n};
1340 }
1341#endif
1342
1343 if (_M_spec._M_localized)
1344 {
1345 const auto& __l = __fc.locale();
1346 if (__l.name() != "C")
1347 {
1348 auto& __np = use_facet<numpunct<_CharT>>(__l);
1349 string __grp = __np.grouping();
1350 if (!__grp.empty())
1351 {
1352 size_t __n = __str.size() - __prefix_len;
1353 auto __p = (_CharT*)__builtin_alloca(2 * __n
1354 * sizeof(_CharT)
1355 + __prefix_len);
1356 auto __s = __str.data();
1357 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1358 __s += __prefix_len;
1359 auto __end = std::__add_grouping(__p + __prefix_len,
1360 __np.thousands_sep(),
1361 __grp.data(),
1362 __grp.size(),
1363 __s, __s + __n);
1364 __str = {__p, size_t(__end - __p)};
1365 }
1366 }
1367 }
1368
1369 if (__width <= __str.size())
1370 return __format::__write(__fc.out(), __str);
1371
1372 char32_t __fill_char = _M_spec._M_fill;
1373 _Align __align = _M_spec._M_align;
1374
1375 size_t __nfill = __width - __str.size();
1376 auto __out = __fc.out();
1377 if (__align == _Align_default)
1378 {
1379 __align = _Align_right;
1380 if (_M_spec._M_zero_fill)
1381 {
1382 __fill_char = _CharT('0');
1383 // Write sign and base prefix before zero filling.
1384 if (__prefix_len != 0)
1385 {
1386 __out = __format::__write(std::move(__out),
1387 __str.substr(0, __prefix_len));
1388 __str.remove_prefix(__prefix_len);
1389 }
1390 }
1391 else
1392 __fill_char = _CharT(' ');
1393 }
1394 return __format::__write_padded(std::move(__out), __str,
1395 __align, __nfill, __fill_char);
1396 }
1397
1398#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1399 template<typename _Tp>
1400 using make_unsigned_t
1401 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1403 type_identity<unsigned __int128>>::type;
1404
1405 // std::to_chars is not overloaded for int128 in strict mode.
1406 template<typename _Int>
1407 static to_chars_result
1408 to_chars(char* __first, char* __last, _Int __value, int __base)
1409 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1410#endif
1411
1412 _Spec<_CharT> _M_spec{};
1413 };
1414
1415 // Decide how 128-bit floating-point types should be formatted (or not).
1416 // When supported, the typedef __format::__float128_t is the type that
1417 // format arguments should be converted to for storage in basic_format_arg.
1418 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1419 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1420 // by converting them to long double (or __ieee128 for powerpc64le).
1421 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1422 // support for _Float128, rather than formatting it as another type.
1423#undef _GLIBCXX_FORMAT_F128
1424
1425#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1426
1427 // Format 128-bit floating-point types using __ieee128.
1428 using __float128_t = __ieee128;
1429# define _GLIBCXX_FORMAT_F128 1
1430
1431#ifdef __LONG_DOUBLE_IEEE128__
1432 // These overloads exist in the library, but are not declared.
1433 // Make them available as std::__format::to_chars.
1434 to_chars_result
1435 to_chars(char*, char*, __ibm128) noexcept
1436 __asm("_ZSt8to_charsPcS_e");
1437
1438 to_chars_result
1439 to_chars(char*, char*, __ibm128, chars_format) noexcept
1440 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1441
1442 to_chars_result
1443 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1444 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1445#elif __cplusplus == 202002L
1446 to_chars_result
1447 to_chars(char*, char*, __ieee128) noexcept
1448 __asm("_ZSt8to_charsPcS_u9__ieee128");
1449
1450 to_chars_result
1451 to_chars(char*, char*, __ieee128, chars_format) noexcept
1452 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1453
1454 to_chars_result
1455 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1456 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1457#endif
1458
1459#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1460
1461 // Format 128-bit floating-point types using long double.
1462 using __float128_t = long double;
1463# define _GLIBCXX_FORMAT_F128 1
1464
1465#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1466
1467 // Format 128-bit floating-point types using _Float128.
1468 using __float128_t = _Float128;
1469# define _GLIBCXX_FORMAT_F128 2
1470
1471# if __cplusplus == 202002L
1472 // These overloads exist in the library, but are not declared for C++20.
1473 // Make them available as std::__format::to_chars.
1474 to_chars_result
1475 to_chars(char*, char*, _Float128) noexcept
1476# if _GLIBCXX_INLINE_VERSION
1477 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1478# else
1479 __asm("_ZSt8to_charsPcS_DF128_");
1480# endif
1481
1482 to_chars_result
1483 to_chars(char*, char*, _Float128, chars_format) noexcept
1484# if _GLIBCXX_INLINE_VERSION
1485 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1486# else
1487 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1488# endif
1489
1490 to_chars_result
1491 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1492# if _GLIBCXX_INLINE_VERSION
1493 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1494# else
1495 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1496# endif
1497# endif
1498#endif
1499
1500 using std::to_chars;
1501
1502 // We can format a floating-point type iff it is usable with to_chars.
1503 template<typename _Tp>
1504 concept __formattable_float
1505 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1506 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1507
1508 template<__char _CharT>
1509 struct __formatter_fp
1510 {
1511 constexpr typename basic_format_parse_context<_CharT>::iterator
1512 parse(basic_format_parse_context<_CharT>& __pc)
1513 {
1514 _Spec<_CharT> __spec{};
1515 const auto __last = __pc.end();
1516 auto __first = __pc.begin();
1517
1518 auto __finalize = [this, &__spec] {
1519 _M_spec = __spec;
1520 };
1521
1522 auto __finished = [&] {
1523 if (__first == __last || *__first == '}')
1524 {
1525 __finalize();
1526 return true;
1527 }
1528 return false;
1529 };
1530
1531 if (__finished())
1532 return __first;
1533
1534 __first = __spec._M_parse_fill_and_align(__first, __last);
1535 if (__finished())
1536 return __first;
1537
1538 __first = __spec._M_parse_sign(__first, __last);
1539 if (__finished())
1540 return __first;
1541
1542 __first = __spec._M_parse_alternate_form(__first, __last);
1543 if (__finished())
1544 return __first;
1545
1546 __first = __spec._M_parse_zero_fill(__first, __last);
1547 if (__finished())
1548 return __first;
1549
1550 if (__first[0] != '.')
1551 {
1552 __first = __spec._M_parse_width(__first, __last, __pc);
1553 if (__finished())
1554 return __first;
1555 }
1556
1557 __first = __spec._M_parse_precision(__first, __last, __pc);
1558 if (__finished())
1559 return __first;
1560
1561 __first = __spec._M_parse_locale(__first, __last);
1562 if (__finished())
1563 return __first;
1564
1565 switch (*__first)
1566 {
1567 case 'a':
1568 __spec._M_type = _Pres_a;
1569 ++__first;
1570 break;
1571 case 'A':
1572 __spec._M_type = _Pres_A;
1573 ++__first;
1574 break;
1575 case 'e':
1576 __spec._M_type = _Pres_e;
1577 ++__first;
1578 break;
1579 case 'E':
1580 __spec._M_type = _Pres_E;
1581 ++__first;
1582 break;
1583 case 'f':
1584 __spec._M_type = _Pres_f;
1585 ++__first;
1586 break;
1587 case 'F':
1588 __spec._M_type = _Pres_F;
1589 ++__first;
1590 break;
1591 case 'g':
1592 __spec._M_type = _Pres_g;
1593 ++__first;
1594 break;
1595 case 'G':
1596 __spec._M_type = _Pres_G;
1597 ++__first;
1598 break;
1599 }
1600
1601 if (__finished())
1602 return __first;
1603
1604 __format::__failed_to_parse_format_spec();
1605 }
1606
1607 template<typename _Fp, typename _Out>
1608 typename basic_format_context<_Out, _CharT>::iterator
1609 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
1610 {
1611 std::string __dynbuf;
1612 char __buf[128];
1613 to_chars_result __res{};
1614
1615 size_t __prec = 6;
1616 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
1617 if (__use_prec)
1618 __prec = _M_spec._M_get_precision(__fc);
1619
1620 char* __start = __buf + 1; // reserve space for sign
1621 char* __end = __buf + sizeof(__buf);
1622
1623 chars_format __fmt{};
1624 bool __upper = false;
1625 bool __trailing_zeros = false;
1626 char __expc = 'e';
1627
1628 switch (_M_spec._M_type)
1629 {
1630 case _Pres_A:
1631 __upper = true;
1632 __expc = 'P';
1633 [[fallthrough]];
1634 case _Pres_a:
1635 if (_M_spec._M_type != _Pres_A)
1636 __expc = 'p';
1637 __fmt = chars_format::hex;
1638 break;
1639 case _Pres_E:
1640 __upper = true;
1641 __expc = 'E';
1642 [[fallthrough]];
1643 case _Pres_e:
1644 __use_prec = true;
1645 __fmt = chars_format::scientific;
1646 break;
1647 case _Pres_F:
1648 __upper = true;
1649 [[fallthrough]];
1650 case _Pres_f:
1651 __use_prec = true;
1652 __fmt = chars_format::fixed;
1653 break;
1654 case _Pres_G:
1655 __upper = true;
1656 __expc = 'E';
1657 [[fallthrough]];
1658 case _Pres_g:
1659 __trailing_zeros = true;
1660 __use_prec = true;
1661 __fmt = chars_format::general;
1662 break;
1663 case _Pres_none:
1664 if (__use_prec)
1665 __fmt = chars_format::general;
1666 break;
1667 default:
1668 __builtin_unreachable();
1669 }
1670
1671 // Write value into buffer using std::to_chars.
1672 auto __to_chars = [&](char* __b, char* __e) {
1673 if (__use_prec)
1674 return __format::to_chars(__b, __e, __v, __fmt, __prec);
1675 else if (__fmt != chars_format{})
1676 return __format::to_chars(__b, __e, __v, __fmt);
1677 else
1678 return __format::to_chars(__b, __e, __v);
1679 };
1680
1681 // First try using stack buffer.
1682 __res = __to_chars(__start, __end);
1683
1684 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
1685 {
1686 // If the buffer is too small it's probably because of a large
1687 // precision, or a very large value in fixed format.
1688 size_t __guess = 8 + __prec;
1689 if (__fmt == chars_format::fixed) // +ddd.prec
1690 {
1691 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
1692 || is_same_v<_Fp, long double>)
1693 {
1694 // The number of digits to the left of the decimal point
1695 // is floor(log10(max(abs(__v),1)))+1
1696 int __exp{};
1697 if constexpr (is_same_v<_Fp, float>)
1698 __builtin_frexpf(__v, &__exp);
1699 else if constexpr (is_same_v<_Fp, double>)
1700 __builtin_frexp(__v, &__exp);
1701 else if constexpr (is_same_v<_Fp, long double>)
1702 __builtin_frexpl(__v, &__exp);
1703 if (__exp > 0)
1704 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
1705 }
1706 else
1707 __guess += numeric_limits<_Fp>::max_exponent10;
1708 }
1709 if (__guess <= sizeof(__buf)) [[unlikely]]
1710 __guess = sizeof(__buf) * 2;
1711 __dynbuf.reserve(__guess);
1712
1713 do
1714 {
1715 // Mangling of this lambda, and thus resize_and_overwrite
1716 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
1717 // <format> was new in G++ 13, and is experimental, that
1718 // isn't a problem.
1719 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
1720 {
1721 __res = __to_chars(__p + 1, __p + __n - 1);
1722 return __res.ec == errc{} ? __res.ptr - __p : 0;
1723 };
1724
1725 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
1726 __overwrite);
1727 __start = __dynbuf.data() + 1; // reserve space for sign
1728 __end = __dynbuf.data() + __dynbuf.size();
1729 }
1730 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
1731 }
1732
1733 // Use uppercase for 'A', 'E', and 'G' formats.
1734 if (__upper)
1735 {
1736 for (char* __p = __start; __p != __res.ptr; ++__p)
1737 *__p = std::toupper(*__p);
1738 }
1739
1740 bool __have_sign = true;
1741 // Add sign for non-negative values.
1742 if (!__builtin_signbit(__v))
1743 {
1744 if (_M_spec._M_sign == _Sign_plus)
1745 *--__start = '+';
1746 else if (_M_spec._M_sign == _Sign_space)
1747 *--__start = ' ';
1748 else
1749 __have_sign = false;
1750 }
1751
1752 string_view __narrow_str(__start, __res.ptr - __start);
1753
1754 // Use alternate form. Ensure decimal point is always present,
1755 // and add trailing zeros (up to precision) for g and G forms.
1756 if (_M_spec._M_alt && __builtin_isfinite(__v))
1757 {
1758 string_view __s = __narrow_str;
1759 size_t __sigfigs; // Number of significant figures.
1760 size_t __z = 0; // Number of trailing zeros to add.
1761 size_t __p; // Position of the exponent character (if any).
1762 size_t __d = __s.find('.'); // Position of decimal point.
1763 if (__d != __s.npos) // Found decimal point.
1764 {
1765 __p = __s.find(__expc, __d + 1);
1766 if (__p == __s.npos)
1767 __p = __s.size();
1768
1769 // If presentation type is g or G we might need to add zeros.
1770 if (__trailing_zeros)
1771 {
1772 // Find number of digits after first significant figure.
1773 if (__s[__have_sign] != '0')
1774 // A string like "D.D" or "-D.DDD"
1775 __sigfigs = __p - __have_sign - 1;
1776 else
1777 // A string like "0.D" or "-0.0DD".
1778 // Safe to assume there is a non-zero digit, because
1779 // otherwise there would be no decimal point.
1780 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
1781 }
1782 }
1783 else // No decimal point, we need to insert one.
1784 {
1785 __p = __s.find(__expc); // Find the exponent, if present.
1786 if (__p == __s.npos)
1787 __p = __s.size();
1788 __d = __p; // Position where '.' should be inserted.
1789 __sigfigs = __d - __have_sign;
1790 }
1791
1792 if (__trailing_zeros && __prec != 0)
1793 {
1794 // For g and G presentation types std::to_chars produces
1795 // no more than prec significant figures. Insert this many
1796 // zeros so the result has exactly prec significant figures.
1797 __z = __prec - __sigfigs;
1798 }
1799
1800 if (size_t __extras = int(__d == __p) + __z) // How many to add.
1801 {
1802 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
1803 {
1804 // The stack buffer is large enough for the result.
1805 // Move exponent to make space for extra chars.
1806 __builtin_memmove(__start + __p + __extras,
1807 __start + __p,
1808 __s.size() - __p);
1809 if (__d == __p)
1810 __start[__p++] = '.';
1811 __builtin_memset(__start + __p, '0', __z);
1812 __narrow_str = {__s.data(), __s.size() + __extras};
1813 }
1814 else // Need to switch to the dynamic buffer.
1815 {
1816 __dynbuf.reserve(__s.size() + __extras);
1817 if (__dynbuf.empty())
1818 {
1819 __dynbuf = __s.substr(0, __p);
1820 if (__d == __p)
1821 __dynbuf += '.';
1822 if (__z)
1823 __dynbuf.append(__z, '0');
1824 __dynbuf.append(__s.substr(__p));
1825 }
1826 else
1827 {
1828 __dynbuf.insert(__p, __extras, '0');
1829 if (__d == __p)
1830 __dynbuf[__p] = '.';
1831 }
1832 __narrow_str = __dynbuf;
1833 }
1834 }
1835 }
1836
1837 basic_string<_CharT> __wstr;
1838 basic_string_view<_CharT> __str;
1839 if constexpr (is_same_v<_CharT, char>)
1840 __str = __narrow_str;
1841#ifdef _GLIBCXX_USE_WCHAR_T
1842 else
1843 {
1844 __wstr = std::__to_wstring_numeric(__narrow_str);
1845 __str = __wstr;
1846 }
1847#endif
1848
1849 if (_M_spec._M_localized && __builtin_isfinite(__v))
1850 {
1851 __wstr = _M_localize(__str, __expc, __fc.locale());
1852 if (!__wstr.empty())
1853 __str = __wstr;
1854 }
1855
1856 size_t __width = _M_spec._M_get_width(__fc);
1857
1858 if (__width <= __str.size())
1859 return __format::__write(__fc.out(), __str);
1860
1861 char32_t __fill_char = _M_spec._M_fill;
1862 _Align __align = _M_spec._M_align;
1863
1864 size_t __nfill = __width - __str.size();
1865 auto __out = __fc.out();
1866 if (__align == _Align_default)
1867 {
1868 __align = _Align_right;
1869 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
1870 {
1871 __fill_char = _CharT('0');
1872 // Write sign before zero filling.
1873 if (!__format::__is_xdigit(__narrow_str[0]))
1874 {
1875 *__out++ = __str[0];
1876 __str.remove_prefix(1);
1877 }
1878 }
1879 else
1880 __fill_char = _CharT(' ');
1881 }
1882 return __format::__write_padded(std::move(__out), __str,
1883 __align, __nfill, __fill_char);
1884 }
1885
1886 // Locale-specific format.
1887 basic_string<_CharT>
1888 _M_localize(basic_string_view<_CharT> __str, char __expc,
1889 const locale& __loc) const
1890 {
1891 basic_string<_CharT> __lstr;
1892
1893 if (__loc == locale::classic())
1894 return __lstr; // Nothing to do.
1895
1896 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1897 const _CharT __point = __np.decimal_point();
1898 const string __grp = __np.grouping();
1899
1900 _CharT __dot, __exp;
1901 if constexpr (is_same_v<_CharT, char>)
1902 {
1903 __dot = '.';
1904 __exp = __expc;
1905 }
1906 else
1907 {
1908 __dot = L'.';
1909 switch (__expc)
1910 {
1911 case 'e':
1912 __exp = L'e';
1913 break;
1914 case 'E':
1915 __exp = L'E';
1916 break;
1917 case 'p':
1918 __exp = L'p';
1919 break;
1920 case 'P':
1921 __exp = L'P';
1922 break;
1923 default:
1924 __builtin_unreachable();
1925 }
1926 }
1927
1928 if (__grp.empty() && __point == __dot)
1929 return __lstr; // Locale uses '.' and no grouping.
1930
1931 size_t __d = __str.find(__dot); // Index of radix character (if any).
1932 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
1933 if (__e == __str.npos)
1934 __e = __str.size();
1935 const size_t __r = __str.size() - __e; // Length of remainder.
1936 auto __overwrite = [&](_CharT* __p, size_t) {
1937 // Apply grouping to the digits before the radix or exponent.
1938 auto __end = std::__add_grouping(__p, __np.thousands_sep(),
1939 __grp.data(), __grp.size(),
1940 __str.data(), __str.data() + __e);
1941 if (__r) // If there's a fractional part or exponent
1942 {
1943 if (__d != __str.npos)
1944 {
1945 *__end = __point; // Add the locale's radix character.
1946 ++__end;
1947 ++__e;
1948 }
1949 const size_t __rlen = __str.size() - __e;
1950 // Append fractional digits and/or exponent:
1951 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
1952 __end += __rlen;
1953 }
1954 return (__end - __p);
1955 };
1956 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
1957 return __lstr;
1958 }
1959
1960 _Spec<_CharT> _M_spec{};
1961 };
1962
1963} // namespace __format
1964/// @endcond
1965
1966 /// Format a character.
1967 template<__format::__char _CharT>
1968 struct formatter<_CharT, _CharT>
1969 {
1970 formatter() = default;
1971
1972 constexpr typename basic_format_parse_context<_CharT>::iterator
1973 parse(basic_format_parse_context<_CharT>& __pc)
1974 {
1975 return _M_f.template _M_parse<_CharT>(__pc);
1976 }
1977
1978 template<typename _Out>
1979 typename basic_format_context<_Out, _CharT>::iterator
1980 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
1981 {
1982 if (_M_f._M_spec._M_type == __format::_Pres_none
1983 || _M_f._M_spec._M_type == __format::_Pres_c)
1984 return _M_f._M_format_character(__u, __fc);
1985 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1986 {
1987 // TODO
1988 return __fc.out();
1989 }
1990 else
1991 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
1992 }
1993
1994#if __cpp_lib_format_ranges
1995 constexpr void
1996 set_debug_format() noexcept
1997 { _M_f._M_spec._M_type = __format::_Pres_esc; }
1998#endif
1999
2000 private:
2001 __format::__formatter_int<_CharT> _M_f;
2002 };
2003
2004#ifdef _GLIBCXX_USE_WCHAR_T
2005 /// Format a char value for wide character output.
2006 template<>
2007 struct formatter<char, wchar_t>
2008 {
2009 formatter() = default;
2010
2011 constexpr typename basic_format_parse_context<wchar_t>::iterator
2012 parse(basic_format_parse_context<wchar_t>& __pc)
2013 {
2014 return _M_f._M_parse<char>(__pc);
2015 }
2016
2017 template<typename _Out>
2018 typename basic_format_context<_Out, wchar_t>::iterator
2019 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2020 {
2021 if (_M_f._M_spec._M_type == __format::_Pres_none
2022 || _M_f._M_spec._M_type == __format::_Pres_c)
2023 return _M_f._M_format_character(__u, __fc);
2024 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
2025 {
2026 // TODO
2027 return __fc.out();
2028 }
2029 else
2030 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2031 }
2032
2033#if __cpp_lib_format_ranges
2034 constexpr void
2035 set_debug_format() noexcept
2036 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2037#endif
2038
2039 private:
2040 __format::__formatter_int<wchar_t> _M_f;
2041 };
2042#endif // USE_WCHAR_T
2043
2044 /** Format a string.
2045 * @{
2046 */
2047 template<__format::__char _CharT>
2048 struct formatter<_CharT*, _CharT>
2049 {
2050 formatter() = default;
2051
2052 [[__gnu__::__always_inline__]]
2053 constexpr typename basic_format_parse_context<_CharT>::iterator
2054 parse(basic_format_parse_context<_CharT>& __pc)
2055 { return _M_f.parse(__pc); }
2056
2057 template<typename _Out>
2058 [[__gnu__::__nonnull__]]
2059 typename basic_format_context<_Out, _CharT>::iterator
2060 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2061 { return _M_f.format(__u, __fc); }
2062
2063#if __cpp_lib_format_ranges
2064 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2065#endif
2066
2067 private:
2068 __format::__formatter_str<_CharT> _M_f;
2069 };
2070
2071 template<__format::__char _CharT>
2072 struct formatter<const _CharT*, _CharT>
2073 {
2074 formatter() = default;
2075
2076 [[__gnu__::__always_inline__]]
2077 constexpr typename basic_format_parse_context<_CharT>::iterator
2078 parse(basic_format_parse_context<_CharT>& __pc)
2079 { return _M_f.parse(__pc); }
2080
2081 template<typename _Out>
2082 [[__gnu__::__nonnull__]]
2083 typename basic_format_context<_Out, _CharT>::iterator
2084 format(const _CharT* __u,
2085 basic_format_context<_Out, _CharT>& __fc) const
2086 { return _M_f.format(__u, __fc); }
2087
2088#if __cpp_lib_format_ranges
2089 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2090#endif
2091
2092 private:
2093 __format::__formatter_str<_CharT> _M_f;
2094 };
2095
2096 template<__format::__char _CharT, size_t _Nm>
2097 struct formatter<_CharT[_Nm], _CharT>
2098 {
2099 formatter() = default;
2100
2101 [[__gnu__::__always_inline__]]
2102 constexpr typename basic_format_parse_context<_CharT>::iterator
2103 parse(basic_format_parse_context<_CharT>& __pc)
2104 { return _M_f.parse(__pc); }
2105
2106 template<typename _Out>
2107 typename basic_format_context<_Out, _CharT>::iterator
2108 format(const _CharT (&__u)[_Nm],
2109 basic_format_context<_Out, _CharT>& __fc) const
2110 { return _M_f.format({__u, _Nm}, __fc); }
2111
2112#if __cpp_lib_format_ranges
2113 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2114#endif
2115
2116 private:
2117 __format::__formatter_str<_CharT> _M_f;
2118 };
2119
2120 template<typename _Traits, typename _Alloc>
2121 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2122 {
2123 formatter() = default;
2124
2125 [[__gnu__::__always_inline__]]
2126 constexpr typename basic_format_parse_context<char>::iterator
2127 parse(basic_format_parse_context<char>& __pc)
2128 { return _M_f.parse(__pc); }
2129
2130 template<typename _Out>
2131 typename basic_format_context<_Out, char>::iterator
2132 format(const basic_string<char, _Traits, _Alloc>& __u,
2133 basic_format_context<_Out, char>& __fc) const
2134 { return _M_f.format(__u, __fc); }
2135
2136#if __cpp_lib_format_ranges
2137 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2138#endif
2139
2140 private:
2141 __format::__formatter_str<char> _M_f;
2142 };
2143
2144#ifdef _GLIBCXX_USE_WCHAR_T
2145 template<typename _Traits, typename _Alloc>
2146 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2147 {
2148 formatter() = default;
2149
2150 [[__gnu__::__always_inline__]]
2151 constexpr typename basic_format_parse_context<wchar_t>::iterator
2152 parse(basic_format_parse_context<wchar_t>& __pc)
2153 { return _M_f.parse(__pc); }
2154
2155 template<typename _Out>
2156 typename basic_format_context<_Out, wchar_t>::iterator
2157 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2158 basic_format_context<_Out, wchar_t>& __fc) const
2159 { return _M_f.format(__u, __fc); }
2160
2161#if __cpp_lib_format_ranges
2162 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2163#endif
2164
2165 private:
2166 __format::__formatter_str<wchar_t> _M_f;
2167 };
2168#endif // USE_WCHAR_T
2169
2170 template<typename _Traits>
2171 struct formatter<basic_string_view<char, _Traits>, char>
2172 {
2173 formatter() = default;
2174
2175 [[__gnu__::__always_inline__]]
2176 constexpr typename basic_format_parse_context<char>::iterator
2177 parse(basic_format_parse_context<char>& __pc)
2178 { return _M_f.parse(__pc); }
2179
2180 template<typename _Out>
2181 typename basic_format_context<_Out, char>::iterator
2182 format(basic_string_view<char, _Traits> __u,
2183 basic_format_context<_Out, char>& __fc) const
2184 { return _M_f.format(__u, __fc); }
2185
2186#if __cpp_lib_format_ranges
2187 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2188#endif
2189
2190 private:
2191 __format::__formatter_str<char> _M_f;
2192 };
2193
2194#ifdef _GLIBCXX_USE_WCHAR_T
2195 template<typename _Traits>
2196 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2197 {
2198 formatter() = default;
2199
2200 [[__gnu__::__always_inline__]]
2201 constexpr typename basic_format_parse_context<wchar_t>::iterator
2202 parse(basic_format_parse_context<wchar_t>& __pc)
2203 { return _M_f.parse(__pc); }
2204
2205 template<typename _Out>
2206 typename basic_format_context<_Out, wchar_t>::iterator
2207 format(basic_string_view<wchar_t, _Traits> __u,
2208 basic_format_context<_Out, wchar_t>& __fc) const
2209 { return _M_f.format(__u, __fc); }
2210
2211#if __cpp_lib_format_ranges
2212 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2213#endif
2214
2215 private:
2216 __format::__formatter_str<wchar_t> _M_f;
2217 };
2218#endif // USE_WCHAR_T
2219 /// @}
2220
2221/// @cond undocumented
2222namespace __format
2223{
2224 // each cv-unqualified arithmetic type ArithmeticT other than
2225 // char, wchar_t, char8_t, char16_t, or char32_t
2226 template<typename _Tp>
2227 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2228
2229#if defined __SIZEOF_INT128__
2230 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2231 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2232 = true;
2233#endif
2234
2235 template<> inline constexpr bool __is_formattable_integer<char> = false;
2236 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2237#ifdef _GLIBCXX_USE_CHAR8_T
2238 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2239#endif
2240 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2241 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2242}
2243/// @endcond
2244
2245 /// Format an integer.
2246 template<typename _Tp, __format::__char _CharT>
2247 requires __format::__is_formattable_integer<_Tp>
2248 struct formatter<_Tp, _CharT>
2249 {
2250 formatter() = default;
2251
2252 [[__gnu__::__always_inline__]]
2253 constexpr typename basic_format_parse_context<_CharT>::iterator
2254 parse(basic_format_parse_context<_CharT>& __pc)
2255 {
2256 return _M_f.template _M_parse<_Tp>(__pc);
2257 }
2258
2259 template<typename _Out>
2260 typename basic_format_context<_Out, _CharT>::iterator
2261 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2262 { return _M_f.format(__u, __fc); }
2263
2264 private:
2265 __format::__formatter_int<_CharT> _M_f;
2266 };
2267
2268#if defined __glibcxx_to_chars
2269 /// Format a floating-point value.
2270 template<__format::__formattable_float _Tp, __format::__char _CharT>
2271 struct formatter<_Tp, _CharT>
2272 {
2273 formatter() = default;
2274
2275 [[__gnu__::__always_inline__]]
2276 constexpr typename basic_format_parse_context<_CharT>::iterator
2277 parse(basic_format_parse_context<_CharT>& __pc)
2278 { return _M_f.parse(__pc); }
2279
2280 template<typename _Out>
2281 typename basic_format_context<_Out, _CharT>::iterator
2282 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2283 { return _M_f.format(__u, __fc); }
2284
2285 private:
2286 __format::__formatter_fp<_CharT> _M_f;
2287 };
2288
2289#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2290 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2291 template<__format::__char _CharT>
2292 struct formatter<long double, _CharT>
2293 {
2294 formatter() = default;
2295
2296 [[__gnu__::__always_inline__]]
2297 constexpr typename basic_format_parse_context<_CharT>::iterator
2298 parse(basic_format_parse_context<_CharT>& __pc)
2299 { return _M_f.parse(__pc); }
2300
2301 template<typename _Out>
2302 typename basic_format_context<_Out, _CharT>::iterator
2303 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2304 { return _M_f.format((double)__u, __fc); }
2305
2306 private:
2307 __format::__formatter_fp<_CharT> _M_f;
2308 };
2309#endif
2310
2311#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2312 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2313 template<__format::__char _CharT>
2314 struct formatter<_Float16, _CharT>
2315 {
2316 formatter() = default;
2317
2318 [[__gnu__::__always_inline__]]
2319 constexpr typename basic_format_parse_context<_CharT>::iterator
2320 parse(basic_format_parse_context<_CharT>& __pc)
2321 { return _M_f.parse(__pc); }
2322
2323 template<typename _Out>
2324 typename basic_format_context<_Out, _CharT>::iterator
2325 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2326 { return _M_f.format((float)__u, __fc); }
2327
2328 private:
2329 __format::__formatter_fp<_CharT> _M_f;
2330 };
2331#endif
2332
2333#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2334 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2335 template<__format::__char _CharT>
2336 struct formatter<_Float32, _CharT>
2337 {
2338 formatter() = default;
2339
2340 [[__gnu__::__always_inline__]]
2341 constexpr typename basic_format_parse_context<_CharT>::iterator
2342 parse(basic_format_parse_context<_CharT>& __pc)
2343 { return _M_f.parse(__pc); }
2344
2345 template<typename _Out>
2346 typename basic_format_context<_Out, _CharT>::iterator
2347 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2348 { return _M_f.format((float)__u, __fc); }
2349
2350 private:
2351 __format::__formatter_fp<_CharT> _M_f;
2352 };
2353#endif
2354
2355#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2356 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2357 template<__format::__char _CharT>
2358 struct formatter<_Float64, _CharT>
2359 {
2360 formatter() = default;
2361
2362 [[__gnu__::__always_inline__]]
2363 constexpr typename basic_format_parse_context<_CharT>::iterator
2364 parse(basic_format_parse_context<_CharT>& __pc)
2365 { return _M_f.parse(__pc); }
2366
2367 template<typename _Out>
2368 typename basic_format_context<_Out, _CharT>::iterator
2369 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2370 { return _M_f.format((double)__u, __fc); }
2371
2372 private:
2373 __format::__formatter_fp<_CharT> _M_f;
2374 };
2375#endif
2376
2377#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2378 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2379 template<__format::__char _CharT>
2380 struct formatter<_Float128, _CharT>
2381 {
2382 formatter() = default;
2383
2384 [[__gnu__::__always_inline__]]
2385 constexpr typename basic_format_parse_context<_CharT>::iterator
2386 parse(basic_format_parse_context<_CharT>& __pc)
2387 { return _M_f.parse(__pc); }
2388
2389 template<typename _Out>
2390 typename basic_format_context<_Out, _CharT>::iterator
2391 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2392 { return _M_f.format((__format::__float128_t)__u, __fc); }
2393
2394 private:
2395 __format::__formatter_fp<_CharT> _M_f;
2396 };
2397#endif
2398
2399#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2400 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2401 template<__format::__char _CharT>
2402 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2403 {
2404 formatter() = default;
2405
2406 [[__gnu__::__always_inline__]]
2407 constexpr typename basic_format_parse_context<_CharT>::iterator
2408 parse(basic_format_parse_context<_CharT>& __pc)
2409 { return _M_f.parse(__pc); }
2410
2411 template<typename _Out>
2412 typename basic_format_context<_Out, _CharT>::iterator
2413 format(__gnu_cxx::__bfloat16_t __u,
2414 basic_format_context<_Out, _CharT>& __fc) const
2415 { return _M_f.format((float)__u, __fc); }
2416
2417 private:
2418 __format::__formatter_fp<_CharT> _M_f;
2419 };
2420#endif
2421#endif // __cpp_lib_to_chars
2422
2423 /** Format a pointer.
2424 * @{
2425 */
2426 template<__format::__char _CharT>
2427 struct formatter<const void*, _CharT>
2428 {
2429 formatter() = default;
2430
2431 constexpr typename basic_format_parse_context<_CharT>::iterator
2432 parse(basic_format_parse_context<_CharT>& __pc)
2433 {
2434 __format::_Spec<_CharT> __spec{};
2435 const auto __last = __pc.end();
2436 auto __first = __pc.begin();
2437
2438 auto __finalize = [this, &__spec] {
2439 _M_spec = __spec;
2440 };
2441
2442 auto __finished = [&] {
2443 if (__first == __last || *__first == '}')
2444 {
2445 __finalize();
2446 return true;
2447 }
2448 return false;
2449 };
2450
2451 if (__finished())
2452 return __first;
2453
2454 __first = __spec._M_parse_fill_and_align(__first, __last);
2455 if (__finished())
2456 return __first;
2457
2458// _GLIBCXX_RESOLVE_LIB_DEFECTS
2459// P2510R3 Formatting pointers
2460#if __glibcxx_format >= 202304L
2461 __first = __spec._M_parse_zero_fill(__first, __last);
2462 if (__finished())
2463 return __first;
2464#endif
2465
2466 __first = __spec._M_parse_width(__first, __last, __pc);
2467
2468 if (__first != __last)
2469 {
2470 if (*__first == 'p')
2471 ++__first;
2472#if __glibcxx_format >= 202304L
2473 else if (*__first == 'P')
2474 {
2475 __spec._M_type = __format::_Pres_P;
2476 ++__first;
2477 }
2478#endif
2479 }
2480
2481 if (__finished())
2482 return __first;
2483
2484 __format::__failed_to_parse_format_spec();
2485 }
2486
2487 template<typename _Out>
2488 typename basic_format_context<_Out, _CharT>::iterator
2489 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2490 {
2491 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2492 char __buf[2 + sizeof(__v) * 2];
2493 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2494 __u, 16);
2495 int __n = __ptr - __buf;
2496 __buf[0] = '0';
2497 __buf[1] = 'x';
2498#if __glibcxx_format >= 202304L
2499 if (_M_spec._M_type == __format::_Pres_P)
2500 {
2501 __buf[1] = 'X';
2502 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2503#if __has_builtin(__builtin_toupper)
2504 *__p = __builtin_toupper(*__p);
2505#else
2506 *__p = std::toupper(*__p);
2507#endif
2508 }
2509#endif
2510
2511 basic_string_view<_CharT> __str;
2512 if constexpr (is_same_v<_CharT, char>)
2513 __str = string_view(__buf, __n);
2514#ifdef _GLIBCXX_USE_WCHAR_T
2515 else
2516 {
2517 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2518 std::__to_wstring_numeric(__buf, __n, __p);
2519 __str = wstring_view(__p, __n);
2520 }
2521#endif
2522
2523#if __glibcxx_format >= 202304L
2524 if (_M_spec._M_zero_fill)
2525 {
2526 size_t __width = _M_spec._M_get_width(__fc);
2527 if (__width <= __str.size())
2528 return __format::__write(__fc.out(), __str);
2529
2530 auto __out = __fc.out();
2531 // Write "0x" or "0X" prefix before zero-filling.
2532 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2533 __str.remove_prefix(2);
2534 size_t __nfill = __width - __n;
2535 return __format::__write_padded(std::move(__out), __str,
2536 __format::_Align_right,
2537 __nfill, _CharT('0'));
2538 }
2539#endif
2540
2541 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2542 __format::_Align_right);
2543 }
2544
2545 private:
2546 __format::_Spec<_CharT> _M_spec{};
2547 };
2548
2549 template<__format::__char _CharT>
2550 struct formatter<void*, _CharT>
2551 {
2552 formatter() = default;
2553
2554 [[__gnu__::__always_inline__]]
2555 constexpr typename basic_format_parse_context<_CharT>::iterator
2556 parse(basic_format_parse_context<_CharT>& __pc)
2557 { return _M_f.parse(__pc); }
2558
2559 template<typename _Out>
2560 typename basic_format_context<_Out, _CharT>::iterator
2561 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2562 { return _M_f.format(__v, __fc); }
2563
2564 private:
2565 formatter<const void*, _CharT> _M_f;
2566 };
2567
2568 template<__format::__char _CharT>
2569 struct formatter<nullptr_t, _CharT>
2570 {
2571 formatter() = default;
2572
2573 [[__gnu__::__always_inline__]]
2574 constexpr typename basic_format_parse_context<_CharT>::iterator
2575 parse(basic_format_parse_context<_CharT>& __pc)
2576 { return _M_f.parse(__pc); }
2577
2578 template<typename _Out>
2579 typename basic_format_context<_Out, _CharT>::iterator
2580 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2581 { return _M_f.format(nullptr, __fc); }
2582
2583 private:
2584 formatter<const void*, _CharT> _M_f;
2585 };
2586 /// @}
2587
2588#if defined _GLIBCXX_USE_WCHAR_T && __cpp_lib_format_ranges
2589 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2590 // 3944. Formatters converting sequences of char to sequences of wchar_t
2591
2592 namespace __format { struct __disabled; }
2593
2594 // std::formatter<__disabled, C> uses the primary template, which is disabled.
2595 template<>
2596 struct formatter<char*, wchar_t>
2597 : private formatter<__format::__disabled, wchar_t> { };
2598 template<>
2599 struct formatter<const char*, wchar_t>
2600 : private formatter<__format::__disabled, wchar_t> { };
2601 template<size_t _Nm>
2602 struct formatter<char[_Nm], wchar_t>
2603 : private formatter<__format::__disabled, wchar_t> { };
2604 template<class _Traits, class _Allocator>
2605 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
2606 : private formatter<__format::__disabled, wchar_t> { };
2607 template<class _Traits>
2608 struct formatter<basic_string_view<char, _Traits>, wchar_t>
2609 : private formatter<__format::__disabled, wchar_t> { };
2610#endif
2611
2612/// @cond undocumented
2613namespace __format
2614{
2615 template<typename _Tp, typename _Context,
2616 typename _Formatter
2617 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2618 typename _ParseContext
2619 = basic_format_parse_context<typename _Context::char_type>>
2620 concept __parsable_with
2621 = semiregular<_Formatter>
2622 && requires (_Formatter __f, _ParseContext __pc)
2623 {
2624 { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
2625 };
2626
2627 template<typename _Tp, typename _Context,
2628 typename _Formatter
2629 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2630 typename _ParseContext
2631 = basic_format_parse_context<typename _Context::char_type>>
2632 concept __formattable_with
2633 = semiregular<_Formatter>
2634 && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
2635 {
2636 { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
2637 };
2638
2639 // An unspecified output iterator type used in the `formattable` concept.
2640 template<typename _CharT>
2641 using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
2642
2643 template<typename _Tp, typename _CharT,
2644 typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
2645 concept __formattable_impl
2646 = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
2647
2648} // namespace __format
2649/// @endcond
2650
2651// Concept std::formattable was introduced by P2286R8 "Formatting Ranges",
2652// but we can't guard it with __cpp_lib_format_ranges until we define that!
2653#if __cplusplus > 202002L
2654 // [format.formattable], concept formattable
2655 template<typename _Tp, typename _CharT>
2656 concept formattable
2657 = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
2658#endif
2659
2660#if __cpp_lib_format_ranges
2661 /// @cond undocumented
2662namespace __format
2663{
2664 template<typename _Rg, typename _CharT>
2665 concept __const_formattable_range
2666 = ranges::input_range<const _Rg>
2667 && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
2668
2669 template<typename _Rg, typename _CharT>
2670 using __maybe_const_range
2671 = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
2672} // namespace __format
2673 /// @endcond
2674#endif // format_ranges
2675
2676 /// An iterator after the last character written, and the number of
2677 /// characters that would have been written.
2678 template<typename _Out>
2679 struct format_to_n_result
2680 {
2681 _Out out;
2682 iter_difference_t<_Out> size;
2683 };
2684
2685_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
2686template<typename, typename> class vector;
2687_GLIBCXX_END_NAMESPACE_CONTAINER
2688
2689/// @cond undocumented
2690namespace __format
2691{
2692 template<typename _CharT>
2693 class _Sink_iter
2694 {
2695 _Sink<_CharT>* _M_sink = nullptr;
2696
2697 public:
2698 using iterator_category = output_iterator_tag;
2699 using value_type = void;
2700 using difference_type = ptrdiff_t;
2701 using pointer = void;
2702 using reference = void;
2703
2704 _Sink_iter() = default;
2705 _Sink_iter(const _Sink_iter&) = default;
2706 _Sink_iter& operator=(const _Sink_iter&) = default;
2707
2708 [[__gnu__::__always_inline__]]
2709 explicit constexpr
2710 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
2711
2712 [[__gnu__::__always_inline__]]
2713 constexpr _Sink_iter&
2714 operator=(_CharT __c)
2715 {
2716 _M_sink->_M_write(__c);
2717 return *this;
2718 }
2719
2720 [[__gnu__::__always_inline__]]
2721 constexpr _Sink_iter&
2722 operator=(basic_string_view<_CharT> __s)
2723 {
2724 _M_sink->_M_write(__s);
2725 return *this;
2726 }
2727
2728 [[__gnu__::__always_inline__]]
2729 constexpr _Sink_iter&
2730 operator*() { return *this; }
2731
2732 [[__gnu__::__always_inline__]]
2733 constexpr _Sink_iter&
2734 operator++() { return *this; }
2735
2736 [[__gnu__::__always_inline__]]
2737 constexpr _Sink_iter
2738 operator++(int) { return *this; }
2739
2740 auto
2741 _M_reserve(size_t __n) const
2742 { return _M_sink->_M_reserve(__n); }
2743 };
2744
2745 // Abstract base class for type-erased character sinks.
2746 // All formatting and output is done via this type's iterator,
2747 // to reduce the number of different template instantiations.
2748 template<typename _CharT>
2749 class _Sink
2750 {
2751 friend class _Sink_iter<_CharT>;
2752
2753 span<_CharT> _M_span;
2754 typename span<_CharT>::iterator _M_next;
2755
2756 // Called when the span is full, to make more space available.
2757 // Precondition: _M_next != _M_span.begin()
2758 // Postcondition: _M_next != _M_span.end()
2759 // TODO: remove the precondition? could make overflow handle it.
2760 virtual void _M_overflow() = 0;
2761
2762 protected:
2763 // Precondition: __span.size() != 0
2764 [[__gnu__::__always_inline__]]
2765 explicit constexpr
2766 _Sink(span<_CharT> __span) noexcept
2767 : _M_span(__span), _M_next(__span.begin())
2768 { }
2769
2770 // The portion of the span that has been written to.
2771 [[__gnu__::__always_inline__]]
2772 span<_CharT>
2773 _M_used() const noexcept
2774 { return _M_span.first(_M_next - _M_span.begin()); }
2775
2776 // The portion of the span that has not been written to.
2777 [[__gnu__::__always_inline__]]
2778 constexpr span<_CharT>
2779 _M_unused() const noexcept
2780 { return _M_span.subspan(_M_next - _M_span.begin()); }
2781
2782 // Use the start of the span as the next write position.
2783 [[__gnu__::__always_inline__]]
2784 constexpr void
2785 _M_rewind() noexcept
2786 { _M_next = _M_span.begin(); }
2787
2788 // Replace the current output range.
2789 void
2790 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
2791 {
2792 _M_span = __s;
2793 _M_next = __s.begin() + __pos;
2794 }
2795
2796 // Called by the iterator for *it++ = c
2797 constexpr void
2798 _M_write(_CharT __c)
2799 {
2800 *_M_next++ = __c;
2801 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
2802 _M_overflow();
2803 }
2804
2805 constexpr void
2806 _M_write(basic_string_view<_CharT> __s)
2807 {
2808 span __to = _M_unused();
2809 while (__to.size() <= __s.size())
2810 {
2811 __s.copy(__to.data(), __to.size());
2812 _M_next += __to.size();
2813 __s.remove_prefix(__to.size());
2814 _M_overflow();
2815 __to = _M_unused();
2816 }
2817 if (__s.size())
2818 {
2819 __s.copy(__to.data(), __s.size());
2820 _M_next += __s.size();
2821 }
2822 }
2823
2824 // A successful _Reservation can be used to directly write
2825 // up to N characters to the sink to avoid unwanted buffering.
2826 struct _Reservation
2827 {
2828 // True if the reservation was successful, false otherwise.
2829 explicit operator bool() const noexcept { return _M_sink; }
2830 // A pointer to write directly to the sink.
2831 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
2832 // Add n to the _M_next iterator for the sink.
2833 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
2834 _Sink* _M_sink;
2835 };
2836
2837 // Attempt to reserve space to write n characters to the sink.
2838 // If anything is written to the reservation then there must be a call
2839 // to _M_bump(N2) before any call to another member function of *this,
2840 // where N2 is the number of characters written.
2841 virtual _Reservation
2842 _M_reserve(size_t __n)
2843 {
2844 if (__n <= _M_unused().size())
2845 return { this };
2846
2847 if (__n <= _M_span.size()) // Cannot meet the request.
2848 {
2849 _M_overflow(); // Make more space available.
2850 if (__n <= _M_unused().size())
2851 return { this };
2852 }
2853 return { nullptr };
2854 }
2855
2856 // Update the next output position after writing directly to the sink.
2857 // pre: no calls to _M_write or _M_overflow since _M_reserve.
2858 virtual void
2859 _M_bump(size_t __n)
2860 { _M_next += __n; }
2861
2862 public:
2863 _Sink(const _Sink&) = delete;
2864 _Sink& operator=(const _Sink&) = delete;
2865
2866 [[__gnu__::__always_inline__]]
2867 constexpr _Sink_iter<_CharT>
2868 out() noexcept
2869 { return _Sink_iter<_CharT>(*this); }
2870 };
2871
2872 // A sink with an internal buffer. This is used to implement concrete sinks.
2873 template<typename _CharT>
2874 class _Buf_sink : public _Sink<_CharT>
2875 {
2876 protected:
2877 _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
2878
2879 [[__gnu__::__always_inline__]]
2880 constexpr
2881 _Buf_sink() noexcept
2882 : _Sink<_CharT>(_M_buf)
2883 { }
2884 };
2885
2886 using _GLIBCXX_STD_C::vector;
2887
2888 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
2889 // Writes to a buffer then appends that to the sequence when it fills up.
2890 template<typename _Seq>
2891 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
2892 {
2893 using _CharT = typename _Seq::value_type;
2894
2895 _Seq _M_seq;
2896
2897 // Transfer buffer contents to the sequence, so buffer can be refilled.
2898 void
2899 _M_overflow() override
2900 {
2901 auto __s = this->_M_used();
2902 if (__s.empty()) [[unlikely]]
2903 return; // Nothing in the buffer to transfer to _M_seq.
2904
2905 // If _M_reserve was called then _M_bump must have been called too.
2906 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
2907
2908 if constexpr (__is_specialization_of<_Seq, basic_string>)
2909 _M_seq.append(__s.data(), __s.size());
2910 else
2911 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
2912
2913 // Make the whole of _M_buf available for the next write:
2914 this->_M_rewind();
2915 }
2916
2917 typename _Sink<_CharT>::_Reservation
2918 _M_reserve(size_t __n) override
2919 {
2920 // We might already have n characters available in this->_M_unused(),
2921 // but the whole point of this function is to be an optimization for
2922 // the std::format("{}", x) case. We want to avoid writing to _M_buf
2923 // and then copying that into a basic_string if possible, so this
2924 // function prefers to create space directly in _M_seq rather than
2925 // using _M_buf.
2926
2927 if constexpr (__is_specialization_of<_Seq, basic_string>
2928 || __is_specialization_of<_Seq, vector>)
2929 {
2930 // Flush the buffer to _M_seq first (should not be needed).
2931 if (this->_M_used().size()) [[unlikely]]
2932 _Seq_sink::_M_overflow();
2933
2934 // Expand _M_seq to make __n new characters available:
2935 const auto __sz = _M_seq.size();
2936 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
2937 _M_seq.__resize_and_overwrite(__sz + __n,
2938 [](auto, auto __n2) {
2939 return __n2;
2940 });
2941 else
2942 _M_seq.resize(__sz + __n);
2943
2944 // Set _M_used() to be a span over the original part of _M_seq
2945 // and _M_unused() to be the extra capacity we just created:
2946 this->_M_reset(_M_seq, __sz);
2947 return { this };
2948 }
2949 else // Try to use the base class' buffer.
2950 return _Sink<_CharT>::_M_reserve(__n);
2951 }
2952
2953 void
2954 _M_bump(size_t __n) override
2955 {
2956 if constexpr (__is_specialization_of<_Seq, basic_string>
2957 || __is_specialization_of<_Seq, vector>)
2958 {
2959 auto __s = this->_M_used();
2960 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
2961 // Truncate the sequence to the part that was actually written to:
2962 _M_seq.resize(__s.size() + __n);
2963 // Switch back to using buffer:
2964 this->_M_reset(this->_M_buf);
2965 }
2966 }
2967
2968 public:
2969 // TODO: for SSO string, use SSO buffer as initial span, then switch
2970 // to _M_buf if it overflows? Or even do that for all unused capacity?
2971
2972 [[__gnu__::__always_inline__]]
2973 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
2974 { }
2975
2976 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
2977 : _M_seq(std::move(__s))
2978 { }
2979
2980 using _Sink<_CharT>::out;
2981
2982 _Seq
2983 get() &&
2984 {
2985 if (this->_M_used().size() != 0)
2986 _Seq_sink::_M_overflow();
2987 return std::move(_M_seq);
2988 }
2989
2990 // A writable span that views everything written to the sink.
2991 // Will be either a view over _M_seq or the used part of _M_buf.
2992 span<_CharT>
2993 view()
2994 {
2995 auto __s = this->_M_used();
2996 if (_M_seq.size())
2997 {
2998 if (__s.size() != 0)
2999 _Seq_sink::_M_overflow();
3000 return _M_seq;
3001 }
3002 return __s;
3003 }
3004 };
3005
3006 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3007 using _Str_sink
3008 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3009
3010 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3011 // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
3012
3013 // A sink that writes to an output iterator.
3014 // Writes to a fixed-size buffer and then flushes to the output iterator
3015 // when the buffer fills up.
3016 template<typename _CharT, typename _OutIter>
3017 class _Iter_sink : public _Buf_sink<_CharT>
3018 {
3019 _OutIter _M_out;
3020 iter_difference_t<_OutIter> _M_max;
3021
3022 protected:
3023 size_t _M_count = 0;
3024
3025 void
3026 _M_overflow() override
3027 {
3028 auto __s = this->_M_used();
3029 if (_M_max < 0) // No maximum.
3030 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3031 else if (_M_count < static_cast<size_t>(_M_max))
3032 {
3033 auto __max = _M_max - _M_count;
3034 span<_CharT> __first;
3035 if (__max < __s.size())
3036 __first = __s.first(static_cast<size_t>(__max));
3037 else
3038 __first = __s;
3039 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3040 }
3041 this->_M_rewind();
3042 _M_count += __s.size();
3043 }
3044
3045 public:
3046 [[__gnu__::__always_inline__]]
3047 explicit
3048 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3049 : _M_out(std::move(__out)), _M_max(__max)
3050 { }
3051
3052 using _Sink<_CharT>::out;
3053
3054 format_to_n_result<_OutIter>
3055 _M_finish() &&
3056 {
3057 if (this->_M_used().size() != 0)
3058 _Iter_sink::_M_overflow();
3059 iter_difference_t<_OutIter> __count(_M_count);
3060 return { std::move(_M_out), __count };
3061 }
3062 };
3063
3064 // Partial specialization for contiguous iterators.
3065 // No buffer is used, characters are written straight to the iterator.
3066 // We do not know the size of the output range, so the span size just grows
3067 // as needed. The end of the span might be an invalid pointer outside the
3068 // valid range, but we never actually call _M_span.end(). This class does
3069 // not introduce any invalid pointer arithmetic or overflows that would not
3070 // have happened anyway.
3071 template<typename _CharT, contiguous_iterator _OutIter>
3072 requires same_as<iter_value_t<_OutIter>, _CharT>
3073 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3074 {
3075 _OutIter _M_first;
3076 iter_difference_t<_OutIter> _M_max = -1;
3077 protected:
3078 size_t _M_count = 0;
3079 private:
3080 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3081
3082 protected:
3083 void
3084 _M_overflow() override
3085 {
3086 if (this->_M_unused().size() != 0)
3087 return; // No need to switch to internal buffer yet.
3088
3089 auto __s = this->_M_used();
3090
3091 if (_M_max >= 0)
3092 {
3093 _M_count += __s.size();
3094 // Span was already sized for the maximum character count,
3095 // if it overflows then any further output must go to the
3096 // internal buffer, to be discarded.
3097 this->_M_reset(this->_M_buf);
3098 }
3099 else
3100 {
3101 // No maximum character count. Just extend the span to allow
3102 // writing more characters to it.
3103 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3104 }
3105 }
3106
3107 typename _Sink<_CharT>::_Reservation
3108 _M_reserve(size_t __n) final
3109 {
3110 auto __avail = this->_M_unused();
3111 if (__n > __avail.size())
3112 {
3113 if (_M_max >= 0)
3114 return {}; // cannot grow
3115
3116 auto __s = this->_M_used();
3117 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3118 }
3119 return { this };
3120 }
3121
3122 private:
3123 static span<_CharT>
3124 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3125 span<_CharT> __buf) noexcept
3126 {
3127 if (__n == 0)
3128 return __buf; // Only write to the internal buffer.
3129
3130 if (__n > 0)
3131 {
3132 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3133 || sizeof(__n) > sizeof(size_t))
3134 {
3135 // __int128 or __detail::__max_diff_type
3136 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3137 if (__n > __m)
3138 __n = __m;
3139 }
3140 return {__ptr, (size_t)__n};
3141 }
3142
3143#if __has_builtin(__builtin_dynamic_object_size)
3144 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3145 return {__ptr, __bytes / sizeof(_CharT)};
3146#endif
3147 // Avoid forming a pointer to a different memory page.
3148 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3149 __n = (1024 - __off) / sizeof(_CharT);
3150 if (__n > 0) [[likely]]
3151 return {__ptr, static_cast<size_t>(__n)};
3152 else // Misaligned/packed buffer of wchar_t?
3153 return {__ptr, 1};
3154 }
3155
3156 public:
3157 explicit
3158 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3159 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3160 _M_first(__out), _M_max(__n)
3161 { }
3162
3163 format_to_n_result<_OutIter>
3164 _M_finish() &&
3165 {
3166 auto __s = this->_M_used();
3167 if (__s.data() == _M_buf)
3168 {
3169 // Switched to internal buffer, so must have written _M_max.
3170 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3171 return { _M_first + _M_max, __count };
3172 }
3173 else // Not using internal buffer yet
3174 {
3175 iter_difference_t<_OutIter> __count(__s.size());
3176 return { _M_first + __count, __count };
3177 }
3178 }
3179 };
3180
3181 enum _Arg_t : unsigned char {
3182 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3183 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3184 _Arg_i128, _Arg_u128,
3185 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3186#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3187 _Arg_next_value_,
3188 _Arg_f128 = _Arg_ldbl,
3189 _Arg_ibm128 = _Arg_next_value_,
3190#else
3191 _Arg_f128,
3192#endif
3193 _Arg_max_
3194 };
3195
3196 template<typename _Context>
3197 struct _Arg_value
3198 {
3199 using _CharT = typename _Context::char_type;
3200
3201 struct _HandleBase
3202 {
3203 const void* _M_ptr;
3204 void (*_M_func)();
3205 };
3206
3207 union
3208 {
3209 monostate _M_none;
3210 bool _M_bool;
3211 _CharT _M_c;
3212 int _M_i;
3213 unsigned _M_u;
3214 long long _M_ll;
3215 unsigned long long _M_ull;
3216 float _M_flt;
3217 double _M_dbl;
3218#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3219 long double _M_ldbl;
3220#endif
3221 const _CharT* _M_str;
3222 basic_string_view<_CharT> _M_sv;
3223 const void* _M_ptr;
3224 _HandleBase _M_handle;
3225#ifdef __SIZEOF_INT128__
3226 __int128 _M_i128;
3227 unsigned __int128 _M_u128;
3228#endif
3229#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3230 __ieee128 _M_f128;
3231 __ibm128 _M_ibm128;
3232#elif _GLIBCXX_FORMAT_F128 == 2
3233 __float128_t _M_f128;
3234#endif
3235 };
3236
3237 [[__gnu__::__always_inline__]]
3238 _Arg_value() : _M_none() { }
3239
3240#if 0
3241 template<typename _Tp>
3242 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3243 { _S_get<_Tp>() = __val; }
3244#endif
3245
3246 template<typename _Tp, typename _Self>
3247 [[__gnu__::__always_inline__]]
3248 static auto&
3249 _S_get(_Self& __u) noexcept
3250 {
3251 if constexpr (is_same_v<_Tp, bool>)
3252 return __u._M_bool;
3253 else if constexpr (is_same_v<_Tp, _CharT>)
3254 return __u._M_c;
3255 else if constexpr (is_same_v<_Tp, int>)
3256 return __u._M_i;
3257 else if constexpr (is_same_v<_Tp, unsigned>)
3258 return __u._M_u;
3259 else if constexpr (is_same_v<_Tp, long long>)
3260 return __u._M_ll;
3261 else if constexpr (is_same_v<_Tp, unsigned long long>)
3262 return __u._M_ull;
3263 else if constexpr (is_same_v<_Tp, float>)
3264 return __u._M_flt;
3265 else if constexpr (is_same_v<_Tp, double>)
3266 return __u._M_dbl;
3267#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3268 else if constexpr (is_same_v<_Tp, long double>)
3269 return __u._M_ldbl;
3270#else
3271 else if constexpr (is_same_v<_Tp, __ieee128>)
3272 return __u._M_f128;
3273 else if constexpr (is_same_v<_Tp, __ibm128>)
3274 return __u._M_ibm128;
3275#endif
3276 else if constexpr (is_same_v<_Tp, const _CharT*>)
3277 return __u._M_str;
3278 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3279 return __u._M_sv;
3280 else if constexpr (is_same_v<_Tp, const void*>)
3281 return __u._M_ptr;
3282#ifdef __SIZEOF_INT128__
3283 else if constexpr (is_same_v<_Tp, __int128>)
3284 return __u._M_i128;
3285 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3286 return __u._M_u128;
3287#endif
3288#if _GLIBCXX_FORMAT_F128 == 2
3289 else if constexpr (is_same_v<_Tp, __float128_t>)
3290 return __u._M_f128;
3291#endif
3292 else if constexpr (derived_from<_Tp, _HandleBase>)
3293 return static_cast<_Tp&>(__u._M_handle);
3294 // Otherwise, ill-formed.
3295 }
3296
3297 template<typename _Tp>
3298 [[__gnu__::__always_inline__]]
3299 auto&
3300 _M_get() noexcept
3301 { return _S_get<_Tp>(*this); }
3302
3303 template<typename _Tp>
3304 [[__gnu__::__always_inline__]]
3305 const auto&
3306 _M_get() const noexcept
3307 { return _S_get<_Tp>(*this); }
3308
3309 template<typename _Tp>
3310 [[__gnu__::__always_inline__]]
3311 void
3312 _M_set(_Tp __v) noexcept
3313 {
3314 if constexpr (derived_from<_Tp, _HandleBase>)
3315 std::construct_at(&_M_handle, __v);
3316 else
3317 _S_get<_Tp>(*this) = __v;
3318 }
3319 };
3320
3321 // [format.arg.store], class template format-arg-store
3322 template<typename _Context, typename... _Args>
3323 class _Arg_store;
3324
3325 template<typename _Visitor, typename _Ctx>
3326 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
3327
3328 template<typename _Ch, typename _Tp>
3329 consteval _Arg_t
3330 __to_arg_t_enum() noexcept;
3331} // namespace __format
3332/// @endcond
3333
3334 template<typename _Context>
3335 class basic_format_arg
3336 {
3337 using _CharT = typename _Context::char_type;
3338
3339 template<typename _Tp>
3340 static constexpr bool __formattable
3341 = __format::__formattable_with<_Tp, _Context>;
3342
3343 public:
3344 class handle : public __format::_Arg_value<_Context>::_HandleBase
3345 {
3346 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3347
3348 // Format as const if possible, to reduce instantiations.
3349 template<typename _Tp>
3350 using __maybe_const_t
3351 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3352
3353 template<typename _Tq>
3354 static void
3355 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3356 _Context& __format_ctx, const void* __ptr)
3357 {
3358 using _Td = remove_const_t<_Tq>;
3359 typename _Context::template formatter_type<_Td> __f;
3360 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3361 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3362 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3363 }
3364
3365 template<typename _Tp>
3366 explicit
3367 handle(_Tp& __val) noexcept
3368 {
3369 this->_M_ptr = __builtin_addressof(__val);
3370 auto __func = _S_format<__maybe_const_t<_Tp>>;
3371 this->_M_func = reinterpret_cast<void(*)()>(__func);
3372 }
3373
3374 friend class basic_format_arg<_Context>;
3375
3376 public:
3377 handle(const handle&) = default;
3378 handle& operator=(const handle&) = default;
3379
3380 [[__gnu__::__always_inline__]]
3381 void
3382 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3383 {
3384 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3385 _Context&, const void*);
3386 auto __f = reinterpret_cast<_Func>(this->_M_func);
3387 __f(__pc, __fc, this->_M_ptr);
3388 }
3389 };
3390
3391 [[__gnu__::__always_inline__]]
3392 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3393
3394 [[nodiscard,__gnu__::__always_inline__]]
3395 explicit operator bool() const noexcept
3396 { return _M_type != __format::_Arg_none; }
3397
3398#if __cpp_lib_format >= 202306L // >= C++26
3399 template<typename _Visitor>
3400 decltype(auto)
3401 visit(this basic_format_arg __arg, _Visitor&& __vis)
3402 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3403
3404 template<typename _Res, typename _Visitor>
3405 _Res
3406 visit(this basic_format_arg __arg, _Visitor&& __vis)
3407 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3408#endif
3409
3410 private:
3411 template<typename _Ctx>
3412 friend class basic_format_args;
3413
3414 template<typename _Ctx, typename... _Args>
3415 friend class __format::_Arg_store;
3416
3417 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3418
3419 __format::_Arg_value<_Context> _M_val;
3420 __format::_Arg_t _M_type;
3421
3422 // Transform incoming argument type to the type stored in _Arg_value.
3423 // e.g. short -> int, std::string -> std::string_view,
3424 // char[3] -> const char*.
3425 template<typename _Tp>
3426 static consteval auto
3427 _S_to_arg_type()
3428 {
3429 using _Td = remove_const_t<_Tp>;
3430 if constexpr (is_same_v<_Td, bool>)
3431 return type_identity<bool>();
3432 else if constexpr (is_same_v<_Td, _CharT>)
3433 return type_identity<_CharT>();
3434 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3435 return type_identity<_CharT>();
3436#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3437 else if constexpr (is_same_v<_Td, __int128>)
3438 return type_identity<__int128>();
3439 else if constexpr (is_same_v<_Td, unsigned __int128>)
3440 return type_identity<unsigned __int128>();
3441#endif
3442 else if constexpr (__is_signed_integer<_Td>::value)
3443 {
3444 if constexpr (sizeof(_Td) <= sizeof(int))
3445 return type_identity<int>();
3446 else if constexpr (sizeof(_Td) <= sizeof(long long))
3447 return type_identity<long long>();
3448 }
3449 else if constexpr (__is_unsigned_integer<_Td>::value)
3450 {
3451 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3452 return type_identity<unsigned>();
3453 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3454 return type_identity<unsigned long long>();
3455 }
3456 else if constexpr (is_same_v<_Td, float>)
3457 return type_identity<float>();
3458 else if constexpr (is_same_v<_Td, double>)
3459 return type_identity<double>();
3460#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3461 else if constexpr (is_same_v<_Td, long double>)
3462 return type_identity<long double>();
3463#else
3464 else if constexpr (is_same_v<_Td, __ibm128>)
3465 return type_identity<__ibm128>();
3466 else if constexpr (is_same_v<_Td, __ieee128>)
3467 return type_identity<__ieee128>();
3468#endif
3469
3470#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3471 else if constexpr (is_same_v<_Td, _Float16>)
3472 return type_identity<float>();
3473#endif
3474
3475#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3476 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3477 return type_identity<float>();
3478#endif
3479
3480#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3481 else if constexpr (is_same_v<_Td, _Float32>)
3482 return type_identity<float>();
3483#endif
3484
3485#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3486 else if constexpr (is_same_v<_Td, _Float64>)
3487 return type_identity<double>();
3488#endif
3489
3490#if _GLIBCXX_FORMAT_F128
3491# if __FLT128_DIG__
3492 else if constexpr (is_same_v<_Td, _Float128>)
3493 return type_identity<__format::__float128_t>();
3494# endif
3495# if __SIZEOF_FLOAT128__
3496 else if constexpr (is_same_v<_Td, __float128>)
3497 return type_identity<__format::__float128_t>();
3498# endif
3499#endif
3500 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3501 || __is_specialization_of<_Td, basic_string>)
3502 {
3503 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3504 return type_identity<basic_string_view<_CharT>>();
3505 else
3506 return type_identity<handle>();
3507 }
3508 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3509 return type_identity<const _CharT*>();
3510 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3511 return type_identity<const _CharT*>();
3512 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3513 return type_identity<const void*>();
3514 else if constexpr (is_same_v<_Td, nullptr_t>)
3515 return type_identity<const void*>();
3516 else
3517 return type_identity<handle>();
3518 }
3519
3520 // Transform a formattable type to the appropriate storage type.
3521 template<typename _Tp>
3522 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3523
3524 // Get the _Arg_t value corresponding to a normalized type.
3525 template<typename _Tp>
3526 static consteval __format::_Arg_t
3527 _S_to_enum()
3528 {
3529 using namespace __format;
3530 if constexpr (is_same_v<_Tp, bool>)
3531 return _Arg_bool;
3532 else if constexpr (is_same_v<_Tp, _CharT>)
3533 return _Arg_c;
3534 else if constexpr (is_same_v<_Tp, int>)
3535 return _Arg_i;
3536 else if constexpr (is_same_v<_Tp, unsigned>)
3537 return _Arg_u;
3538 else if constexpr (is_same_v<_Tp, long long>)
3539 return _Arg_ll;
3540 else if constexpr (is_same_v<_Tp, unsigned long long>)
3541 return _Arg_ull;
3542 else if constexpr (is_same_v<_Tp, float>)
3543 return _Arg_flt;
3544 else if constexpr (is_same_v<_Tp, double>)
3545 return _Arg_dbl;
3546#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3547 else if constexpr (is_same_v<_Tp, long double>)
3548 return _Arg_ldbl;
3549#else
3550 // Don't use _Arg_ldbl for this target, it's ambiguous.
3551 else if constexpr (is_same_v<_Tp, __ibm128>)
3552 return _Arg_ibm128;
3553 else if constexpr (is_same_v<_Tp, __ieee128>)
3554 return _Arg_f128;
3555#endif
3556 else if constexpr (is_same_v<_Tp, const _CharT*>)
3557 return _Arg_str;
3558 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3559 return _Arg_sv;
3560 else if constexpr (is_same_v<_Tp, const void*>)
3561 return _Arg_ptr;
3562#ifdef __SIZEOF_INT128__
3563 else if constexpr (is_same_v<_Tp, __int128>)
3564 return _Arg_i128;
3565 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3566 return _Arg_u128;
3567#endif
3568
3569#if _GLIBCXX_FORMAT_F128 == 2
3570 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3571 return _Arg_f128;
3572#endif
3573 else if constexpr (is_same_v<_Tp, handle>)
3574 return _Arg_handle;
3575 }
3576
3577 template<typename _Tp>
3578 void
3579 _M_set(_Tp __v) noexcept
3580 {
3581 _M_type = _S_to_enum<_Tp>();
3582 _M_val._M_set(__v);
3583 }
3584
3585 template<typename _Tp>
3586 requires __format::__formattable_with<_Tp, _Context>
3587 explicit
3588 basic_format_arg(_Tp& __v) noexcept
3589 {
3590 using _Td = _Normalize<_Tp>;
3591 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3592 _M_set(_Td{__v.data(), __v.size()});
3593 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3594 && is_same_v<_CharT, wchar_t>)
3595 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3596 else
3597 _M_set(static_cast<_Td>(__v));
3598 }
3599
3600 template<typename _Ctx, typename... _Argz>
3601 friend auto
3602 make_format_args(_Argz&...) noexcept;
3603
3604 template<typename _Visitor, typename _Ctx>
3605 friend decltype(auto)
3606 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3607
3608 template<typename _Visitor, typename _Ctx>
3609 friend decltype(auto)
3610 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
3611
3612 template<typename _Ch, typename _Tp>
3613 friend consteval __format::_Arg_t
3614 __format::__to_arg_t_enum() noexcept;
3615
3616 template<typename _Visitor>
3617 decltype(auto)
3618 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
3619 {
3620 using namespace __format;
3621 switch (__type)
3622 {
3623 case _Arg_none:
3624 return std::forward<_Visitor>(__vis)(_M_val._M_none);
3625 case _Arg_bool:
3626 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
3627 case _Arg_c:
3628 return std::forward<_Visitor>(__vis)(_M_val._M_c);
3629 case _Arg_i:
3630 return std::forward<_Visitor>(__vis)(_M_val._M_i);
3631 case _Arg_u:
3632 return std::forward<_Visitor>(__vis)(_M_val._M_u);
3633 case _Arg_ll:
3634 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
3635 case _Arg_ull:
3636 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
3637#if __glibcxx_to_chars // FIXME: need to be able to format these types!
3638 case _Arg_flt:
3639 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
3640 case _Arg_dbl:
3641 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
3642#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3643 case _Arg_ldbl:
3644 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
3645#else
3646 case _Arg_f128:
3647 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3648 case _Arg_ibm128:
3649 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
3650#endif
3651#endif
3652 case _Arg_str:
3653 return std::forward<_Visitor>(__vis)(_M_val._M_str);
3654 case _Arg_sv:
3655 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
3656 case _Arg_ptr:
3657 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
3658 case _Arg_handle:
3659 {
3660 auto& __h = static_cast<handle&>(_M_val._M_handle);
3661 return std::forward<_Visitor>(__vis)(__h);
3662 }
3663#ifdef __SIZEOF_INT128__
3664 case _Arg_i128:
3665 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
3666 case _Arg_u128:
3667 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
3668#endif
3669
3670#if _GLIBCXX_FORMAT_F128 == 2
3671 case _Arg_f128:
3672 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3673#endif
3674
3675 default:
3676 // _Arg_f16 etc.
3677 __builtin_unreachable();
3678 }
3679 }
3680
3681 template<typename _Visitor>
3682 decltype(auto)
3683 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
3684 {
3685 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
3686 {
3687 constexpr bool __user_facing = __is_one_of<_Tp,
3688 monostate, bool, _CharT,
3689 int, unsigned int, long long int, unsigned long long int,
3690 float, double, long double,
3691 const _CharT*, basic_string_view<_CharT>,
3692 const void*, handle>::value;
3693 if constexpr (__user_facing)
3694 return std::forward<_Visitor>(__vis)(__val);
3695 else
3696 {
3697 handle __h(__val);
3698 return std::forward<_Visitor>(__vis)(__h);
3699 }
3700 }, __type);
3701 }
3702 };
3703
3704 template<typename _Visitor, typename _Context>
3705 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
3706 inline decltype(auto)
3707 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
3708 {
3709 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
3710 }
3711
3712/// @cond undocumented
3713namespace __format
3714{
3715 template<typename _Visitor, typename _Ctx>
3716 inline decltype(auto)
3717 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
3718 {
3719 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
3720 }
3721
3722 struct _WidthPrecVisitor
3723 {
3724 template<typename _Tp>
3725 size_t
3726 operator()(_Tp& __arg) const
3727 {
3728 if constexpr (is_same_v<_Tp, monostate>)
3729 __format::__invalid_arg_id_in_format_string();
3730 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3731 // 3720. Restrict the valid types of arg-id for width and precision
3732 // 3721. Allow an arg-id with a value of zero for width
3733 else if constexpr (sizeof(_Tp) <= sizeof(long long))
3734 {
3735 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3736 // 3720. Restrict the valid types of arg-id for width and precision
3737 if constexpr (__is_unsigned_integer<_Tp>::value)
3738 return __arg;
3739 else if constexpr (__is_signed_integer<_Tp>::value)
3740 if (__arg >= 0)
3741 return __arg;
3742 }
3743 __throw_format_error("format error: argument used for width or "
3744 "precision must be a non-negative integer");
3745 }
3746 };
3747
3748#pragma GCC diagnostic push
3749#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
3750 template<typename _Context>
3751 inline size_t
3752 __int_from_arg(const basic_format_arg<_Context>& __arg)
3753 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
3754
3755 // Pack _Arg_t enum values into a single 60-bit integer.
3756 template<int _Bits, size_t _Nm>
3757 constexpr auto
3758 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
3759 {
3760 __UINT64_TYPE__ __packed_types = 0;
3761 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
3762 __packed_types = (__packed_types << _Bits) | *__i;
3763 return __packed_types;
3764 }
3765} // namespace __format
3766/// @endcond
3767
3768 template<typename _Context>
3769 class basic_format_args
3770 {
3771 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
3772 static constexpr int _S_packed_type_mask = 0b11111;
3773 static constexpr int _S_max_packed_args = 12;
3774
3775 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
3776
3777 template<typename... _Args>
3778 using _Store = __format::_Arg_store<_Context, _Args...>;
3779
3780 template<typename _Ctx, typename... _Args>
3781 friend class __format::_Arg_store;
3782
3783 using uint64_t = __UINT64_TYPE__;
3784 using _Format_arg = basic_format_arg<_Context>;
3785 using _Format_arg_val = __format::_Arg_value<_Context>;
3786
3787 // If args are packed then the number of args is in _M_packed_size and
3788 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
3789 // If args are not packed then the number of args is in _M_unpacked_size
3790 // and _M_packed_size is zero.
3791 uint64_t _M_packed_size : 4;
3792 uint64_t _M_unpacked_size : 60;
3793
3794 union {
3795 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
3796 const _Format_arg* _M_args; // Active when _M_packed_size == 0
3797 };
3798
3799 size_t
3800 _M_size() const noexcept
3801 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
3802
3803 typename __format::_Arg_t
3804 _M_type(size_t __i) const noexcept
3805 {
3806 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
3807 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
3808 }
3809
3810 template<typename _Ctx, typename... _Args>
3811 friend auto
3812 make_format_args(_Args&...) noexcept;
3813
3814 // An array of _Arg_t enums corresponding to _Args...
3815 template<typename... _Args>
3816 static consteval array<__format::_Arg_t, sizeof...(_Args)>
3817 _S_types_to_pack()
3818 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
3819
3820 public:
3821 template<typename... _Args>
3822 basic_format_args(const _Store<_Args...>& __store) noexcept;
3823
3824 [[nodiscard,__gnu__::__always_inline__]]
3825 basic_format_arg<_Context>
3826 get(size_t __i) const noexcept
3827 {
3828 basic_format_arg<_Context> __arg;
3829 if (__i < _M_packed_size)
3830 {
3831 __arg._M_type = _M_type(__i);
3832 __arg._M_val = _M_values[__i];
3833 }
3834 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
3835 __arg = _M_args[__i];
3836 return __arg;
3837 }
3838 };
3839
3840 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3841 // 3810. CTAD for std::basic_format_args
3842 template<typename _Context, typename... _Args>
3843 basic_format_args(__format::_Arg_store<_Context, _Args...>)
3844 -> basic_format_args<_Context>;
3845
3846 template<typename _Context, typename... _Args>
3847 auto
3848 make_format_args(_Args&... __fmt_args) noexcept;
3849
3850 // An array of type-erased formatting arguments.
3851 template<typename _Context, typename... _Args>
3852 class __format::_Arg_store
3853 {
3854 friend std::basic_format_args<_Context>;
3855
3856 template<typename _Ctx, typename... _Argz>
3857 friend auto std::
3858#if _GLIBCXX_INLINE_VERSION
3859 __8:: // Needed for PR c++/59256
3860#endif
3861 make_format_args(_Argz&...) noexcept;
3862
3863 // For a sufficiently small number of arguments we only store values.
3864 // basic_format_args can get the types from the _Args pack.
3865 static constexpr bool _S_values_only
3866 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
3867
3868 using _Element_t
3869 = __conditional_t<_S_values_only,
3870 __format::_Arg_value<_Context>,
3871 basic_format_arg<_Context>>;
3872
3873 _Element_t _M_args[sizeof...(_Args)];
3874
3875 template<typename _Tp>
3876 static _Element_t
3877 _S_make_elt(_Tp& __v)
3878 {
3879 using _Tq = remove_const_t<_Tp>;
3880 using _CharT = typename _Context::char_type;
3881 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
3882 "std::formatter must be specialized for the type "
3883 "of each format arg");
3884 using __format::__formattable_with;
3885 if constexpr (is_const_v<_Tp>)
3886 if constexpr (!__formattable_with<_Tp, _Context>)
3887 if constexpr (__formattable_with<_Tq, _Context>)
3888 static_assert(__formattable_with<_Tp, _Context>,
3889 "format arg must be non-const because its "
3890 "std::formatter specialization has a "
3891 "non-const reference parameter");
3892 basic_format_arg<_Context> __arg(__v);
3893 if constexpr (_S_values_only)
3894 return __arg._M_val;
3895 else
3896 return __arg;
3897 }
3898
3899 template<typename... _Tp>
3900 requires (sizeof...(_Tp) == sizeof...(_Args))
3901 [[__gnu__::__always_inline__]]
3902 _Arg_store(_Tp&... __a) noexcept
3903 : _M_args{_S_make_elt(__a)...}
3904 { }
3905 };
3906
3907 template<typename _Context>
3908 class __format::_Arg_store<_Context>
3909 { };
3910
3911 template<typename _Context>
3912 template<typename... _Args>
3913 inline
3914 basic_format_args<_Context>::
3915 basic_format_args(const _Store<_Args...>& __store) noexcept
3916 {
3917 if constexpr (sizeof...(_Args) == 0)
3918 {
3919 _M_packed_size = 0;
3920 _M_unpacked_size = 0;
3921 _M_args = nullptr;
3922 }
3923 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
3924 {
3925 // The number of packed arguments:
3926 _M_packed_size = sizeof...(_Args);
3927 // The packed type enums:
3928 _M_unpacked_size
3929 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
3930 // The _Arg_value objects.
3931 _M_values = __store._M_args;
3932 }
3933 else
3934 {
3935 // No packed arguments:
3936 _M_packed_size = 0;
3937 // The number of unpacked arguments:
3938 _M_unpacked_size = sizeof...(_Args);
3939 // The basic_format_arg objects:
3940 _M_args = __store._M_args;
3941 }
3942 }
3943
3944 /// Capture formatting arguments for use by `std::vformat`.
3945 template<typename _Context = format_context, typename... _Args>
3946 [[nodiscard,__gnu__::__always_inline__]]
3947 inline auto
3948 make_format_args(_Args&... __fmt_args) noexcept
3949 {
3950 using _Fmt_arg = basic_format_arg<_Context>;
3951 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
3952 _Normalize<_Args>...>;
3953 return _Store(__fmt_args...);
3954 }
3955
3956#ifdef _GLIBCXX_USE_WCHAR_T
3957 /// Capture formatting arguments for use by `std::vformat` (for wide output).
3958 template<typename... _Args>
3959 [[nodiscard,__gnu__::__always_inline__]]
3960 inline auto
3961 make_wformat_args(_Args&... __args) noexcept
3962 { return std::make_format_args<wformat_context>(__args...); }
3963#endif
3964
3965/// @cond undocumented
3966namespace __format
3967{
3968 template<typename _Out, typename _CharT, typename _Context>
3969 _Out
3970 __do_vformat_to(_Out, basic_string_view<_CharT>,
3971 const basic_format_args<_Context>&,
3972 const locale* = nullptr);
3973
3974 template<typename _CharT> struct __formatter_chrono;
3975
3976} // namespace __format
3977/// @endcond
3978
3979 /** Context for std::format and similar functions.
3980 *
3981 * A formatting context contains an output iterator and locale to use
3982 * for the formatting operations. Most programs will never need to use
3983 * this class template explicitly. For typical uses of `std::format` the
3984 * library will use the specializations `std::format_context` (for `char`)
3985 * and `std::wformat_context` (for `wchar_t`).
3986 *
3987 * You are not allowed to define partial or explicit specializations of
3988 * this class template.
3989 *
3990 * @since C++20
3991 */
3992 template<typename _Out, typename _CharT>
3993 class basic_format_context
3994 {
3995 static_assert( output_iterator<_Out, const _CharT&> );
3996
3997 basic_format_args<basic_format_context> _M_args;
3998 _Out _M_out;
3999 __format::_Optional_locale _M_loc;
4000
4001 basic_format_context(basic_format_args<basic_format_context> __args,
4002 _Out __out)
4003 : _M_args(__args), _M_out(std::move(__out))
4004 { }
4005
4006 basic_format_context(basic_format_args<basic_format_context> __args,
4007 _Out __out, const std::locale& __loc)
4008 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4009 { }
4010
4011 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4012 // 4061. Should std::basic_format_context be
4013 // default-constructible/copyable/movable?
4014 basic_format_context(const basic_format_context&) = delete;
4015 basic_format_context& operator=(const basic_format_context&) = delete;
4016
4017 template<typename _Out2, typename _CharT2, typename _Context2>
4018 friend _Out2
4019 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4020 const basic_format_args<_Context2>&,
4021 const locale*);
4022
4023 friend __format::__formatter_chrono<_CharT>;
4024
4025 public:
4026 ~basic_format_context() = default;
4027
4028 using iterator = _Out;
4029 using char_type = _CharT;
4030 template<typename _Tp>
4031 using formatter_type = formatter<_Tp, _CharT>;
4032
4033 [[nodiscard]]
4034 basic_format_arg<basic_format_context>
4035 arg(size_t __id) const noexcept
4036 { return _M_args.get(__id); }
4037
4038 [[nodiscard]]
4039 std::locale locale() { return _M_loc.value(); }
4040
4041 [[nodiscard]]
4042 iterator out() { return std::move(_M_out); }
4043
4044 void advance_to(iterator __it) { _M_out = std::move(__it); }
4045 };
4046
4047
4048/// @cond undocumented
4049namespace __format
4050{
4051 // Abstract base class defining an interface for scanning format strings.
4052 // Scan the characters in a format string, dividing it up into strings of
4053 // ordinary characters, escape sequences, and replacement fields.
4054 // Call virtual functions for derived classes to parse format-specifiers
4055 // or write formatted output.
4056 template<typename _CharT>
4057 struct _Scanner
4058 {
4059 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4060
4061 struct _Parse_context : basic_format_parse_context<_CharT>
4062 {
4063 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4064 const _Arg_t* _M_types = nullptr;
4065 } _M_pc;
4066
4067 constexpr explicit
4068 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4069 : _M_pc(__str, __nargs)
4070 { }
4071
4072 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4073 constexpr iterator end() const noexcept { return _M_pc.end(); }
4074
4075 constexpr void
4076 _M_scan()
4077 {
4078 basic_string_view<_CharT> __fmt = _M_fmt_str();
4079
4080 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4081 {
4082 _M_pc.advance_to(begin() + 1);
4083 _M_format_arg(_M_pc.next_arg_id());
4084 return;
4085 }
4086
4087 size_t __lbr = __fmt.find('{');
4088 size_t __rbr = __fmt.find('}');
4089
4090 while (__fmt.size())
4091 {
4092 auto __cmp = __lbr <=> __rbr;
4093 if (__cmp == 0)
4094 {
4095 _M_on_chars(end());
4096 _M_pc.advance_to(end());
4097 return;
4098 }
4099 else if (__cmp < 0)
4100 {
4101 if (__lbr + 1 == __fmt.size()
4102 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4103 __format::__unmatched_left_brace_in_format_string();
4104 const bool __is_escape = __fmt[__lbr + 1] == '{';
4105 iterator __last = begin() + __lbr + int(__is_escape);
4106 _M_on_chars(__last);
4107 _M_pc.advance_to(__last + 1);
4108 __fmt = _M_fmt_str();
4109 if (__is_escape)
4110 {
4111 if (__rbr != __fmt.npos)
4112 __rbr -= __lbr + 2;
4113 __lbr = __fmt.find('{');
4114 }
4115 else
4116 {
4117 _M_on_replacement_field();
4118 __fmt = _M_fmt_str();
4119 __lbr = __fmt.find('{');
4120 __rbr = __fmt.find('}');
4121 }
4122 }
4123 else
4124 {
4125 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4126 __format::__unmatched_right_brace_in_format_string();
4127 iterator __last = begin() + __rbr;
4128 _M_on_chars(__last);
4129 _M_pc.advance_to(__last + 1);
4130 __fmt = _M_fmt_str();
4131 if (__lbr != __fmt.npos)
4132 __lbr -= __rbr + 1;
4133 __rbr = __fmt.find('}');
4134 }
4135 }
4136 }
4137
4138 constexpr basic_string_view<_CharT>
4139 _M_fmt_str() const noexcept
4140 { return {begin(), end()}; }
4141
4142 constexpr virtual void _M_on_chars(iterator) { }
4143
4144 constexpr void _M_on_replacement_field()
4145 {
4146 auto __next = begin();
4147
4148 size_t __id;
4149 if (*__next == '}')
4150 __id = _M_pc.next_arg_id();
4151 else if (*__next == ':')
4152 {
4153 __id = _M_pc.next_arg_id();
4154 _M_pc.advance_to(++__next);
4155 }
4156 else
4157 {
4158 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4159 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4160 __format::__invalid_arg_id_in_format_string();
4161 _M_pc.check_arg_id(__id = __i);
4162 if (*__ptr == ':')
4163 {
4164 _M_pc.advance_to(++__ptr);
4165 }
4166 else
4167 _M_pc.advance_to(__ptr);
4168 }
4169 _M_format_arg(__id);
4170 if (begin() == end() || *begin() != '}')
4171 __format::__unmatched_left_brace_in_format_string();
4172 _M_pc.advance_to(begin() + 1); // Move past '}'
4173 }
4174
4175 constexpr virtual void _M_format_arg(size_t __id) = 0;
4176 };
4177
4178 // Process a format string and format the arguments in the context.
4179 template<typename _Out, typename _CharT>
4180 class _Formatting_scanner : public _Scanner<_CharT>
4181 {
4182 public:
4183 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4184 basic_string_view<_CharT> __str)
4185 : _Scanner<_CharT>(__str), _M_fc(__fc)
4186 { }
4187
4188 private:
4189 basic_format_context<_Out, _CharT>& _M_fc;
4190
4191 using iterator = typename _Scanner<_CharT>::iterator;
4192
4193 constexpr void
4194 _M_on_chars(iterator __last) override
4195 {
4196 basic_string_view<_CharT> __str(this->begin(), __last);
4197 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4198 }
4199
4200 constexpr void
4201 _M_format_arg(size_t __id) override
4202 {
4203 using _Context = basic_format_context<_Out, _CharT>;
4204 using handle = typename basic_format_arg<_Context>::handle;
4205
4206 __format::__visit_format_arg([this](auto& __arg) {
4207 using _Type = remove_reference_t<decltype(__arg)>;
4208 using _Formatter = typename _Context::template formatter_type<_Type>;
4209 if constexpr (is_same_v<_Type, monostate>)
4210 __format::__invalid_arg_id_in_format_string();
4211 else if constexpr (is_same_v<_Type, handle>)
4212 __arg.format(this->_M_pc, this->_M_fc);
4213 else if constexpr (is_default_constructible_v<_Formatter>)
4214 {
4215 _Formatter __f;
4216 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4217 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4218 }
4219 else
4220 static_assert(__format::__formattable_with<_Type, _Context>);
4221 }, _M_fc.arg(__id));
4222 }
4223 };
4224
4225 template<typename _CharT, typename _Tp>
4226 consteval _Arg_t
4227 __to_arg_t_enum() noexcept
4228 {
4229 using _Context = __format::__format_context<_CharT>;
4230 using _Fmt_arg = basic_format_arg<_Context>;
4231 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4232 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4233 }
4234
4235 // Validate a format string for Args.
4236 template<typename _CharT, typename... _Args>
4237 class _Checking_scanner : public _Scanner<_CharT>
4238 {
4239 static_assert(
4240 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4241 "std::formatter must be specialized for each type being formatted");
4242
4243 public:
4244 consteval
4245 _Checking_scanner(basic_string_view<_CharT> __str)
4246 : _Scanner<_CharT>(__str, sizeof...(_Args))
4247 {
4248#if __cpp_lib_format >= 202305L
4249 this->_M_pc._M_types = _M_types.data();
4250#endif
4251 }
4252
4253 private:
4254 constexpr void
4255 _M_format_arg(size_t __id) override
4256 {
4257 if constexpr (sizeof...(_Args) != 0)
4258 {
4259 if (__id < sizeof...(_Args))
4260 {
4261 _M_parse_format_spec<_Args...>(__id);
4262 return;
4263 }
4264 }
4265 __builtin_unreachable();
4266 }
4267
4268 template<typename _Tp, typename... _OtherArgs>
4269 constexpr void
4270 _M_parse_format_spec(size_t __id)
4271 {
4272 if (__id == 0)
4273 {
4274 formatter<_Tp, _CharT> __f;
4275 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4276 }
4277 else if constexpr (sizeof...(_OtherArgs) != 0)
4278 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4279 else
4280 __builtin_unreachable();
4281 }
4282
4283#if __cpp_lib_format >= 202305L
4284 array<_Arg_t, sizeof...(_Args)>
4285 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
4286#endif
4287 };
4288
4289 template<typename _Out, typename _CharT, typename _Context>
4290 inline _Out
4291 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4292 const basic_format_args<_Context>& __args,
4293 const locale* __loc)
4294 {
4295 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4296 _Sink_iter<_CharT> __sink_out;
4297
4298 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4299 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4300 else
4301 __sink_out = __sink.out();
4302
4303 if constexpr (is_same_v<_CharT, char>)
4304 // Fast path for "{}" format strings and simple format arg types.
4305 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4306 {
4307 bool __done = false;
4308 __format::__visit_format_arg([&](auto& __arg) {
4309 using _Tp = remove_cvref_t<decltype(__arg)>;
4310 if constexpr (is_same_v<_Tp, bool>)
4311 {
4312 size_t __len = 4 + !__arg;
4313 const char* __chars[] = { "false", "true" };
4314 if (auto __res = __sink_out._M_reserve(__len))
4315 {
4316 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4317 __res._M_bump(__len);
4318 __done = true;
4319 }
4320 }
4321 else if constexpr (is_same_v<_Tp, char>)
4322 {
4323 if (auto __res = __sink_out._M_reserve(1))
4324 {
4325 *__res.get() = __arg;
4326 __res._M_bump(1);
4327 __done = true;
4328 }
4329 }
4330 else if constexpr (is_integral_v<_Tp>)
4331 {
4332 make_unsigned_t<_Tp> __uval;
4333 const bool __neg = __arg < 0;
4334 if (__neg)
4335 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4336 else
4337 __uval = __arg;
4338 const auto __n = __detail::__to_chars_len(__uval);
4339 if (auto __res = __sink_out._M_reserve(__n + __neg))
4340 {
4341 auto __ptr = __res.get();
4342 *__ptr = '-';
4343 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4344 __uval);
4345 __res._M_bump(__n + __neg);
4346 __done = true;
4347 }
4348 }
4349 else if constexpr (is_convertible_v<_Tp, string_view>)
4350 {
4351 string_view __sv = __arg;
4352 if (auto __res = __sink_out._M_reserve(__sv.size()))
4353 {
4354 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4355 __res._M_bump(__sv.size());
4356 __done = true;
4357 }
4358 }
4359 }, __args.get(0));
4360
4361 if (__done)
4362 {
4363 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4364 return __sink_out;
4365 else
4366 return std::move(__sink)._M_finish().out;
4367 }
4368 }
4369
4370 auto __ctx = __loc == nullptr
4371 ? _Context(__args, __sink_out)
4372 : _Context(__args, __sink_out, *__loc);
4373 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4374 __scanner._M_scan();
4375
4376 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4377 return __ctx.out();
4378 else
4379 return std::move(__sink)._M_finish().out;
4380 }
4381#pragma GCC diagnostic pop
4382
4383} // namespace __format
4384/// @endcond
4385
4386#if __cpp_lib_format >= 202305L // >= C++26
4387 /// @cond undocumented
4388 // Common implementation of check_dynamic_spec{,_string,_integral}
4389 template<typename _CharT>
4390 template<typename... _Ts>
4391 consteval void
4392 basic_format_parse_context<_CharT>::
4393 __check_dynamic_spec(size_t __id) noexcept
4394 {
4395 if (__id >= _M_num_args)
4396 __format::__invalid_arg_id_in_format_string();
4397 if constexpr (sizeof...(_Ts) != 0)
4398 {
4399 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
4400 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
4401 __format::_Arg_t __types[] = {
4402 __format::__to_arg_t_enum<_CharT, _Ts>()...
4403 };
4404 for (auto __t : __types)
4405 if (__arg == __t)
4406 return;
4407 }
4408 __invalid_dynamic_spec("arg(id) type does not match");
4409 }
4410 /// @endcond
4411#endif
4412
4413 template<typename _CharT, typename... _Args>
4414 template<typename _Tp>
4415 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4416 consteval
4417 basic_format_string<_CharT, _Args...>::
4418 basic_format_string(const _Tp& __s)
4419 : _M_str(__s)
4420 {
4421 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4422 __scanner(_M_str);
4423 __scanner._M_scan();
4424 }
4425
4426 // [format.functions], formatting functions
4427
4428 template<typename _Out> requires output_iterator<_Out, const char&>
4429 [[__gnu__::__always_inline__]]
4430 inline _Out
4431 vformat_to(_Out __out, string_view __fmt, format_args __args)
4432 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4433
4434#ifdef _GLIBCXX_USE_WCHAR_T
4435 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4436 [[__gnu__::__always_inline__]]
4437 inline _Out
4438 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4439 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4440#endif
4441
4442 template<typename _Out> requires output_iterator<_Out, const char&>
4443 [[__gnu__::__always_inline__]]
4444 inline _Out
4445 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4446 format_args __args)
4447 {
4448 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4449 }
4450
4451#ifdef _GLIBCXX_USE_WCHAR_T
4452 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4453 [[__gnu__::__always_inline__]]
4454 inline _Out
4455 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4456 wformat_args __args)
4457 {
4458 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4459 }
4460#endif
4461
4462 [[nodiscard]]
4463 inline string
4464 vformat(string_view __fmt, format_args __args)
4465 {
4466 __format::_Str_sink<char> __buf;
4467 std::vformat_to(__buf.out(), __fmt, __args);
4468 return std::move(__buf).get();
4469 }
4470
4471#ifdef _GLIBCXX_USE_WCHAR_T
4472 [[nodiscard]]
4473 inline wstring
4474 vformat(wstring_view __fmt, wformat_args __args)
4475 {
4476 __format::_Str_sink<wchar_t> __buf;
4477 std::vformat_to(__buf.out(), __fmt, __args);
4478 return std::move(__buf).get();
4479 }
4480#endif
4481
4482 [[nodiscard]]
4483 inline string
4484 vformat(const locale& __loc, string_view __fmt, format_args __args)
4485 {
4486 __format::_Str_sink<char> __buf;
4487 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4488 return std::move(__buf).get();
4489 }
4490
4491#ifdef _GLIBCXX_USE_WCHAR_T
4492 [[nodiscard]]
4493 inline wstring
4494 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4495 {
4496 __format::_Str_sink<wchar_t> __buf;
4497 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4498 return std::move(__buf).get();
4499 }
4500#endif
4501
4502 template<typename... _Args>
4503 [[nodiscard]]
4504 inline string
4505 format(format_string<_Args...> __fmt, _Args&&... __args)
4506 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4507
4508#ifdef _GLIBCXX_USE_WCHAR_T
4509 template<typename... _Args>
4510 [[nodiscard]]
4511 inline wstring
4512 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4513 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4514#endif
4515
4516 template<typename... _Args>
4517 [[nodiscard]]
4518 inline string
4519 format(const locale& __loc, format_string<_Args...> __fmt,
4520 _Args&&... __args)
4521 {
4522 return std::vformat(__loc, __fmt.get(),
4523 std::make_format_args(__args...));
4524 }
4525
4526#ifdef _GLIBCXX_USE_WCHAR_T
4527 template<typename... _Args>
4528 [[nodiscard]]
4529 inline wstring
4530 format(const locale& __loc, wformat_string<_Args...> __fmt,
4531 _Args&&... __args)
4532 {
4533 return std::vformat(__loc, __fmt.get(),
4534 std::make_wformat_args(__args...));
4535 }
4536#endif
4537
4538 template<typename _Out, typename... _Args>
4539 requires output_iterator<_Out, const char&>
4540 inline _Out
4541 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4542 {
4543 return std::vformat_to(std::move(__out), __fmt.get(),
4544 std::make_format_args(__args...));
4545 }
4546
4547#ifdef _GLIBCXX_USE_WCHAR_T
4548 template<typename _Out, typename... _Args>
4549 requires output_iterator<_Out, const wchar_t&>
4550 inline _Out
4551 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4552 {
4553 return std::vformat_to(std::move(__out), __fmt.get(),
4554 std::make_wformat_args(__args...));
4555 }
4556#endif
4557
4558 template<typename _Out, typename... _Args>
4559 requires output_iterator<_Out, const char&>
4560 inline _Out
4561 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4562 _Args&&... __args)
4563 {
4564 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4565 std::make_format_args(__args...));
4566 }
4567
4568#ifdef _GLIBCXX_USE_WCHAR_T
4569 template<typename _Out, typename... _Args>
4570 requires output_iterator<_Out, const wchar_t&>
4571 inline _Out
4572 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4573 _Args&&... __args)
4574 {
4575 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4576 std::make_wformat_args(__args...));
4577 }
4578#endif
4579
4580 template<typename _Out, typename... _Args>
4581 requires output_iterator<_Out, const char&>
4582 inline format_to_n_result<_Out>
4583 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4584 format_string<_Args...> __fmt, _Args&&... __args)
4585 {
4586 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4587 std::vformat_to(__sink.out(), __fmt.get(),
4588 std::make_format_args(__args...));
4589 return std::move(__sink)._M_finish();
4590 }
4591
4592#ifdef _GLIBCXX_USE_WCHAR_T
4593 template<typename _Out, typename... _Args>
4594 requires output_iterator<_Out, const wchar_t&>
4595 inline format_to_n_result<_Out>
4596 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4597 wformat_string<_Args...> __fmt, _Args&&... __args)
4598 {
4599 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4600 std::vformat_to(__sink.out(), __fmt.get(),
4601 std::make_wformat_args(__args...));
4602 return std::move(__sink)._M_finish();
4603 }
4604#endif
4605
4606 template<typename _Out, typename... _Args>
4607 requires output_iterator<_Out, const char&>
4608 inline format_to_n_result<_Out>
4609 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4610 format_string<_Args...> __fmt, _Args&&... __args)
4611 {
4612 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4613 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4614 std::make_format_args(__args...));
4615 return std::move(__sink)._M_finish();
4616 }
4617
4618#ifdef _GLIBCXX_USE_WCHAR_T
4619 template<typename _Out, typename... _Args>
4620 requires output_iterator<_Out, const wchar_t&>
4621 inline format_to_n_result<_Out>
4622 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4623 wformat_string<_Args...> __fmt, _Args&&... __args)
4624 {
4625 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4626 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4627 std::make_wformat_args(__args...));
4628 return std::move(__sink)._M_finish();
4629 }
4630#endif
4631
4632/// @cond undocumented
4633namespace __format
4634{
4635#if 1
4636 template<typename _CharT>
4637 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
4638 {
4639 public:
4640 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
4641
4642 [[__gnu__::__always_inline__]]
4643 size_t
4644 count() const
4645 { return this->_M_count + this->_M_used().size(); }
4646 };
4647#else
4648 template<typename _CharT>
4649 class _Counting_sink : public _Buf_sink<_CharT>
4650 {
4651 size_t _M_count = 0;
4652
4653 void
4654 _M_overflow() override
4655 {
4656 if (!std::is_constant_evaluated())
4657 _M_count += this->_M_used().size();
4658 this->_M_rewind();
4659 }
4660
4661 public:
4662 _Counting_sink() = default;
4663
4664 [[__gnu__::__always_inline__]]
4665 size_t
4666 count() noexcept
4667 {
4668 _Counting_sink::_M_overflow();
4669 return _M_count;
4670 }
4671 };
4672#endif
4673} // namespace __format
4674/// @endcond
4675
4676 template<typename... _Args>
4677 [[nodiscard]]
4678 inline size_t
4679 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
4680 {
4681 __format::_Counting_sink<char> __buf;
4682 std::vformat_to(__buf.out(), __fmt.get(),
4683 std::make_format_args(__args...));
4684 return __buf.count();
4685 }
4686
4687#ifdef _GLIBCXX_USE_WCHAR_T
4688 template<typename... _Args>
4689 [[nodiscard]]
4690 inline size_t
4691 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
4692 {
4693 __format::_Counting_sink<wchar_t> __buf;
4694 std::vformat_to(__buf.out(), __fmt.get(),
4695 std::make_wformat_args(__args...));
4696 return __buf.count();
4697 }
4698#endif
4699
4700 template<typename... _Args>
4701 [[nodiscard]]
4702 inline size_t
4703 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
4704 _Args&&... __args)
4705 {
4706 __format::_Counting_sink<char> __buf;
4707 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4708 std::make_format_args(__args...));
4709 return __buf.count();
4710 }
4711
4712#ifdef _GLIBCXX_USE_WCHAR_T
4713 template<typename... _Args>
4714 [[nodiscard]]
4715 inline size_t
4716 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
4717 _Args&&... __args)
4718 {
4719 __format::_Counting_sink<wchar_t> __buf;
4720 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4721 std::make_wformat_args(__args...));
4722 return __buf.count();
4723 }
4724#endif
4725
4726#if __cpp_lib_format_ranges
4727 // [format.range], formatting of ranges
4728 // [format.range.fmtkind], variable template format_kind
4729 enum class range_format {
4730 disabled,
4731 map,
4732 set,
4733 sequence,
4734 string,
4735 debug_string
4736 };
4737
4738 /// @cond undocumented
4739 template<typename _Rg>
4740 constexpr auto format_kind = not defined(format_kind<_Rg>);
4741
4742 template<typename _Tp>
4743 consteval range_format
4744 __fmt_kind()
4745 {
4746 using _Ref = ranges::range_reference_t<_Tp>;
4747 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
4748 return range_format::disabled;
4749 else if constexpr (requires { typename _Tp::key_type; })
4750 {
4751 if constexpr (requires { typename _Tp::mapped_type; })
4752 {
4753 using _Up = remove_cvref_t<_Ref>;
4754 if constexpr (__is_pair<_Up>)
4755 return range_format::map;
4756 else if constexpr (__is_specialization_of<_Up, tuple>)
4757 if constexpr (tuple_size_v<_Up> == 2)
4758 return range_format::map;
4759 }
4760 return range_format::set;
4761 }
4762 else
4763 return range_format::sequence;
4764 }
4765 /// @endcond
4766
4767 /// A constant determining how a range should be formatted.
4768 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
4769 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
4770
4771 // [format.range.formatter], class template range_formatter
4772 template<typename _Tp, typename _CharT = char>
4773 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
4774 class range_formatter; // TODO
4775
4776/// @cond undocumented
4777namespace __format
4778{
4779 // [format.range.fmtdef], class template range-default-formatter
4780 template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
4781 struct __range_default_formatter; // TODO
4782} // namespace __format
4783/// @endcond
4784
4785 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
4786 // specializations for maps, sets, and strings
4787 template<ranges::input_range _Rg, typename _CharT>
4788 requires (format_kind<_Rg> != range_format::disabled)
4789 && formattable<ranges::range_reference_t<_Rg>, _CharT>
4790 struct formatter<_Rg, _CharT>
4791 : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
4792 { };
4793#endif // C++23 formatting ranges
4794
4795_GLIBCXX_END_NAMESPACE_VERSION
4796} // namespace std
4797#endif // __cpp_lib_format
4798#pragma GCC diagnostic pop
4799#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.