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