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