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