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