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