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 case _Pres_none:
1726 // Should not reach here with _Pres_none for bool or charT, so:
1727 [[fallthrough]];
1728 case _Pres_d:
1729 __res = to_chars(__start, __end, __u, 10);
1730 break;
1731 case _Pres_o:
1732 if (__i != 0)
1733 __base_prefix = "0";
1734 __res = to_chars(__start, __end, __u, 8);
1735 break;
1736 case _Pres_x:
1737 case _Pres_X:
1738 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1739 __res = to_chars(__start, __end, __u, 16);
1740 if (_M_spec._M_type == _Pres_X)
1741 for (auto __p = __start; __p != __res.ptr; ++__p)
1742 *__p = __format::__toupper_numeric(*__p);
1743 break;
1744 default:
1745 __builtin_unreachable();
1746 }
1747
1748 if (_M_spec._M_alt && __base_prefix.size())
1749 {
1750 __start -= __base_prefix.size();
1751 ranges::copy(__base_prefix, __start);
1752 }
1753 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1754
1755
1756 string_view __narrow_str(__start, __res.ptr - __start);
1757 size_t __prefix_len = __start_digits - __start;
1758 if constexpr (is_same_v<char, _CharT>)
1759 return _M_format_int(__narrow_str, __prefix_len, __fc);
1760#ifdef _GLIBCXX_USE_WCHAR_T
1761 else
1762 {
1763 _CharT __wbuf[__buf_size];
1764 size_t __n = __narrow_str.size();
1765 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1766 // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
1767 std::__to_wstring_numeric(__narrow_str.data(), __n, __wbuf);
1768 return _M_format_int(basic_string_view<_CharT>(__wbuf, __n),
1769 __prefix_len, __fc);
1770 }
1771#endif
1772 }
1773
1774 template<typename _Out>
1775 _GLIBCXX_CONSTEXPR_FORMAT
1776 typename basic_format_context<_Out, _CharT>::iterator
1777 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1778 {
1779 if (_M_spec._M_type == _Pres_c)
1780 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1781 if (_M_spec._M_type != _Pres_s)
1782 return format(static_cast<unsigned char>(__i), __fc);
1783
1784 basic_string<_CharT> __s;
1785 size_t __est_width;
1786 if (_M_spec._M_localized) [[unlikely]]
1787 {
1788 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1789 __s = __i ? __np.truename() : __np.falsename();
1790 __est_width = __s.size(); // TODO Unicode-aware estimate
1791 }
1792 else
1793 {
1794 if constexpr (is_same_v<char, _CharT>)
1795 __s = __i ? "true" : "false";
1796 else
1797 __s = __i ? L"true" : L"false";
1798 __est_width = __s.size();
1799 }
1800
1801 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1802 _M_spec);
1803 }
1804
1805 template<typename _Out>
1806 _GLIBCXX_CONSTEXPR_FORMAT
1807 typename basic_format_context<_Out, _CharT>::iterator
1808 _M_format_character(_CharT __c,
1809 basic_format_context<_Out, _CharT>& __fc) const
1810 {
1811 basic_string_view<_CharT> __in(&__c, 1u);
1812 size_t __width = 1u;
1813 // N.B. single byte cannot encode character of width greater than 1
1814 if constexpr (sizeof(_CharT) > 1u &&
1815 __unicode::__literal_encoding_is_unicode<_CharT>())
1816 __width = __unicode::__field_width(__c);
1817
1818 if (!_M_spec._M_debug)
1819 return __format::__write_padded_as_spec(__in, __width,
1820 __fc, _M_spec);
1821
1822 __width += 2;
1823 if (_M_spec._M_get_width(__fc) <= __width)
1824 return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1825
1826 _CharT __buf[12];
1827 _Fixedbuf_sink<_CharT> __sink(__buf);
1828 __format::__write_escaped(__sink.out(), __in, _Term_apos);
1829
1830 __in = __sink.view();
1831 if (__in[1] == _Escapes<_CharT>::_S_bslash()[0]) // escape sequence
1832 __width = __in.size();
1833 return __format::__write_padded_as_spec(__in, __width,
1834 __fc, _M_spec);
1835 }
1836
1837 template<typename _Int>
1838 static _GLIBCXX_CONSTEXPR_FORMAT _CharT
1839 _S_to_character(_Int __i)
1840 {
1841 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1842 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1843 {
1844 if (_Traits::__min <= __i && __i <= _Traits::__max)
1845 return static_cast<_CharT>(__i);
1846 }
1847 else if constexpr (is_signed_v<_Int>)
1848 {
1849 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1850 return static_cast<_CharT>(__i);
1851 }
1852 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1853 return static_cast<_CharT>(__i);
1854 __throw_format_error("format error: integer not representable as "
1855 "character");
1856 }
1857
1858 template<typename _Out>
1859 _GLIBCXX_CONSTEXPR_FORMAT
1860 typename basic_format_context<_Out, _CharT>::iterator
1861 _M_format_int(basic_string_view<_CharT> __str, size_t __prefix_len,
1862 basic_format_context<_Out, _CharT>& __fc) const
1863 {
1864 size_t __width = _M_spec._M_get_width(__fc);
1865 if (_M_spec._M_localized)
1866 {
1867 const auto& __l = __fc.locale();
1868 if (__l.name() != "C")
1869 {
1870 auto& __np = use_facet<numpunct<_CharT>>(__l);
1871 string __grp = __np.grouping();
1872 if (!__grp.empty())
1873 {
1874 size_t __n = __str.size() - __prefix_len;
1875 auto __p = (_CharT*)__builtin_alloca(2 * __n
1876 * sizeof(_CharT)
1877 + __prefix_len);
1878 auto __s = __str.data();
1879 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1880 __s += __prefix_len;
1881 auto __end = std::__add_grouping(__p + __prefix_len,
1882 __np.thousands_sep(),
1883 __grp.data(),
1884 __grp.size(),
1885 __s, __s + __n);
1886 __str = {__p, size_t(__end - __p)};
1887 }
1888 }
1889 }
1890
1891 if (__width <= __str.size())
1892 return __format::__write(__fc.out(), __str);
1893
1894 char32_t __fill_char = _M_spec._M_fill;
1895 _Align __align = _M_spec._M_align;
1896
1897 size_t __nfill = __width - __str.size();
1898 auto __out = __fc.out();
1899 if (__align == _Align_default)
1900 {
1901 __align = _Align_right;
1902 if (_M_spec._M_zero_fill)
1903 {
1904 __fill_char = _CharT('0');
1905 // Write sign and base prefix before zero filling.
1906 if (__prefix_len != 0)
1907 {
1908 __out = __format::__write(std::move(__out),
1909 __str.substr(0, __prefix_len));
1910 __str.remove_prefix(__prefix_len);
1911 }
1912 }
1913 else
1914 __fill_char = _CharT(' ');
1915 }
1916 return __format::__write_padded(std::move(__out), __str,
1917 __align, __nfill, __fill_char);
1918 }
1919
1920 _Spec<_CharT> _M_spec{};
1921 };
1922
1923#ifdef __BFLT16_DIG__
1924 using __bflt16_t = decltype(0.0bf16);
1925#endif
1926
1927 // Decide how 128-bit floating-point types should be formatted (or not).
1928 // When supported, the typedef __format::__flt128_t is the type that format
1929 // arguments should be converted to before passing them to __formatter_fp.
1930 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1931 // The __float128, _Float128 will be formatted by converting them to:
1932 // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1933 // long double when _GLIBCXX_FORMAT_F128=2,
1934 // _Float128 when _GLIBCXX_FORMAT_F128=3.
1935#undef _GLIBCXX_FORMAT_F128
1936
1937#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1938
1939 // Format 128-bit floating-point types using __ieee128.
1940 using __flt128_t = __ieee128;
1941# define _GLIBCXX_FORMAT_F128 1
1942
1943#ifdef __LONG_DOUBLE_IEEE128__
1944 // These overloads exist in the library, but are not declared.
1945 // Make them available as std::__format::to_chars.
1946 to_chars_result
1947 to_chars(char*, char*, __ibm128) noexcept
1948 __asm("_ZSt8to_charsPcS_e");
1949
1950 to_chars_result
1951 to_chars(char*, char*, __ibm128, chars_format) noexcept
1952 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1953
1954 to_chars_result
1955 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1956 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1957#elif __cplusplus == 202002L
1958 to_chars_result
1959 to_chars(char*, char*, __ieee128) noexcept
1960 __asm("_ZSt8to_charsPcS_u9__ieee128");
1961
1962 to_chars_result
1963 to_chars(char*, char*, __ieee128, chars_format) noexcept
1964 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1965
1966 to_chars_result
1967 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1968 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1969#endif
1970
1971#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1972
1973 // Format 128-bit floating-point types using long double.
1974 using __flt128_t = long double;
1975# define _GLIBCXX_FORMAT_F128 2
1976
1977#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1978
1979 // Format 128-bit floating-point types using _Float128.
1980 using __flt128_t = _Float128;
1981# define _GLIBCXX_FORMAT_F128 3
1982
1983# if __cplusplus == 202002L
1984 // These overloads exist in the library, but are not declared for C++20.
1985 // Make them available as std::__format::to_chars.
1986 to_chars_result
1987 to_chars(char*, char*, _Float128) noexcept
1988# if _GLIBCXX_INLINE_VERSION
1989 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1990# else
1991 __asm("_ZSt8to_charsPcS_DF128_");
1992# endif
1993
1994 to_chars_result
1995 to_chars(char*, char*, _Float128, chars_format) noexcept
1996# if _GLIBCXX_INLINE_VERSION
1997 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1998# else
1999 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
2000# endif
2001
2002 to_chars_result
2003 to_chars(char*, char*, _Float128, chars_format, int) noexcept
2004# if _GLIBCXX_INLINE_VERSION
2005 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
2006# else
2007 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
2008# endif
2009# endif
2010#endif
2011
2012 using std::to_chars;
2013
2014 // We can format a floating-point type iff it is usable with to_chars.
2015 template<typename _Tp>
2016 concept __formattable_float
2017 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
2018 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
2019
2020 template<__char _CharT>
2021 struct __formatter_fp
2022 {
2023 constexpr typename basic_format_parse_context<_CharT>::iterator
2024 parse(basic_format_parse_context<_CharT>& __pc)
2025 {
2026 _Spec<_CharT> __spec{};
2027 const auto __last = __pc.end();
2028 auto __first = __pc.begin();
2029
2030 auto __finalize = [this, &__spec] {
2031 _M_spec = __spec;
2032 };
2033
2034 auto __finished = [&] {
2035 if (__first == __last || *__first == '}')
2036 {
2037 __finalize();
2038 return true;
2039 }
2040 return false;
2041 };
2042
2043 if (__finished())
2044 return __first;
2045
2046 __first = __spec._M_parse_fill_and_align(__first, __last);
2047 if (__finished())
2048 return __first;
2049
2050 __first = __spec._M_parse_sign(__first, __last);
2051 if (__finished())
2052 return __first;
2053
2054 __first = __spec._M_parse_alternate_form(__first, __last);
2055 if (__finished())
2056 return __first;
2057
2058 __first = __spec._M_parse_zero_fill(__first, __last);
2059 if (__finished())
2060 return __first;
2061
2062 if (__first[0] != '.')
2063 {
2064 __first = __spec._M_parse_width(__first, __last, __pc);
2065 if (__finished())
2066 return __first;
2067 }
2068
2069 __first = __spec._M_parse_precision(__first, __last, __pc);
2070 if (__finished())
2071 return __first;
2072
2073 __first = __spec._M_parse_locale(__first, __last);
2074 if (__finished())
2075 return __first;
2076
2077 switch (*__first)
2078 {
2079 case 'a':
2080 __spec._M_type = _Pres_a;
2081 ++__first;
2082 break;
2083 case 'A':
2084 __spec._M_type = _Pres_A;
2085 ++__first;
2086 break;
2087 case 'e':
2088 __spec._M_type = _Pres_e;
2089 ++__first;
2090 break;
2091 case 'E':
2092 __spec._M_type = _Pres_E;
2093 ++__first;
2094 break;
2095 case 'f':
2096 __spec._M_type = _Pres_f;
2097 ++__first;
2098 break;
2099 case 'F':
2100 __spec._M_type = _Pres_F;
2101 ++__first;
2102 break;
2103 case 'g':
2104 __spec._M_type = _Pres_g;
2105 ++__first;
2106 break;
2107 case 'G':
2108 __spec._M_type = _Pres_G;
2109 ++__first;
2110 break;
2111 }
2112
2113 if (__finished())
2114 return __first;
2115
2116 __format::__failed_to_parse_format_spec();
2117 }
2118
2119 template<typename _Fp, typename _Out>
2120 typename basic_format_context<_Out, _CharT>::iterator
2121 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2122 {
2123 std::string __dynbuf;
2124 char __buf[128];
2125 to_chars_result __res{};
2126
2127 size_t __prec = 6;
2128 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2129 if (__use_prec)
2130 __prec = _M_spec._M_get_precision(__fc);
2131
2132 char* __start = __buf + 1; // reserve space for sign
2133 char* __end = __buf + sizeof(__buf);
2134
2135 chars_format __fmt{};
2136 bool __upper = false;
2137 bool __trailing_zeros = false;
2138 char __expc = 'e';
2139
2140 switch (_M_spec._M_type)
2141 {
2142 case _Pres_A:
2143 __upper = true;
2144 __expc = 'P';
2145 [[fallthrough]];
2146 case _Pres_a:
2147 if (_M_spec._M_type != _Pres_A)
2148 __expc = 'p';
2149 __fmt = chars_format::hex;
2150 break;
2151 case _Pres_E:
2152 __upper = true;
2153 __expc = 'E';
2154 [[fallthrough]];
2155 case _Pres_e:
2156 __use_prec = true;
2157 __fmt = chars_format::scientific;
2158 break;
2159 case _Pres_F:
2160 __upper = true;
2161 [[fallthrough]];
2162 case _Pres_f:
2163 __use_prec = true;
2164 __fmt = chars_format::fixed;
2165 break;
2166 case _Pres_G:
2167 __upper = true;
2168 __expc = 'E';
2169 [[fallthrough]];
2170 case _Pres_g:
2171 __trailing_zeros = true;
2172 __use_prec = true;
2173 __fmt = chars_format::general;
2174 break;
2175 case _Pres_none:
2176 if (__use_prec)
2177 __fmt = chars_format::general;
2178 break;
2179 default:
2180 __builtin_unreachable();
2181 }
2182
2183 // Write value into buffer using std::to_chars.
2184 auto __to_chars = [&](char* __b, char* __e) {
2185 if (__use_prec)
2186 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2187 else if (__fmt != chars_format{})
2188 return __format::to_chars(__b, __e, __v, __fmt);
2189 else
2190 return __format::to_chars(__b, __e, __v);
2191 };
2192
2193 // First try using stack buffer.
2194 __res = __to_chars(__start, __end);
2195
2196 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2197 {
2198 // If the buffer is too small it's probably because of a large
2199 // precision, or a very large value in fixed format.
2200 size_t __guess = 8 + __prec;
2201 if (__fmt == chars_format::fixed) // +ddd.prec
2202 {
2203 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2204 || is_same_v<_Fp, long double>)
2205 {
2206 // The number of digits to the left of the decimal point
2207 // is floor(log10(max(abs(__v),1)))+1
2208 int __exp{};
2209 if constexpr (is_same_v<_Fp, float>)
2210 __builtin_frexpf(__v, &__exp);
2211 else if constexpr (is_same_v<_Fp, double>)
2212 __builtin_frexp(__v, &__exp);
2213 else if constexpr (is_same_v<_Fp, long double>)
2214 __builtin_frexpl(__v, &__exp);
2215 if (__exp > 0)
2216 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2217 }
2218 else
2219 __guess += numeric_limits<_Fp>::max_exponent10;
2220 }
2221 if (__guess <= sizeof(__buf)) [[unlikely]]
2222 __guess = sizeof(__buf) * 2;
2223 __dynbuf.reserve(__guess);
2224
2225 do
2226 {
2227 // Mangling of this lambda, and thus resize_and_overwrite
2228 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2229 // <format> was new in G++ 13, and is experimental, that
2230 // isn't a problem.
2231 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
2232 {
2233 __res = __to_chars(__p + 1, __p + __n - 1);
2234 return __res.ec == errc{} ? __res.ptr - __p : 0;
2235 };
2236
2237 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2238 __overwrite);
2239 __start = __dynbuf.data() + 1; // reserve space for sign
2240 __end = __dynbuf.data() + __dynbuf.size();
2241 }
2242 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2243 }
2244
2245 // Use uppercase for 'A', 'E', and 'G' formats.
2246 if (__upper)
2247 {
2248 for (char* __p = __start; __p != __res.ptr; ++__p)
2249 *__p = __format::__toupper_numeric(*__p);
2250 }
2251
2252 bool __have_sign = true;
2253 // Add sign for non-negative values.
2254 if (!__builtin_signbit(__v))
2255 {
2256 if (_M_spec._M_sign == _Sign_plus)
2257 *--__start = '+';
2258 else if (_M_spec._M_sign == _Sign_space)
2259 *--__start = ' ';
2260 else
2261 __have_sign = false;
2262 }
2263
2264 string_view __narrow_str(__start, __res.ptr - __start);
2265
2266 // Use alternate form. Ensure decimal point is always present,
2267 // and add trailing zeros (up to precision) for g and G forms.
2268 if (_M_spec._M_alt && __builtin_isfinite(__v))
2269 {
2270 string_view __s = __narrow_str;
2271 size_t __sigfigs; // Number of significant figures.
2272 size_t __z = 0; // Number of trailing zeros to add.
2273 size_t __p; // Position of the exponent character (if any).
2274 size_t __d = __s.find('.'); // Position of decimal point.
2275 if (__d != __s.npos) // Found decimal point.
2276 {
2277 __p = __s.find(__expc, __d + 1);
2278 if (__p == __s.npos)
2279 __p = __s.size();
2280
2281 // If presentation type is g or G we might need to add zeros.
2282 if (__trailing_zeros)
2283 {
2284 // Find number of digits after first significant figure.
2285 if (__s[__have_sign] != '0')
2286 // A string like "D.D" or "-D.DDD"
2287 __sigfigs = __p - __have_sign - 1;
2288 else
2289 // A string like "0.D" or "-0.0DD".
2290 // Safe to assume there is a non-zero digit, because
2291 // otherwise there would be no decimal point.
2292 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2293 }
2294 }
2295 else // No decimal point, we need to insert one.
2296 {
2297 __p = __s.find(__expc); // Find the exponent, if present.
2298 if (__p == __s.npos)
2299 __p = __s.size();
2300 __d = __p; // Position where '.' should be inserted.
2301 __sigfigs = __d - __have_sign;
2302 }
2303
2304 if (__trailing_zeros && __prec != 0)
2305 {
2306 // For g and G presentation types std::to_chars produces
2307 // no more than prec significant figures. Insert this many
2308 // zeros so the result has exactly prec significant figures.
2309 __z = __prec - __sigfigs;
2310 }
2311
2312 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2313 {
2314 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2315 {
2316 // The stack buffer is large enough for the result.
2317 // Move exponent to make space for extra chars.
2318 __builtin_memmove(__start + __p + __extras,
2319 __start + __p,
2320 __s.size() - __p);
2321 if (__d == __p)
2322 __start[__p++] = '.';
2323 __builtin_memset(__start + __p, '0', __z);
2324 __narrow_str = {__s.data(), __s.size() + __extras};
2325 }
2326 else // Need to switch to the dynamic buffer.
2327 {
2328 __dynbuf.reserve(__s.size() + __extras);
2329 if (__dynbuf.empty())
2330 {
2331 __dynbuf = __s.substr(0, __p);
2332 if (__d == __p)
2333 __dynbuf += '.';
2334 if (__z)
2335 __dynbuf.append(__z, '0');
2336 __dynbuf.append(__s.substr(__p));
2337 }
2338 else
2339 {
2340 __dynbuf.insert(__p, __extras, '0');
2341 if (__d == __p)
2342 __dynbuf[__p] = '.';
2343 }
2344 __narrow_str = __dynbuf;
2345 }
2346 }
2347 }
2348
2349 basic_string<_CharT> __wstr;
2350 basic_string_view<_CharT> __str;
2351 if constexpr (is_same_v<_CharT, char>)
2352 __str = __narrow_str;
2353#ifdef _GLIBCXX_USE_WCHAR_T
2354 else
2355 {
2356 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2357 // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
2358 __wstr = std::__to_wstring_numeric(__narrow_str);
2359 __str = __wstr;
2360 }
2361#endif
2362
2363 if (_M_spec._M_localized && __builtin_isfinite(__v))
2364 {
2365 auto __s = _M_localize(__str, __expc, __fc.locale());
2366 if (!__s.empty())
2367 __str = __wstr = std::move(__s);
2368 }
2369
2370 size_t __width = _M_spec._M_get_width(__fc);
2371
2372 if (__width <= __str.size())
2373 return __format::__write(__fc.out(), __str);
2374
2375 char32_t __fill_char = _M_spec._M_fill;
2376 _Align __align = _M_spec._M_align;
2377
2378 size_t __nfill = __width - __str.size();
2379 auto __out = __fc.out();
2380 if (__align == _Align_default)
2381 {
2382 __align = _Align_right;
2383 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2384 {
2385 __fill_char = _CharT('0');
2386 // Write sign before zero filling.
2387 if (!__format::__is_xdigit(__narrow_str[0]))
2388 {
2389 *__out++ = __str[0];
2390 __str.remove_prefix(1);
2391 }
2392 }
2393 else
2394 __fill_char = _CharT(' ');
2395 }
2396 return __format::__write_padded(std::move(__out), __str,
2397 __align, __nfill, __fill_char);
2398 }
2399
2400 // Locale-specific format.
2401 basic_string<_CharT>
2402 _M_localize(basic_string_view<_CharT> __str, char __expc,
2403 const locale& __loc) const
2404 {
2405 basic_string<_CharT> __lstr;
2406
2407 if (__loc == locale::classic())
2408 return __lstr; // Nothing to do.
2409
2410 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2411 const _CharT __point = __np.decimal_point();
2412 const string __grp = __np.grouping();
2413
2414 _CharT __dot, __exp;
2415 if constexpr (is_same_v<_CharT, char>)
2416 {
2417 __dot = '.';
2418 __exp = __expc;
2419 }
2420 else
2421 {
2422 __dot = L'.';
2423 switch (__expc)
2424 {
2425 case 'e':
2426 __exp = L'e';
2427 break;
2428 case 'E':
2429 __exp = L'E';
2430 break;
2431 case 'p':
2432 __exp = L'p';
2433 break;
2434 case 'P':
2435 __exp = L'P';
2436 break;
2437 default:
2438 __builtin_unreachable();
2439 }
2440 }
2441
2442 if (__grp.empty() && __point == __dot)
2443 return __lstr; // Locale uses '.' and no grouping.
2444
2445 size_t __d = __str.find(__dot); // Index of radix character (if any).
2446 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2447 if (__e == __str.npos)
2448 __e = __str.size();
2449 const size_t __r = __str.size() - __e; // Length of remainder.
2450 auto __overwrite = [&](_CharT* __p, size_t) {
2451 // Apply grouping to the digits before the radix or exponent.
2452 int __off = 0;
2453 if (auto __c = __str.front(); __c == '-' || __c == '+' || __c == ' ')
2454 {
2455 *__p = __c;
2456 __off = 1;
2457 }
2458 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
2459 __grp.data(), __grp.size(),
2460 __str.data() + __off,
2461 __str.data() + __e);
2462 if (__r) // If there's a fractional part or exponent
2463 {
2464 if (__d != __str.npos)
2465 {
2466 *__end = __point; // Add the locale's radix character.
2467 ++__end;
2468 ++__e;
2469 }
2470 const size_t __rlen = __str.size() - __e;
2471 // Append fractional digits and/or exponent:
2472 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2473 __end += __rlen;
2474 }
2475 return (__end - __p);
2476 };
2477 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2478 return __lstr;
2479 }
2480
2481 _Spec<_CharT> _M_spec{};
2482 };
2483
2484 template<__format::__char _CharT>
2485 struct __formatter_ptr
2486 {
2487 constexpr
2488 __formatter_ptr() noexcept
2489 : _M_spec()
2490 {
2491 _M_spec._M_type = _Pres_p;
2492 _M_spec._M_alt = true;
2493 }
2494
2495 constexpr
2496 __formatter_ptr(_Spec<_CharT> __spec) noexcept
2497 : _M_spec(__spec)
2498 { _M_set_default(_Pres_p); }
2499
2500 constexpr typename basic_format_parse_context<_CharT>::iterator
2501 parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type = _Pres_p)
2502 {
2503 __format::_Spec<_CharT> __spec{};
2504 const auto __last = __pc.end();
2505 auto __first = __pc.begin();
2506
2507 auto __finalize = [this, &__spec, __type] {
2508 _M_spec = __spec;
2509 _M_set_default(__type);
2510 };
2511
2512 auto __finished = [&] {
2513 if (__first == __last || *__first == '}')
2514 {
2515 __finalize();
2516 return true;
2517 }
2518 return false;
2519 };
2520
2521 if (__finished())
2522 return __first;
2523
2524 __first = __spec._M_parse_fill_and_align(__first, __last);
2525 if (__finished())
2526 return __first;
2527
2528// _GLIBCXX_RESOLVE_LIB_DEFECTS
2529// P2510R3 Formatting pointers
2530#if __glibcxx_format >= 202304L
2531 __first = __spec._M_parse_zero_fill(__first, __last);
2532 if (__finished())
2533 return __first;
2534#endif
2535
2536 __first = __spec._M_parse_width(__first, __last, __pc);
2537 if (__finished())
2538 return __first;
2539
2540 if (*__first == 'p')
2541 {
2542 __spec._M_type = _Pres_p;
2543 __spec._M_alt = !__spec._M_alt;
2544 ++__first;
2545 }
2546#if __glibcxx_format >= 202304L
2547 else if (*__first == 'P')
2548 {
2549 __spec._M_type = _Pres_P;
2550 __spec._M_alt = !__spec._M_alt;
2551 ++__first;
2552 }
2553#endif
2554
2555 if (__finished())
2556 return __first;
2557
2558 __format::__failed_to_parse_format_spec();
2559 }
2560
2561 template<typename _Out>
2562 _GLIBCXX_CONSTEXPR_FORMAT
2563 typename basic_format_context<_Out, _CharT>::iterator
2564 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2565 {
2566 auto __u = __v
2567 ? reinterpret_cast<__UINTPTR_TYPE__>(__v)
2568 : static_cast<__UINTPTR_TYPE__>(0);
2569 return __formatter_int<_CharT>(_M_spec).format(__u, __fc);
2570 }
2571
2572 private:
2573 [[__gnu__::__always_inline__]]
2574 constexpr void
2575 _M_set_default(_Pres_type __type)
2576 {
2577 if (_M_spec._M_type == _Pres_none && __type != _Pres_none)
2578 {
2579 _M_spec._M_type = __type;
2580 _M_spec._M_alt = !_M_spec._M_alt;
2581 }
2582 }
2583
2584 __format::_Spec<_CharT> _M_spec;
2585 };
2586
2587} // namespace __format
2588/// @endcond
2589
2590 /// Format a character.
2591 template<__format::__char _CharT>
2592 struct formatter<_CharT, _CharT>
2593 {
2594 formatter() = default;
2595
2596 constexpr typename basic_format_parse_context<_CharT>::iterator
2597 parse(basic_format_parse_context<_CharT>& __pc)
2598 {
2599 return _M_f.template _M_parse<_CharT>(__pc);
2600 }
2601
2602 template<typename _Out>
2603 _GLIBCXX_CONSTEXPR_FORMAT
2604 typename basic_format_context<_Out, _CharT>::iterator
2605 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2606 {
2607 if (_M_f._M_spec._M_type == __format::_Pres_c)
2608 return _M_f._M_format_character(__u, __fc);
2609 else
2610 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2611 }
2612
2613#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2614 constexpr void
2615 set_debug_format() noexcept
2616 { _M_f._M_spec._M_debug = true; }
2617#endif
2618
2619 private:
2620 __format::__formatter_int<_CharT> _M_f;
2621 };
2622
2623#if __glibcxx_print >= 202403L
2624 template<__format::__char _CharT>
2625 constexpr bool enable_nonlocking_formatter_optimization<_CharT> = true;
2626#endif
2627
2628#ifdef _GLIBCXX_USE_WCHAR_T
2629 /// Format a char value for wide character output.
2630 template<>
2631 struct formatter<char, wchar_t>
2632 {
2633 formatter() = default;
2634
2635 constexpr typename basic_format_parse_context<wchar_t>::iterator
2636 parse(basic_format_parse_context<wchar_t>& __pc)
2637 {
2638 return _M_f._M_parse<char>(__pc);
2639 }
2640
2641 template<typename _Out>
2642 _GLIBCXX_CONSTEXPR_FORMAT
2643 typename basic_format_context<_Out, wchar_t>::iterator
2644 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2645 {
2646 if (_M_f._M_spec._M_type == __format::_Pres_c)
2647 return _M_f._M_format_character(__u, __fc);
2648 else
2649 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2650 }
2651
2652#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2653 constexpr void
2654 set_debug_format() noexcept
2655 { _M_f._M_spec._M_debug = true; }
2656#endif
2657
2658 private:
2659 __format::__formatter_int<wchar_t> _M_f;
2660 };
2661#endif // USE_WCHAR_T
2662
2663 /** Format a string.
2664 * @{
2665 */
2666 template<__format::__char _CharT>
2667 struct formatter<_CharT*, _CharT>
2668 {
2669 formatter() = default;
2670
2671 [[__gnu__::__always_inline__]]
2672 constexpr typename basic_format_parse_context<_CharT>::iterator
2673 parse(basic_format_parse_context<_CharT>& __pc)
2674 { return _M_f.parse(__pc); }
2675
2676 template<typename _Out>
2677 [[__gnu__::__nonnull__]]
2678 _GLIBCXX_CONSTEXPR_FORMAT
2679 typename basic_format_context<_Out, _CharT>::iterator
2680 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2681 { return _M_f.format(__u, __fc); }
2682
2683#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2684 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2685#endif
2686
2687 private:
2688 __format::__formatter_str<_CharT> _M_f;
2689 };
2690
2691#if __glibcxx_print >= 202403L
2692 template<__format::__char _CharT>
2693 constexpr bool enable_nonlocking_formatter_optimization<_CharT*> = true;
2694#endif
2695
2696 template<__format::__char _CharT>
2697 struct formatter<const _CharT*, _CharT>
2698 {
2699 formatter() = default;
2700
2701 [[__gnu__::__always_inline__]]
2702 constexpr typename basic_format_parse_context<_CharT>::iterator
2703 parse(basic_format_parse_context<_CharT>& __pc)
2704 { return _M_f.parse(__pc); }
2705
2706 template<typename _Out>
2707 [[__gnu__::__nonnull__]]
2708 _GLIBCXX_CONSTEXPR_FORMAT
2709 typename basic_format_context<_Out, _CharT>::iterator
2710 format(const _CharT* __u,
2711 basic_format_context<_Out, _CharT>& __fc) const
2712 { return _M_f.format(__u, __fc); }
2713
2714#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2715 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2716#endif
2717
2718 private:
2719 __format::__formatter_str<_CharT> _M_f;
2720 };
2721
2722#if __glibcxx_print >= 202403L
2723 template<__format::__char _CharT>
2724 constexpr bool
2725 enable_nonlocking_formatter_optimization<const _CharT*> = true;
2726#endif
2727
2728 template<__format::__char _CharT, size_t _Nm>
2729 struct formatter<_CharT[_Nm], _CharT>
2730 {
2731 formatter() = default;
2732
2733 [[__gnu__::__always_inline__]]
2734 constexpr typename basic_format_parse_context<_CharT>::iterator
2735 parse(basic_format_parse_context<_CharT>& __pc)
2736 { return _M_f.parse(__pc); }
2737
2738 template<typename _Out>
2739 _GLIBCXX_CONSTEXPR_FORMAT
2740 typename basic_format_context<_Out, _CharT>::iterator
2741 format(const _CharT (&__u)[_Nm],
2742 basic_format_context<_Out, _CharT>& __fc) const
2743 { return _M_f.format({__u, _Nm}, __fc); }
2744
2745#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2746 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2747#endif
2748
2749 private:
2750 __format::__formatter_str<_CharT> _M_f;
2751 };
2752
2753#if __glibcxx_print >= 202403L
2754 template<__format::__char _CharT, size_t _Nm>
2755 constexpr bool enable_nonlocking_formatter_optimization<_CharT[_Nm]> = true;
2756#endif
2757
2758 template<typename _Traits, typename _Alloc>
2759 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2760 {
2761 formatter() = default;
2762
2763 [[__gnu__::__always_inline__]]
2764 constexpr typename basic_format_parse_context<char>::iterator
2765 parse(basic_format_parse_context<char>& __pc)
2766 { return _M_f.parse(__pc); }
2767
2768 template<typename _Out>
2769 _GLIBCXX_CONSTEXPR_FORMAT
2770 typename basic_format_context<_Out, char>::iterator
2771 format(const basic_string<char, _Traits, _Alloc>& __u,
2772 basic_format_context<_Out, char>& __fc) const
2773 { return _M_f.format(__u, __fc); }
2774
2775#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2776 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2777#endif
2778
2779 private:
2780 __format::__formatter_str<char> _M_f;
2781 };
2782
2783#if __glibcxx_print >= 202403L
2784 template<typename _Tr, typename _Alloc>
2785 constexpr bool
2786 enable_nonlocking_formatter_optimization<basic_string<char, _Tr, _Alloc>>
2787 = true;
2788#endif
2789
2790#ifdef _GLIBCXX_USE_WCHAR_T
2791 template<typename _Traits, typename _Alloc>
2792 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2793 {
2794 formatter() = default;
2795
2796 [[__gnu__::__always_inline__]]
2797 constexpr typename basic_format_parse_context<wchar_t>::iterator
2798 parse(basic_format_parse_context<wchar_t>& __pc)
2799 { return _M_f.parse(__pc); }
2800
2801 template<typename _Out>
2802 _GLIBCXX_CONSTEXPR_FORMAT
2803 typename basic_format_context<_Out, wchar_t>::iterator
2804 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2805 basic_format_context<_Out, wchar_t>& __fc) const
2806 { return _M_f.format(__u, __fc); }
2807
2808#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2809 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2810#endif
2811
2812 private:
2813 __format::__formatter_str<wchar_t> _M_f;
2814 };
2815
2816#if __glibcxx_print >= 202403L
2817 template<typename _Tr, typename _Alloc>
2818 constexpr bool
2819 enable_nonlocking_formatter_optimization<basic_string<wchar_t, _Tr, _Alloc>>
2820 = true;
2821#endif
2822
2823#endif // USE_WCHAR_T
2824
2825 template<typename _Traits>
2826 struct formatter<basic_string_view<char, _Traits>, char>
2827 {
2828 formatter() = default;
2829
2830 [[__gnu__::__always_inline__]]
2831 constexpr typename basic_format_parse_context<char>::iterator
2832 parse(basic_format_parse_context<char>& __pc)
2833 { return _M_f.parse(__pc); }
2834
2835 template<typename _Out>
2836 _GLIBCXX_CONSTEXPR_FORMAT
2837 typename basic_format_context<_Out, char>::iterator
2838 format(basic_string_view<char, _Traits> __u,
2839 basic_format_context<_Out, char>& __fc) const
2840 { return _M_f.format(__u, __fc); }
2841
2842#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2843 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2844#endif
2845
2846 private:
2847 __format::__formatter_str<char> _M_f;
2848 };
2849
2850#if __glibcxx_print >= 202403L
2851 template<typename _Tr>
2852 constexpr bool
2853 enable_nonlocking_formatter_optimization<basic_string_view<char, _Tr>>
2854 = true;
2855#endif
2856
2857#ifdef _GLIBCXX_USE_WCHAR_T
2858 template<typename _Traits>
2859 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2860 {
2861 formatter() = default;
2862
2863 [[__gnu__::__always_inline__]]
2864 constexpr typename basic_format_parse_context<wchar_t>::iterator
2865 parse(basic_format_parse_context<wchar_t>& __pc)
2866 { return _M_f.parse(__pc); }
2867
2868 template<typename _Out>
2869 _GLIBCXX_CONSTEXPR_FORMAT
2870 typename basic_format_context<_Out, wchar_t>::iterator
2871 format(basic_string_view<wchar_t, _Traits> __u,
2872 basic_format_context<_Out, wchar_t>& __fc) const
2873 { return _M_f.format(__u, __fc); }
2874
2875#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2876 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2877#endif
2878
2879 private:
2880 __format::__formatter_str<wchar_t> _M_f;
2881 };
2882
2883#if __glibcxx_print >= 202403L
2884 template<typename _Tr>
2885 constexpr bool
2886 enable_nonlocking_formatter_optimization<basic_string_view<wchar_t, _Tr>>
2887 = true;
2888#endif
2889#endif // USE_WCHAR_T
2890 /// @}
2891
2892/// @cond undocumented
2893namespace __format
2894{
2895 // each cv-unqualified arithmetic type ArithmeticT other than
2896 // char, wchar_t, char8_t, char16_t, or char32_t
2897 template<typename _Tp>
2898 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2899
2900#if defined __SIZEOF_INT128__
2901 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2902 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2903 = true;
2904#endif
2905
2906 template<> inline constexpr bool __is_formattable_integer<char> = false;
2907 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2908#ifdef _GLIBCXX_USE_CHAR8_T
2909 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2910#endif
2911 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2912 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2913
2914 template<typename _Tp>
2915 concept __formattable_integer = __is_formattable_integer<_Tp>;
2916}
2917/// @endcond
2918
2919 /// Format an integer.
2920 template<__format::__formattable_integer _Tp, __format::__char _CharT>
2921 struct formatter<_Tp, _CharT>
2922 {
2923 formatter() = default;
2924
2925 [[__gnu__::__always_inline__]]
2926 constexpr typename basic_format_parse_context<_CharT>::iterator
2927 parse(basic_format_parse_context<_CharT>& __pc)
2928 {
2929 return _M_f.template _M_parse<_Tp>(__pc);
2930 }
2931
2932 template<typename _Out>
2933 _GLIBCXX_CONSTEXPR_FORMAT
2934 typename basic_format_context<_Out, _CharT>::iterator
2935 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2936 { return _M_f.format(__u, __fc); }
2937
2938 private:
2939 __format::__formatter_int<_CharT> _M_f;
2940 };
2941
2942#if __glibcxx_print >= 202403L
2943 template<__format::__formattable_integer _Tp>
2944 constexpr bool
2945 enable_nonlocking_formatter_optimization<_Tp> = true;
2946#endif
2947
2948#if defined __glibcxx_to_chars
2949 /// Format a floating-point value.
2950 template<__format::__formattable_float _Tp, __format::__char _CharT>
2951 struct formatter<_Tp, _CharT>
2952 {
2953 formatter() = default;
2954
2955 [[__gnu__::__always_inline__]]
2956 constexpr typename basic_format_parse_context<_CharT>::iterator
2957 parse(basic_format_parse_context<_CharT>& __pc)
2958 { return _M_f.parse(__pc); }
2959
2960 template<typename _Out>
2961 typename basic_format_context<_Out, _CharT>::iterator
2962 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2963 { return _M_f.format(__u, __fc); }
2964
2965 private:
2966 __format::__formatter_fp<_CharT> _M_f;
2967 };
2968
2969#if __glibcxx_print >= 202403L
2970 template<__format::__formattable_float _Tp>
2971 constexpr bool
2972 enable_nonlocking_formatter_optimization<_Tp> = true;
2973#endif
2974
2975#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2976 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2977 template<__format::__char _CharT>
2978 struct formatter<long double, _CharT>
2979 {
2980 formatter() = default;
2981
2982 [[__gnu__::__always_inline__]]
2983 constexpr typename basic_format_parse_context<_CharT>::iterator
2984 parse(basic_format_parse_context<_CharT>& __pc)
2985 { return _M_f.parse(__pc); }
2986
2987 template<typename _Out>
2988 typename basic_format_context<_Out, _CharT>::iterator
2989 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2990 { return _M_f.format((double)__u, __fc); }
2991
2992 private:
2993 __format::__formatter_fp<_CharT> _M_f;
2994 };
2995#endif
2996
2997#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2998 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2999 template<__format::__char _CharT>
3000 struct formatter<_Float16, _CharT>
3001 {
3002 formatter() = default;
3003
3004 [[__gnu__::__always_inline__]]
3005 constexpr typename basic_format_parse_context<_CharT>::iterator
3006 parse(basic_format_parse_context<_CharT>& __pc)
3007 { return _M_f.parse(__pc); }
3008
3009 template<typename _Out>
3010 typename basic_format_context<_Out, _CharT>::iterator
3011 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
3012 { return _M_f.format((float)__u, __fc); }
3013
3014 private:
3015 __format::__formatter_fp<_CharT> _M_f;
3016 };
3017#endif
3018
3019#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3020 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
3021 template<__format::__char _CharT>
3022 struct formatter<_Float32, _CharT>
3023 {
3024 formatter() = default;
3025
3026 [[__gnu__::__always_inline__]]
3027 constexpr typename basic_format_parse_context<_CharT>::iterator
3028 parse(basic_format_parse_context<_CharT>& __pc)
3029 { return _M_f.parse(__pc); }
3030
3031 template<typename _Out>
3032 typename basic_format_context<_Out, _CharT>::iterator
3033 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
3034 { return _M_f.format((float)__u, __fc); }
3035
3036 private:
3037 __format::__formatter_fp<_CharT> _M_f;
3038 };
3039#endif
3040
3041#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3042 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
3043 template<__format::__char _CharT>
3044 struct formatter<_Float64, _CharT>
3045 {
3046 formatter() = default;
3047
3048 [[__gnu__::__always_inline__]]
3049 constexpr typename basic_format_parse_context<_CharT>::iterator
3050 parse(basic_format_parse_context<_CharT>& __pc)
3051 { return _M_f.parse(__pc); }
3052
3053 template<typename _Out>
3054 typename basic_format_context<_Out, _CharT>::iterator
3055 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
3056 { return _M_f.format((double)__u, __fc); }
3057
3058 private:
3059 __format::__formatter_fp<_CharT> _M_f;
3060 };
3061#endif
3062
3063#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
3064 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
3065 template<__format::__char _CharT>
3066 struct formatter<_Float128, _CharT>
3067 {
3068 formatter() = default;
3069
3070 [[__gnu__::__always_inline__]]
3071 constexpr typename basic_format_parse_context<_CharT>::iterator
3072 parse(basic_format_parse_context<_CharT>& __pc)
3073 { return _M_f.parse(__pc); }
3074
3075 template<typename _Out>
3076 typename basic_format_context<_Out, _CharT>::iterator
3077 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3078 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3079
3080 private:
3081 __format::__formatter_fp<_CharT> _M_f;
3082 };
3083#endif
3084
3085#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
3086 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
3087 // when long double is not 128bit IEEE type.
3088 template<__format::__char _CharT>
3089 struct formatter<__float128, _CharT>
3090 {
3091 formatter() = default;
3092
3093 [[__gnu__::__always_inline__]]
3094 constexpr typename basic_format_parse_context<_CharT>::iterator
3095 parse(basic_format_parse_context<_CharT>& __pc)
3096 { return _M_f.parse(__pc); }
3097
3098 template<typename _Out>
3099 typename basic_format_context<_Out, _CharT>::iterator
3100 format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3101 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3102
3103 private:
3104 __format::__formatter_fp<_CharT> _M_f;
3105 };
3106#endif
3107
3108#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3109 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3110 template<__format::__char _CharT>
3111 struct formatter<__format::__bflt16_t, _CharT>
3112 {
3113 formatter() = default;
3114
3115 [[__gnu__::__always_inline__]]
3116 constexpr typename basic_format_parse_context<_CharT>::iterator
3117 parse(basic_format_parse_context<_CharT>& __pc)
3118 { return _M_f.parse(__pc); }
3119
3120 template<typename _Out>
3121 typename basic_format_context<_Out, _CharT>::iterator
3122 format(__gnu_cxx::__bfloat16_t __u,
3123 basic_format_context<_Out, _CharT>& __fc) const
3124 { return _M_f.format((float)__u, __fc); }
3125
3126 private:
3127 __format::__formatter_fp<_CharT> _M_f;
3128 };
3129#endif
3130#endif // __cpp_lib_to_chars
3131
3132 /** Format a pointer.
3133 * @{
3134 */
3135 template<__format::__char _CharT>
3136 struct formatter<const void*, _CharT>
3137 {
3138 formatter() = default;
3139
3140 constexpr typename basic_format_parse_context<_CharT>::iterator
3141 parse(basic_format_parse_context<_CharT>& __pc)
3142 { return _M_f.parse(__pc); }
3143
3144 template<typename _Out>
3145 _GLIBCXX_CONSTEXPR_FORMAT
3146 typename basic_format_context<_Out, _CharT>::iterator
3147 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3148 { return _M_f.format(__v, __fc); }
3149
3150 private:
3151 __format::__formatter_ptr<_CharT> _M_f;
3152 };
3153
3154#if __glibcxx_print >= 202403L
3155 template<>
3156 inline constexpr bool
3157 enable_nonlocking_formatter_optimization<const void*> = true;
3158#endif
3159
3160 template<__format::__char _CharT>
3161 struct formatter<void*, _CharT>
3162 {
3163 formatter() = default;
3164
3165 [[__gnu__::__always_inline__]]
3166 constexpr typename basic_format_parse_context<_CharT>::iterator
3167 parse(basic_format_parse_context<_CharT>& __pc)
3168 { return _M_f.parse(__pc); }
3169
3170 template<typename _Out>
3171 _GLIBCXX_CONSTEXPR_FORMAT
3172 typename basic_format_context<_Out, _CharT>::iterator
3173 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3174 { return _M_f.format(__v, __fc); }
3175
3176 private:
3177 __format::__formatter_ptr<_CharT> _M_f;
3178 };
3179
3180#if __glibcxx_print >= 202403l
3181 template<>
3182 inline constexpr bool
3183 enable_nonlocking_formatter_optimization<void*> = true;
3184#endif
3185
3186 template<__format::__char _CharT>
3187 struct formatter<nullptr_t, _CharT>
3188 {
3189 formatter() = default;
3190
3191 [[__gnu__::__always_inline__]]
3192 constexpr typename basic_format_parse_context<_CharT>::iterator
3193 parse(basic_format_parse_context<_CharT>& __pc)
3194 { return _M_f.parse(__pc); }
3195
3196 template<typename _Out>
3197 _GLIBCXX_CONSTEXPR_FORMAT
3198 typename basic_format_context<_Out, _CharT>::iterator
3199 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3200 { return _M_f.format(nullptr, __fc); }
3201
3202 private:
3203 __format::__formatter_ptr<_CharT> _M_f;
3204 };
3205 /// @}
3206
3207#if __glibcxx_print >= 202403L
3208 template<>
3209 inline constexpr bool
3210 enable_nonlocking_formatter_optimization<nullptr_t> = true;
3211#endif
3212
3213#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3214 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3215 // 3944. Formatters converting sequences of char to sequences of wchar_t
3216
3217 struct __formatter_disabled
3218 {
3219 __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3220 __formatter_disabled(const __formatter_disabled&) = delete;
3221 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3222 };
3223
3224 template<>
3225 struct formatter<char*, wchar_t>
3226 : private __formatter_disabled { };
3227 template<>
3228 struct formatter<const char*, wchar_t>
3229 : private __formatter_disabled { };
3230 template<size_t _Nm>
3231 struct formatter<char[_Nm], wchar_t>
3232 : private __formatter_disabled { };
3233 template<class _Traits, class _Allocator>
3234 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3235 : private __formatter_disabled { };
3236 template<class _Traits>
3237 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3238 : private __formatter_disabled { };
3239#endif
3240
3241 /// An iterator after the last character written, and the number of
3242 /// characters that would have been written.
3243 template<typename _Out>
3244 struct format_to_n_result
3245 {
3246 _Out out;
3247 iter_difference_t<_Out> size;
3248 };
3249
3250_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3251template<typename, typename> class vector;
3252_GLIBCXX_END_NAMESPACE_CONTAINER
3253
3254/// @cond undocumented
3255namespace __format
3256{
3257 template<typename _CharT>
3258 class _Drop_iter
3259 {
3260 public:
3261 using iterator_category = output_iterator_tag;
3262 using value_type = void;
3263 using difference_type = ptrdiff_t;
3264 using pointer = void;
3265 using reference = void;
3266
3267 _Drop_iter() = default;
3268 _Drop_iter(const _Drop_iter&) = default;
3269 _Drop_iter& operator=(const _Drop_iter&) = default;
3270
3271 [[__gnu__::__always_inline__]]
3272 constexpr _Drop_iter&
3273 operator=(_CharT __c)
3274 { return *this; }
3275
3276 [[__gnu__::__always_inline__]]
3277 constexpr _Drop_iter&
3278 operator=(basic_string_view<_CharT> __s)
3279 { return *this; }
3280
3281 [[__gnu__::__always_inline__]]
3282 constexpr _Drop_iter&
3283 operator*() { return *this; }
3284
3285 [[__gnu__::__always_inline__]]
3286 constexpr _Drop_iter&
3287 operator++() { return *this; }
3288
3289 [[__gnu__::__always_inline__]]
3290 constexpr _Drop_iter
3291 operator++(int) { return *this; }
3292 };
3293
3294 template<typename _CharT>
3295 class _Sink_iter
3296 {
3297 _Sink<_CharT>* _M_sink = nullptr;
3298
3299 public:
3300 using iterator_category = output_iterator_tag;
3301 using value_type = void;
3302 using difference_type = ptrdiff_t;
3303 using pointer = void;
3304 using reference = void;
3305
3306 _Sink_iter() = default;
3307 _Sink_iter(const _Sink_iter&) = default;
3308 _Sink_iter& operator=(const _Sink_iter&) = default;
3309
3310 [[__gnu__::__always_inline__]]
3311 explicit constexpr
3312 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3313
3314 [[__gnu__::__always_inline__]]
3315 constexpr _Sink_iter&
3316 operator=(_CharT __c)
3317 {
3318 _M_sink->_M_write(__c);
3319 return *this;
3320 }
3321
3322 [[__gnu__::__always_inline__]]
3323 constexpr _Sink_iter&
3324 operator=(basic_string_view<_CharT> __s)
3325 {
3326 _M_sink->_M_write(__s);
3327 return *this;
3328 }
3329
3330 [[__gnu__::__always_inline__]]
3331 constexpr _Sink_iter&
3332 operator*() { return *this; }
3333
3334 [[__gnu__::__always_inline__]]
3335 constexpr _Sink_iter&
3336 operator++() { return *this; }
3337
3338 [[__gnu__::__always_inline__]]
3339 constexpr _Sink_iter
3340 operator++(int) { return *this; }
3341
3342 _GLIBCXX_CONSTEXPR_FORMAT auto
3343 _M_reserve(size_t __n) const
3344 { return _M_sink->_M_reserve(__n); }
3345
3346 _GLIBCXX_CONSTEXPR_FORMAT bool
3347 _M_discarding() const
3348 { return _M_sink->_M_discarding(); }
3349 };
3350
3351 // Abstract base class for type-erased character sinks.
3352 // All formatting and output is done via this type's iterator,
3353 // to reduce the number of different template instantiations.
3354 template<typename _CharT>
3355 class _Sink
3356 {
3357 friend class _Sink_iter<_CharT>;
3358
3359 span<_CharT> _M_span;
3360 typename span<_CharT>::iterator _M_next;
3361
3362 // Called when the span is full, to make more space available.
3363 // Precondition: _M_next != _M_span.begin()
3364 // Postcondition: _M_next != _M_span.end()
3365 // TODO: remove the precondition? could make overflow handle it.
3366 virtual void _M_overflow() = 0;
3367
3368 protected:
3369 // Precondition: __span.size() != 0
3370 [[__gnu__::__always_inline__]]
3371 explicit constexpr
3372 _Sink(span<_CharT> __span) noexcept
3373 : _M_span(__span), _M_next(__span.begin())
3374 { }
3375
3376 // The portion of the span that has been written to.
3377 [[__gnu__::__always_inline__]]
3378 _GLIBCXX_CONSTEXPR_FORMAT span<_CharT>
3379 _M_used() const noexcept
3380 { return _M_span.first(_M_next - _M_span.begin()); }
3381
3382 // The portion of the span that has not been written to.
3383 [[__gnu__::__always_inline__]]
3384 constexpr span<_CharT>
3385 _M_unused() const noexcept
3386 { return _M_span.subspan(_M_next - _M_span.begin()); }
3387
3388 // Use the start of the span as the next write position.
3389 [[__gnu__::__always_inline__]]
3390 constexpr void
3391 _M_rewind() noexcept
3392 { _M_next = _M_span.begin(); }
3393
3394 // Replace the current output range.
3395 _GLIBCXX_CONSTEXPR_FORMAT void
3396 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3397 {
3398 _M_span = __s;
3399 _M_next = __s.begin() + __pos;
3400 }
3401
3402 // Called by the iterator for *it++ = c
3403 constexpr void
3404 _M_write(_CharT __c)
3405 {
3406 *_M_next++ = __c;
3407 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3408 _M_overflow();
3409 }
3410
3411 constexpr void
3412 _M_write(basic_string_view<_CharT> __s)
3413 {
3414 span __to = _M_unused();
3415 while (__to.size() <= __s.size())
3416 {
3417 __s.copy(__to.data(), __to.size());
3418 _M_next += __to.size();
3419 __s.remove_prefix(__to.size());
3420 _M_overflow();
3421 __to = _M_unused();
3422 }
3423 if (__s.size())
3424 {
3425 __s.copy(__to.data(), __s.size());
3426 _M_next += __s.size();
3427 }
3428 }
3429
3430 // A successful _Reservation can be used to directly write
3431 // up to N characters to the sink to avoid unwanted buffering.
3432 struct _Reservation
3433 {
3434 // True if the reservation was successful, false otherwise.
3435 _GLIBCXX_CONSTEXPR_FORMAT
3436 explicit operator bool() const noexcept { return _M_sink; }
3437 // A pointer to write directly to the sink.
3438 _GLIBCXX_CONSTEXPR_FORMAT _CharT*
3439 get() const noexcept { return _M_sink->_M_next.operator->(); }
3440 // Add n to the _M_next iterator for the sink.
3441 _GLIBCXX_CONSTEXPR_FORMAT void
3442 _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3443 _Sink* _M_sink;
3444 };
3445
3446 // Attempt to reserve space to write n characters to the sink.
3447 // If anything is written to the reservation then there must be a call
3448 // to _M_bump(N2) before any call to another member function of *this,
3449 // where N2 is the number of characters written.
3450 _GLIBCXX_CONSTEXPR_FORMAT virtual _Reservation
3451 _M_reserve(size_t __n)
3452 {
3453 if (__n <= _M_unused().size())
3454 return { this };
3455
3456 if (__n <= _M_span.size()) // Cannot meet the request.
3457 {
3458 _M_overflow(); // Make more space available.
3459 if (__n <= _M_unused().size())
3460 return { this };
3461 }
3462 return { nullptr };
3463 }
3464
3465 // Update the next output position after writing directly to the sink.
3466 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3467 _GLIBCXX_CONSTEXPR_FORMAT virtual void
3468 _M_bump(size_t __n)
3469 { _M_next += __n; }
3470
3471 // Returns true if the _Sink is discarding incoming characters.
3472 _GLIBCXX_CONSTEXPR_FORMAT virtual bool
3473 _M_discarding() const
3474 { return false; }
3475
3476 public:
3477 _Sink(const _Sink&) = delete;
3478 _Sink& operator=(const _Sink&) = delete;
3479
3480 [[__gnu__::__always_inline__]]
3481 constexpr _Sink_iter<_CharT>
3482 out() noexcept
3483 { return _Sink_iter<_CharT>(*this); }
3484 };
3485
3486
3487 template<typename _CharT>
3488 class _Fixedbuf_sink final : public _Sink<_CharT>
3489 {
3490 _GLIBCXX_CONSTEXPR_FORMAT void
3491 _M_overflow() override
3492 {
3493 __glibcxx_assert(false);
3494 this->_M_rewind();
3495 }
3496
3497 public:
3498 [[__gnu__::__always_inline__]]
3499 constexpr explicit
3500 _Fixedbuf_sink(span<_CharT> __buf)
3501 : _Sink<_CharT>(__buf)
3502 { }
3503
3504 constexpr basic_string_view<_CharT>
3505 view() const
3506 {
3507 auto __s = this->_M_used();
3508 return basic_string_view<_CharT>(__s.data(), __s.size());
3509 }
3510 };
3511
3512 // A sink with an internal buffer. This is used to implement concrete sinks.
3513 template<typename _CharT>
3514 class _Buf_sink : public _Sink<_CharT>
3515 {
3516 protected:
3517 _CharT _M_buf[__stackbuf_size<_CharT>];
3518
3519 [[__gnu__::__always_inline__]]
3520 constexpr
3521 _Buf_sink() noexcept
3522 : _Sink<_CharT>(_M_buf)
3523 { }
3524 };
3525
3526 using _GLIBCXX_STD_C::vector;
3527
3528 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3529 // Writes to a buffer then appends that to the sequence when it fills up.
3530 template<typename _Seq>
3531 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3532 {
3533 using _CharT = typename _Seq::value_type;
3534
3535 _Seq _M_seq;
3536 protected:
3537 // Transfer buffer contents to the sequence, so buffer can be refilled.
3538 _GLIBCXX_CONSTEXPR_FORMAT void
3539 _M_overflow() override
3540 {
3541 auto __s = this->_M_used();
3542 if (__s.empty()) [[unlikely]]
3543 return; // Nothing in the buffer to transfer to _M_seq.
3544
3545 // If _M_reserve was called then _M_bump must have been called too.
3546 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3547
3548 if constexpr (__is_specialization_of<_Seq, basic_string>)
3549 _M_seq.append(__s.data(), __s.size());
3550 else
3551 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3552
3553 // Make the whole of _M_buf available for the next write:
3554 this->_M_rewind();
3555 }
3556
3557 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
3558 _M_reserve(size_t __n) override
3559 {
3560 // We might already have n characters available in this->_M_unused(),
3561 // but the whole point of this function is to be an optimization for
3562 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3563 // and then copying that into a basic_string if possible, so this
3564 // function prefers to create space directly in _M_seq rather than
3565 // using _M_buf.
3566
3567 if constexpr (__is_specialization_of<_Seq, basic_string>
3568 || __is_specialization_of<_Seq, vector>)
3569 {
3570 // Flush the buffer to _M_seq first (should not be needed).
3571 if (this->_M_used().size()) [[unlikely]]
3572 _Seq_sink::_M_overflow();
3573
3574 // Expand _M_seq to make __n new characters available:
3575 const auto __sz = _M_seq.size();
3576 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3577 _M_seq.__resize_and_overwrite(__sz + __n,
3578 [](auto, auto __n2) {
3579 return __n2;
3580 });
3581 else
3582 _M_seq.resize(__sz + __n);
3583
3584 // Set _M_used() to be a span over the original part of _M_seq
3585 // and _M_unused() to be the extra capacity we just created:
3586 this->_M_reset(_M_seq, __sz);
3587 return { this };
3588 }
3589 else // Try to use the base class' buffer.
3590 return _Sink<_CharT>::_M_reserve(__n);
3591 }
3592
3593 _GLIBCXX_CONSTEXPR_FORMAT void
3594 _M_bump(size_t __n) override
3595 {
3596 if constexpr (__is_specialization_of<_Seq, basic_string>
3597 || __is_specialization_of<_Seq, vector>)
3598 {
3599 auto __s = this->_M_used();
3600 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3601 // Truncate the sequence to the part that was actually written to:
3602 _M_seq.resize(__s.size() + __n);
3603 // Switch back to using buffer:
3604 this->_M_reset(this->_M_buf);
3605 }
3606 }
3607
3608 _GLIBCXX_CONSTEXPR_FORMAT void
3609 _M_trim(span<const _CharT> __s)
3610 requires __is_specialization_of<_Seq, basic_string>
3611 {
3612 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3613 || __s.data() == _M_seq.data());
3614 if (__s.data() == _M_seq.data())
3615 _M_seq.resize(__s.size());
3616 else
3617 this->_M_reset(this->_M_buf, __s.size());
3618 }
3619
3620 public:
3621 // TODO: for SSO string, use SSO buffer as initial span, then switch
3622 // to _M_buf if it overflows? Or even do that for all unused capacity?
3623
3624 [[__gnu__::__always_inline__]]
3625 _GLIBCXX_CONSTEXPR_FORMAT
3626 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3627 { }
3628
3629 _GLIBCXX_CONSTEXPR_FORMAT
3630 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3631 : _M_seq(std::move(__s))
3632 { }
3633
3634 using _Sink<_CharT>::out;
3635
3636 _GLIBCXX_CONSTEXPR_FORMAT _Seq
3637 get() &&
3638 {
3639 if (this->_M_used().size() != 0)
3640 _Seq_sink::_M_overflow();
3641 return std::move(_M_seq);
3642 }
3643
3644 // A writable span that views everything written to the sink.
3645 // Will be either a view over _M_seq or the used part of _M_buf.
3646 _GLIBCXX_CONSTEXPR_FORMAT span<_CharT>
3647 _M_span()
3648 {
3649 auto __s = this->_M_used();
3650 if (_M_seq.size())
3651 {
3652 if (__s.size() != 0)
3653 _Seq_sink::_M_overflow();
3654 return _M_seq;
3655 }
3656 return __s;
3657 }
3658
3659 _GLIBCXX_CONSTEXPR_FORMAT basic_string_view<_CharT>
3660 view()
3661 {
3662 auto __span = _M_span();
3663 return basic_string_view<_CharT>(__span.data(), __span.size());
3664 }
3665 };
3666
3667 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3668 using _Str_sink
3669 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3670
3671 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3672 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3673 // Writes to a fixed-size buffer and then flushes to the output iterator
3674 // when the buffer fills up.
3675 template<typename _CharT, typename _OutIter>
3676 class _Iter_sink : public _Buf_sink<_CharT>
3677 {
3678 _OutIter _M_out;
3679 iter_difference_t<_OutIter> _M_max;
3680
3681 protected:
3682 size_t _M_count = 0;
3683
3684 _GLIBCXX_CONSTEXPR_FORMAT void
3685 _M_overflow() override
3686 {
3687 auto __s = this->_M_used();
3688 if (_M_max < 0) // No maximum.
3689 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3690 else if (_M_count < static_cast<size_t>(_M_max))
3691 {
3692 auto __max = _M_max - _M_count;
3693 span<_CharT> __first;
3694 if (__max < __s.size())
3695 __first = __s.first(static_cast<size_t>(__max));
3696 else
3697 __first = __s;
3698 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3699 }
3700 this->_M_rewind();
3701 _M_count += __s.size();
3702 }
3703
3704 _GLIBCXX_CONSTEXPR_FORMAT bool
3705 _M_discarding() const override
3706 {
3707 // format_to_n return total number of characters, that would be written,
3708 // see C++20 [format.functions] p20
3709 return false;
3710 }
3711
3712 public:
3713 [[__gnu__::__always_inline__]]
3714 _GLIBCXX_CONSTEXPR_FORMAT explicit
3715 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3716 : _M_out(std::move(__out)), _M_max(__max)
3717 { }
3718
3719 using _Sink<_CharT>::out;
3720
3721 _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_OutIter>
3722 _M_finish() &&
3723 {
3724 if (this->_M_used().size() != 0)
3725 _Iter_sink::_M_overflow();
3726 iter_difference_t<_OutIter> __count(_M_count);
3727 return { std::move(_M_out), __count };
3728 }
3729 };
3730
3731 // Used for contiguous iterators.
3732 // No buffer is used, characters are written straight to the iterator.
3733 // We do not know the size of the output range, so the span size just grows
3734 // as needed. The end of the span might be an invalid pointer outside the
3735 // valid range, but we never actually call _M_span.end(). This class does
3736 // not introduce any invalid pointer arithmetic or overflows that would not
3737 // have happened anyway.
3738 template<typename _CharT>
3739 class _Ptr_sink : public _Sink<_CharT>
3740 {
3741 static constexpr size_t _S_no_limit = size_t(-1);
3742
3743 size_t _M_max;
3744 protected:
3745 size_t _M_count = 0;
3746 private:
3747 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3748
3749 protected:
3750 _GLIBCXX_CONSTEXPR_FORMAT void
3751 _M_overflow() override
3752 {
3753 if (this->_M_unused().size() != 0)
3754 return; // No need to switch to internal buffer yet.
3755
3756 auto __s = this->_M_used();
3757
3758 if (_M_max != _S_no_limit)
3759 {
3760 _M_count += __s.size();
3761 // Span was already sized for the maximum character count,
3762 // if it overflows then any further output must go to the
3763 // internal buffer, to be discarded.
3764 this->_M_reset(this->_M_buf);
3765 }
3766 else
3767 {
3768 // No maximum character count. Just extend the span to allow
3769 // writing more characters to it.
3770 _M_rebuf(__s.data(), __s.size() + 1024, __s.size());
3771 }
3772 }
3773
3774 _GLIBCXX_CONSTEXPR_FORMAT bool
3775 _M_discarding() const override
3776 {
3777 // format_to_n return total number of characters, that would be written,
3778 // see C++20 [format.functions] p20
3779 return false;
3780 }
3781
3782 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
3783 _M_reserve(size_t __n) final
3784 {
3785 auto __avail = this->_M_unused();
3786 if (__n > __avail.size())
3787 {
3788 if (_M_max != _S_no_limit)
3789 return {}; // cannot grow
3790
3791 auto __s = this->_M_used();
3792 _M_rebuf(__s.data(), __s.size() + __n, __s.size());
3793 }
3794 return { this };
3795 }
3796
3797 private:
3798 template<typename _IterDifference>
3799 static _GLIBCXX_CONSTEXPR_FORMAT size_t
3800 _S_trim_max(_IterDifference __max)
3801 {
3802 if (__max < 0)
3803 return _S_no_limit;
3804 if constexpr (!is_integral_v<_IterDifference> || sizeof(__max) > sizeof(size_t))
3805 // __int128 or __detail::__max_diff_type
3806 if (_IterDifference((size_t)-1) < __max)
3807 return _S_no_limit;
3808 return size_t(__max);
3809 }
3810
3811 [[__gnu__::__always_inline__]]
3812 _GLIBCXX_CONSTEXPR_FORMAT void
3813 _M_rebuf(_CharT* __ptr, size_t __total, size_t __inuse = 0)
3814 {
3815 std::span<_CharT> __span(__ptr, __total);
3816 this->_M_reset(__span, __inuse);
3817 }
3818
3819 public:
3820 _GLIBCXX_CONSTEXPR_FORMAT explicit
3821 _Ptr_sink(_CharT* __ptr, size_t __n = _S_no_limit) noexcept
3822 : _Sink<_CharT>(_M_buf), _M_max(__n)
3823 {
3824 if (__n == 0)
3825 return; // Only write to the internal buffer.
3826 else if (__n != _S_no_limit)
3827 _M_rebuf(__ptr, __n);
3828#if __has_builtin(__builtin_dynamic_object_size)
3829 else if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3830 _M_rebuf(__ptr, __bytes / sizeof(_CharT));
3831#endif
3832 else
3833 {
3834 // Avoid forming a pointer to a different memory page.
3835 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3836 __n = (1024 - __off) / sizeof(_CharT);
3837 if (__n > 0) [[likely]]
3838 _M_rebuf(__ptr, __n);
3839 else // Misaligned/packed buffer of wchar_t?
3840 _M_rebuf(__ptr, 1);
3841 }
3842 }
3843
3844 template<contiguous_iterator _OutIter>
3845 _GLIBCXX_CONSTEXPR_FORMAT explicit
3846 _Ptr_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1)
3847 : _Ptr_sink(std::to_address(__out), _S_trim_max(__n))
3848 { }
3849
3850 template<contiguous_iterator _OutIter>
3851 _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_OutIter>
3852 _M_finish(_OutIter __first) const
3853 {
3854 auto __s = this->_M_used();
3855 if (__s.data() == _M_buf)
3856 {
3857 // Switched to internal buffer, so must have written _M_max.
3858 iter_difference_t<_OutIter> __m(_M_max);
3859 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3860 return { __first + __m, __count };
3861 }
3862 else // Not using internal buffer yet
3863 {
3864 iter_difference_t<_OutIter> __count(__s.size());
3865 return { __first + __count, __count };
3866 }
3867 }
3868 };
3869
3870 template<typename _CharT, typename _OutIter>
3871 concept __contiguous_char_iter
3872 = contiguous_iterator<_OutIter>
3873 && same_as<iter_value_t<_OutIter>, _CharT>;
3874
3875 // A sink for handling the padded outputs (_M_padwidth) or truncated
3876 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3877 // until sufficient number of characters is written. After that if sequence
3878 // is longer than _M_padwidth it's written to _M_out, and further writes are
3879 // either:
3880 // * buffered and forwarded to _M_out, if below _M_maxwidth,
3881 // * ignored otherwise
3882 // If field width of written sequence is no greater than _M_padwidth, the
3883 // sequence is written during _M_finish call.
3884 template<typename _Out, typename _CharT>
3885 class _Padding_sink : public _Str_sink<_CharT>
3886 {
3887 size_t _M_padwidth;
3888 size_t _M_maxwidth;
3889 _Out _M_out;
3890 size_t _M_printwidth;
3891
3892 [[__gnu__::__always_inline__]]
3893 _GLIBCXX_CONSTEXPR_FORMAT bool
3894 _M_ignoring() const
3895 { return _M_printwidth >= _M_maxwidth; }
3896
3897 [[__gnu__::__always_inline__]]
3898 _GLIBCXX_CONSTEXPR_FORMAT bool
3899 _M_buffering() const
3900 {
3901 if (_M_printwidth < _M_padwidth)
3902 return true;
3903 if (_M_maxwidth != (size_t)-1)
3904 return _M_printwidth < _M_maxwidth;
3905 return false;
3906 }
3907
3908 _GLIBCXX_CONSTEXPR_FORMAT void
3909 _M_sync_discarding()
3910 {
3911 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3912 if (_M_out._M_discarding())
3913 _M_maxwidth = _M_printwidth;
3914 }
3915
3916 _GLIBCXX_CONSTEXPR_FORMAT void
3917 _M_flush()
3918 {
3919 span<_CharT> __new = this->_M_used();
3920 basic_string_view<_CharT> __str(__new.data(), __new.size());
3921 _M_out = __format::__write(std::move(_M_out), __str);
3922 _M_sync_discarding();
3923 this->_M_rewind();
3924 }
3925
3926 _GLIBCXX_CONSTEXPR_FORMAT bool
3927 _M_force_update()
3928 {
3929 auto __str = this->view();
3930 // Compute actual field width, possibly truncated.
3931 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3932 if (_M_ignoring())
3933 this->_M_trim(__str);
3934 if (_M_buffering())
3935 return true;
3936
3937 // We have more characters than padidng, no padding is needed,
3938 // write direclty to _M_out.
3939 if (_M_printwidth >= _M_padwidth)
3940 {
3941 _M_out = __format::__write(std::move(_M_out), __str);
3942 _M_sync_discarding();
3943 }
3944 // We reached _M_maxwidth that is smaller than _M_padwidth.
3945 // Store the prefix sequence in _M_seq, and free _M_buf.
3946 else
3947 _Str_sink<_CharT>::_M_overflow();
3948
3949 // Use internal buffer for writes to _M_out.
3950 this->_M_reset(this->_M_buf);
3951 return false;
3952 }
3953
3954 _GLIBCXX_CONSTEXPR_FORMAT bool
3955 _M_update(size_t __new)
3956 {
3957 _M_printwidth += __new;
3958 // Compute estimated width, to see if is not reduced.
3959 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3960 return _M_force_update();
3961 return true;
3962 }
3963
3964 _GLIBCXX_CONSTEXPR_FORMAT void
3965 _M_overflow() override
3966 {
3967 // Ignore characters in buffer, and override it.
3968 if (_M_ignoring())
3969 this->_M_rewind();
3970 // Write buffer to _M_out, and override it.
3971 else if (!_M_buffering())
3972 _M_flush();
3973 // Update written count, and if input still should be buffered,
3974 // flush the to _M_seq.
3975 else if (_M_update(this->_M_used().size()))
3976 _Str_sink<_CharT>::_M_overflow();
3977 }
3978
3979 _GLIBCXX_CONSTEXPR_FORMAT bool
3980 _M_discarding() const override
3981 { return _M_ignoring(); }
3982
3983 _GLIBCXX_CONSTEXPR_FORMAT typename _Sink<_CharT>::_Reservation
3984 _M_reserve(size_t __n) override
3985 {
3986 // Ignore characters in buffer, if any.
3987 if (_M_ignoring())
3988 this->_M_rewind();
3989 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3990 if (!_M_buffering())
3991 {
3992 // Write pending characters if any
3993 if (!this->_M_used().empty())
3994 _M_flush();
3995 // Try to reserve from _M_out sink.
3996 if (auto __reserved = _M_out._M_reserve(__n))
3997 return __reserved;
3998 }
3999 return _Sink<_CharT>::_M_reserve(__n);
4000 }
4001
4002 _GLIBCXX_CONSTEXPR_FORMAT void
4003 _M_bump(size_t __n) override
4004 {
4005 // Ignore the written characters.
4006 if (_M_ignoring())
4007 return;
4008 // If reservation was made directy sink associated _M_out,
4009 // _M_bump will be called on that sink.
4010 _Sink<_CharT>::_M_bump(__n);
4011 if (_M_buffering())
4012 _M_update(__n);
4013 }
4014
4015 public:
4016 [[__gnu__::__always_inline__]]
4017 _GLIBCXX_CONSTEXPR_FORMAT explicit
4018 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
4019 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
4020 _M_out(std::move(__out)), _M_printwidth(0)
4021 { _M_sync_discarding(); }
4022
4023 [[__gnu__::__always_inline__]]
4024 _GLIBCXX_CONSTEXPR_FORMAT explicit
4025 _Padding_sink(_Out __out, size_t __padwidth)
4026 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
4027 { }
4028
4029 _GLIBCXX_CONSTEXPR_FORMAT _Out
4030 _M_finish(_Align __align, char32_t __fill_char)
4031 {
4032 // Handle any characters in the buffer.
4033 if (auto __rem = this->_M_used().size())
4034 {
4035 if (_M_ignoring())
4036 this->_M_rewind();
4037 else if (!_M_buffering())
4038 _M_flush();
4039 else
4040 _M_update(__rem);
4041 }
4042
4043 if (!_M_buffering() || !_M_force_update())
4044 // Characters were already written to _M_out.
4045 if (_M_printwidth >= _M_padwidth)
4046 return std::move(_M_out);
4047
4048 const auto __str = this->view();
4049 if (_M_printwidth >= _M_padwidth)
4050 return __format::__write(std::move(_M_out), __str);
4051
4052 const size_t __nfill = _M_padwidth - _M_printwidth;
4053 return __format::__write_padded(std::move(_M_out), __str,
4054 __align, __nfill, __fill_char);
4055 }
4056 };
4057
4058 template<typename _Out, typename _CharT>
4059 class _Escaping_sink : public _Buf_sink<_CharT>
4060 {
4061 using _Esc = _Escapes<_CharT>;
4062
4063 _Out _M_out;
4064 _Term_char _M_term : 2;
4065 unsigned _M_prev_escape : 1;
4066 unsigned _M_out_discards : 1;
4067
4068 _GLIBCXX_CONSTEXPR_FORMAT void
4069 _M_sync_discarding()
4070 {
4071 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4072 _M_out_discards = _M_out._M_discarding();
4073 }
4074
4075 _GLIBCXX_CONSTEXPR_FORMAT void
4076 _M_write()
4077 {
4078 span<_CharT> __bytes = this->_M_used();
4079 basic_string_view<_CharT> __str(__bytes.data(), __bytes.size());
4080
4081 size_t __rem = 0;
4082 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4083 {
4084 bool __prev_escape = _M_prev_escape;
4085 _M_out = __format::__write_escaped_unicode_part(
4086 std::move(_M_out), __str, __prev_escape, _M_term);
4087 _M_prev_escape = __prev_escape;
4088
4089 __rem = __str.size();
4090 if (__rem > 0 && __str.data() != this->_M_buf) [[unlikely]]
4091 ranges::move(__str, this->_M_buf);
4092 }
4093 else
4094 _M_out = __format::__write_escaped_ascii(
4095 std::move(_M_out), __str, _M_term);
4096
4097 this->_M_reset(this->_M_buf, __rem);
4098 _M_sync_discarding();
4099 }
4100
4101 _GLIBCXX_CONSTEXPR_FORMAT void
4102 _M_overflow() override
4103 {
4104 if (_M_out_discards)
4105 this->_M_rewind();
4106 else
4107 _M_write();
4108 }
4109
4110 _GLIBCXX_CONSTEXPR_FORMAT bool
4111 _M_discarding() const override
4112 { return _M_out_discards; }
4113
4114 public:
4115 [[__gnu__::__always_inline__]]
4116 _GLIBCXX_CONSTEXPR_FORMAT explicit
4117 _Escaping_sink(_Out __out, _Term_char __term)
4118 : _M_out(std::move(__out)), _M_term(__term),
4119 _M_prev_escape(true), _M_out_discards(false)
4120 {
4121 _M_out = __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4122 _M_sync_discarding();
4123 }
4124
4125 _GLIBCXX_CONSTEXPR_FORMAT _Out
4126 _M_finish()
4127 {
4128 if (_M_out_discards)
4129 return std::move(_M_out);
4130
4131 if (!this->_M_used().empty())
4132 {
4133 _M_write();
4134 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4135 if (auto __rem = this->_M_used(); !__rem.empty())
4136 {
4137 basic_string_view<_CharT> __str(__rem.data(), __rem.size());
4138 _M_out = __format::__write_escape_seqs(std::move(_M_out), __str);
4139 }
4140 }
4141 return __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4142 }
4143 };
4144
4145 enum class _Arg_t : unsigned char {
4146 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
4147 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
4148 _Arg_i128, _Arg_u128, _Arg_float128,
4149 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
4150 _Arg_max_,
4151
4152#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4153 _Arg_ibm128 = _Arg_ldbl,
4154 _Arg_ieee128 = _Arg_float128,
4155#endif
4156 };
4157 using enum _Arg_t;
4158
4159 template<typename _Context>
4160 struct _Arg_value
4161 {
4162 using _CharT = typename _Context::char_type;
4163
4164 class handle
4165 {
4166 using _CharT = typename _Context::char_type;
4167 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4168 _Context&, const void*);
4169
4170 // Format as const if possible, to reduce instantiations.
4171 template<typename _Tp>
4172 using __maybe_const_t
4173 = __conditional_t<__formattable_with<const _Tp, _Context>,
4174 const _Tp, _Tp>;
4175
4176 template<typename _Tq>
4177 static _GLIBCXX_CONSTEXPR_FORMAT void
4178 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4179 _Context& __format_ctx, const void* __ptr)
4180 {
4181 using _Td = remove_const_t<_Tq>;
4182 typename _Context::template formatter_type<_Td> __f;
4183 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4184 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4185 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4186 }
4187
4188 template<typename _Tp>
4189 requires (!is_same_v<remove_cv_t<_Tp>, handle>)
4190 explicit _GLIBCXX_CONSTEXPR_FORMAT
4191 handle(_Tp& __val) noexcept
4192 : _M_ptr(__builtin_addressof(__val))
4193 , _M_func(&_S_format<__maybe_const_t<_Tp>>)
4194 { }
4195
4196 friend class basic_format_arg<_Context>;
4197
4198 public:
4199 handle(const handle&) = default;
4200 handle& operator=(const handle&) = default;
4201
4202 [[__gnu__::__always_inline__]]
4203 void _GLIBCXX_CONSTEXPR_FORMAT
4204 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4205 { _M_func(__pc, __fc, this->_M_ptr); }
4206
4207 private:
4208 const void* _M_ptr;
4209 _Func _M_func;
4210 };
4211
4212 union
4213 {
4214 monostate _M_none;
4215 bool _M_bool;
4216 _CharT _M_c;
4217 int _M_i;
4218 unsigned _M_u;
4219 long long _M_ll;
4220 unsigned long long _M_ull;
4221 float _M_flt;
4222 double _M_dbl;
4223#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4224 long double _M_ldbl;
4225#else
4226 __ibm128 _M_ibm128;
4227 __ieee128 _M_ieee128;
4228#endif
4229#ifdef __SIZEOF_FLOAT128__
4230 __float128 _M_float128;
4231#endif
4232 const _CharT* _M_str;
4233 basic_string_view<_CharT> _M_sv;
4234 const void* _M_ptr;
4235 handle _M_handle;
4236#ifdef __SIZEOF_INT128__
4237 __int128 _M_i128;
4238 unsigned __int128 _M_u128;
4239#endif
4240#ifdef __BFLT16_DIG__
4241 __bflt16_t _M_bf16;
4242#endif
4243#ifdef __FLT16_DIG__
4244 _Float16 _M_f16;
4245#endif
4246#ifdef __FLT32_DIG__
4247 _Float32 _M_f32;
4248#endif
4249#ifdef __FLT64_DIG__
4250 _Float64 _M_f64;
4251#endif
4252 };
4253
4254 [[__gnu__::__always_inline__]]
4255 _GLIBCXX_CONSTEXPR_FORMAT
4256 _Arg_value() : _M_none() { }
4257
4258#if 0
4259 template<typename _Tp>
4260 _GLIBCXX_CONSTEXPR_FORMAT
4261 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4262 { _S_get<_Tp>() = __val; }
4263#endif
4264
4265 // Returns reference to the _Arg_value member with the type _Tp.
4266 // Value of second argument (if provided), is assigned to that member.
4267 template<typename _Tp, typename _Self, typename... _Value>
4268 [[__gnu__::__always_inline__]]
4269 static _GLIBCXX_CONSTEXPR_FORMAT auto&
4270 _S_access(_Self& __u, _Value... __value) noexcept
4271 {
4272 static_assert(sizeof...(_Value) <= 1);
4273 if constexpr (is_same_v<_Tp, bool>)
4274 return (__u._M_bool = ... = __value);
4275 else if constexpr (is_same_v<_Tp, _CharT>)
4276 return (__u._M_c = ... = __value);
4277 else if constexpr (is_same_v<_Tp, int>)
4278 return (__u._M_i = ... = __value);
4279 else if constexpr (is_same_v<_Tp, unsigned>)
4280 return (__u._M_u = ... = __value);
4281 else if constexpr (is_same_v<_Tp, long long>)
4282 return (__u._M_ll = ... = __value);
4283 else if constexpr (is_same_v<_Tp, unsigned long long>)
4284 return (__u._M_ull = ... = __value);
4285 else if constexpr (is_same_v<_Tp, float>)
4286 return (__u._M_flt = ... = __value);
4287 else if constexpr (is_same_v<_Tp, double>)
4288 return (__u._M_dbl = ... = __value);
4289#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4290 else if constexpr (is_same_v<_Tp, long double>)
4291 return (__u._M_ldbl = ... = __value);
4292#else
4293 else if constexpr (is_same_v<_Tp, __ibm128>)
4294 return (__u._M_ibm128 = ... = __value);
4295 else if constexpr (is_same_v<_Tp, __ieee128>)
4296 return (__u._M_ieee128 = ... = __value);
4297#endif
4298#ifdef __SIZEOF_FLOAT128__
4299 else if constexpr (is_same_v<_Tp, __float128>)
4300 return (__u._M_float128 = ... = __value);
4301#endif
4302 else if constexpr (is_same_v<_Tp, const _CharT*>)
4303 return (__u._M_str = ... = __value);
4304 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4305 return (__u._M_sv = ... = __value);
4306 else if constexpr (is_same_v<_Tp, const void*>)
4307 return (__u._M_ptr = ... = __value);
4308#ifdef __SIZEOF_INT128__
4309 else if constexpr (is_same_v<_Tp, __int128>)
4310 return (__u._M_i128 = ... = __value);
4311 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4312 return (__u._M_u128 = ... = __value);
4313#endif
4314#ifdef __BFLT16_DIG__
4315 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4316 return (__u._M_bf16 = ... = __value);
4317#endif
4318#ifdef __FLT16_DIG__
4319 else if constexpr (is_same_v<_Tp, _Float16>)
4320 return (__u._M_f16 = ... = __value);
4321#endif
4322#ifdef __FLT32_DIG__
4323 else if constexpr (is_same_v<_Tp, _Float32>)
4324 return (__u._M_f32 = ... = __value);
4325#endif
4326#ifdef __FLT64_DIG__
4327 else if constexpr (is_same_v<_Tp, _Float64>)
4328 return (__u._M_f64 = ... = __value);
4329#endif
4330 else if constexpr (is_same_v<_Tp, handle>)
4331 return __u._M_handle;
4332 // Otherwise, ill-formed.
4333 __builtin_unreachable();
4334 }
4335
4336 template<typename _Tp>
4337 [[__gnu__::__always_inline__]]
4338 _GLIBCXX_CONSTEXPR_FORMAT auto&
4339 _M_get() noexcept
4340 { return _S_access<_Tp>(*this); }
4341
4342 template<typename _Tp>
4343 [[__gnu__::__always_inline__]]
4344 _GLIBCXX_CONSTEXPR_FORMAT const auto&
4345 _M_get() const noexcept
4346 { return _S_access<_Tp>(*this); }
4347
4348 template<typename _Tp>
4349 [[__gnu__::__always_inline__]]
4350 _GLIBCXX_CONSTEXPR_FORMAT void
4351 _M_set(_Tp __v) noexcept
4352 {
4353 // Explicitly construct types without trivial default constructor.
4354 if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4355 std::construct_at(&_M_sv, __v);
4356 else if constexpr (is_same_v<_Tp, handle>)
4357 std::construct_at(&_M_handle, __v);
4358 else
4359 // Builtin types are trivially default constructible, and assignment
4360 // changes active member per N5032 [class.union.general] p5.
4361 _S_access<_Tp>(*this, __v);
4362 }
4363 };
4364
4365 // [format.arg.store], class template format-arg-store
4366 template<typename _Context, typename... _Args>
4367 class _Arg_store;
4368
4369 template<typename _Visitor, typename _Ctx>
4370 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4371 __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4372
4373 template<typename _Ch, typename _Tp>
4374 consteval _Arg_t
4375 __to_arg_t_enum() noexcept;
4376} // namespace __format
4377/// @endcond
4378
4379 template<typename _Context>
4380 class basic_format_arg
4381 {
4382 using _CharT = typename _Context::char_type;
4383
4384 public:
4385 using handle = __format::_Arg_value<_Context>::handle;
4386
4387 [[__gnu__::__always_inline__]]
4388 _GLIBCXX_CONSTEXPR_FORMAT
4389 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4390
4391 [[nodiscard,__gnu__::__always_inline__]]
4392 explicit _GLIBCXX_CONSTEXPR_FORMAT operator bool() const noexcept
4393 { return _M_type != __format::_Arg_none; }
4394
4395#if __cpp_lib_format >= 202306L // >= C++26
4396 template<typename _Visitor>
4397 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4398 visit(this basic_format_arg __arg, _Visitor&& __vis)
4399 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4400
4401 template<typename _Res, typename _Visitor>
4402 _GLIBCXX_CONSTEXPR_FORMAT _Res
4403 visit(this basic_format_arg __arg, _Visitor&& __vis)
4404 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4405#endif
4406
4407 private:
4408 template<typename _Ctx>
4409 friend class basic_format_args;
4410
4411 template<typename _Ctx, typename... _Args>
4412 friend class __format::_Arg_store;
4413
4414 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4415
4416 __format::_Arg_value<_Context> _M_val;
4417 __format::_Arg_t _M_type;
4418
4419 // Transform incoming argument type to the type stored in _Arg_value.
4420 // e.g. short -> int, std::string -> std::string_view,
4421 // char[3] -> const char*.
4422 template<typename _Tp>
4423 static consteval auto
4424 _S_to_arg_type()
4425 {
4426 using _Td = remove_const_t<_Tp>;
4427 if constexpr (is_same_v<_Td, bool>)
4428 return type_identity<bool>();
4429 else if constexpr (is_same_v<_Td, _CharT>)
4430 return type_identity<_CharT>();
4431 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4432 return type_identity<_CharT>();
4433#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4434 else if constexpr (is_same_v<_Td, __int128>)
4435 return type_identity<__int128>();
4436 else if constexpr (is_same_v<_Td, unsigned __int128>)
4437 return type_identity<unsigned __int128>();
4438#endif
4439 else if constexpr (__is_signed_integer<_Td>::value)
4440 {
4441 if constexpr (sizeof(_Td) <= sizeof(int))
4442 return type_identity<int>();
4443 else if constexpr (sizeof(_Td) <= sizeof(long long))
4444 return type_identity<long long>();
4445 }
4446 else if constexpr (__is_unsigned_integer<_Td>::value)
4447 {
4448 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4449 return type_identity<unsigned>();
4450 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4451 return type_identity<unsigned long long>();
4452 }
4453 else if constexpr (is_same_v<_Td, float>)
4454 return type_identity<float>();
4455 else if constexpr (is_same_v<_Td, double>)
4456 return type_identity<double>();
4457#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4458 else if constexpr (is_same_v<_Td, long double>)
4459 return type_identity<long double>();
4460#else
4461 else if constexpr (is_same_v<_Td, __ibm128>)
4462 return type_identity<__ibm128>();
4463 else if constexpr (is_same_v<_Td, __ieee128>)
4464 return type_identity<__ieee128>();
4465#endif
4466#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4467 else if constexpr (is_same_v<_Td, __float128>)
4468 return type_identity<__float128>();
4469#endif
4470#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4471 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4472 return type_identity<__format::__bflt16_t>();
4473#endif
4474#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4475 else if constexpr (is_same_v<_Td, _Float16>)
4476 return type_identity<_Float16>();
4477#endif
4478#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4479 else if constexpr (is_same_v<_Td, _Float32>)
4480 return type_identity<_Float32>();
4481#endif
4482#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4483 else if constexpr (is_same_v<_Td, _Float64>)
4484 return type_identity<_Float64>();
4485#endif
4486 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4487 || __is_specialization_of<_Td, basic_string>)
4488 {
4489 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4490 return type_identity<basic_string_view<_CharT>>();
4491 else
4492 return type_identity<handle>();
4493 }
4494 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4495 return type_identity<const _CharT*>();
4496 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4497 return type_identity<const _CharT*>();
4498 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4499 return type_identity<const void*>();
4500 else if constexpr (is_same_v<_Td, nullptr_t>)
4501 return type_identity<const void*>();
4502 else
4503 return type_identity<handle>();
4504 }
4505
4506 // Transform a formattable type to the appropriate storage type.
4507 template<typename _Tp>
4508 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4509
4510 // Get the _Arg_t value corresponding to a normalized type.
4511 template<typename _Tp>
4512 static consteval __format::_Arg_t
4513 _S_to_enum()
4514 {
4515 using namespace __format;
4516 if constexpr (is_same_v<_Tp, bool>)
4517 return _Arg_bool;
4518 else if constexpr (is_same_v<_Tp, _CharT>)
4519 return _Arg_c;
4520 else if constexpr (is_same_v<_Tp, int>)
4521 return _Arg_i;
4522 else if constexpr (is_same_v<_Tp, unsigned>)
4523 return _Arg_u;
4524 else if constexpr (is_same_v<_Tp, long long>)
4525 return _Arg_ll;
4526 else if constexpr (is_same_v<_Tp, unsigned long long>)
4527 return _Arg_ull;
4528 else if constexpr (is_same_v<_Tp, float>)
4529 return _Arg_flt;
4530 else if constexpr (is_same_v<_Tp, double>)
4531 return _Arg_dbl;
4532#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4533 else if constexpr (is_same_v<_Tp, long double>)
4534 return _Arg_ldbl;
4535#else
4536 // Don't use _Arg_ldbl for this target, it's ambiguous.
4537 else if constexpr (is_same_v<_Tp, __ibm128>)
4538 return _Arg_ibm128;
4539 else if constexpr (is_same_v<_Tp, __ieee128>)
4540 return _Arg_ieee128;
4541#endif
4542#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4543 else if constexpr (is_same_v<_Tp, __float128>)
4544 return _Arg_float128;
4545#endif
4546#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4547 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4548 return _Arg_bf16;
4549#endif
4550#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4551 else if constexpr (is_same_v<_Tp, _Float16>)
4552 return _Arg_f16;
4553#endif
4554#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4555 else if constexpr (is_same_v<_Tp, _Float32>)
4556 return _Arg_f32;
4557#endif
4558#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4559 else if constexpr (is_same_v<_Tp, _Float64>)
4560 return _Arg_f64;
4561#endif
4562 else if constexpr (is_same_v<_Tp, const _CharT*>)
4563 return _Arg_str;
4564 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4565 return _Arg_sv;
4566 else if constexpr (is_same_v<_Tp, const void*>)
4567 return _Arg_ptr;
4568#ifdef __SIZEOF_INT128__
4569 else if constexpr (is_same_v<_Tp, __int128>)
4570 return _Arg_i128;
4571 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4572 return _Arg_u128;
4573#endif
4574 else if constexpr (is_same_v<_Tp, handle>)
4575 return _Arg_handle;
4576 }
4577
4578 template<typename _Tp>
4579 _GLIBCXX_CONSTEXPR_FORMAT void
4580 _M_set(_Tp __v) noexcept
4581 {
4582 _M_type = _S_to_enum<_Tp>();
4583 _M_val._M_set(__v);
4584 }
4585
4586 template<typename _Tp>
4587 requires __format::__formattable_with<_Tp, _Context>
4588 _GLIBCXX_CONSTEXPR_FORMAT explicit
4589 basic_format_arg(_Tp& __v) noexcept
4590 {
4591 using _Td = _Normalize<_Tp>;
4592 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4593 _M_set(_Td{__v.data(), __v.size()});
4594 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4595 && is_same_v<_CharT, wchar_t>)
4596 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4597 else
4598 _M_set(static_cast<_Td>(__v));
4599 }
4600
4601 template<typename _Ctx, typename... _Argz>
4602 friend _GLIBCXX_CONSTEXPR_FORMAT auto
4603 make_format_args(_Argz&...) noexcept;
4604
4605 template<typename _Visitor, typename _Ctx>
4606 friend _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4607 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4608
4609 template<typename _Visitor, typename _Ctx>
4610 friend _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4611 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4612
4613 template<typename _Ch, typename _Tp>
4614 friend consteval __format::_Arg_t
4615 __format::__to_arg_t_enum() noexcept;
4616
4617 template<typename _Visitor>
4618 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4619 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4620 {
4621 using namespace __format;
4622 switch (__type)
4623 {
4624 case _Arg_none:
4625 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4626 case _Arg_bool:
4627 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4628 case _Arg_c:
4629 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4630 case _Arg_i:
4631 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4632 case _Arg_u:
4633 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4634 case _Arg_ll:
4635 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4636 case _Arg_ull:
4637 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4638#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4639 case _Arg_flt:
4640 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4641 case _Arg_dbl:
4642 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4643#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4644 case _Arg_ldbl:
4645 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4646#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4647 case _Arg_float128:
4648 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4649#endif
4650#else
4651 case _Arg_ibm128:
4652 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4653 case _Arg_ieee128:
4654 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4655#endif
4656#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4657 case _Arg_bf16:
4658 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4659#endif
4660#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4661 case _Arg_f16:
4662 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4663#endif
4664#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4665 case _Arg_f32:
4666 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4667#endif
4668#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4669 case _Arg_f64:
4670 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4671#endif
4672#endif // __glibcxx_to_chars
4673 case _Arg_str:
4674 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4675 case _Arg_sv:
4676 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4677 case _Arg_ptr:
4678 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4679 case _Arg_handle:
4680 return std::forward<_Visitor>(__vis)(_M_val._M_handle);
4681#ifdef __SIZEOF_INT128__
4682 case _Arg_i128:
4683 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4684 case _Arg_u128:
4685 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4686#endif
4687 default:
4688 __builtin_unreachable();
4689 }
4690 }
4691
4692 template<typename _Visitor>
4693 _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4694 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4695 {
4696 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4697 {
4698 constexpr bool __user_facing = __is_one_of<_Tp,
4699 monostate, bool, _CharT,
4700 int, unsigned int, long long int, unsigned long long int,
4701 float, double, long double,
4702 const _CharT*, basic_string_view<_CharT>,
4703 const void*, handle>::value;
4704 if constexpr (__user_facing)
4705 return std::forward<_Visitor>(__vis)(__val);
4706 else
4707 {
4708 handle __h(__val);
4709 return std::forward<_Visitor>(__vis)(__h);
4710 }
4711 }, __type);
4712 }
4713 };
4714
4715 template<typename _Visitor, typename _Context>
4716 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4717 inline _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4718 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4719 {
4720 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4721 }
4722
4723/// @cond undocumented
4724namespace __format
4725{
4726 template<typename _Visitor, typename _Ctx>
4727 inline _GLIBCXX_CONSTEXPR_FORMAT decltype(auto)
4728 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4729 {
4730 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4731 }
4732
4733 struct _WidthPrecVisitor
4734 {
4735 template<typename _Tp>
4736 _GLIBCXX_CONSTEXPR_FORMAT size_t
4737 operator()(_Tp& __arg) const
4738 {
4739 if constexpr (is_same_v<_Tp, monostate>)
4740 __format::__invalid_arg_id_in_format_string();
4741 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4742 // 3720. Restrict the valid types of arg-id for width and precision
4743 // 3721. Allow an arg-id with a value of zero for width
4744 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4745 {
4746 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4747 // 3720. Restrict the valid types of arg-id for width and precision
4748 if constexpr (__is_unsigned_integer<_Tp>::value)
4749 return __arg;
4750 else if constexpr (__is_signed_integer<_Tp>::value)
4751 if (__arg >= 0)
4752 return __arg;
4753 }
4754 __throw_format_error("format error: argument used for width or "
4755 "precision must be a non-negative integer");
4756 }
4757 };
4758
4759#pragma GCC diagnostic push
4760#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4761 template<typename _Context>
4762 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
4763 __int_from_arg(const basic_format_arg<_Context>& __arg)
4764 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4765
4766 // Pack _Arg_t enum values into a single 60-bit integer.
4767 template<int _Bits, size_t _Nm>
4768 constexpr auto
4769 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4770 {
4771 __UINT64_TYPE__ __packed_types = 0;
4772 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4773 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4774 return __packed_types;
4775 }
4776} // namespace __format
4777/// @endcond
4778
4779 template<typename _Context>
4780 class basic_format_args
4781 {
4782 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4783 static constexpr int _S_packed_type_mask = 0b11111;
4784 static constexpr int _S_max_packed_args = 12;
4785
4786 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4787
4788 template<typename... _Args>
4789 using _Store = __format::_Arg_store<_Context, _Args...>;
4790
4791 template<typename _Ctx, typename... _Args>
4792 friend class __format::_Arg_store;
4793
4794 using uint64_t = __UINT64_TYPE__;
4795 using _Format_arg = basic_format_arg<_Context>;
4796 using _Format_arg_val = __format::_Arg_value<_Context>;
4797
4798 // If args are packed then the number of args is in _M_packed_size and
4799 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4800 // If args are not packed then the number of args is in _M_unpacked_size
4801 // and _M_packed_size is zero.
4802 uint64_t _M_packed_size : 4;
4803 uint64_t _M_unpacked_size : 60;
4804
4805 union {
4806 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4807 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4808 };
4809
4810 _GLIBCXX_CONSTEXPR_FORMAT size_t
4811 _M_size() const noexcept
4812 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4813
4814 _GLIBCXX_CONSTEXPR_FORMAT typename __format::_Arg_t
4815 _M_type(size_t __i) const noexcept
4816 {
4817 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4818 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4819 }
4820
4821 template<typename _Ctx, typename... _Args>
4822 friend _GLIBCXX_CONSTEXPR_FORMAT auto
4823 make_format_args(_Args&...) noexcept;
4824
4825 // An array of _Arg_t enums corresponding to _Args...
4826 template<typename... _Args>
4827 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4828 _S_types_to_pack()
4829 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4830
4831 public:
4832 template<typename... _Args>
4833 _GLIBCXX_CONSTEXPR_FORMAT
4834 basic_format_args(const _Store<_Args...>& __store) noexcept;
4835
4836 [[nodiscard,__gnu__::__always_inline__]]
4837 _GLIBCXX_CONSTEXPR_FORMAT basic_format_arg<_Context>
4838 get(size_t __i) const noexcept
4839 {
4840 basic_format_arg<_Context> __arg;
4841 if (__i < _M_packed_size)
4842 {
4843 __arg._M_type = _M_type(__i);
4844 __arg._M_val = _M_values[__i];
4845 }
4846 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4847 __arg = _M_args[__i];
4848 return __arg;
4849 }
4850 };
4851
4852 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4853 // 3810. CTAD for std::basic_format_args
4854 template<typename _Context, typename... _Args>
4855 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4856 -> basic_format_args<_Context>;
4857
4858 template<typename _Context, typename... _Args>
4859 _GLIBCXX_CONSTEXPR_FORMAT auto
4860 make_format_args(_Args&... __fmt_args) noexcept;
4861
4862 // An array of type-erased formatting arguments.
4863 template<typename _Context, typename... _Args>
4864 class __format::_Arg_store
4865 {
4866 friend std::basic_format_args<_Context>;
4867
4868 template<typename _Ctx, typename... _Argz>
4869 friend _GLIBCXX_CONSTEXPR_FORMAT auto std::
4870#if _GLIBCXX_INLINE_VERSION
4871 __8:: // Needed for PR c++/59256
4872#endif
4873 make_format_args(_Argz&...) noexcept;
4874
4875 // For a sufficiently small number of arguments we only store values.
4876 // basic_format_args can get the types from the _Args pack.
4877 static constexpr bool _S_values_only
4878 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4879
4880 using _Element_t
4881 = __conditional_t<_S_values_only,
4882 __format::_Arg_value<_Context>,
4883 basic_format_arg<_Context>>;
4884
4885 _Element_t _M_args[sizeof...(_Args)];
4886
4887 template<typename _Tp>
4888 static _GLIBCXX_CONSTEXPR_FORMAT _Element_t
4889 _S_make_elt(_Tp& __v)
4890 {
4891 using _Tq = remove_const_t<_Tp>;
4892 using _CharT = typename _Context::char_type;
4893 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4894 "std::formatter must be specialized for the type "
4895 "of each format arg");
4896 using __format::__formattable_with;
4897 if constexpr (is_const_v<_Tp>)
4898 if constexpr (!__formattable_with<_Tp, _Context>)
4899 if constexpr (__formattable_with<_Tq, _Context>)
4900 static_assert(__formattable_with<_Tp, _Context>,
4901 "format arg must be non-const because its "
4902 "std::formatter specialization has a "
4903 "non-const reference parameter");
4904 basic_format_arg<_Context> __arg(__v);
4905 if constexpr (_S_values_only)
4906 return __arg._M_val;
4907 else
4908 return __arg;
4909 }
4910
4911 template<typename... _Tp>
4912 requires (sizeof...(_Tp) == sizeof...(_Args))
4913 [[__gnu__::__always_inline__]]
4914 _GLIBCXX_CONSTEXPR_FORMAT
4915 _Arg_store(_Tp&... __a) noexcept
4916 : _M_args{_S_make_elt(__a)...}
4917 { }
4918 };
4919
4920 template<typename _Context>
4921 class __format::_Arg_store<_Context>
4922 { };
4923
4924 template<typename _Context>
4925 template<typename... _Args>
4926 inline _GLIBCXX_CONSTEXPR_FORMAT
4927 basic_format_args<_Context>::
4928 basic_format_args(const _Store<_Args...>& __store) noexcept
4929 {
4930 if constexpr (sizeof...(_Args) == 0)
4931 {
4932 _M_packed_size = 0;
4933 _M_unpacked_size = 0;
4934 _M_args = nullptr;
4935 }
4936 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4937 {
4938 // The number of packed arguments:
4939 _M_packed_size = sizeof...(_Args);
4940 // The packed type enums:
4941 _M_unpacked_size
4942 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4943 // The _Arg_value objects.
4944 _M_values = __store._M_args;
4945 }
4946 else
4947 {
4948 // No packed arguments:
4949 _M_packed_size = 0;
4950 // The number of unpacked arguments:
4951 _M_unpacked_size = sizeof...(_Args);
4952 // The basic_format_arg objects:
4953 _M_args = __store._M_args;
4954 }
4955 }
4956
4957 /// Capture formatting arguments for use by `std::vformat`.
4958 template<typename _Context = format_context, typename... _Args>
4959 [[nodiscard,__gnu__::__always_inline__]]
4960 inline _GLIBCXX_CONSTEXPR_FORMAT auto
4961 make_format_args(_Args&... __fmt_args) noexcept
4962 {
4963 using _Fmt_arg = basic_format_arg<_Context>;
4964 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4965 _Normalize<_Args>...>;
4966 return _Store(__fmt_args...);
4967 }
4968
4969#ifdef _GLIBCXX_USE_WCHAR_T
4970 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4971 template<typename... _Args>
4972 [[nodiscard,__gnu__::__always_inline__]]
4973 inline _GLIBCXX_CONSTEXPR_FORMAT auto
4974 make_wformat_args(_Args&... __args) noexcept
4975 { return std::make_format_args<wformat_context>(__args...); }
4976#endif
4977
4978/// @cond undocumented
4979namespace __format
4980{
4981 template<typename _Out, typename _CharT, typename _Context>
4982 _GLIBCXX_CONSTEXPR_FORMAT _Out
4983 __do_vformat_to(_Out, basic_string_view<_CharT>,
4984 const basic_format_args<_Context>&,
4985 const locale* = nullptr);
4986
4987 template<typename _CharT> struct __formatter_chrono;
4988
4989} // namespace __format
4990/// @endcond
4991
4992 /** Context for std::format and similar functions.
4993 *
4994 * A formatting context contains an output iterator and locale to use
4995 * for the formatting operations. Most programs will never need to use
4996 * this class template explicitly. For typical uses of `std::format` the
4997 * library will use the specializations `std::format_context` (for `char`)
4998 * and `std::wformat_context` (for `wchar_t`).
4999 *
5000 * You are not allowed to define partial or explicit specializations of
5001 * this class template.
5002 *
5003 * @since C++20
5004 */
5005 template<typename _Out, typename _CharT>
5006 class basic_format_context
5007 {
5008 static_assert( output_iterator<_Out, const _CharT&> );
5009
5010 basic_format_args<basic_format_context> _M_args;
5011 _Out _M_out;
5012 __format::_Optional_locale _M_loc;
5013
5014 _GLIBCXX_CONSTEXPR_FORMAT
5015 basic_format_context(basic_format_args<basic_format_context> __args,
5016 _Out __out)
5017 : _M_args(__args), _M_out(std::move(__out))
5018 { }
5019
5020 _GLIBCXX_CONSTEXPR_FORMAT
5021 basic_format_context(basic_format_args<basic_format_context> __args,
5022 _Out __out, const std::locale& __loc)
5023 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
5024 { }
5025
5026 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5027 // 4061. Should std::basic_format_context be
5028 // default-constructible/copyable/movable?
5029 basic_format_context(const basic_format_context&) = delete;
5030 basic_format_context& operator=(const basic_format_context&) = delete;
5031
5032 template<typename _Out2, typename _CharT2, typename _Context2>
5033 friend _GLIBCXX_CONSTEXPR_FORMAT _Out2
5034 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
5035 const basic_format_args<_Context2>&,
5036 const locale*);
5037
5038 friend __format::__formatter_chrono<_CharT>;
5039
5040 public:
5041 ~basic_format_context() = default;
5042
5043 using iterator = _Out;
5044 using char_type = _CharT;
5045 template<typename _Tp>
5046 using formatter_type = formatter<_Tp, _CharT>;
5047
5048 [[nodiscard]]
5049 _GLIBCXX_CONSTEXPR_FORMAT basic_format_arg<basic_format_context>
5050 arg(size_t __id) const noexcept
5051 { return _M_args.get(__id); }
5052
5053 [[nodiscard]]
5054 std::locale locale() { return _M_loc.value(); }
5055
5056 [[nodiscard]]
5057 _GLIBCXX_CONSTEXPR_FORMAT iterator
5058 out() { return std::move(_M_out); }
5059
5060 _GLIBCXX_CONSTEXPR_FORMAT void
5061 advance_to(iterator __it) { _M_out = std::move(__it); }
5062 };
5063
5064
5065/// @cond undocumented
5066namespace __format
5067{
5068 // Abstract base class defining an interface for scanning format strings.
5069 // Scan the characters in a format string, dividing it up into strings of
5070 // ordinary characters, escape sequences, and replacement fields.
5071 // Call virtual functions for derived classes to parse format-specifiers
5072 // or write formatted output.
5073 template<typename _CharT>
5074 struct _Scanner
5075 {
5076 using iterator = typename basic_format_parse_context<_CharT>::iterator;
5077
5078 struct _Parse_context : basic_format_parse_context<_CharT>
5079 {
5080 using basic_format_parse_context<_CharT>::basic_format_parse_context;
5081 const _Arg_t* _M_types = nullptr;
5082 } _M_pc;
5083
5084 constexpr explicit
5085 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
5086 : _M_pc(__str, __nargs)
5087 { }
5088
5089 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
5090 constexpr iterator end() const noexcept { return _M_pc.end(); }
5091
5092 constexpr void
5093 _M_scan()
5094 {
5095 basic_string_view<_CharT> __fmt = _M_fmt_str();
5096
5097 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5098 {
5099 _M_pc.advance_to(begin() + 1);
5100 _M_format_arg(_M_pc.next_arg_id());
5101 return;
5102 }
5103
5104 size_t __lbr = __fmt.find('{');
5105 size_t __rbr = __fmt.find('}');
5106
5107 while (__fmt.size())
5108 {
5109 auto __cmp = __lbr <=> __rbr;
5110 if (__cmp == 0)
5111 {
5112 _M_on_chars(end());
5113 _M_pc.advance_to(end());
5114 return;
5115 }
5116 else if (__cmp < 0)
5117 {
5118 if (__lbr + 1 == __fmt.size()
5119 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
5120 __format::__unmatched_left_brace_in_format_string();
5121 const bool __is_escape = __fmt[__lbr + 1] == '{';
5122 iterator __last = begin() + __lbr + int(__is_escape);
5123 _M_on_chars(__last);
5124 _M_pc.advance_to(__last + 1);
5125 __fmt = _M_fmt_str();
5126 if (__is_escape)
5127 {
5128 if (__rbr != __fmt.npos)
5129 __rbr -= __lbr + 2;
5130 __lbr = __fmt.find('{');
5131 }
5132 else
5133 {
5134 _M_on_replacement_field();
5135 __fmt = _M_fmt_str();
5136 __lbr = __fmt.find('{');
5137 __rbr = __fmt.find('}');
5138 }
5139 }
5140 else
5141 {
5142 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
5143 __format::__unmatched_right_brace_in_format_string();
5144 iterator __last = begin() + __rbr;
5145 _M_on_chars(__last);
5146 _M_pc.advance_to(__last + 1);
5147 __fmt = _M_fmt_str();
5148 if (__lbr != __fmt.npos)
5149 __lbr -= __rbr + 1;
5150 __rbr = __fmt.find('}');
5151 }
5152 }
5153 }
5154
5155 constexpr basic_string_view<_CharT>
5156 _M_fmt_str() const noexcept
5157 { return {begin(), end()}; }
5158
5159 constexpr virtual void _M_on_chars(iterator) { }
5160
5161 constexpr void _M_on_replacement_field()
5162 {
5163 auto __next = begin();
5164
5165 size_t __id;
5166 if (*__next == '}')
5167 __id = _M_pc.next_arg_id();
5168 else if (*__next == ':')
5169 {
5170 __id = _M_pc.next_arg_id();
5171 _M_pc.advance_to(++__next);
5172 }
5173 else
5174 {
5175 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5176 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5177 __format::__invalid_arg_id_in_format_string();
5178 _M_pc.check_arg_id(__id = __i);
5179 if (*__ptr == ':')
5180 {
5181 _M_pc.advance_to(++__ptr);
5182 }
5183 else
5184 _M_pc.advance_to(__ptr);
5185 }
5186 _M_format_arg(__id);
5187 if (begin() == end() || *begin() != '}')
5188 __format::__unmatched_left_brace_in_format_string();
5189 _M_pc.advance_to(begin() + 1); // Move past '}'
5190 }
5191
5192 constexpr virtual void _M_format_arg(size_t __id) = 0;
5193 };
5194
5195 // Process a format string and format the arguments in the context.
5196 template<typename _Out, typename _CharT>
5197 class _Formatting_scanner : public _Scanner<_CharT>
5198 {
5199 public:
5200 _GLIBCXX_CONSTEXPR_FORMAT
5201 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5202 basic_string_view<_CharT> __str)
5203 : _Scanner<_CharT>(__str), _M_fc(__fc)
5204 { }
5205
5206 private:
5207 basic_format_context<_Out, _CharT>& _M_fc;
5208
5209 using iterator = typename _Scanner<_CharT>::iterator;
5210
5211 constexpr void
5212 _M_on_chars(iterator __last) override
5213 {
5214 basic_string_view<_CharT> __str(this->begin(), __last);
5215 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5216 }
5217
5218 constexpr void
5219 _M_format_arg(size_t __id) override
5220 {
5221 using _Context = basic_format_context<_Out, _CharT>;
5222 using handle = typename basic_format_arg<_Context>::handle;
5223
5224 __format::__visit_format_arg([this](auto& __arg) {
5225 using _Type = remove_reference_t<decltype(__arg)>;
5226 using _Formatter = typename _Context::template formatter_type<_Type>;
5227 if constexpr (is_same_v<_Type, monostate>)
5228 __format::__invalid_arg_id_in_format_string();
5229 else if constexpr (is_same_v<_Type, handle>)
5230 __arg.format(this->_M_pc, this->_M_fc);
5231 else if constexpr (is_default_constructible_v<_Formatter>)
5232 {
5233 _Formatter __f;
5234 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5235 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5236 }
5237 else
5238 static_assert(__format::__formattable_with<_Type, _Context>);
5239 }, _M_fc.arg(__id));
5240 }
5241 };
5242
5243 template<typename _CharT, typename _Tp>
5244 consteval _Arg_t
5245 __to_arg_t_enum() noexcept
5246 {
5247 using _Context = __format::__format_context<_CharT>;
5248 using _Fmt_arg = basic_format_arg<_Context>;
5249 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5250 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5251 }
5252
5253 // Validate a format string for Args.
5254 template<typename _CharT, typename... _Args>
5255 class _Checking_scanner : public _Scanner<_CharT>
5256 {
5257 static_assert(
5258 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5259 "std::formatter must be specialized for each type being formatted");
5260
5261 public:
5262 consteval
5263 _Checking_scanner(basic_string_view<_CharT> __str)
5264 : _Scanner<_CharT>(__str, sizeof...(_Args))
5265 {
5266#if __cpp_lib_format >= 202305L
5267 this->_M_pc._M_types = _M_types.data();
5268#endif
5269 }
5270
5271 private:
5272 constexpr void
5273 _M_format_arg(size_t __id) override
5274 {
5275 if constexpr (sizeof...(_Args) != 0)
5276 {
5277 if (__id < sizeof...(_Args))
5278 {
5279 _M_parse_format_spec<_Args...>(__id);
5280 return;
5281 }
5282 }
5283 __builtin_unreachable();
5284 }
5285
5286 template<typename _Tp, typename... _OtherArgs>
5287 constexpr void
5288 _M_parse_format_spec(size_t __id)
5289 {
5290 if (__id == 0)
5291 {
5292 formatter<_Tp, _CharT> __f;
5293 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5294 }
5295 else if constexpr (sizeof...(_OtherArgs) != 0)
5296 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5297 else
5298 __builtin_unreachable();
5299 }
5300
5301#if __cpp_lib_format >= 202305L
5302 array<_Arg_t, sizeof...(_Args)>
5303 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5304#endif
5305 };
5306
5307 template<typename _CharT, unsigned = __unicode::__literal_encoding_is_unicode<_CharT>()>
5308 _GLIBCXX_CONSTEXPR_FORMAT _Sink_iter<_CharT>
5309 __do_vformat_to(_Sink_iter<_CharT> __out, basic_string_view<_CharT> __fmt,
5310 __format_context<_CharT>& __ctx)
5311 {
5312 if constexpr (is_same_v<_CharT, char>)
5313 // Fast path for "{}" format strings and simple format arg types.
5314 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5315 {
5316 bool __done = false;
5317 __format::__visit_format_arg([&](auto& __arg) {
5318 using _Tp = remove_cvref_t<decltype(__arg)>;
5319 if constexpr (is_same_v<_Tp, bool>)
5320 {
5321 size_t __len = 4 + !__arg;
5322 const char* __chars[] = { "false", "true" };
5323 if (auto __res = __out._M_reserve(__len))
5324 {
5325 ranges::copy_n(__chars[__arg], __len, __res.get());
5326 __res._M_bump(__len);
5327 __done = true;
5328 }
5329 }
5330 else if constexpr (is_same_v<_Tp, char>)
5331 {
5332 if (auto __res = __out._M_reserve(1))
5333 {
5334 *__res.get() = __arg;
5335 __res._M_bump(1);
5336 __done = true;
5337 }
5338 }
5339 else if constexpr (is_integral_v<_Tp>)
5340 {
5341 make_unsigned_t<_Tp> __uval;
5342 const bool __neg = __arg < 0;
5343 if (__neg)
5344 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5345 else
5346 __uval = __arg;
5347 const auto __n = __detail::__to_chars_len(__uval);
5348 if (auto __res = __out._M_reserve(__n + __neg))
5349 {
5350 auto __ptr = __res.get();
5351 *__ptr = '-';
5352 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5353 __uval);
5354 __res._M_bump(__n + __neg);
5355 __done = true;
5356 }
5357 }
5358 else if constexpr (is_convertible_v<_Tp, string_view>)
5359 {
5360 string_view __sv = __arg;
5361 if (auto __res = __out._M_reserve(__sv.size()))
5362 {
5363 ranges::copy(__sv, __res.get());
5364 __res._M_bump(__sv.size());
5365 __done = true;
5366 }
5367 }
5368 }, __ctx.arg(0));
5369
5370 if (__done)
5371 return __out;
5372 }
5373
5374 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5375 __scanner._M_scan();
5376 return __out;
5377 }
5378
5379// The behavior of the formatters (interpretation of fill character) depends
5380// on the literal encoding. As explicit instantiation of __do_vformat_to
5381// instantiates formatters for types stored in basic_format_arg, we can
5382// support only single encoding, in this case unicode. This should cover
5383// most common use cases.
5384#if __cplusplus <= 202002L && _GLIBCXX_EXTERN_TEMPLATE > 0
5385 extern template _Sink_iter<char>
5386 __do_vformat_to<char, 1>(_Sink_iter<char>, string_view,
5387 format_context&);
5388# ifdef _GLIBCXX_USE_WCHAR_T
5389 extern template _Sink_iter<wchar_t>
5390 __do_vformat_to<wchar_t, 1>(_Sink_iter<wchar_t>, wstring_view,
5391 wformat_context&);
5392# endif
5393#endif
5394
5395 template<typename _Out, typename _CharT, typename _Context>
5396 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5397 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5398 const basic_format_args<_Context>& __args,
5399 const locale* __loc)
5400 {
5401 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5402 {
5403 auto __ctx = __loc == nullptr
5404 ? _Context(__args, __out)
5405 : _Context(__args, __out, *__loc);
5406 return __format::__do_vformat_to(__out, __fmt, __ctx);
5407 }
5408 else if constexpr (__contiguous_char_iter<_CharT, _Out>)
5409 {
5410 _Ptr_sink<_CharT> __sink(__out);
5411 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5412 return std::move(__sink)._M_finish(__out).out;
5413 }
5414 else
5415 {
5416 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5417 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5418 return std::move(__sink)._M_finish().out;
5419 }
5420 }
5421
5422 template<typename _Out, typename _CharT>
5423 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5424 __do_vformat_to_n(_Out __out, iter_difference_t<_Out> __n,
5425 basic_string_view<_CharT> __fmt,
5426 const type_identity_t<
5427 basic_format_args<__format_context<_CharT>>>& __args,
5428 const locale* __loc = nullptr)
5429 {
5430 if constexpr (__contiguous_char_iter<_CharT, _Out>)
5431 {
5432 _Ptr_sink<_CharT> __sink(__out, __n);
5433 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5434 return std::move(__sink)._M_finish(__out);
5435 }
5436 else
5437 {
5438 _Iter_sink<_CharT, _Out> __sink(std::move(__out), __n);
5439 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5440 return std::move(__sink)._M_finish();
5441 }
5442 }
5443
5444#pragma GCC diagnostic pop
5445
5446} // namespace __format
5447/// @endcond
5448
5449#if __cpp_lib_format >= 202305L // >= C++26
5450 /// @cond undocumented
5451 // Common implementation of check_dynamic_spec{,_string,_integral}
5452 template<typename _CharT>
5453 template<typename... _Ts>
5454 consteval void
5455 basic_format_parse_context<_CharT>::
5456 __check_dynamic_spec(size_t __id) noexcept
5457 {
5458 if (__id >= _M_num_args)
5459 __format::__invalid_arg_id_in_format_string();
5460 if constexpr (sizeof...(_Ts) != 0)
5461 {
5462 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5463 auto* __args = static_cast<_Parse_ctx*>(this)->_M_types;
5464 // Formatting scanner, no type check.
5465 if (!__args)
5466 return;
5467
5468 auto __arg = __args[__id];
5469 __format::_Arg_t __types[] = {
5470 __format::__to_arg_t_enum<_CharT, _Ts>()...
5471 };
5472 for (auto __t : __types)
5473 if (__arg == __t)
5474 return;
5475 }
5476 __invalid_dynamic_spec("arg(id) type does not match");
5477 }
5478 /// @endcond
5479#endif
5480
5481 template<typename _CharT, typename... _Args>
5482 template<typename _Tp>
5483 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5484 consteval
5485 basic_format_string<_CharT, _Args...>::
5486 basic_format_string(const _Tp& __s) noexcept
5487 : _M_str(__s)
5488 {
5489 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5490 __scanner(_M_str);
5491 __scanner._M_scan();
5492 }
5493
5494 // [format.functions], formatting functions
5495
5496 template<typename _Out> requires output_iterator<_Out, const char&>
5497 [[__gnu__::__always_inline__]]
5498 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5499 vformat_to(_Out __out, string_view __fmt, format_args __args)
5500 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5501
5502#ifdef _GLIBCXX_USE_WCHAR_T
5503 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5504 [[__gnu__::__always_inline__]]
5505 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5506 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5507 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5508#endif
5509
5510 template<typename _Out> requires output_iterator<_Out, const char&>
5511 [[__gnu__::__always_inline__]]
5512 inline _Out
5513 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5514 format_args __args)
5515 {
5516 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5517 }
5518
5519#ifdef _GLIBCXX_USE_WCHAR_T
5520 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5521 [[__gnu__::__always_inline__]]
5522 inline _Out
5523 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5524 wformat_args __args)
5525 {
5526 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5527 }
5528#endif
5529
5530 [[nodiscard]]
5531 inline _GLIBCXX_CONSTEXPR_FORMAT string
5532 vformat(string_view __fmt, format_args __args)
5533 {
5534 __format::_Str_sink<char> __buf;
5535 std::vformat_to(__buf.out(), __fmt, __args);
5536 return std::move(__buf).get();
5537 }
5538
5539#ifdef _GLIBCXX_USE_WCHAR_T
5540 [[nodiscard]]
5541 inline _GLIBCXX_CONSTEXPR_FORMAT wstring
5542 vformat(wstring_view __fmt, wformat_args __args)
5543 {
5544 __format::_Str_sink<wchar_t> __buf;
5545 std::vformat_to(__buf.out(), __fmt, __args);
5546 return std::move(__buf).get();
5547 }
5548#endif
5549
5550 [[nodiscard]]
5551 inline string
5552 vformat(const locale& __loc, string_view __fmt, format_args __args)
5553 {
5554 __format::_Str_sink<char> __buf;
5555 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5556 return std::move(__buf).get();
5557 }
5558
5559#ifdef _GLIBCXX_USE_WCHAR_T
5560 [[nodiscard]]
5561 inline wstring
5562 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5563 {
5564 __format::_Str_sink<wchar_t> __buf;
5565 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5566 return std::move(__buf).get();
5567 }
5568#endif
5569
5570 template<typename... _Args>
5571 [[nodiscard]]
5572 inline _GLIBCXX_CONSTEXPR_FORMAT string
5573 format(format_string<_Args...> __fmt, _Args&&... __args)
5574 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5575
5576#ifdef _GLIBCXX_USE_WCHAR_T
5577 template<typename... _Args>
5578 [[nodiscard]]
5579 inline _GLIBCXX_CONSTEXPR_FORMAT wstring
5580 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5581 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5582#endif
5583
5584 template<typename... _Args>
5585 [[nodiscard]]
5586 inline string
5587 format(const locale& __loc, format_string<_Args...> __fmt,
5588 _Args&&... __args)
5589 {
5590 return std::vformat(__loc, __fmt.get(),
5591 std::make_format_args(__args...));
5592 }
5593
5594#ifdef _GLIBCXX_USE_WCHAR_T
5595 template<typename... _Args>
5596 [[nodiscard]]
5597 inline wstring
5598 format(const locale& __loc, wformat_string<_Args...> __fmt,
5599 _Args&&... __args)
5600 {
5601 return std::vformat(__loc, __fmt.get(),
5602 std::make_wformat_args(__args...));
5603 }
5604#endif
5605
5606 template<typename _Out, typename... _Args>
5607 requires output_iterator<_Out, const char&>
5608 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5609 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5610 {
5611 return std::vformat_to(std::move(__out), __fmt.get(),
5612 std::make_format_args(__args...));
5613 }
5614
5615#ifdef _GLIBCXX_USE_WCHAR_T
5616 template<typename _Out, typename... _Args>
5617 requires output_iterator<_Out, const wchar_t&>
5618 inline _GLIBCXX_CONSTEXPR_FORMAT _Out
5619 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5620 {
5621 return std::vformat_to(std::move(__out), __fmt.get(),
5622 std::make_wformat_args(__args...));
5623 }
5624#endif
5625
5626 template<typename _Out, typename... _Args>
5627 requires output_iterator<_Out, const char&>
5628 inline _Out
5629 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5630 _Args&&... __args)
5631 {
5632 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5633 std::make_format_args(__args...));
5634 }
5635
5636#ifdef _GLIBCXX_USE_WCHAR_T
5637 template<typename _Out, typename... _Args>
5638 requires output_iterator<_Out, const wchar_t&>
5639 inline _Out
5640 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5641 _Args&&... __args)
5642 {
5643 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5644 std::make_wformat_args(__args...));
5645 }
5646#endif
5647
5648 template<typename _Out, typename... _Args>
5649 requires output_iterator<_Out, const char&>
5650 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5651 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5652 format_string<_Args...> __fmt, _Args&&... __args)
5653 {
5654 return __format::__do_vformat_to_n(
5655 std::move(__out), __n, __fmt.get(),
5656 std::make_format_args(__args...));
5657 }
5658
5659#ifdef _GLIBCXX_USE_WCHAR_T
5660 template<typename _Out, typename... _Args>
5661 requires output_iterator<_Out, const wchar_t&>
5662 inline _GLIBCXX_CONSTEXPR_FORMAT format_to_n_result<_Out>
5663 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5664 wformat_string<_Args...> __fmt, _Args&&... __args)
5665 {
5666 return __format::__do_vformat_to_n(
5667 std::move(__out), __n, __fmt.get(),
5668 std::make_wformat_args(__args...));
5669 }
5670#endif
5671
5672 template<typename _Out, typename... _Args>
5673 requires output_iterator<_Out, const char&>
5674 inline format_to_n_result<_Out>
5675 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5676 format_string<_Args...> __fmt, _Args&&... __args)
5677 {
5678 return __format::__do_vformat_to_n(
5679 std::move(__out), __n, __fmt.get(),
5680 std::make_format_args(__args...), &__loc);
5681 }
5682
5683#ifdef _GLIBCXX_USE_WCHAR_T
5684 template<typename _Out, typename... _Args>
5685 requires output_iterator<_Out, const wchar_t&>
5686 inline format_to_n_result<_Out>
5687 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5688 wformat_string<_Args...> __fmt, _Args&&... __args)
5689 {
5690 return __format::__do_vformat_to_n(
5691 std::move(__out), __n, __fmt.get(),
5692 std::make_wformat_args(__args...), &__loc);
5693 }
5694#endif
5695
5696/// @cond undocumented
5697namespace __format
5698{
5699#if 1
5700 template<typename _CharT>
5701 class _Counting_sink final : public _Ptr_sink<_CharT>
5702 {
5703 public:
5704 _GLIBCXX_CONSTEXPR_FORMAT
5705 _Counting_sink() : _Ptr_sink<_CharT>(nullptr, 0) { }
5706
5707 [[__gnu__::__always_inline__]]
5708 _GLIBCXX_CONSTEXPR_FORMAT size_t
5709 count() const
5710 { return this->_M_count + this->_M_used().size(); }
5711 };
5712#else
5713 template<typename _CharT>
5714 class _Counting_sink : public _Buf_sink<_CharT>
5715 {
5716 size_t _M_count = 0;
5717
5718 void
5719 _M_overflow() override
5720 {
5721 if (!std::is_constant_evaluated())
5722 _M_count += this->_M_used().size();
5723 this->_M_rewind();
5724 }
5725
5726 public:
5727 _Counting_sink() = default;
5728
5729 [[__gnu__::__always_inline__]]
5730 size_t
5731 count() noexcept
5732 {
5733 _Counting_sink::_M_overflow();
5734 return _M_count;
5735 }
5736 };
5737#endif
5738} // namespace __format
5739/// @endcond
5740
5741 template<typename... _Args>
5742 [[nodiscard]]
5743 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
5744 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5745 {
5746 __format::_Counting_sink<char> __buf;
5747 std::vformat_to(__buf.out(), __fmt.get(),
5748 std::make_format_args(__args...));
5749 return __buf.count();
5750 }
5751
5752#ifdef _GLIBCXX_USE_WCHAR_T
5753 template<typename... _Args>
5754 [[nodiscard]]
5755 inline _GLIBCXX_CONSTEXPR_FORMAT size_t
5756 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5757 {
5758 __format::_Counting_sink<wchar_t> __buf;
5759 std::vformat_to(__buf.out(), __fmt.get(),
5760 std::make_wformat_args(__args...));
5761 return __buf.count();
5762 }
5763#endif
5764
5765 template<typename... _Args>
5766 [[nodiscard]]
5767 inline size_t
5768 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5769 _Args&&... __args)
5770 {
5771 __format::_Counting_sink<char> __buf;
5772 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5773 std::make_format_args(__args...));
5774 return __buf.count();
5775 }
5776
5777#ifdef _GLIBCXX_USE_WCHAR_T
5778 template<typename... _Args>
5779 [[nodiscard]]
5780 inline size_t
5781 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5782 _Args&&... __args)
5783 {
5784 __format::_Counting_sink<wchar_t> __buf;
5785 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5786 std::make_wformat_args(__args...));
5787 return __buf.count();
5788 }
5789#endif
5790
5791#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5792 /// @cond undocumented
5793 template<typename _Tp>
5794 consteval range_format
5795 __fmt_kind()
5796 {
5797 using _Ref = ranges::range_reference_t<_Tp>;
5798 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5799 return range_format::disabled;
5800 else if constexpr (requires { typename _Tp::key_type; })
5801 {
5802 if constexpr (requires { typename _Tp::mapped_type; })
5803 {
5804 using _Up = remove_cvref_t<_Ref>;
5805 if constexpr (__is_pair<_Up>)
5806 return range_format::map;
5807 else if constexpr (__is_specialization_of<_Up, tuple>)
5808 if constexpr (tuple_size_v<_Up> == 2)
5809 return range_format::map;
5810 }
5811 return range_format::set;
5812 }
5813 else
5814 return range_format::sequence;
5815 }
5816 /// @endcond
5817
5818 /// A constant determining how a range should be formatted.
5819 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5820 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5821
5822/// @cond undocumented
5823namespace __format
5824{
5825 template<typename _CharT, typename _Out, typename _Callback>
5826 _GLIBCXX_CONSTEXPR_FORMAT
5827 typename basic_format_context<_Out, _CharT>::iterator
5828 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5829 const _Spec<_CharT>& __spec,
5830 _Callback&& __call)
5831 {
5832 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5833 return __fc.out();
5834 else
5835 {
5836 // This is required to implement formatting with padding,
5837 // as we need to format to temporary buffer, using the same iterator.
5838 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5839
5840 const size_t __padwidth = __spec._M_get_width(__fc);
5841 if (__padwidth == 0)
5842 return __call(__fc);
5843
5844 struct _Restore_out
5845 {
5846 _GLIBCXX_CONSTEXPR_FORMAT
5847 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5848 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5849 { }
5850
5851 _GLIBCXX_CONSTEXPR_FORMAT void
5852 _M_disarm()
5853 { _M_ctx = nullptr; }
5854
5855 _GLIBCXX_CONSTEXPR_FORMAT
5856 ~_Restore_out()
5857 {
5858 if (_M_ctx)
5859 _M_ctx->advance_to(_M_out);
5860 }
5861
5862 private:
5863 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5864 _Sink_iter<_CharT> _M_out;
5865 };
5866
5867 _Restore_out __restore(__fc);
5868 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5869 __fc.advance_to(__sink.out());
5870 __call(__fc);
5871 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5872 __restore._M_disarm();
5873 return __fc.out();
5874 }
5875 }
5876
5877 template<size_t _Pos, typename _Tp, typename _CharT>
5878 struct __indexed_formatter_storage
5879 {
5880 constexpr void
5881 _M_parse()
5882 {
5883 basic_format_parse_context<_CharT> __pc({});
5884 if (_M_formatter.parse(__pc) != __pc.end())
5885 __format::__failed_to_parse_format_spec();
5886 }
5887
5888 template<typename _Out>
5889 _GLIBCXX_CONSTEXPR_FORMAT void
5890 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5891 basic_format_context<_Out, _CharT>& __fc,
5892 basic_string_view<_CharT> __sep) const
5893 {
5894 if constexpr (_Pos != 0)
5895 __fc.advance_to(__format::__write(__fc.out(), __sep));
5896 __fc.advance_to(_M_formatter.format(__elem, __fc));
5897 }
5898
5899 [[__gnu__::__always_inline__]]
5900 constexpr void
5901 set_debug_format()
5902 {
5903 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5904 _M_formatter.set_debug_format();
5905 }
5906
5907 private:
5908 formatter<_Tp, _CharT> _M_formatter;
5909 };
5910
5911 template<typename _CharT, typename... _Tps>
5912 class __tuple_formatter
5913 {
5914 using _String_view = basic_string_view<_CharT>;
5915 using _Seps = __format::_Separators<_CharT>;
5916
5917 public:
5918 constexpr void
5919 set_separator(basic_string_view<_CharT> __sep) noexcept
5920 { _M_sep = __sep; }
5921
5922 constexpr void
5923 set_brackets(basic_string_view<_CharT> __open,
5924 basic_string_view<_CharT> __close) noexcept
5925 {
5926 _M_open = __open;
5927 _M_close = __close;
5928 }
5929
5930 // We deviate from standard, that declares this as template accepting
5931 // unconstrained ParseContext type, which seems unimplementable.
5932 constexpr typename basic_format_parse_context<_CharT>::iterator
5933 parse(basic_format_parse_context<_CharT>& __pc)
5934 {
5935 auto __first = __pc.begin();
5936 const auto __last = __pc.end();
5937 __format::_Spec<_CharT> __spec{};
5938
5939 auto __finished = [&]
5940 {
5941 if (__first != __last && *__first != '}')
5942 return false;
5943
5944 _M_spec = __spec;
5945 _M_felems._M_parse();
5946 _M_felems.set_debug_format();
5947 return true;
5948 };
5949
5950 if (__finished())
5951 return __first;
5952
5953 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5954 if (__finished())
5955 return __first;
5956
5957 __first = __spec._M_parse_width(__first, __last, __pc);
5958 if (__finished())
5959 return __first;
5960
5961 if (*__first == 'n')
5962 {
5963 ++__first;
5964 _M_open = _M_close = _String_view();
5965 }
5966 else if (*__first == 'm')
5967 {
5968 ++__first;
5969 if constexpr (sizeof...(_Tps) == 2)
5970 {
5971 _M_sep = _Seps::_S_colon();
5972 _M_open = _M_close = _String_view();
5973 }
5974 else
5975 __throw_format_error("format error: 'm' specifier requires range"
5976 " of pair or tuple of two elements");
5977 }
5978
5979 if (__finished())
5980 return __first;
5981
5982 __format::__failed_to_parse_format_spec();
5983 }
5984
5985 protected:
5986 template<typename _Tuple, typename _Out, size_t... _Ids>
5987 _GLIBCXX_CONSTEXPR_FORMAT
5988 typename basic_format_context<_Out, _CharT>::iterator
5989 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5990 basic_format_context<_Out, _CharT>& __fc) const
5991 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5992
5993 template<typename _Out>
5994 _GLIBCXX_CONSTEXPR_FORMAT
5995 typename basic_format_context<_Out, _CharT>::iterator
5996 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5997 basic_format_context<_Out, _CharT>& __fc) const
5998 {
5999 return __format::__format_padded(
6000 __fc, _M_spec,
6001 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
6002 {
6003 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
6004 _M_felems._M_format(__elems..., __nfc, _M_sep);
6005 return __format::__write(__nfc.out(), _M_close);
6006 });
6007 }
6008
6009 private:
6010 template<size_t... _Ids>
6011 struct __formatters_storage
6012 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
6013 {
6014 template<size_t _Id, typename _Up>
6015 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
6016
6017 constexpr void
6018 _M_parse()
6019 {
6020 (_Base<_Ids, _Tps>::_M_parse(), ...);
6021 }
6022
6023 template<typename _Out>
6024 _GLIBCXX_CONSTEXPR_FORMAT void
6025 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
6026 basic_format_context<_Out, _CharT>& __fc,
6027 _String_view __sep) const
6028 {
6029 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
6030 }
6031
6032 constexpr void
6033 set_debug_format()
6034 {
6035 (_Base<_Ids, _Tps>::set_debug_format(), ...);
6036 }
6037 };
6038
6039 template<size_t... _Ids>
6040 static _GLIBCXX_CONSTEXPR_FORMAT auto
6041 _S_create_storage(index_sequence<_Ids...>)
6042 -> __formatters_storage<_Ids...>;
6043 using _Formatters
6044 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
6045
6046 _Spec<_CharT> _M_spec{};
6047 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
6048 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
6049 _String_view _M_sep = _Seps::_S_comma();
6050 _Formatters _M_felems;
6051 };
6052
6053 template<typename _Tp>
6054 concept __is_map_formattable
6055 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
6056
6057} // namespace __format
6058/// @endcond
6059
6060 // [format.tuple] Tuple formatter
6061 template<__format::__char _CharT, formattable<_CharT> _Fp,
6062 formattable<_CharT> _Sp>
6063 struct formatter<pair<_Fp, _Sp>, _CharT>
6064 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
6065 remove_cvref_t<_Sp>>
6066 {
6067 private:
6068 using __maybe_const_pair
6069 = __conditional_t<formattable<const _Fp, _CharT>
6070 && formattable<const _Sp, _CharT>,
6071 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
6072 public:
6073 // We deviate from standard, that declares this as template accepting
6074 // unconstrained FormatContext type, which seems unimplementable.
6075 template<typename _Out>
6076 _GLIBCXX_CONSTEXPR_FORMAT
6077 typename basic_format_context<_Out, _CharT>::iterator
6078 format(__maybe_const_pair& __p,
6079 basic_format_context<_Out, _CharT>& __fc) const
6080 { return this->_M_format_elems(__p.first, __p.second, __fc); }
6081 };
6082
6083#if __glibcxx_print >= 202406L
6084 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6085 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6086 template<typename _Fp, typename _Sp>
6087 constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
6088 = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
6089 && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
6090#endif
6091
6092 template<__format::__char _CharT, formattable<_CharT>... _Tps>
6093 struct formatter<tuple<_Tps...>, _CharT>
6094 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
6095 {
6096 private:
6097 using __maybe_const_tuple
6098 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
6099 const tuple<_Tps...>, tuple<_Tps...>>;
6100 public:
6101 // We deviate from standard, that declares this as template accepting
6102 // unconstrained FormatContext type, which seems unimplementable.
6103 template<typename _Out>
6104 _GLIBCXX_CONSTEXPR_FORMAT
6105 typename basic_format_context<_Out, _CharT>::iterator
6106 format(__maybe_const_tuple& __t,
6107 basic_format_context<_Out, _CharT>& __fc) const
6108 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
6109 };
6110
6111#if __glibcxx_print >= 202406L
6112 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6113 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6114 template<typename... _Tps>
6115 constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
6116 = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
6117#endif
6118
6119 // [format.range.formatter], class template range_formatter
6120 template<typename _Tp, __format::__char _CharT>
6121 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
6122 class range_formatter
6123 {
6124 using _String_view = basic_string_view<_CharT>;
6125 using _Seps = __format::_Separators<_CharT>;
6126
6127 public:
6128 constexpr void
6129 set_separator(basic_string_view<_CharT> __sep) noexcept
6130 { _M_sep = __sep; }
6131
6132 constexpr void
6133 set_brackets(basic_string_view<_CharT> __open,
6134 basic_string_view<_CharT> __close) noexcept
6135 {
6136 _M_open = __open;
6137 _M_close = __close;
6138 }
6139
6140 constexpr formatter<_Tp, _CharT>&
6141 underlying() noexcept
6142 { return _M_fval; }
6143
6144 constexpr const formatter<_Tp, _CharT>&
6145 underlying() const noexcept
6146 { return _M_fval; }
6147
6148 // We deviate from standard, that declares this as template accepting
6149 // unconstrained ParseContext type, which seems unimplementable.
6150 constexpr typename basic_format_parse_context<_CharT>::iterator
6151 parse(basic_format_parse_context<_CharT>& __pc)
6152 {
6153 auto __first = __pc.begin();
6154 const auto __last = __pc.end();
6155 __format::_Spec<_CharT> __spec{};
6156 bool __no_brace = false;
6157
6158 auto __finished = [&]
6159 { return __first == __last || *__first == '}'; };
6160
6161 auto __finalize = [&]
6162 {
6163 _M_spec = __spec;
6164 return __first;
6165 };
6166
6167 auto __parse_val = [&](_String_view __nfs = _String_view())
6168 {
6169 basic_format_parse_context<_CharT> __npc(__nfs);
6170 if (_M_fval.parse(__npc) != __npc.end())
6171 __format::__failed_to_parse_format_spec();
6172 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
6173 _M_fval.set_debug_format();
6174 return __finalize();
6175 };
6176
6177 if (__finished())
6178 return __parse_val();
6179
6180 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6181 if (__finished())
6182 return __parse_val();
6183
6184 __first = __spec._M_parse_width(__first, __last, __pc);
6185 if (__finished())
6186 return __parse_val();
6187
6188 if (*__first == '?')
6189 {
6190 ++__first;
6191 __spec._M_debug = true;
6192 if (__finished() || *__first != 's')
6193 __throw_format_error("format error: '?' is allowed only in"
6194 " combination with 's'");
6195 }
6196
6197 if (*__first == 's')
6198 {
6199 ++__first;
6200 if constexpr (same_as<_Tp, _CharT>)
6201 {
6202 __spec._M_type = __format::_Pres_s;
6203 if (__finished())
6204 return __finalize();
6205 __throw_format_error("format error: element format specifier"
6206 " cannot be provided when 's' specifier is used");
6207 }
6208 else
6209 __throw_format_error("format error: 's' specifier requires"
6210 " range of character types");
6211 }
6212
6213 if (__finished())
6214 return __parse_val();
6215
6216 if (*__first == 'n')
6217 {
6218 ++__first;
6219 _M_open = _M_close = _String_view();
6220 __no_brace = true;
6221 }
6222
6223 if (__finished())
6224 return __parse_val();
6225
6226 if (*__first == 'm')
6227 {
6228 _String_view __m(__first, 1);
6229 ++__first;
6230 if constexpr (__format::__is_map_formattable<_Tp>)
6231 {
6232 _M_sep = _Seps::_S_comma();
6233 if (!__no_brace)
6234 {
6235 _M_open = _Seps::_S_braces().substr(0, 1);
6236 _M_close = _Seps::_S_braces().substr(1, 1);
6237 }
6238 if (__finished())
6239 return __parse_val(__m);
6240 __throw_format_error("format error: element format specifier"
6241 " cannot be provided when 'm' specifier is used");
6242 }
6243 else
6244 __throw_format_error("format error: 'm' specifier requires"
6245 " range of pairs or tuples of two elements");
6246 }
6247
6248 if (__finished())
6249 return __parse_val();
6250
6251 if (*__first == ':')
6252 {
6253 __pc.advance_to(++__first);
6254 __first = _M_fval.parse(__pc);
6255 }
6256
6257 if (__finished())
6258 return __finalize();
6259
6260 __format::__failed_to_parse_format_spec();
6261 }
6262
6263 // We deviate from standard, that declares this as template accepting
6264 // unconstrained FormatContext type, which seems unimplementable.
6265 template<ranges::input_range _Rg, typename _Out>
6266 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6267 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6268 _GLIBCXX_CONSTEXPR_FORMAT
6269 typename basic_format_context<_Out, _CharT>::iterator
6270 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6271 {
6272 using _Range = remove_reference_t<_Rg>;
6273 if constexpr (ranges::contiguous_range<_Rg>)
6274 {
6275 const span<__format::__maybe_const<_Tp, _CharT>>
6276 __spn(ranges::data(__rg), size_t(ranges::distance(__rg)));
6277 return _M_format(__spn, __fc);
6278 }
6279 else if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6280 return _M_format<const _Range>(__rg, __fc);
6281 else
6282 return _M_format(__rg, __fc);
6283 }
6284
6285 private:
6286 template<ranges::input_range _Rg, typename _Out>
6287 _GLIBCXX_CONSTEXPR_FORMAT
6288 typename basic_format_context<_Out, _CharT>::iterator
6289 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6290 {
6291 if constexpr (same_as<_Tp, _CharT>)
6292 if (_M_spec._M_type == __format::_Pres_s)
6293 {
6294 __format::__formatter_str __fstr(_M_spec);
6295 return __fstr._M_format_range(__rg, __fc);
6296 }
6297 return __format::__format_padded(
6298 __fc, _M_spec,
6299 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6300 { return _M_format_elems(__rg, __nfc); });
6301 }
6302
6303
6304 template<ranges::input_range _Rg, typename _Out>
6305 _GLIBCXX_CONSTEXPR_FORMAT
6306 typename basic_format_context<_Out, _CharT>::iterator
6307 _M_format_elems(_Rg& __rg,
6308 basic_format_context<_Out, _CharT>& __fc) const
6309 {
6310 auto __out = __format::__write(__fc.out(), _M_open);
6311
6312 auto __first = ranges::begin(__rg);
6313 auto const __last = ranges::end(__rg);
6314 if (__first == __last)
6315 return __format::__write(__out, _M_close);
6316
6317 __fc.advance_to(__out);
6318 __out = _M_fval.format(*__first, __fc);
6319 for (++__first; __first != __last; ++__first)
6320 {
6321 __out = __format::__write(__out, _M_sep);
6322 __fc.advance_to(__out);
6323 __out = _M_fval.format(*__first, __fc);
6324 }
6325
6326 return __format::__write(__out, _M_close);
6327 }
6328
6329 __format::_Spec<_CharT> _M_spec{};
6330 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6331 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6332 _String_view _M_sep = _Seps::_S_comma();
6333 formatter<_Tp, _CharT> _M_fval;
6334 };
6335
6336 // In standard this is shown as inheriting from specialization of
6337 // exposition only specialization for range-default-formatter for
6338 // each range_format. We opt for simpler implementation.
6339 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6340 // specializations for maps, sets, and strings
6341 template<ranges::input_range _Rg, __format::__char _CharT>
6342 requires (format_kind<_Rg> != range_format::disabled)
6343 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6344 struct formatter<_Rg, _CharT>
6345 {
6346 private:
6347 static const bool _S_range_format_is_string =
6348 (format_kind<_Rg> == range_format::string)
6349 || (format_kind<_Rg> == range_format::debug_string);
6350 using _Vt = remove_cvref_t<
6351 ranges::range_reference_t<
6352 __format::__maybe_const_range<_Rg, _CharT>>>;
6353
6354 static consteval bool _S_is_correct()
6355 {
6356 if constexpr (_S_range_format_is_string)
6357 static_assert(same_as<_Vt, _CharT>);
6358 return true;
6359 }
6360
6361 static_assert(_S_is_correct());
6362
6363 public:
6364 constexpr formatter() noexcept
6365 {
6366 using _Seps = __format::_Separators<_CharT>;
6367 if constexpr (format_kind<_Rg> == range_format::map)
6368 {
6369 static_assert(__format::__is_map_formattable<_Vt>);
6370 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6371 _Seps::_S_braces().substr(1, 1));
6372 _M_under.underlying().set_brackets({}, {});
6373 _M_under.underlying().set_separator(_Seps::_S_colon());
6374 }
6375 else if constexpr (format_kind<_Rg> == range_format::set)
6376 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6377 _Seps::_S_braces().substr(1, 1));
6378 }
6379
6380 constexpr void
6381 set_separator(basic_string_view<_CharT> __sep) noexcept
6382 requires (format_kind<_Rg> == range_format::sequence)
6383 { _M_under.set_separator(__sep); }
6384
6385 constexpr void
6386 set_brackets(basic_string_view<_CharT> __open,
6387 basic_string_view<_CharT> __close) noexcept
6388 requires (format_kind<_Rg> == range_format::sequence)
6389 { _M_under.set_brackets(__open, __close); }
6390
6391 // We deviate from standard, that declares this as template accepting
6392 // unconstrained ParseContext type, which seems unimplementable.
6393 constexpr typename basic_format_parse_context<_CharT>::iterator
6394 parse(basic_format_parse_context<_CharT>& __pc)
6395 {
6396 auto __res = _M_under.parse(__pc);
6397 if constexpr (format_kind<_Rg> == range_format::debug_string)
6398 _M_under.set_debug_format();
6399 return __res;
6400 }
6401
6402 // We deviate from standard, that declares this as template accepting
6403 // unconstrained FormatContext type, which seems unimplementable.
6404 template<typename _Out>
6405 _GLIBCXX_CONSTEXPR_FORMAT
6406 typename basic_format_context<_Out, _CharT>::iterator
6407 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6408 basic_format_context<_Out, _CharT>& __fc) const
6409 {
6410 if constexpr (_S_range_format_is_string)
6411 return _M_under._M_format_range(__rg, __fc);
6412 else
6413 return _M_under.format(__rg, __fc);
6414 }
6415
6416 private:
6417 using _Formatter_under
6418 = __conditional_t<_S_range_format_is_string,
6419 __format::__formatter_str<_CharT>,
6420 range_formatter<_Vt, _CharT>>;
6421 _Formatter_under _M_under;
6422 };
6423
6424#if __glibcxx_print >= 202406L
6425 template<ranges::input_range _Rg>
6426 requires (format_kind<_Rg> != range_format::disabled)
6427 constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6428#endif
6429
6430#endif // C++23 formatting ranges
6431#undef _GLIBCXX_WIDEN
6432#undef _GLIBCXX_CONSTEXPR_FORMAT
6433
6434_GLIBCXX_END_NAMESPACE_VERSION
6435} // namespace std
6436#endif // __cpp_lib_format
6437#pragma GCC diagnostic pop
6438#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:113
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