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