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