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