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