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