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