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