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