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