1 // <format> Formatting -*- C++ -*-
3 // Copyright The GNU Toolchain Authors.
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)
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.
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.
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/>.
25 /** @file include/format
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_FORMAT
30 #define _GLIBCXX_FORMAT 1
32 #ifdef _GLIBCXX_SYSHDR
33 #pragma GCC system_header
36 #include <bits/requires_hosted.h> // for std::string
38 #define __glibcxx_want_format
39 #define __glibcxx_want_format_ranges
40 #define __glibcxx_want_format_uchar
41 #define __glibcxx_want_constexpr_exceptions
42 #include <bits/version.h>
44 #ifdef __cpp_lib_format // C++ >= 20 && HOSTED
53 #include <string_view>
55 #include <bits/monostate.h>
56 #include <bits/formatfwd.h>
57 #include <bits/ranges_base.h> // input_range, range_reference_t
58 #include <bits/ranges_util.h> // subrange
59 #include <bits/ranges_algobase.h> // ranges::copy
60 #include <bits/stl_iterator.h> // counted_iterator
61 #include <bits/stl_pair.h> // __is_pair
62 #include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
63 #include <bits/utility.h> // tuple_size_v
64 #include <ext/numeric_traits.h> // __int_traits
66 #if !__has_builtin(__builtin_toupper)
70 #pragma GCC diagnostic push
71 #pragma GCC diagnostic ignored "-Wpedantic" // __int128
72 #pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
74 namespace std _GLIBCXX_VISIBILITY(default)
76 _GLIBCXX_BEGIN_NAMESPACE_VERSION
78 // [format.fmt.string], class template basic_format_string
79 template<typename _CharT, typename... _Args> struct basic_format_string;
81 /// @cond undocumented
84 // STATICALLY-WIDEN, see C++20 [time.general]
85 // It doesn't matter for format strings (which can only be char or wchar_t)
86 // but this returns the narrow string for anything that isn't wchar_t. This
87 // is done because const char* can be inserted into any ostream type, and
88 // will be widened at runtime if necessary.
89 template<typename _CharT>
91 _Widen(const char* __narrow, const wchar_t* __wide)
93 if constexpr (is_same_v<_CharT, wchar_t>)
98 #define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
99 #define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
101 // Size for stack located buffer
102 template<typename _CharT>
103 constexpr size_t __stackbuf_size = 32 * sizeof(void*) / sizeof(_CharT);
105 // Type-erased character sinks.
106 template<typename _CharT> class _Sink;
107 template<typename _CharT> class _Fixedbuf_sink;
108 template<typename _Out, typename _CharT> class _Padding_sink;
109 template<typename _Out, typename _CharT> class _Escaping_sink;
111 // Output iterator that writes to a type-erase character sink.
112 template<typename _CharT>
115 // Output iterator that ignores the characters
116 template<typename _CharT>
119 // An unspecified output iterator type used in the `formattable` concept.
120 template<typename _CharT>
122 { using type = _Drop_iter<_CharT>; };
124 template<typename _CharT>
125 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
127 template<typename _CharT>
128 struct _Dynamic_format_string
130 [[__gnu__::__always_inline__]]
131 _Dynamic_format_string(basic_string_view<_CharT> __s) noexcept
134 _Dynamic_format_string(const _Dynamic_format_string&) = delete;
135 void operator=(const _Dynamic_format_string&) = delete;
138 basic_string_view<_CharT> _M_str;
140 template<typename, typename...> friend struct std::basic_format_string;
143 } // namespace __format
146 using format_context = __format::__format_context<char>;
147 #ifdef _GLIBCXX_USE_WCHAR_T
148 using wformat_context = __format::__format_context<wchar_t>;
151 // [format.args], class template basic_format_args
152 template<typename _Context> class basic_format_args;
153 using format_args = basic_format_args<format_context>;
154 #ifdef _GLIBCXX_USE_WCHAR_T
155 using wformat_args = basic_format_args<wformat_context>;
158 // [format.arguments], arguments
159 // [format.arg], class template basic_format_arg
160 template<typename _Context>
161 class basic_format_arg;
163 /** A compile-time checked format string for the specified argument types.
165 * @since C++23 but available as an extension in C++20.
167 template<typename _CharT, typename... _Args>
168 struct basic_format_string
170 template<typename _Tp>
171 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
173 basic_format_string(const _Tp& __s);
175 [[__gnu__::__always_inline__]]
176 basic_format_string(__format::_Dynamic_format_string<_CharT> __s) noexcept
180 [[__gnu__::__always_inline__]]
181 constexpr basic_string_view<_CharT>
186 basic_string_view<_CharT> _M_str;
189 template<typename... _Args>
190 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
192 #ifdef _GLIBCXX_USE_WCHAR_T
193 template<typename... _Args>
195 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
198 #if __cpp_lib_format >= 202603L // >= C++26
199 [[__gnu__::__always_inline__]]
200 inline __format::_Dynamic_format_string<char>
201 dynamic_format(string_view __fmt) noexcept
204 #ifdef _GLIBCXX_USE_WCHAR_T
205 [[__gnu__::__always_inline__]]
206 inline __format::_Dynamic_format_string<wchar_t>
207 dynamic_format(wstring_view __fmt) noexcept
212 // [format.formatter], formatter
214 /// The primary template of std::formatter is disabled.
215 template<typename _Tp, typename _CharT>
218 formatter() = delete; // No std::formatter specialization for this type.
219 formatter(const formatter&) = delete;
220 formatter& operator=(const formatter&) = delete;
223 #if __cpp_lib_constexpr_exceptions >= 202502L
224 #define _GLIBCXX_CONSTEXPR_FORMAT_ERROR constexpr
226 #define _GLIBCXX_CONSTEXPR_FORMAT_ERROR
229 // [format.error], class format_error
230 class format_error : public runtime_error
233 _GLIBCXX_CONSTEXPR_FORMAT_ERROR explicit format_error(const string& __what)
234 : runtime_error(__what) { }
235 _GLIBCXX_CONSTEXPR_FORMAT_ERROR explicit format_error(const char* __what)
236 : runtime_error(__what) { }
239 /// @cond undocumented
242 __throw_format_error(const char* __what)
243 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
245 #undef _GLIBCXX_CONSTEXPR_FORMAT_ERROR
249 // XXX use named functions for each constexpr error?
253 __unmatched_left_brace_in_format_string()
254 { __throw_format_error("format error: unmatched '{' in format string"); }
258 __unmatched_right_brace_in_format_string()
259 { __throw_format_error("format error: unmatched '}' in format string"); }
263 __conflicting_indexing_in_format_string()
264 { __throw_format_error("format error: conflicting indexing style in format string"); }
268 __invalid_arg_id_in_format_string()
269 { __throw_format_error("format error: invalid arg-id in format string"); }
273 __failed_to_parse_format_spec()
274 { __throw_format_error("format error: failed to parse format-spec"); }
276 template<typename _CharT> class _Scanner;
278 } // namespace __format
281 // [format.parse.ctx], class template basic_format_parse_context
282 template<typename _CharT> class basic_format_parse_context;
283 using format_parse_context = basic_format_parse_context<char>;
284 #ifdef _GLIBCXX_USE_WCHAR_T
285 using wformat_parse_context = basic_format_parse_context<wchar_t>;
288 template<typename _CharT>
289 class basic_format_parse_context
292 using char_type = _CharT;
293 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
294 using iterator = const_iterator;
297 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
298 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
301 basic_format_parse_context(const basic_format_parse_context&) = delete;
302 void operator=(const basic_format_parse_context&) = delete;
304 constexpr const_iterator begin() const noexcept { return _M_begin; }
305 constexpr const_iterator end() const noexcept { return _M_end; }
308 advance_to(const_iterator __it) noexcept
314 if (_M_indexing == _Manual)
315 __format::__conflicting_indexing_in_format_string();
318 // _GLIBCXX_RESOLVE_LIB_DEFECTS
319 // 3825. Missing compile-time argument id check in next_arg_id
320 if (std::is_constant_evaluated())
321 if (_M_next_arg_id == _M_num_args)
322 __format::__invalid_arg_id_in_format_string();
323 return _M_next_arg_id++;
327 check_arg_id(size_t __id)
329 if (_M_indexing == _Auto)
330 __format::__conflicting_indexing_in_format_string();
331 _M_indexing = _Manual;
333 if (std::is_constant_evaluated())
334 if (__id >= _M_num_args)
335 __format::__invalid_arg_id_in_format_string();
338 #if __cpp_lib_format >= 202305L
339 template<typename... _Ts>
341 check_dynamic_spec(size_t __id) noexcept
343 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
344 "template arguments for check_dynamic_spec<Ts...>(id) "
345 "must be unique and must be one of the allowed types");
347 __check_dynamic_spec<_Ts...>(__id);
352 check_dynamic_spec_integral(size_t __id) noexcept
355 __check_dynamic_spec<int, unsigned, long long,
356 unsigned long long>(__id);
361 check_dynamic_spec_string(size_t __id) noexcept
364 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
369 // True if _Tp occurs exactly once in _Ts.
370 template<typename _Tp, typename... _Ts>
371 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
373 template<typename... _Ts>
375 __valid_types_for_check_dynamic_spec()
377 // _GLIBCXX_RESOLVE_LIB_DEFECTS
378 // 4142. check_dynamic_spec should require at least one type
379 if constexpr (sizeof...(_Ts) == 0)
383 // The types in Ts... are unique. Each type in Ts... is one of
384 // bool, char_type, int, unsigned int, long long int,
385 // unsigned long long int, float, double, long double,
386 // const char_type*, basic_string_view<char_type>, or const void*.
388 = __once<bool, _Ts...>
389 + __once<char_type, _Ts...>
390 + __once<int, _Ts...>
391 + __once<unsigned int, _Ts...>
392 + __once<long long int, _Ts...>
393 + __once<unsigned long long int, _Ts...>
394 + __once<float, _Ts...>
395 + __once<double, _Ts...>
396 + __once<long double, _Ts...>
397 + __once<const char_type*, _Ts...>
398 + __once<basic_string_view<char_type>, _Ts...>
399 + __once<const void*, _Ts...>;
400 return __sum == sizeof...(_Ts);
404 template<typename... _Ts>
406 __check_dynamic_spec(size_t __id) noexcept;
408 // This must not be constexpr.
409 static void __invalid_dynamic_spec(const char*);
411 friend __format::_Scanner<_CharT>;
414 // This constructor should only be used by the implementation.
416 basic_format_parse_context(basic_string_view<_CharT> __fmt,
417 size_t __num_args) noexcept
418 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
424 enum _Indexing { _Unknown, _Manual, _Auto };
425 _Indexing _M_indexing = _Unknown;
426 size_t _M_next_arg_id = 0;
427 size_t _M_num_args = 0;
430 /// @cond undocumented
431 template<typename _Tp, template<typename...> class _Class>
432 constexpr bool __is_specialization_of = false;
433 template<template<typename...> class _Class, typename... _Args>
434 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
438 // pre: first != last
439 template<typename _CharT>
440 constexpr pair<unsigned short, const _CharT*>
441 __parse_integer(const _CharT* __first, const _CharT* __last)
443 if (__first == __last)
444 __builtin_unreachable();
446 if constexpr (is_same_v<_CharT, char>)
448 const auto __start = __first;
449 unsigned short __val = 0;
450 // N.B. std::from_chars is not constexpr in C++20.
451 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
452 && __first != __start) [[likely]]
453 return {__val, __first};
457 constexpr int __n = 32;
459 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
460 __buf[__i] = __first[__i];
461 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
462 if (__ptr) [[likely]]
463 return {__v, __first + (__ptr - __buf)};
468 template<typename _CharT>
469 constexpr pair<unsigned short, const _CharT*>
470 __parse_arg_id(const _CharT* __first, const _CharT* __last)
472 if (__first == __last)
473 __builtin_unreachable();
476 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
478 if ('1' <= *__first && *__first <= '9')
480 const unsigned short __id = *__first - '0';
481 const auto __next = __first + 1;
482 // Optimize for most likely case of single digit arg-id.
483 if (__next == __last || !('0' <= *__next && *__next <= '9'))
484 return {__id, __next};
486 return __format::__parse_integer(__first, __last);
491 enum class _Pres_type : unsigned char {
492 _Pres_none = 0, // Default type (not valid for integer presentation types).
493 _Pres_s = 1, // For strings, bool, ranges
494 // Presentation types for integral types (including bool and charT).
495 _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
496 // Presentation types for floating-point types
497 _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
501 using enum _Pres_type;
503 enum class _Sign : unsigned char {
506 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
511 enum _WidthPrec : unsigned char {
512 _WP_none, // No width/prec specified.
513 _WP_value, // Fixed width/prec specified.
514 _WP_from_arg // Use a formatting argument for width/prec.
516 using enum _WidthPrec;
518 template<typename _Context>
520 __int_from_arg(const basic_format_arg<_Context>& __arg);
522 constexpr bool __is_digit(char __c)
523 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
525 constexpr bool __is_xdigit(char __c)
526 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
528 // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
529 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
533 template<typename _CharT>
534 struct _Spec : _SpecBase
536 unsigned short _M_width;
537 unsigned short _M_prec;
538 char32_t _M_fill = ' ';
542 unsigned _M_localized : 1;
543 unsigned _M_zero_fill : 1;
544 _WidthPrec _M_width_kind : 2;
545 _WidthPrec _M_prec_kind : 2;
546 unsigned _M_debug : 1;
547 _Pres_type _M_type : 4;
548 unsigned _M_reserved : 8;
549 // This class has 8 bits of tail padding, that can be used by
552 using iterator = typename basic_string_view<_CharT>::iterator;
554 static constexpr _Align
555 _S_align(_CharT __c) noexcept
559 case '<': return _Align_left;
560 case '>': return _Align_right;
561 case '^': return _Align_centre;
562 default: return _Align_default;
566 // pre: __first != __last
568 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
569 { return _M_parse_fill_and_align(__first, __last, "{"); }
571 // pre: __first != __last
573 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
575 for (char __c : __not_fill)
576 if (*__first == static_cast<_CharT>(__c))
579 using namespace __unicode;
580 if constexpr (__literal_encoding_is_unicode<_CharT>())
582 // Accept any UCS scalar value as fill character.
583 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
586 auto __beg = __uv.begin();
587 char32_t __c = *__beg++;
588 if (__is_scalar_value(__c))
589 if (auto __next = __beg.base(); __next != __last)
590 if (_Align __align = _S_align(*__next); __align != _Align_default)
598 else if (__last - __first >= 2)
599 if (_Align __align = _S_align(__first[1]); __align != _Align_default)
606 if (_Align __align = _S_align(__first[0]); __align != _Align_default)
615 static constexpr _Sign
616 _S_sign(_CharT __c) noexcept
620 case '+': return _Sign_plus;
621 case '-': return _Sign_minus;
622 case ' ': return _Sign_space;
623 default: return _Sign_default;
627 // pre: __first != __last
629 _M_parse_sign(iterator __first, iterator) noexcept
631 if (_Sign __sign = _S_sign(*__first); __sign != _Sign_default)
639 // pre: *__first is valid
641 _M_parse_alternate_form(iterator __first, iterator) noexcept
651 // pre: __first != __last
653 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
663 // pre: __first != __last
664 static constexpr iterator
665 _S_parse_width_or_precision(iterator __first, iterator __last,
666 unsigned short& __val, bool& __arg_id,
667 basic_format_parse_context<_CharT>& __pc)
669 if (__format::__is_digit(*__first))
671 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
673 __throw_format_error("format error: invalid width or precision "
678 else if (*__first == '{')
682 if (__first == __last)
683 __format::__unmatched_left_brace_in_format_string();
685 __val = __pc.next_arg_id();
688 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
689 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
690 __format::__invalid_arg_id_in_format_string();
692 __pc.check_arg_id(__v);
695 #if __cpp_lib_format >= 202305L
696 __pc.check_dynamic_spec_integral(__val);
698 ++__first; // past the '}'
703 // pre: __first != __last
705 _M_parse_width(iterator __first, iterator __last,
706 basic_format_parse_context<_CharT>& __pc)
708 bool __arg_id = false;
710 __throw_format_error("format error: width must be non-zero in "
712 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
714 if (__next != __first)
715 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
719 // pre: __first != __last
721 _M_parse_precision(iterator __first, iterator __last,
722 basic_format_parse_context<_CharT>& __pc)
724 if (__first[0] != '.')
727 iterator __next = ++__first;
728 bool __arg_id = false;
729 if (__next != __last)
730 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
732 if (__next == __first)
733 __throw_format_error("format error: missing precision after '.' in "
735 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
739 // pre: __first != __last
741 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
751 template<typename _Context>
753 _M_get_width(_Context& __ctx) const
756 if (_M_width_kind == _WP_value)
758 else if (_M_width_kind == _WP_from_arg)
759 __width = __format::__int_from_arg(__ctx.arg(_M_width));
763 template<typename _Context>
765 _M_get_precision(_Context& __ctx) const
768 if (_M_prec_kind == _WP_value)
770 else if (_M_prec_kind == _WP_from_arg)
771 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
776 template<typename _Int>
778 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
782 else if (__sign == _Sign_plus)
784 else if (__sign == _Sign_space)
791 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
792 template<typename _Out, typename _CharT>
793 requires output_iterator<_Out, const _CharT&>
795 __write(_Out __out, basic_string_view<_CharT> __str)
797 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
803 for (_CharT __c : __str)
808 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
809 // pre: __align != _Align_default
810 template<typename _Out, typename _CharT>
812 __write_padded(_Out __out, basic_string_view<_CharT> __str,
813 _Align __align, size_t __nfill, char32_t __fill_char)
815 const size_t __buflen = 0x20;
816 _CharT __padding_chars[__buflen];
817 __padding_chars[0] = _CharT();
818 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
820 auto __pad = [&__padding] (size_t __n, _Out& __o) {
823 while (__n > __padding.size())
825 __o = __format::__write(std::move(__o), __padding);
826 __n -= __padding.size();
829 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
832 size_t __l, __r, __max;
833 if (__align == _Align_centre)
836 __r = __l + (__nfill & 1);
839 else if (__align == _Align_right)
852 using namespace __unicode;
853 if constexpr (__literal_encoding_is_unicode<_CharT>())
854 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
856 // Encode fill char as multiple code units of type _CharT.
857 const char32_t __arr[1]{ __fill_char };
858 _Utf_view<_CharT, span<const char32_t, 1>> __v(__arr);
859 basic_string<_CharT> __padstr(__v.begin(), __v.end());
860 __padding = __padstr;
862 __out = __format::__write(std::move(__out), __padding);
863 __out = __format::__write(std::move(__out), __str);
865 __out = __format::__write(std::move(__out), __padding);
869 if (__max < __buflen)
870 __padding.remove_suffix(__buflen - __max);
874 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
876 __out = __format::__write(std::move(__out), __str);
882 // Write STR to OUT, with alignment and padding as determined by SPEC.
883 // pre: __spec._M_align != _Align_default || __align != _Align_default
884 template<typename _CharT, typename _Out>
886 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
887 size_t __estimated_width,
888 basic_format_context<_Out, _CharT>& __fc,
889 const _Spec<_CharT>& __spec,
890 _Align __align = _Align_left)
892 size_t __width = __spec._M_get_width(__fc);
894 if (__width <= __estimated_width)
895 return __format::__write(__fc.out(), __str);
897 const size_t __nfill = __width - __estimated_width;
899 if (__spec._M_align != _Align_default)
900 __align = __spec._M_align;
902 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
906 template<typename _CharT>
908 __truncate(basic_string_view<_CharT>& __s, size_t __prec)
910 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
912 if (__prec != (size_t)-1)
913 return __unicode::__truncate(__s, __prec);
915 return __unicode::__field_width(__s);
919 __s = __s.substr(0, __prec);
924 enum class _Term_char : unsigned char {
929 using enum _Term_char;
931 template<typename _CharT>
934 using _Str_view = basic_string_view<_CharT>;
938 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
942 { return _S_all().substr(0, 3); }
945 _Str_view _S_newline()
946 { return _S_all().substr(3, 3); }
949 _Str_view _S_return()
950 { return _S_all().substr(6, 3); }
953 _Str_view _S_bslash()
954 { return _S_all().substr(9, 3); }
958 { return _S_all().substr(12, 3); }
962 { return _S_all().substr(15, 3); }
966 { return _S_all().substr(18, 2); }
970 { return _S_all().substr(20, 2); }
973 _Str_view _S_term(_Term_char __term)
980 return _S_quote().substr(0, 1);
982 return _S_apos().substr(0, 1);
984 __builtin_unreachable();
988 template<typename _CharT>
991 using _Str_view = basic_string_view<_CharT>;
995 { return _GLIBCXX_WIDEN("[]{}(), : "); }
998 _Str_view _S_squares()
999 { return _S_all().substr(0, 2); }
1002 _Str_view _S_braces()
1003 { return _S_all().substr(2, 2); }
1006 _Str_view _S_parens()
1007 { return _S_all().substr(4, 2); }
1010 _Str_view _S_comma()
1011 { return _S_all().substr(6, 2); }
1014 _Str_view _S_colon()
1015 { return _S_all().substr(8, 2); }
1018 template<typename _CharT>
1019 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1021 using _Esc = _Escapes<_CharT>;
1024 case _Esc::_S_tab()[0]:
1025 case _Esc::_S_newline()[0]:
1026 case _Esc::_S_return()[0]:
1027 case _Esc::_S_bslash()[0]:
1029 case _Esc::_S_quote()[0]:
1030 return __term == _Term_quote;
1031 case _Esc::_S_apos()[0]:
1032 return __term == _Term_apos;
1034 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1038 // @pre __c <= 0x10FFFF
1039 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1041 if (__unicode::__should_escape_category(__c))
1045 return __unicode::__grapheme_cluster_break_property(__c)
1046 == __unicode::_Gcb_property::_Gcb_Extend;
1049 using uint_least32_t = __UINT_LEAST32_TYPE__;
1050 template<typename _Out, typename _CharT>
1052 __write_escape_seq(_Out __out, uint_least32_t __val,
1053 basic_string_view<_CharT> __prefix)
1055 constexpr size_t __max = 8;
1057 const string_view __narrow(
1059 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1061 __out = __format::__write(__out, __prefix);
1062 *__out = _Separators<_CharT>::_S_braces()[0];
1064 if constexpr (is_same_v<char, _CharT>)
1065 __out = __format::__write(__out, __narrow);
1066 #ifdef _GLIBCXX_USE_WCHAR_T
1069 wchar_t __wbuf[__max];
1070 const size_t __n = __narrow.size();
1071 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1072 __out = __format::__write(__out, wstring_view(__wbuf, __n));
1075 *__out = _Separators<_CharT>::_S_braces()[1];
1079 template<typename _Out, typename _CharT>
1081 __write_escape_seqs(_Out __out, basic_string_view<_CharT> __units)
1083 using _UChar = make_unsigned_t<_CharT>;
1084 for (_CharT __c : __units)
1085 __out = __format::__write_escape_seq(
1086 __out, static_cast<_UChar>(__c), _Escapes<_CharT>::_S_x());
1090 template<typename _Out, typename _CharT>
1092 __write_escaped_char(_Out __out, _CharT __c)
1094 using _UChar = make_unsigned_t<_CharT>;
1095 using _Esc = _Escapes<_CharT>;
1098 case _Esc::_S_tab()[0]:
1099 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1100 case _Esc::_S_newline()[0]:
1101 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1102 case _Esc::_S_return()[0]:
1103 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1104 case _Esc::_S_bslash()[0]:
1105 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1106 case _Esc::_S_quote()[0]:
1107 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1108 case _Esc::_S_apos()[0]:
1109 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1111 return __format::__write_escape_seq(
1112 __out, static_cast<_UChar>(__c), _Esc::_S_u());
1116 template<typename _CharT, typename _Out>
1118 __write_escaped_ascii(_Out __out,
1119 basic_string_view<_CharT> __str,
1122 using _Str_view = basic_string_view<_CharT>;
1123 auto __first = __str.begin();
1124 auto const __last = __str.end();
1125 while (__first != __last)
1127 auto __print = __first;
1128 // assume anything outside ASCII is printable
1129 while (__print != __last
1130 && !__format::__should_escape_ascii(*__print, __term))
1133 if (__print != __first)
1134 __out = __format::__write(__out, _Str_view(__first, __print));
1136 if (__print == __last)
1140 __out = __format::__write_escaped_char(__out, *__first);
1146 template<typename _CharT, typename _Out>
1148 __write_escaped_unicode_part(_Out __out, basic_string_view<_CharT>& __str,
1149 bool& __prev_esc, _Term_char __term)
1151 using _Str_view = basic_string_view<_CharT>;
1152 using _Esc = _Escapes<_CharT>;
1154 static constexpr char32_t __replace = U'\uFFFD';
1155 static constexpr _Str_view __replace_rep = []
1157 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1158 if constexpr (is_same_v<char, _CharT>)
1159 return "\xEF\xBF\xBD";
1164 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1167 auto __first = __v.begin();
1168 auto const __last = __v.end();
1169 while (__first != __last)
1171 bool __esc_ascii = false;
1172 bool __esc_unicode = false;
1173 bool __esc_replace = false;
1174 auto __should_escape = [&](auto const& __it)
1178 = __format::__should_escape_ascii(*__it.base(), __term);
1179 if (__format::__should_escape_unicode(*__it, __prev_esc))
1180 return __esc_unicode = true;
1181 if (*__it == __replace)
1183 _Str_view __units(__it.base(), __it._M_units());
1184 return __esc_replace = (__units != __replace_rep);
1189 auto __print = __first;
1190 while (__print != __last && !__should_escape(__print))
1196 if (__print != __first)
1197 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1199 if (__print == __last)
1204 __out = __format::__write_escaped_char(__out, *__first.base());
1205 else if (__esc_unicode)
1206 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1208 else if (_Str_view __units(__first.base(), __first._M_units());
1209 __units.end() != __last.base())
1210 __out = __format::__write_escape_seqs(__out, __units);
1224 template<typename _CharT, typename _Out>
1226 __write_escaped_unicode(_Out __out, basic_string_view<_CharT> __str,
1229 bool __prev_escape = true;
1230 __out = __format::__write_escaped_unicode_part(__out, __str,
1231 __prev_escape, __term);
1232 __out = __format::__write_escape_seqs(__out, __str);
1236 template<typename _CharT, typename _Out>
1238 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1240 __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1242 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1243 __out = __format::__write_escaped_unicode(__out, __str, __term);
1244 else if constexpr (is_same_v<char, _CharT>
1245 && __unicode::__literal_encoding_is_extended_ascii())
1246 __out = __format::__write_escaped_ascii(__out, __str, __term);
1248 // TODO Handle non-ascii extended encoding
1249 __out = __format::__write_escaped_ascii(__out, __str, __term);
1251 return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1254 // A lightweight optional<locale>.
1255 struct _Optional_locale
1257 [[__gnu__::__always_inline__]]
1258 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1260 _Optional_locale(const locale& __loc) noexcept
1261 : _M_loc(__loc), _M_hasval(true)
1264 _Optional_locale(const _Optional_locale& __l) noexcept
1265 : _M_dummy(), _M_hasval(__l._M_hasval)
1268 std::construct_at(&_M_loc, __l._M_loc);
1272 operator=(const _Optional_locale& __l) noexcept
1277 _M_loc = __l._M_loc;
1284 else if (__l._M_hasval)
1286 std::construct_at(&_M_loc, __l._M_loc);
1292 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1295 operator=(locale&& __loc) noexcept
1298 _M_loc = std::move(__loc);
1301 std::construct_at(&_M_loc, std::move(__loc));
1312 std::construct_at(&_M_loc);
1318 bool has_value() const noexcept { return _M_hasval; }
1321 char _M_dummy = '\0';
1324 bool _M_hasval = false;
1327 template<__char _CharT>
1328 struct __formatter_str
1330 __formatter_str() = default;
1333 __formatter_str(_Spec<_CharT> __spec) noexcept
1337 constexpr typename basic_format_parse_context<_CharT>::iterator
1338 parse(basic_format_parse_context<_CharT>& __pc)
1340 auto __first = __pc.begin();
1341 const auto __last = __pc.end();
1342 _Spec<_CharT> __spec{};
1344 auto __finalize = [this, &__spec] {
1348 auto __finished = [&] {
1349 if (__first == __last || *__first == '}')
1360 __first = __spec._M_parse_fill_and_align(__first, __last);
1364 __first = __spec._M_parse_width(__first, __last, __pc);
1368 __first = __spec._M_parse_precision(__first, __last, __pc);
1372 if (*__first == 's')
1374 __spec._M_type = _Pres_s;
1377 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1378 else if (*__first == '?')
1380 __spec._M_debug = true;
1388 __format::__failed_to_parse_format_spec();
1391 template<typename _Out>
1393 format(basic_string_view<_CharT> __s,
1394 basic_format_context<_Out, _CharT>& __fc) const
1396 if (_M_spec._M_debug)
1397 return _M_format_escaped(__s, __fc);
1399 if (_M_spec._M_width_kind == _WP_none
1400 && _M_spec._M_prec_kind == _WP_none)
1401 return __format::__write(__fc.out(), __s);
1403 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1404 const size_t __width = __format::__truncate(__s, __maxwidth);
1405 return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1408 template<typename _Out>
1410 _M_format_escaped(basic_string_view<_CharT> __s,
1411 basic_format_context<_Out, _CharT>& __fc) const
1413 const size_t __padwidth = _M_spec._M_get_width(__fc);
1414 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1415 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1417 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1418 const size_t __width = __truncate(__s, __maxwidth);
1419 // N.B. Escaping only increases width
1420 if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1421 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1423 // N.B. [tab:format.type.string] defines '?' as
1424 // Copies the escaped string ([format.string.escaped]) to the output,
1425 // so precision seem to appy to escaped string.
1426 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1427 __format::__write_escaped(__sink.out(), __s, _Term_quote);
1428 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1431 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1432 template<ranges::input_range _Rg, typename _Out>
1433 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1435 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1437 using _Range = remove_reference_t<_Rg>;
1438 using _String_view = basic_string_view<_CharT>;
1439 if constexpr (!is_lvalue_reference_v<_Rg>)
1440 return _M_format_range<_Range&>(__rg, __fc);
1441 else if constexpr (!is_const_v<_Range>
1442 && __simply_formattable_range<_Range, _CharT>)
1443 return _M_format_range<const _Range&>(__rg, __fc);
1444 else if constexpr (ranges::contiguous_range<_Rg>)
1446 _String_view __str(ranges::data(__rg),
1447 size_t(ranges::distance(__rg)));
1448 return format(__str, __fc);
1452 auto __handle_debug = [this, &__rg]<typename _NOut>(_NOut __nout)
1454 if (!_M_spec._M_debug)
1455 return ranges::copy(__rg, std::move(__nout)).out;
1457 _Escaping_sink<_NOut, _CharT>
1458 __sink(std::move(__nout), _Term_quote);
1459 ranges::copy(__rg, __sink.out());
1460 return __sink._M_finish();
1463 const size_t __padwidth = _M_spec._M_get_width(__fc);
1464 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1465 return __handle_debug(__fc.out());
1467 _Padding_sink<_Out, _CharT>
1468 __sink(__fc.out(), __padwidth, _M_spec._M_get_precision(__fc));
1469 __handle_debug(__sink.out());
1470 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1475 set_debug_format() noexcept
1476 { _M_spec._M_debug = true; }
1480 _Spec<_CharT> _M_spec{};
1483 template<__char _CharT>
1484 struct __formatter_int
1486 // If no presentation type is specified, meaning of "none" depends
1487 // whether we are formatting an integer or a char or a bool.
1488 static constexpr _Pres_type _AsInteger = _Pres_d;
1489 static constexpr _Pres_type _AsBool = _Pres_s;
1490 static constexpr _Pres_type _AsChar = _Pres_c;
1492 __formatter_int() = default;
1495 __formatter_int(_Spec<_CharT> __spec) noexcept
1498 if (_M_spec._M_type == _Pres_none)
1499 _M_spec._M_type = _Pres_d;
1502 constexpr typename basic_format_parse_context<_CharT>::iterator
1503 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1505 _Spec<_CharT> __spec{};
1506 __spec._M_type = __type;
1508 const auto __last = __pc.end();
1509 auto __first = __pc.begin();
1511 auto __finalize = [this, &__spec] {
1515 auto __finished = [&] {
1516 if (__first == __last || *__first == '}')
1527 __first = __spec._M_parse_fill_and_align(__first, __last);
1531 __first = __spec._M_parse_sign(__first, __last);
1535 __first = __spec._M_parse_alternate_form(__first, __last);
1539 __first = __spec._M_parse_zero_fill(__first, __last);
1543 __first = __spec._M_parse_width(__first, __last, __pc);
1547 __first = __spec._M_parse_locale(__first, __last);
1554 __spec._M_type = _Pres_b;
1558 __spec._M_type = _Pres_B;
1562 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1563 // 3586. format should not print bool with 'c'
1564 if (__type != _AsBool)
1566 __spec._M_type = _Pres_c;
1571 __spec._M_type = _Pres_d;
1575 __spec._M_type = _Pres_o;
1579 __spec._M_type = _Pres_x;
1583 __spec._M_type = _Pres_X;
1587 if (__type == _AsBool)
1589 __spec._M_type = _Pres_s; // same meaning as "none" for bool
1593 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1595 if (__type == _AsChar)
1597 __spec._M_debug = true;
1607 __format::__failed_to_parse_format_spec();
1610 template<typename _Tp>
1611 constexpr typename basic_format_parse_context<_CharT>::iterator
1612 _M_parse(basic_format_parse_context<_CharT>& __pc)
1614 if constexpr (is_same_v<_Tp, bool>)
1616 auto __end = _M_do_parse(__pc, _AsBool);
1617 if (_M_spec._M_type == _Pres_s)
1618 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1619 || _M_spec._M_zero_fill)
1620 __throw_format_error("format error: format-spec contains "
1621 "invalid formatting options for "
1625 else if constexpr (__char<_Tp>)
1627 auto __end = _M_do_parse(__pc, _AsChar);
1628 if (_M_spec._M_type == _Pres_c)
1629 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1630 || _M_spec._M_zero_fill
1631 /* XXX should be invalid? || _M_spec._M_localized */)
1632 __throw_format_error("format error: format-spec contains "
1633 "invalid formatting options for "
1638 return _M_do_parse(__pc, _AsInteger);
1641 template<typename _Int, typename _Out>
1642 typename basic_format_context<_Out, _CharT>::iterator
1643 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1645 if (_M_spec._M_type == _Pres_c)
1646 return _M_format_character(_S_to_character(__i), __fc);
1648 constexpr size_t __buf_size = sizeof(_Int) * __CHAR_BIT__ + 3;
1649 char __buf[__buf_size];
1650 to_chars_result __res{};
1652 string_view __base_prefix;
1653 make_unsigned_t<_Int> __u;
1655 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1659 char* __start = __buf + 3;
1660 char* const __end = __buf + sizeof(__buf);
1661 char* const __start_digits = __start;
1663 switch (_M_spec._M_type)
1667 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1668 __res = to_chars(__start, __end, __u, 2);
1672 return _M_format_character(_S_to_character(__i), __fc);
1674 default: // Fallback for _Pres_type values introduces in later versions.
1676 // Should not reach here with _Pres_none for bool or charT, so:
1679 __res = to_chars(__start, __end, __u, 10);
1683 __base_prefix = "0";
1684 __res = to_chars(__start, __end, __u, 8);
1688 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1689 __res = to_chars(__start, __end, __u, 16);
1690 if (_M_spec._M_type == _Pres_X)
1691 for (auto __p = __start; __p != __res.ptr; ++__p)
1692 #if __has_builtin(__builtin_toupper)
1693 *__p = __builtin_toupper(*__p);
1695 *__p = std::toupper(*__p);
1700 if (_M_spec._M_alt && __base_prefix.size())
1702 __start -= __base_prefix.size();
1703 __builtin_memcpy(__start, __base_prefix.data(),
1704 __base_prefix.size());
1706 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1708 string_view __narrow_str(__start, __res.ptr - __start);
1709 size_t __prefix_len = __start_digits - __start;
1710 if constexpr (is_same_v<char, _CharT>)
1711 return _M_format_int(__narrow_str, __prefix_len, __fc);
1712 #ifdef _GLIBCXX_USE_WCHAR_T
1715 _CharT __wbuf[__buf_size];
1716 size_t __n = __narrow_str.size();
1717 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1718 // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
1719 std::__to_wstring_numeric(__narrow_str.data(), __n, __wbuf);
1720 return _M_format_int(basic_string_view<_CharT>(__wbuf, __n),
1721 __prefix_len, __fc);
1726 template<typename _Out>
1727 typename basic_format_context<_Out, _CharT>::iterator
1728 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1730 if (_M_spec._M_type == _Pres_c)
1731 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1732 if (_M_spec._M_type != _Pres_s)
1733 return format(static_cast<unsigned char>(__i), __fc);
1735 basic_string<_CharT> __s;
1737 if (_M_spec._M_localized) [[unlikely]]
1739 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1740 __s = __i ? __np.truename() : __np.falsename();
1741 __est_width = __s.size(); // TODO Unicode-aware estimate
1745 if constexpr (is_same_v<char, _CharT>)
1746 __s = __i ? "true" : "false";
1748 __s = __i ? L"true" : L"false";
1749 __est_width = __s.size();
1752 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1756 template<typename _Out>
1757 typename basic_format_context<_Out, _CharT>::iterator
1758 _M_format_character(_CharT __c,
1759 basic_format_context<_Out, _CharT>& __fc) const
1761 basic_string_view<_CharT> __in(&__c, 1u);
1762 size_t __width = 1u;
1763 // N.B. single byte cannot encode character of width greater than 1
1764 if constexpr (sizeof(_CharT) > 1u &&
1765 __unicode::__literal_encoding_is_unicode<_CharT>())
1766 __width = __unicode::__field_width(__c);
1768 if (!_M_spec._M_debug)
1769 return __format::__write_padded_as_spec(__in, __width,
1773 if (_M_spec._M_get_width(__fc) <= __width)
1774 return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1777 _Fixedbuf_sink<_CharT> __sink(__buf);
1778 __format::__write_escaped(__sink.out(), __in, _Term_apos);
1780 __in = __sink.view();
1781 if (__in[1] == _Escapes<_CharT>::_S_bslash()[0]) // escape sequence
1782 __width = __in.size();
1783 return __format::__write_padded_as_spec(__in, __width,
1787 template<typename _Int>
1789 _S_to_character(_Int __i)
1791 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1792 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1794 if (_Traits::__min <= __i && __i <= _Traits::__max)
1795 return static_cast<_CharT>(__i);
1797 else if constexpr (is_signed_v<_Int>)
1799 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1800 return static_cast<_CharT>(__i);
1802 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1803 return static_cast<_CharT>(__i);
1804 __throw_format_error("format error: integer not representable as "
1808 template<typename _Out>
1809 typename basic_format_context<_Out, _CharT>::iterator
1810 _M_format_int(basic_string_view<_CharT> __str, size_t __prefix_len,
1811 basic_format_context<_Out, _CharT>& __fc) const
1813 size_t __width = _M_spec._M_get_width(__fc);
1814 if (_M_spec._M_localized)
1816 const auto& __l = __fc.locale();
1817 if (__l.name() != "C")
1819 auto& __np = use_facet<numpunct<_CharT>>(__l);
1820 string __grp = __np.grouping();
1823 size_t __n = __str.size() - __prefix_len;
1824 auto __p = (_CharT*)__builtin_alloca(2 * __n
1827 auto __s = __str.data();
1828 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1829 __s += __prefix_len;
1830 auto __end = std::__add_grouping(__p + __prefix_len,
1831 __np.thousands_sep(),
1835 __str = {__p, size_t(__end - __p)};
1840 if (__width <= __str.size())
1841 return __format::__write(__fc.out(), __str);
1843 char32_t __fill_char = _M_spec._M_fill;
1844 _Align __align = _M_spec._M_align;
1846 size_t __nfill = __width - __str.size();
1847 auto __out = __fc.out();
1848 if (__align == _Align_default)
1850 __align = _Align_right;
1851 if (_M_spec._M_zero_fill)
1853 __fill_char = _CharT('0');
1854 // Write sign and base prefix before zero filling.
1855 if (__prefix_len != 0)
1857 __out = __format::__write(std::move(__out),
1858 __str.substr(0, __prefix_len));
1859 __str.remove_prefix(__prefix_len);
1863 __fill_char = _CharT(' ');
1865 return __format::__write_padded(std::move(__out), __str,
1866 __align, __nfill, __fill_char);
1869 _Spec<_CharT> _M_spec{};
1872 #ifdef __BFLT16_DIG__
1873 using __bflt16_t = decltype(0.0bf16);
1876 // Decide how 128-bit floating-point types should be formatted (or not).
1877 // When supported, the typedef __format::__flt128_t is the type that format
1878 // arguments should be converted to before passing them to __formatter_fp.
1879 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1880 // The __float128, _Float128 will be formatted by converting them to:
1881 // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1882 // long double when _GLIBCXX_FORMAT_F128=2,
1883 // _Float128 when _GLIBCXX_FORMAT_F128=3.
1884 #undef _GLIBCXX_FORMAT_F128
1886 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1888 // Format 128-bit floating-point types using __ieee128.
1889 using __flt128_t = __ieee128;
1890 # define _GLIBCXX_FORMAT_F128 1
1892 #ifdef __LONG_DOUBLE_IEEE128__
1893 // These overloads exist in the library, but are not declared.
1894 // Make them available as std::__format::to_chars.
1896 to_chars(char*, char*, __ibm128) noexcept
1897 __asm("_ZSt8to_charsPcS_e");
1900 to_chars(char*, char*, __ibm128, chars_format) noexcept
1901 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1904 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1905 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1906 #elif __cplusplus == 202002L
1908 to_chars(char*, char*, __ieee128) noexcept
1909 __asm("_ZSt8to_charsPcS_u9__ieee128");
1912 to_chars(char*, char*, __ieee128, chars_format) noexcept
1913 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1916 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1917 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1920 #elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1922 // Format 128-bit floating-point types using long double.
1923 using __flt128_t = long double;
1924 # define _GLIBCXX_FORMAT_F128 2
1926 #elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1928 // Format 128-bit floating-point types using _Float128.
1929 using __flt128_t = _Float128;
1930 # define _GLIBCXX_FORMAT_F128 3
1932 # if __cplusplus == 202002L
1933 // These overloads exist in the library, but are not declared for C++20.
1934 // Make them available as std::__format::to_chars.
1936 to_chars(char*, char*, _Float128) noexcept
1937 # if _GLIBCXX_INLINE_VERSION
1938 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1940 __asm("_ZSt8to_charsPcS_DF128_");
1944 to_chars(char*, char*, _Float128, chars_format) noexcept
1945 # if _GLIBCXX_INLINE_VERSION
1946 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1948 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1952 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1953 # if _GLIBCXX_INLINE_VERSION
1954 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1956 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1961 using std::to_chars;
1963 // We can format a floating-point type iff it is usable with to_chars.
1964 template<typename _Tp>
1965 concept __formattable_float
1966 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1967 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1969 template<__char _CharT>
1970 struct __formatter_fp
1972 constexpr typename basic_format_parse_context<_CharT>::iterator
1973 parse(basic_format_parse_context<_CharT>& __pc)
1975 _Spec<_CharT> __spec{};
1976 const auto __last = __pc.end();
1977 auto __first = __pc.begin();
1979 auto __finalize = [this, &__spec] {
1983 auto __finished = [&] {
1984 if (__first == __last || *__first == '}')
1995 __first = __spec._M_parse_fill_and_align(__first, __last);
1999 __first = __spec._M_parse_sign(__first, __last);
2003 __first = __spec._M_parse_alternate_form(__first, __last);
2007 __first = __spec._M_parse_zero_fill(__first, __last);
2011 if (__first[0] != '.')
2013 __first = __spec._M_parse_width(__first, __last, __pc);
2018 __first = __spec._M_parse_precision(__first, __last, __pc);
2022 __first = __spec._M_parse_locale(__first, __last);
2029 __spec._M_type = _Pres_a;
2033 __spec._M_type = _Pres_A;
2037 __spec._M_type = _Pres_e;
2041 __spec._M_type = _Pres_E;
2045 __spec._M_type = _Pres_f;
2049 __spec._M_type = _Pres_F;
2053 __spec._M_type = _Pres_g;
2057 __spec._M_type = _Pres_G;
2065 __format::__failed_to_parse_format_spec();
2068 template<typename _Fp, typename _Out>
2069 typename basic_format_context<_Out, _CharT>::iterator
2070 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2072 std::string __dynbuf;
2074 to_chars_result __res{};
2077 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2079 __prec = _M_spec._M_get_precision(__fc);
2081 chars_format __fmt{};
2082 bool __upper = false;
2083 bool __trailing_zeros = false;
2085 size_t __offset = 1; // reserve space for sign
2087 switch (_M_spec._M_type)
2090 if (__builtin_isfinite(__v))
2091 __offset += 2; // reserve space for prefix
2096 __fmt = chars_format::hex;
2099 if (__builtin_isfinite(__v))
2100 __offset += 2; // reserve space for prefix
2104 __fmt = chars_format::hex;
2112 __fmt = chars_format::scientific;
2119 __fmt = chars_format::fixed;
2126 __trailing_zeros = true;
2128 __fmt = chars_format::general;
2130 default: // Fallback for _Pres_type values introduces in later versions.
2133 __fmt = chars_format::general;
2137 char* __start = __buf + __offset;
2138 char* __end = __buf + sizeof(__buf);
2140 // Write value into buffer using std::to_chars.
2141 auto __to_chars = [&](char* __b, char* __e) {
2143 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2144 else if (__fmt != chars_format{})
2145 return __format::to_chars(__b, __e, __v, __fmt);
2147 return __format::to_chars(__b, __e, __v);
2150 // First try using stack buffer.
2151 __res = __to_chars(__start, __end);
2153 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2155 // If the buffer is too small it's probably because of a large
2156 // precision, or a very large value in fixed format.
2157 size_t __guess = 7 + __offset + __prec;
2158 if (__fmt == chars_format::fixed) // +ddd.prec
2160 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2161 || is_same_v<_Fp, long double>)
2163 // The number of digits to the left of the decimal point
2164 // is floor(log10(max(abs(__v),1)))+1
2166 if constexpr (is_same_v<_Fp, float>)
2167 __builtin_frexpf(__v, &__exp);
2168 else if constexpr (is_same_v<_Fp, double>)
2169 __builtin_frexp(__v, &__exp);
2170 else if constexpr (is_same_v<_Fp, long double>)
2171 __builtin_frexpl(__v, &__exp);
2173 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2176 __guess += numeric_limits<_Fp>::max_exponent10;
2178 if (__guess <= sizeof(__buf)) [[unlikely]]
2179 __guess = sizeof(__buf) * 2;
2180 __dynbuf.reserve(__guess);
2184 // Mangling of this lambda, and thus resize_and_overwrite
2185 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2186 // <format> was new in G++ 13, and is experimental, that
2188 auto __overwrite = [&__to_chars, &__res, __offset] (char* __p, size_t __n)
2190 __res = __to_chars(__p + __offset, __p + __n - __offset);
2191 return __res.ec == errc{} ? __res.ptr - __p : 0;
2194 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2196 __start = __dynbuf.data() + __offset; // reserve space for sign and prefix
2197 __end = __dynbuf.data() + __dynbuf.size();
2199 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2205 if (__builtin_signbit(__v))
2206 ranges::copy(string_view("-0x"), __start);
2208 ranges::copy(string_view("0x"), __start);
2211 // Use uppercase for 'A', 'P', 'E', and 'G' formats.
2214 for (char* __p = __start; __p != __res.ptr; ++__p)
2215 *__p = std::toupper(*__p);
2218 // Add sign for non-negative values.
2219 if (!__builtin_signbit(__v))
2221 if (_M_spec._M_sign == _Sign_plus)
2223 else if (_M_spec._M_sign == _Sign_space)
2229 string_view __narrow_str(__start, __res.ptr - __start);
2231 // Use alternate form. Ensure decimal point is always present,
2232 // and add trailing zeros (up to precision) for g and G forms.
2233 if (_M_spec._M_alt && __builtin_isfinite(__v))
2235 string_view __s = __narrow_str;
2236 size_t __sigfigs; // Number of significant figures.
2237 size_t __z = 0; // Number of trailing zeros to add.
2238 size_t __p; // Position of the exponent character (if any).
2239 size_t __d = __s.find('.'); // Position of decimal point.
2240 if (__d != __s.npos) // Found decimal point.
2242 __p = __s.find(__expc, __d + 1);
2243 if (__p == __s.npos)
2246 // If presentation type is g or G we might need to add zeros.
2247 if (__trailing_zeros)
2249 // Find number of digits after first significant figure.
2250 if (__s[__offset] != '0')
2251 // A string like "D.D" or "-D.DDD"
2252 __sigfigs = __p - __offset - 1;
2254 // A string like "0.D" or "-0.0DD".
2255 // Safe to assume there is a non-zero digit, because
2256 // otherwise there would be no decimal point.
2257 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2260 else // No decimal point, we need to insert one.
2262 __p = __s.find(__expc); // Find the exponent, if present.
2263 if (__p == __s.npos)
2265 __d = __p; // Position where '.' should be inserted.
2266 __sigfigs = __d - __offset;
2269 if (__trailing_zeros && __prec != 0)
2271 // For g and G presentation types std::to_chars produces
2272 // no more than prec significant figures. Insert this many
2273 // zeros so the result has exactly prec significant figures.
2274 __z = __prec - __sigfigs;
2277 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2279 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2281 // The stack buffer is large enough for the result.
2282 // Move exponent to make space for extra chars.
2283 __builtin_memmove(__start + __p + __extras,
2287 __start[__p++] = '.';
2288 __builtin_memset(__start + __p, '0', __z);
2289 __narrow_str = {__s.data(), __s.size() + __extras};
2291 else // Need to switch to the dynamic buffer.
2293 __dynbuf.reserve(__s.size() + __extras);
2294 if (__dynbuf.empty())
2296 __dynbuf = __s.substr(0, __p);
2300 __dynbuf.append(__z, '0');
2301 __dynbuf.append(__s.substr(__p));
2305 __dynbuf.insert(__p, __extras, '0');
2307 __dynbuf[__p] = '.';
2309 __narrow_str = __dynbuf;
2314 basic_string<_CharT> __wstr;
2315 basic_string_view<_CharT> __str;
2316 if constexpr (is_same_v<_CharT, char>)
2317 __str = __narrow_str;
2318 #ifdef _GLIBCXX_USE_WCHAR_T
2321 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2322 // 4522. Clarify that `std::format` transcodes for `std::wformat_strings`
2323 __wstr = std::__to_wstring_numeric(__narrow_str);
2328 if (_M_spec._M_localized && __builtin_isfinite(__v))
2330 auto __s = _M_localize(__str, __expc, __offset, __fc.locale());
2332 __str = __wstr = std::move(__s);
2335 size_t __width = _M_spec._M_get_width(__fc);
2337 if (__width <= __str.size())
2338 return __format::__write(__fc.out(), __str);
2340 char32_t __fill_char = _M_spec._M_fill;
2341 _Align __align = _M_spec._M_align;
2343 size_t __nfill = __width - __str.size();
2344 auto __out = __fc.out();
2345 if (__align == _Align_default)
2347 __align = _Align_right;
2348 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2350 __fill_char = _CharT('0');
2353 __out = __format::__write(__out, __str.substr(0, __offset));
2354 __str.remove_prefix(__offset);
2358 __fill_char = _CharT(' ');
2360 return __format::__write_padded(std::move(__out), __str,
2361 __align, __nfill, __fill_char);
2364 // Locale-specific format.
2365 basic_string<_CharT>
2366 _M_localize(basic_string_view<_CharT> __str, char __expc,
2367 int __offset, const locale& __loc) const
2369 basic_string<_CharT> __lstr;
2371 if (__loc == locale::classic())
2372 return __lstr; // Nothing to do.
2374 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2375 const _CharT __point = __np.decimal_point();
2376 const string __grp = __np.grouping();
2378 _CharT __dot, __exp;
2379 if constexpr (is_same_v<_CharT, char>)
2402 __builtin_unreachable();
2406 if (__grp.empty() && __point == __dot)
2407 return __lstr; // Locale uses '.' and no grouping.
2409 size_t __d = __str.find(__dot); // Index of radix character (if any).
2410 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2411 if (__e == __str.npos)
2413 const size_t __r = __str.size() - __e; // Length of remainder.
2414 auto __overwrite = [&](_CharT* __p, size_t) {
2415 // Copy any +/- sign and "0x" prefix
2416 ranges::copy_n(__str.data(), __offset, __p);
2417 // Apply grouping to the digits before the radix or exponent.
2418 auto __end = std::__add_grouping(__p + __offset, __np.thousands_sep(),
2419 __grp.data(), __grp.size(),
2420 __str.data() + __offset,
2421 __str.data() + __e);
2422 if (__r) // If there's a fractional part or exponent
2424 if (__d != __str.npos)
2426 *__end = __point; // Add the locale's radix character.
2430 const size_t __rlen = __str.size() - __e;
2431 // Append fractional digits and/or exponent:
2432 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2435 return (__end - __p);
2437 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2441 _Spec<_CharT> _M_spec{};
2444 template<__format::__char _CharT>
2445 struct __formatter_ptr
2448 __formatter_ptr() noexcept
2451 _M_spec._M_type = _Pres_x;
2452 _M_spec._M_alt = true;
2456 __formatter_ptr(_Spec<_CharT> __spec) noexcept
2458 { _M_set_default(); }
2460 constexpr typename basic_format_parse_context<_CharT>::iterator
2461 parse(basic_format_parse_context<_CharT>& __pc)
2463 __format::_Spec<_CharT> __spec{};
2464 const auto __last = __pc.end();
2465 auto __first = __pc.begin();
2467 auto __finalize = [this, &__spec] {
2472 auto __finished = [&] {
2473 if (__first == __last || *__first == '}')
2484 __first = __spec._M_parse_fill_and_align(__first, __last);
2488 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2489 // P2510R3 Formatting pointers
2490 #if __glibcxx_format >= 202304L
2491 __first = __spec._M_parse_zero_fill(__first, __last);
2496 __first = __spec._M_parse_width(__first, __last, __pc);
2500 if (*__first == 'p')
2502 __spec._M_type = _Pres_x;
2503 __spec._M_alt = true;
2506 #if __glibcxx_format >= 202304L
2507 else if (*__first == 'P')
2509 __spec._M_type = _Pres_X;
2510 __spec._M_alt = true;
2518 __format::__failed_to_parse_format_spec();
2521 template<typename _Out>
2522 typename basic_format_context<_Out, _CharT>::iterator
2523 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2525 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2526 return __formatter_int<_CharT>(_M_spec).format(__u, __fc);
2530 [[__gnu__::__always_inline__]]
2534 if (_M_spec._M_type == _Pres_none)
2536 _M_spec._M_type = _Pres_x;
2537 _M_spec._M_alt = true;
2541 __format::_Spec<_CharT> _M_spec;
2544 } // namespace __format
2547 /// Format a character.
2548 template<__format::__char _CharT>
2549 struct formatter<_CharT, _CharT>
2551 formatter() = default;
2553 constexpr typename basic_format_parse_context<_CharT>::iterator
2554 parse(basic_format_parse_context<_CharT>& __pc)
2556 return _M_f.template _M_parse<_CharT>(__pc);
2559 template<typename _Out>
2560 typename basic_format_context<_Out, _CharT>::iterator
2561 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2563 if (_M_f._M_spec._M_type == __format::_Pres_c)
2564 return _M_f._M_format_character(__u, __fc);
2566 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2569 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2571 set_debug_format() noexcept
2572 { _M_f._M_spec._M_debug = true; }
2576 __format::__formatter_int<_CharT> _M_f;
2579 #if __glibcxx_print >= 202403L
2580 template<__format::__char _CharT>
2581 constexpr bool enable_nonlocking_formatter_optimization<_CharT> = true;
2584 #ifdef _GLIBCXX_USE_WCHAR_T
2585 /// Format a char value for wide character output.
2587 struct formatter<char, wchar_t>
2589 formatter() = default;
2591 constexpr typename basic_format_parse_context<wchar_t>::iterator
2592 parse(basic_format_parse_context<wchar_t>& __pc)
2594 return _M_f._M_parse<char>(__pc);
2597 template<typename _Out>
2598 typename basic_format_context<_Out, wchar_t>::iterator
2599 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2601 if (_M_f._M_spec._M_type == __format::_Pres_c)
2602 return _M_f._M_format_character(__u, __fc);
2604 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2607 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2609 set_debug_format() noexcept
2610 { _M_f._M_spec._M_debug = true; }
2614 __format::__formatter_int<wchar_t> _M_f;
2616 #endif // USE_WCHAR_T
2618 /** Format a string.
2621 template<__format::__char _CharT>
2622 struct formatter<_CharT*, _CharT>
2624 formatter() = default;
2626 [[__gnu__::__always_inline__]]
2627 constexpr typename basic_format_parse_context<_CharT>::iterator
2628 parse(basic_format_parse_context<_CharT>& __pc)
2629 { return _M_f.parse(__pc); }
2631 template<typename _Out>
2632 [[__gnu__::__nonnull__]]
2633 typename basic_format_context<_Out, _CharT>::iterator
2634 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2635 { return _M_f.format(__u, __fc); }
2637 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2638 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2642 __format::__formatter_str<_CharT> _M_f;
2645 #if __glibcxx_print >= 202403L
2646 template<__format::__char _CharT>
2647 constexpr bool enable_nonlocking_formatter_optimization<_CharT*> = true;
2650 template<__format::__char _CharT>
2651 struct formatter<const _CharT*, _CharT>
2653 formatter() = default;
2655 [[__gnu__::__always_inline__]]
2656 constexpr typename basic_format_parse_context<_CharT>::iterator
2657 parse(basic_format_parse_context<_CharT>& __pc)
2658 { return _M_f.parse(__pc); }
2660 template<typename _Out>
2661 [[__gnu__::__nonnull__]]
2662 typename basic_format_context<_Out, _CharT>::iterator
2663 format(const _CharT* __u,
2664 basic_format_context<_Out, _CharT>& __fc) const
2665 { return _M_f.format(__u, __fc); }
2667 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2668 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2672 __format::__formatter_str<_CharT> _M_f;
2675 #if __glibcxx_print >= 202403L
2676 template<__format::__char _CharT>
2678 enable_nonlocking_formatter_optimization<const _CharT*> = true;
2681 template<__format::__char _CharT, size_t _Nm>
2682 struct formatter<_CharT[_Nm], _CharT>
2684 formatter() = default;
2686 [[__gnu__::__always_inline__]]
2687 constexpr typename basic_format_parse_context<_CharT>::iterator
2688 parse(basic_format_parse_context<_CharT>& __pc)
2689 { return _M_f.parse(__pc); }
2691 template<typename _Out>
2692 typename basic_format_context<_Out, _CharT>::iterator
2693 format(const _CharT (&__u)[_Nm],
2694 basic_format_context<_Out, _CharT>& __fc) const
2695 { return _M_f.format({__u, _Nm}, __fc); }
2697 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2698 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2702 __format::__formatter_str<_CharT> _M_f;
2705 #if __glibcxx_print >= 202403L
2706 template<__format::__char _CharT, size_t _Nm>
2707 constexpr bool enable_nonlocking_formatter_optimization<_CharT[_Nm]> = true;
2710 template<typename _Traits, typename _Alloc>
2711 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2713 formatter() = default;
2715 [[__gnu__::__always_inline__]]
2716 constexpr typename basic_format_parse_context<char>::iterator
2717 parse(basic_format_parse_context<char>& __pc)
2718 { return _M_f.parse(__pc); }
2720 template<typename _Out>
2721 typename basic_format_context<_Out, char>::iterator
2722 format(const basic_string<char, _Traits, _Alloc>& __u,
2723 basic_format_context<_Out, char>& __fc) const
2724 { return _M_f.format(__u, __fc); }
2726 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2727 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2731 __format::__formatter_str<char> _M_f;
2734 #if __glibcxx_print >= 202403L
2735 template<typename _Tr, typename _Alloc>
2737 enable_nonlocking_formatter_optimization<basic_string<char, _Tr, _Alloc>>
2741 #ifdef _GLIBCXX_USE_WCHAR_T
2742 template<typename _Traits, typename _Alloc>
2743 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2745 formatter() = default;
2747 [[__gnu__::__always_inline__]]
2748 constexpr typename basic_format_parse_context<wchar_t>::iterator
2749 parse(basic_format_parse_context<wchar_t>& __pc)
2750 { return _M_f.parse(__pc); }
2752 template<typename _Out>
2753 typename basic_format_context<_Out, wchar_t>::iterator
2754 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2755 basic_format_context<_Out, wchar_t>& __fc) const
2756 { return _M_f.format(__u, __fc); }
2758 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2759 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2763 __format::__formatter_str<wchar_t> _M_f;
2766 #if __glibcxx_print >= 202403L
2767 template<typename _Tr, typename _Alloc>
2769 enable_nonlocking_formatter_optimization<basic_string<wchar_t, _Tr, _Alloc>>
2773 #endif // USE_WCHAR_T
2775 template<typename _Traits>
2776 struct formatter<basic_string_view<char, _Traits>, char>
2778 formatter() = default;
2780 [[__gnu__::__always_inline__]]
2781 constexpr typename basic_format_parse_context<char>::iterator
2782 parse(basic_format_parse_context<char>& __pc)
2783 { return _M_f.parse(__pc); }
2785 template<typename _Out>
2786 typename basic_format_context<_Out, char>::iterator
2787 format(basic_string_view<char, _Traits> __u,
2788 basic_format_context<_Out, char>& __fc) const
2789 { return _M_f.format(__u, __fc); }
2791 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2792 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2796 __format::__formatter_str<char> _M_f;
2799 #if __glibcxx_print >= 202403L
2800 template<typename _Tr>
2802 enable_nonlocking_formatter_optimization<basic_string_view<char, _Tr>>
2806 #ifdef _GLIBCXX_USE_WCHAR_T
2807 template<typename _Traits>
2808 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2810 formatter() = default;
2812 [[__gnu__::__always_inline__]]
2813 constexpr typename basic_format_parse_context<wchar_t>::iterator
2814 parse(basic_format_parse_context<wchar_t>& __pc)
2815 { return _M_f.parse(__pc); }
2817 template<typename _Out>
2818 typename basic_format_context<_Out, wchar_t>::iterator
2819 format(basic_string_view<wchar_t, _Traits> __u,
2820 basic_format_context<_Out, wchar_t>& __fc) const
2821 { return _M_f.format(__u, __fc); }
2823 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2824 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2828 __format::__formatter_str<wchar_t> _M_f;
2831 #if __glibcxx_print >= 202403L
2832 template<typename _Tr>
2834 enable_nonlocking_formatter_optimization<basic_string_view<wchar_t, _Tr>>
2837 #endif // USE_WCHAR_T
2840 /// @cond undocumented
2843 // each cv-unqualified arithmetic type ArithmeticT other than
2844 // char, wchar_t, char8_t, char16_t, or char32_t
2845 template<typename _Tp>
2846 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2848 #if defined __SIZEOF_INT128__
2849 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2850 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2854 template<> inline constexpr bool __is_formattable_integer<char> = false;
2855 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2856 #ifdef _GLIBCXX_USE_CHAR8_T
2857 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2859 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2860 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2862 template<typename _Tp>
2863 concept __formattable_integer = __is_formattable_integer<_Tp>;
2867 /// Format an integer.
2868 template<__format::__formattable_integer _Tp, __format::__char _CharT>
2869 struct formatter<_Tp, _CharT>
2871 formatter() = default;
2873 [[__gnu__::__always_inline__]]
2874 constexpr typename basic_format_parse_context<_CharT>::iterator
2875 parse(basic_format_parse_context<_CharT>& __pc)
2877 return _M_f.template _M_parse<_Tp>(__pc);
2880 template<typename _Out>
2881 typename basic_format_context<_Out, _CharT>::iterator
2882 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2883 { return _M_f.format(__u, __fc); }
2886 __format::__formatter_int<_CharT> _M_f;
2889 #if __glibcxx_print >= 202403L
2890 template<__format::__formattable_integer _Tp>
2892 enable_nonlocking_formatter_optimization<_Tp> = true;
2895 #if defined __glibcxx_to_chars
2896 /// Format a floating-point value.
2897 template<__format::__formattable_float _Tp, __format::__char _CharT>
2898 struct formatter<_Tp, _CharT>
2900 formatter() = default;
2902 [[__gnu__::__always_inline__]]
2903 constexpr typename basic_format_parse_context<_CharT>::iterator
2904 parse(basic_format_parse_context<_CharT>& __pc)
2905 { return _M_f.parse(__pc); }
2907 template<typename _Out>
2908 typename basic_format_context<_Out, _CharT>::iterator
2909 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2910 { return _M_f.format(__u, __fc); }
2913 __format::__formatter_fp<_CharT> _M_f;
2916 #if __glibcxx_print >= 202403L
2917 template<__format::__formattable_float _Tp>
2919 enable_nonlocking_formatter_optimization<_Tp> = true;
2922 #if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2923 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2924 template<__format::__char _CharT>
2925 struct formatter<long double, _CharT>
2927 formatter() = default;
2929 [[__gnu__::__always_inline__]]
2930 constexpr typename basic_format_parse_context<_CharT>::iterator
2931 parse(basic_format_parse_context<_CharT>& __pc)
2932 { return _M_f.parse(__pc); }
2934 template<typename _Out>
2935 typename basic_format_context<_Out, _CharT>::iterator
2936 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2937 { return _M_f.format((double)__u, __fc); }
2940 __format::__formatter_fp<_CharT> _M_f;
2944 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2945 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2946 template<__format::__char _CharT>
2947 struct formatter<_Float16, _CharT>
2949 formatter() = default;
2951 [[__gnu__::__always_inline__]]
2952 constexpr typename basic_format_parse_context<_CharT>::iterator
2953 parse(basic_format_parse_context<_CharT>& __pc)
2954 { return _M_f.parse(__pc); }
2956 template<typename _Out>
2957 typename basic_format_context<_Out, _CharT>::iterator
2958 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2959 { return _M_f.format((float)__u, __fc); }
2962 __format::__formatter_fp<_CharT> _M_f;
2966 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2967 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2968 template<__format::__char _CharT>
2969 struct formatter<_Float32, _CharT>
2971 formatter() = default;
2973 [[__gnu__::__always_inline__]]
2974 constexpr typename basic_format_parse_context<_CharT>::iterator
2975 parse(basic_format_parse_context<_CharT>& __pc)
2976 { return _M_f.parse(__pc); }
2978 template<typename _Out>
2979 typename basic_format_context<_Out, _CharT>::iterator
2980 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2981 { return _M_f.format((float)__u, __fc); }
2984 __format::__formatter_fp<_CharT> _M_f;
2988 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2989 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2990 template<__format::__char _CharT>
2991 struct formatter<_Float64, _CharT>
2993 formatter() = default;
2995 [[__gnu__::__always_inline__]]
2996 constexpr typename basic_format_parse_context<_CharT>::iterator
2997 parse(basic_format_parse_context<_CharT>& __pc)
2998 { return _M_f.parse(__pc); }
3000 template<typename _Out>
3001 typename basic_format_context<_Out, _CharT>::iterator
3002 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
3003 { return _M_f.format((double)__u, __fc); }
3006 __format::__formatter_fp<_CharT> _M_f;
3010 #if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
3011 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
3012 template<__format::__char _CharT>
3013 struct formatter<_Float128, _CharT>
3015 formatter() = default;
3017 [[__gnu__::__always_inline__]]
3018 constexpr typename basic_format_parse_context<_CharT>::iterator
3019 parse(basic_format_parse_context<_CharT>& __pc)
3020 { return _M_f.parse(__pc); }
3022 template<typename _Out>
3023 typename basic_format_context<_Out, _CharT>::iterator
3024 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3025 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3028 __format::__formatter_fp<_CharT> _M_f;
3032 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
3033 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
3034 // when long double is not 128bit IEEE type.
3035 template<__format::__char _CharT>
3036 struct formatter<__float128, _CharT>
3038 formatter() = default;
3040 [[__gnu__::__always_inline__]]
3041 constexpr typename basic_format_parse_context<_CharT>::iterator
3042 parse(basic_format_parse_context<_CharT>& __pc)
3043 { return _M_f.parse(__pc); }
3045 template<typename _Out>
3046 typename basic_format_context<_Out, _CharT>::iterator
3047 format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3048 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3051 __format::__formatter_fp<_CharT> _M_f;
3055 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3056 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3057 template<__format::__char _CharT>
3058 struct formatter<__format::__bflt16_t, _CharT>
3060 formatter() = default;
3062 [[__gnu__::__always_inline__]]
3063 constexpr typename basic_format_parse_context<_CharT>::iterator
3064 parse(basic_format_parse_context<_CharT>& __pc)
3065 { return _M_f.parse(__pc); }
3067 template<typename _Out>
3068 typename basic_format_context<_Out, _CharT>::iterator
3069 format(__gnu_cxx::__bfloat16_t __u,
3070 basic_format_context<_Out, _CharT>& __fc) const
3071 { return _M_f.format((float)__u, __fc); }
3074 __format::__formatter_fp<_CharT> _M_f;
3077 #endif // __cpp_lib_to_chars
3079 /** Format a pointer.
3082 template<__format::__char _CharT>
3083 struct formatter<const void*, _CharT>
3085 formatter() = default;
3087 constexpr typename basic_format_parse_context<_CharT>::iterator
3088 parse(basic_format_parse_context<_CharT>& __pc)
3089 { return _M_f.parse(__pc); }
3091 template<typename _Out>
3092 typename basic_format_context<_Out, _CharT>::iterator
3093 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3094 { return _M_f.format(__v, __fc); }
3097 __format::__formatter_ptr<_CharT> _M_f;
3100 #if __glibcxx_print >= 202403L
3102 inline constexpr bool
3103 enable_nonlocking_formatter_optimization<const void*> = true;
3106 template<__format::__char _CharT>
3107 struct formatter<void*, _CharT>
3109 formatter() = default;
3111 [[__gnu__::__always_inline__]]
3112 constexpr typename basic_format_parse_context<_CharT>::iterator
3113 parse(basic_format_parse_context<_CharT>& __pc)
3114 { return _M_f.parse(__pc); }
3116 template<typename _Out>
3117 typename basic_format_context<_Out, _CharT>::iterator
3118 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3119 { return _M_f.format(__v, __fc); }
3122 __format::__formatter_ptr<_CharT> _M_f;
3125 #if __glibcxx_print >= 202403l
3127 inline constexpr bool
3128 enable_nonlocking_formatter_optimization<void*> = true;
3131 template<__format::__char _CharT>
3132 struct formatter<nullptr_t, _CharT>
3134 formatter() = default;
3136 [[__gnu__::__always_inline__]]
3137 constexpr typename basic_format_parse_context<_CharT>::iterator
3138 parse(basic_format_parse_context<_CharT>& __pc)
3139 { return _M_f.parse(__pc); }
3141 template<typename _Out>
3142 typename basic_format_context<_Out, _CharT>::iterator
3143 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3144 { return _M_f.format(nullptr, __fc); }
3147 __format::__formatter_ptr<_CharT> _M_f;
3151 #if __glibcxx_print >= 202403L
3153 inline constexpr bool
3154 enable_nonlocking_formatter_optimization<nullptr_t> = true;
3157 #if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3158 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3159 // 3944. Formatters converting sequences of char to sequences of wchar_t
3161 struct __formatter_disabled
3163 __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3164 __formatter_disabled(const __formatter_disabled&) = delete;
3165 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3169 struct formatter<char*, wchar_t>
3170 : private __formatter_disabled { };
3172 struct formatter<const char*, wchar_t>
3173 : private __formatter_disabled { };
3174 template<size_t _Nm>
3175 struct formatter<char[_Nm], wchar_t>
3176 : private __formatter_disabled { };
3177 template<class _Traits, class _Allocator>
3178 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3179 : private __formatter_disabled { };
3180 template<class _Traits>
3181 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3182 : private __formatter_disabled { };
3185 /// An iterator after the last character written, and the number of
3186 /// characters that would have been written.
3187 template<typename _Out>
3188 struct format_to_n_result
3191 iter_difference_t<_Out> size;
3194 _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3195 template<typename, typename> class vector;
3196 _GLIBCXX_END_NAMESPACE_CONTAINER
3198 /// @cond undocumented
3201 template<typename _CharT>
3205 using iterator_category = output_iterator_tag;
3206 using value_type = void;
3207 using difference_type = ptrdiff_t;
3208 using pointer = void;
3209 using reference = void;
3211 _Drop_iter() = default;
3212 _Drop_iter(const _Drop_iter&) = default;
3213 _Drop_iter& operator=(const _Drop_iter&) = default;
3215 [[__gnu__::__always_inline__]]
3216 constexpr _Drop_iter&
3217 operator=(_CharT __c)
3220 [[__gnu__::__always_inline__]]
3221 constexpr _Drop_iter&
3222 operator=(basic_string_view<_CharT> __s)
3225 [[__gnu__::__always_inline__]]
3226 constexpr _Drop_iter&
3227 operator*() { return *this; }
3229 [[__gnu__::__always_inline__]]
3230 constexpr _Drop_iter&
3231 operator++() { return *this; }
3233 [[__gnu__::__always_inline__]]
3234 constexpr _Drop_iter
3235 operator++(int) { return *this; }
3238 template<typename _CharT>
3241 _Sink<_CharT>* _M_sink = nullptr;
3244 using iterator_category = output_iterator_tag;
3245 using value_type = void;
3246 using difference_type = ptrdiff_t;
3247 using pointer = void;
3248 using reference = void;
3250 _Sink_iter() = default;
3251 _Sink_iter(const _Sink_iter&) = default;
3252 _Sink_iter& operator=(const _Sink_iter&) = default;
3254 [[__gnu__::__always_inline__]]
3256 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3258 [[__gnu__::__always_inline__]]
3259 constexpr _Sink_iter&
3260 operator=(_CharT __c)
3262 _M_sink->_M_write(__c);
3266 [[__gnu__::__always_inline__]]
3267 constexpr _Sink_iter&
3268 operator=(basic_string_view<_CharT> __s)
3270 _M_sink->_M_write(__s);
3274 [[__gnu__::__always_inline__]]
3275 constexpr _Sink_iter&
3276 operator*() { return *this; }
3278 [[__gnu__::__always_inline__]]
3279 constexpr _Sink_iter&
3280 operator++() { return *this; }
3282 [[__gnu__::__always_inline__]]
3283 constexpr _Sink_iter
3284 operator++(int) { return *this; }
3287 _M_reserve(size_t __n) const
3288 { return _M_sink->_M_reserve(__n); }
3291 _M_discarding() const
3292 { return _M_sink->_M_discarding(); }
3295 // Abstract base class for type-erased character sinks.
3296 // All formatting and output is done via this type's iterator,
3297 // to reduce the number of different template instantiations.
3298 template<typename _CharT>
3301 friend class _Sink_iter<_CharT>;
3303 span<_CharT> _M_span;
3304 typename span<_CharT>::iterator _M_next;
3306 // Called when the span is full, to make more space available.
3307 // Precondition: _M_next != _M_span.begin()
3308 // Postcondition: _M_next != _M_span.end()
3309 // TODO: remove the precondition? could make overflow handle it.
3310 virtual void _M_overflow() = 0;
3313 // Precondition: __span.size() != 0
3314 [[__gnu__::__always_inline__]]
3316 _Sink(span<_CharT> __span) noexcept
3317 : _M_span(__span), _M_next(__span.begin())
3320 // The portion of the span that has been written to.
3321 [[__gnu__::__always_inline__]]
3323 _M_used() const noexcept
3324 { return _M_span.first(_M_next - _M_span.begin()); }
3326 // The portion of the span that has not been written to.
3327 [[__gnu__::__always_inline__]]
3328 constexpr span<_CharT>
3329 _M_unused() const noexcept
3330 { return _M_span.subspan(_M_next - _M_span.begin()); }
3332 // Use the start of the span as the next write position.
3333 [[__gnu__::__always_inline__]]
3335 _M_rewind() noexcept
3336 { _M_next = _M_span.begin(); }
3338 // Replace the current output range.
3340 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3343 _M_next = __s.begin() + __pos;
3346 // Called by the iterator for *it++ = c
3348 _M_write(_CharT __c)
3351 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3356 _M_write(basic_string_view<_CharT> __s)
3358 span __to = _M_unused();
3359 while (__to.size() <= __s.size())
3361 __s.copy(__to.data(), __to.size());
3362 _M_next += __to.size();
3363 __s.remove_prefix(__to.size());
3369 __s.copy(__to.data(), __s.size());
3370 _M_next += __s.size();
3374 // A successful _Reservation can be used to directly write
3375 // up to N characters to the sink to avoid unwanted buffering.
3378 // True if the reservation was successful, false otherwise.
3379 explicit operator bool() const noexcept { return _M_sink; }
3380 // A pointer to write directly to the sink.
3381 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3382 // Add n to the _M_next iterator for the sink.
3383 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3387 // Attempt to reserve space to write n characters to the sink.
3388 // If anything is written to the reservation then there must be a call
3389 // to _M_bump(N2) before any call to another member function of *this,
3390 // where N2 is the number of characters written.
3391 virtual _Reservation
3392 _M_reserve(size_t __n)
3394 if (__n <= _M_unused().size())
3397 if (__n <= _M_span.size()) // Cannot meet the request.
3399 _M_overflow(); // Make more space available.
3400 if (__n <= _M_unused().size())
3406 // Update the next output position after writing directly to the sink.
3407 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3412 // Returns true if the _Sink is discarding incoming characters.
3414 _M_discarding() const
3418 _Sink(const _Sink&) = delete;
3419 _Sink& operator=(const _Sink&) = delete;
3421 [[__gnu__::__always_inline__]]
3422 constexpr _Sink_iter<_CharT>
3424 { return _Sink_iter<_CharT>(*this); }
3428 template<typename _CharT>
3429 class _Fixedbuf_sink final : public _Sink<_CharT>
3432 _M_overflow() override
3434 __glibcxx_assert(false);
3439 [[__gnu__::__always_inline__]]
3441 _Fixedbuf_sink(span<_CharT> __buf)
3442 : _Sink<_CharT>(__buf)
3445 constexpr basic_string_view<_CharT>
3448 auto __s = this->_M_used();
3449 return basic_string_view<_CharT>(__s.data(), __s.size());
3453 // A sink with an internal buffer. This is used to implement concrete sinks.
3454 template<typename _CharT>
3455 class _Buf_sink : public _Sink<_CharT>
3458 _CharT _M_buf[__stackbuf_size<_CharT>];
3460 [[__gnu__::__always_inline__]]
3462 _Buf_sink() noexcept
3463 : _Sink<_CharT>(_M_buf)
3467 using _GLIBCXX_STD_C::vector;
3469 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3470 // Writes to a buffer then appends that to the sequence when it fills up.
3471 template<typename _Seq>
3472 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3474 using _CharT = typename _Seq::value_type;
3478 // Transfer buffer contents to the sequence, so buffer can be refilled.
3480 _M_overflow() override
3482 auto __s = this->_M_used();
3483 if (__s.empty()) [[unlikely]]
3484 return; // Nothing in the buffer to transfer to _M_seq.
3486 // If _M_reserve was called then _M_bump must have been called too.
3487 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3489 if constexpr (__is_specialization_of<_Seq, basic_string>)
3490 _M_seq.append(__s.data(), __s.size());
3492 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3494 // Make the whole of _M_buf available for the next write:
3498 typename _Sink<_CharT>::_Reservation
3499 _M_reserve(size_t __n) override
3501 // We might already have n characters available in this->_M_unused(),
3502 // but the whole point of this function is to be an optimization for
3503 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3504 // and then copying that into a basic_string if possible, so this
3505 // function prefers to create space directly in _M_seq rather than
3508 if constexpr (__is_specialization_of<_Seq, basic_string>
3509 || __is_specialization_of<_Seq, vector>)
3511 // Flush the buffer to _M_seq first (should not be needed).
3512 if (this->_M_used().size()) [[unlikely]]
3513 _Seq_sink::_M_overflow();
3515 // Expand _M_seq to make __n new characters available:
3516 const auto __sz = _M_seq.size();
3517 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3518 _M_seq.__resize_and_overwrite(__sz + __n,
3519 [](auto, auto __n2) {
3523 _M_seq.resize(__sz + __n);
3525 // Set _M_used() to be a span over the original part of _M_seq
3526 // and _M_unused() to be the extra capacity we just created:
3527 this->_M_reset(_M_seq, __sz);
3530 else // Try to use the base class' buffer.
3531 return _Sink<_CharT>::_M_reserve(__n);
3535 _M_bump(size_t __n) override
3537 if constexpr (__is_specialization_of<_Seq, basic_string>
3538 || __is_specialization_of<_Seq, vector>)
3540 auto __s = this->_M_used();
3541 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3542 // Truncate the sequence to the part that was actually written to:
3543 _M_seq.resize(__s.size() + __n);
3544 // Switch back to using buffer:
3545 this->_M_reset(this->_M_buf);
3549 void _M_trim(span<const _CharT> __s)
3550 requires __is_specialization_of<_Seq, basic_string>
3552 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3553 || __s.data() == _M_seq.data());
3554 if (__s.data() == _M_seq.data())
3555 _M_seq.resize(__s.size());
3557 this->_M_reset(this->_M_buf, __s.size());
3561 // TODO: for SSO string, use SSO buffer as initial span, then switch
3562 // to _M_buf if it overflows? Or even do that for all unused capacity?
3564 [[__gnu__::__always_inline__]]
3565 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3568 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3569 : _M_seq(std::move(__s))
3572 using _Sink<_CharT>::out;
3577 if (this->_M_used().size() != 0)
3578 _Seq_sink::_M_overflow();
3579 return std::move(_M_seq);
3582 // A writable span that views everything written to the sink.
3583 // Will be either a view over _M_seq or the used part of _M_buf.
3587 auto __s = this->_M_used();
3590 if (__s.size() != 0)
3591 _Seq_sink::_M_overflow();
3597 basic_string_view<_CharT>
3600 auto __span = _M_span();
3601 return basic_string_view<_CharT>(__span.data(), __span.size());
3605 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3607 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3609 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3610 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3611 // Writes to a fixed-size buffer and then flushes to the output iterator
3612 // when the buffer fills up.
3613 template<typename _CharT, typename _OutIter>
3614 class _Iter_sink : public _Buf_sink<_CharT>
3617 iter_difference_t<_OutIter> _M_max;
3620 size_t _M_count = 0;
3623 _M_overflow() override
3625 auto __s = this->_M_used();
3626 if (_M_max < 0) // No maximum.
3627 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3628 else if (_M_count < static_cast<size_t>(_M_max))
3630 auto __max = _M_max - _M_count;
3631 span<_CharT> __first;
3632 if (__max < __s.size())
3633 __first = __s.first(static_cast<size_t>(__max));
3636 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3639 _M_count += __s.size();
3643 _M_discarding() const override
3645 // format_to_n return total number of characters, that would be written,
3646 // see C++20 [format.functions] p20
3651 [[__gnu__::__always_inline__]]
3653 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3654 : _M_out(std::move(__out)), _M_max(__max)
3657 using _Sink<_CharT>::out;
3659 format_to_n_result<_OutIter>
3662 if (this->_M_used().size() != 0)
3663 _Iter_sink::_M_overflow();
3664 iter_difference_t<_OutIter> __count(_M_count);
3665 return { std::move(_M_out), __count };
3669 // Used for contiguous iterators.
3670 // No buffer is used, characters are written straight to the iterator.
3671 // We do not know the size of the output range, so the span size just grows
3672 // as needed. The end of the span might be an invalid pointer outside the
3673 // valid range, but we never actually call _M_span.end(). This class does
3674 // not introduce any invalid pointer arithmetic or overflows that would not
3675 // have happened anyway.
3676 template<typename _CharT>
3677 class _Ptr_sink : public _Sink<_CharT>
3679 static constexpr size_t _S_no_limit = size_t(-1);
3683 size_t _M_count = 0;
3685 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3689 _M_overflow() override
3691 if (this->_M_unused().size() != 0)
3692 return; // No need to switch to internal buffer yet.
3694 auto __s = this->_M_used();
3696 if (_M_max != _S_no_limit)
3698 _M_count += __s.size();
3699 // Span was already sized for the maximum character count,
3700 // if it overflows then any further output must go to the
3701 // internal buffer, to be discarded.
3702 this->_M_reset(this->_M_buf);
3706 // No maximum character count. Just extend the span to allow
3707 // writing more characters to it.
3708 _M_rebuf(__s.data(), __s.size() + 1024, __s.size());
3713 _M_discarding() const override
3715 // format_to_n return total number of characters, that would be written,
3716 // see C++20 [format.functions] p20
3720 typename _Sink<_CharT>::_Reservation
3721 _M_reserve(size_t __n) final
3723 auto __avail = this->_M_unused();
3724 if (__n > __avail.size())
3726 if (_M_max != _S_no_limit)
3727 return {}; // cannot grow
3729 auto __s = this->_M_used();
3730 _M_rebuf(__s.data(), __s.size() + __n, __s.size());
3736 template<typename _IterDifference>
3738 _S_trim_max(_IterDifference __max)
3742 if constexpr (!is_integral_v<_IterDifference> || sizeof(__max) > sizeof(size_t))
3743 // __int128 or __detail::__max_diff_type
3744 if (_IterDifference((size_t)-1) < __max)
3746 return size_t(__max);
3749 [[__gnu__::__always_inline__]]
3751 _M_rebuf(_CharT* __ptr, size_t __total, size_t __inuse = 0)
3753 std::span<_CharT> __span(__ptr, __total);
3754 this->_M_reset(__span, __inuse);
3759 _Ptr_sink(_CharT* __ptr, size_t __n = _S_no_limit) noexcept
3760 : _Sink<_CharT>(_M_buf), _M_max(__n)
3763 return; // Only write to the internal buffer.
3764 else if (__n != _S_no_limit)
3765 _M_rebuf(__ptr, __n);
3766 #if __has_builtin(__builtin_dynamic_object_size)
3767 else if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3768 _M_rebuf(__ptr, __bytes / sizeof(_CharT));
3772 // Avoid forming a pointer to a different memory page.
3773 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3774 __n = (1024 - __off) / sizeof(_CharT);
3775 if (__n > 0) [[likely]]
3776 _M_rebuf(__ptr, __n);
3777 else // Misaligned/packed buffer of wchar_t?
3782 template<contiguous_iterator _OutIter>
3784 _Ptr_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1)
3785 : _Ptr_sink(std::to_address(__out), _S_trim_max(__n))
3788 template<contiguous_iterator _OutIter>
3789 format_to_n_result<_OutIter>
3790 _M_finish(_OutIter __first) const
3792 auto __s = this->_M_used();
3793 if (__s.data() == _M_buf)
3795 // Switched to internal buffer, so must have written _M_max.
3796 iter_difference_t<_OutIter> __m(_M_max);
3797 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3798 return { __first + __m, __count };
3800 else // Not using internal buffer yet
3802 iter_difference_t<_OutIter> __count(__s.size());
3803 return { __first + __count, __count };
3808 template<typename _CharT, typename _OutIter>
3809 concept __contiguous_char_iter
3810 = contiguous_iterator<_OutIter>
3811 && same_as<iter_value_t<_OutIter>, _CharT>;
3813 // A sink for handling the padded outputs (_M_padwidth) or truncated
3814 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3815 // until sufficient number of characters is written. After that if sequence
3816 // is longer than _M_padwidth it's written to _M_out, and further writes are
3818 // * buffered and forwarded to _M_out, if below _M_maxwidth,
3819 // * ignored otherwise
3820 // If field width of written sequence is no greater than _M_padwidth, the
3821 // sequence is written during _M_finish call.
3822 template<typename _Out, typename _CharT>
3823 class _Padding_sink : public _Str_sink<_CharT>
3828 size_t _M_printwidth;
3830 [[__gnu__::__always_inline__]]
3833 { return _M_printwidth >= _M_maxwidth; }
3835 [[__gnu__::__always_inline__]]
3837 _M_buffering() const
3839 if (_M_printwidth < _M_padwidth)
3841 if (_M_maxwidth != (size_t)-1)
3842 return _M_printwidth < _M_maxwidth;
3847 _M_sync_discarding()
3849 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3850 if (_M_out._M_discarding())
3851 _M_maxwidth = _M_printwidth;
3857 span<_CharT> __new = this->_M_used();
3858 basic_string_view<_CharT> __str(__new.data(), __new.size());
3859 _M_out = __format::__write(std::move(_M_out), __str);
3860 _M_sync_discarding();
3867 auto __str = this->view();
3868 // Compute actual field width, possibly truncated.
3869 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3871 this->_M_trim(__str);
3875 // We have more characters than padidng, no padding is needed,
3876 // write direclty to _M_out.
3877 if (_M_printwidth >= _M_padwidth)
3879 _M_out = __format::__write(std::move(_M_out), __str);
3880 _M_sync_discarding();
3882 // We reached _M_maxwidth that is smaller than _M_padwidth.
3883 // Store the prefix sequence in _M_seq, and free _M_buf.
3885 _Str_sink<_CharT>::_M_overflow();
3887 // Use internal buffer for writes to _M_out.
3888 this->_M_reset(this->_M_buf);
3893 _M_update(size_t __new)
3895 _M_printwidth += __new;
3896 // Compute estimated width, to see if is not reduced.
3897 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3898 return _M_force_update();
3903 _M_overflow() override
3905 // Ignore characters in buffer, and override it.
3908 // Write buffer to _M_out, and override it.
3909 else if (!_M_buffering())
3911 // Update written count, and if input still should be buffered,
3912 // flush the to _M_seq.
3913 else if (_M_update(this->_M_used().size()))
3914 _Str_sink<_CharT>::_M_overflow();
3918 _M_discarding() const override
3919 { return _M_ignoring(); }
3921 typename _Sink<_CharT>::_Reservation
3922 _M_reserve(size_t __n) override
3924 // Ignore characters in buffer, if any.
3927 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3928 if (!_M_buffering())
3930 // Write pending characters if any
3931 if (!this->_M_used().empty())
3933 // Try to reserve from _M_out sink.
3934 if (auto __reserved = _M_out._M_reserve(__n))
3937 return _Sink<_CharT>::_M_reserve(__n);
3941 _M_bump(size_t __n) override
3943 // Ignore the written characters.
3946 // If reservation was made directy sink associated _M_out,
3947 // _M_bump will be called on that sink.
3948 _Sink<_CharT>::_M_bump(__n);
3954 [[__gnu__::__always_inline__]]
3956 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
3957 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
3958 _M_out(std::move(__out)), _M_printwidth(0)
3959 { _M_sync_discarding(); }
3961 [[__gnu__::__always_inline__]]
3963 _Padding_sink(_Out __out, size_t __padwidth)
3964 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
3968 _M_finish(_Align __align, char32_t __fill_char)
3970 // Handle any characters in the buffer.
3971 if (auto __rem = this->_M_used().size())
3975 else if (!_M_buffering())
3981 if (!_M_buffering() || !_M_force_update())
3982 // Characters were already written to _M_out.
3983 if (_M_printwidth >= _M_padwidth)
3984 return std::move(_M_out);
3986 const auto __str = this->view();
3987 if (_M_printwidth >= _M_padwidth)
3988 return __format::__write(std::move(_M_out), __str);
3990 const size_t __nfill = _M_padwidth - _M_printwidth;
3991 return __format::__write_padded(std::move(_M_out), __str,
3992 __align, __nfill, __fill_char);
3996 template<typename _Out, typename _CharT>
3997 class _Escaping_sink : public _Buf_sink<_CharT>
3999 using _Esc = _Escapes<_CharT>;
4002 _Term_char _M_term : 2;
4003 unsigned _M_prev_escape : 1;
4004 unsigned _M_out_discards : 1;
4007 _M_sync_discarding()
4009 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4010 _M_out_discards = _M_out._M_discarding();
4016 span<_CharT> __bytes = this->_M_used();
4017 basic_string_view<_CharT> __str(__bytes.data(), __bytes.size());
4020 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4022 bool __prev_escape = _M_prev_escape;
4023 _M_out = __format::__write_escaped_unicode_part(
4024 std::move(_M_out), __str, __prev_escape, _M_term);
4025 _M_prev_escape = __prev_escape;
4027 __rem = __str.size();
4028 if (__rem > 0 && __str.data() != this->_M_buf) [[unlikely]]
4029 ranges::move(__str, this->_M_buf);
4032 _M_out = __format::__write_escaped_ascii(
4033 std::move(_M_out), __str, _M_term);
4035 this->_M_reset(this->_M_buf, __rem);
4036 _M_sync_discarding();
4040 _M_overflow() override
4042 if (_M_out_discards)
4049 _M_discarding() const override
4050 { return _M_out_discards; }
4053 [[__gnu__::__always_inline__]]
4055 _Escaping_sink(_Out __out, _Term_char __term)
4056 : _M_out(std::move(__out)), _M_term(__term),
4057 _M_prev_escape(true), _M_out_discards(false)
4059 _M_out = __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4060 _M_sync_discarding();
4066 if (_M_out_discards)
4067 return std::move(_M_out);
4069 if (!this->_M_used().empty())
4072 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4073 if (auto __rem = this->_M_used(); !__rem.empty())
4075 basic_string_view<_CharT> __str(__rem.data(), __rem.size());
4076 _M_out = __format::__write_escape_seqs(std::move(_M_out), __str);
4079 return __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4083 enum class _Arg_t : unsigned char {
4084 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
4085 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
4086 _Arg_i128, _Arg_u128, _Arg_float128,
4087 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
4090 #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4091 _Arg_ibm128 = _Arg_ldbl,
4092 _Arg_ieee128 = _Arg_float128,
4097 template<typename _Context>
4100 using _CharT = typename _Context::char_type;
4104 using _CharT = typename _Context::char_type;
4105 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4106 _Context&, const void*);
4108 // Format as const if possible, to reduce instantiations.
4109 template<typename _Tp>
4110 using __maybe_const_t
4111 = __conditional_t<__formattable_with<const _Tp, _Context>,
4114 template<typename _Tq>
4116 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4117 _Context& __format_ctx, const void* __ptr)
4119 using _Td = remove_const_t<_Tq>;
4120 typename _Context::template formatter_type<_Td> __f;
4121 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4122 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4123 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4126 template<typename _Tp>
4127 requires (!is_same_v<remove_cv_t<_Tp>, handle>)
4129 handle(_Tp& __val) noexcept
4130 : _M_ptr(__builtin_addressof(__val))
4131 , _M_func(&_S_format<__maybe_const_t<_Tp>>)
4134 friend class basic_format_arg<_Context>;
4137 handle(const handle&) = default;
4138 handle& operator=(const handle&) = default;
4140 [[__gnu__::__always_inline__]]
4142 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4143 { _M_func(__pc, __fc, this->_M_ptr); }
4158 unsigned long long _M_ull;
4161 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4162 long double _M_ldbl;
4165 __ieee128 _M_ieee128;
4167 #ifdef __SIZEOF_FLOAT128__
4168 __float128 _M_float128;
4170 const _CharT* _M_str;
4171 basic_string_view<_CharT> _M_sv;
4174 #ifdef __SIZEOF_INT128__
4176 unsigned __int128 _M_u128;
4178 #ifdef __BFLT16_DIG__
4181 #ifdef __FLT16_DIG__
4184 #ifdef __FLT32_DIG__
4187 #ifdef __FLT64_DIG__
4192 [[__gnu__::__always_inline__]]
4193 _Arg_value() : _M_none() { }
4196 template<typename _Tp>
4197 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4198 { _S_get<_Tp>() = __val; }
4201 // Returns reference to the _Arg_value member with the type _Tp.
4202 // Value of second argument (if provided), is assigned to that member.
4203 template<typename _Tp, typename _Self, typename... _Value>
4204 [[__gnu__::__always_inline__]]
4206 _S_access(_Self& __u, _Value... __value) noexcept
4208 static_assert(sizeof...(_Value) <= 1);
4209 if constexpr (is_same_v<_Tp, bool>)
4210 return (__u._M_bool = ... = __value);
4211 else if constexpr (is_same_v<_Tp, _CharT>)
4212 return (__u._M_c = ... = __value);
4213 else if constexpr (is_same_v<_Tp, int>)
4214 return (__u._M_i = ... = __value);
4215 else if constexpr (is_same_v<_Tp, unsigned>)
4216 return (__u._M_u = ... = __value);
4217 else if constexpr (is_same_v<_Tp, long long>)
4218 return (__u._M_ll = ... = __value);
4219 else if constexpr (is_same_v<_Tp, unsigned long long>)
4220 return (__u._M_ull = ... = __value);
4221 else if constexpr (is_same_v<_Tp, float>)
4222 return (__u._M_flt = ... = __value);
4223 else if constexpr (is_same_v<_Tp, double>)
4224 return (__u._M_dbl = ... = __value);
4225 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4226 else if constexpr (is_same_v<_Tp, long double>)
4227 return (__u._M_ldbl = ... = __value);
4229 else if constexpr (is_same_v<_Tp, __ibm128>)
4230 return (__u._M_ibm128 = ... = __value);
4231 else if constexpr (is_same_v<_Tp, __ieee128>)
4232 return (__u._M_ieee128 = ... = __value);
4234 #ifdef __SIZEOF_FLOAT128__
4235 else if constexpr (is_same_v<_Tp, __float128>)
4236 return (__u._M_float128 = ... = __value);
4238 else if constexpr (is_same_v<_Tp, const _CharT*>)
4239 return (__u._M_str = ... = __value);
4240 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4241 return (__u._M_sv = ... = __value);
4242 else if constexpr (is_same_v<_Tp, const void*>)
4243 return (__u._M_ptr = ... = __value);
4244 #ifdef __SIZEOF_INT128__
4245 else if constexpr (is_same_v<_Tp, __int128>)
4246 return (__u._M_i128 = ... = __value);
4247 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4248 return (__u._M_u128 = ... = __value);
4250 #ifdef __BFLT16_DIG__
4251 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4252 return (__u._M_bf16 = ... = __value);
4254 #ifdef __FLT16_DIG__
4255 else if constexpr (is_same_v<_Tp, _Float16>)
4256 return (__u._M_f16 = ... = __value);
4258 #ifdef __FLT32_DIG__
4259 else if constexpr (is_same_v<_Tp, _Float32>)
4260 return (__u._M_f32 = ... = __value);
4262 #ifdef __FLT64_DIG__
4263 else if constexpr (is_same_v<_Tp, _Float64>)
4264 return (__u._M_f64 = ... = __value);
4266 else if constexpr (is_same_v<_Tp, handle>)
4267 return __u._M_handle;
4268 // Otherwise, ill-formed.
4271 template<typename _Tp>
4272 [[__gnu__::__always_inline__]]
4275 { return _S_access<_Tp>(*this); }
4277 template<typename _Tp>
4278 [[__gnu__::__always_inline__]]
4280 _M_get() const noexcept
4281 { return _S_access<_Tp>(*this); }
4283 template<typename _Tp>
4284 [[__gnu__::__always_inline__]]
4286 _M_set(_Tp __v) noexcept
4288 // Explicitly construct types without trivial default constructor.
4289 if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4290 std::construct_at(&_M_sv, __v);
4291 else if constexpr (is_same_v<_Tp, handle>)
4292 std::construct_at(&_M_handle, __v);
4294 // Builtin types are trivially default constructible, and assignment
4295 // changes active member per N5032 [class.union.general] p5.
4296 _S_access<_Tp>(*this, __v);
4300 // [format.arg.store], class template format-arg-store
4301 template<typename _Context, typename... _Args>
4304 template<typename _Visitor, typename _Ctx>
4305 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4307 template<typename _Ch, typename _Tp>
4309 __to_arg_t_enum() noexcept;
4310 } // namespace __format
4313 template<typename _Context>
4314 class basic_format_arg
4316 using _CharT = typename _Context::char_type;
4319 using handle = __format::_Arg_value<_Context>::handle;
4321 [[__gnu__::__always_inline__]]
4322 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4324 [[nodiscard,__gnu__::__always_inline__]]
4325 explicit operator bool() const noexcept
4326 { return _M_type != __format::_Arg_none; }
4328 #if __cpp_lib_format >= 202306L // >= C++26
4329 template<typename _Visitor>
4331 visit(this basic_format_arg __arg, _Visitor&& __vis)
4332 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4334 template<typename _Res, typename _Visitor>
4336 visit(this basic_format_arg __arg, _Visitor&& __vis)
4337 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4341 template<typename _Ctx>
4342 friend class basic_format_args;
4344 template<typename _Ctx, typename... _Args>
4345 friend class __format::_Arg_store;
4347 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4349 __format::_Arg_value<_Context> _M_val;
4350 __format::_Arg_t _M_type;
4352 // Transform incoming argument type to the type stored in _Arg_value.
4353 // e.g. short -> int, std::string -> std::string_view,
4354 // char[3] -> const char*.
4355 template<typename _Tp>
4356 static consteval auto
4359 using _Td = remove_const_t<_Tp>;
4360 if constexpr (is_same_v<_Td, bool>)
4361 return type_identity<bool>();
4362 else if constexpr (is_same_v<_Td, _CharT>)
4363 return type_identity<_CharT>();
4364 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4365 return type_identity<_CharT>();
4366 #ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4367 else if constexpr (is_same_v<_Td, __int128>)
4368 return type_identity<__int128>();
4369 else if constexpr (is_same_v<_Td, unsigned __int128>)
4370 return type_identity<unsigned __int128>();
4372 else if constexpr (__is_signed_integer<_Td>::value)
4374 if constexpr (sizeof(_Td) <= sizeof(int))
4375 return type_identity<int>();
4376 else if constexpr (sizeof(_Td) <= sizeof(long long))
4377 return type_identity<long long>();
4379 else if constexpr (__is_unsigned_integer<_Td>::value)
4381 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4382 return type_identity<unsigned>();
4383 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4384 return type_identity<unsigned long long>();
4386 else if constexpr (is_same_v<_Td, float>)
4387 return type_identity<float>();
4388 else if constexpr (is_same_v<_Td, double>)
4389 return type_identity<double>();
4390 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4391 else if constexpr (is_same_v<_Td, long double>)
4392 return type_identity<long double>();
4394 else if constexpr (is_same_v<_Td, __ibm128>)
4395 return type_identity<__ibm128>();
4396 else if constexpr (is_same_v<_Td, __ieee128>)
4397 return type_identity<__ieee128>();
4399 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4400 else if constexpr (is_same_v<_Td, __float128>)
4401 return type_identity<__float128>();
4403 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4404 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4405 return type_identity<__format::__bflt16_t>();
4407 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4408 else if constexpr (is_same_v<_Td, _Float16>)
4409 return type_identity<_Float16>();
4411 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4412 else if constexpr (is_same_v<_Td, _Float32>)
4413 return type_identity<_Float32>();
4415 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4416 else if constexpr (is_same_v<_Td, _Float64>)
4417 return type_identity<_Float64>();
4419 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4420 || __is_specialization_of<_Td, basic_string>)
4422 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4423 return type_identity<basic_string_view<_CharT>>();
4425 return type_identity<handle>();
4427 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4428 return type_identity<const _CharT*>();
4429 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4430 return type_identity<const _CharT*>();
4431 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4432 return type_identity<const void*>();
4433 else if constexpr (is_same_v<_Td, nullptr_t>)
4434 return type_identity<const void*>();
4436 return type_identity<handle>();
4439 // Transform a formattable type to the appropriate storage type.
4440 template<typename _Tp>
4441 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4443 // Get the _Arg_t value corresponding to a normalized type.
4444 template<typename _Tp>
4445 static consteval __format::_Arg_t
4448 using namespace __format;
4449 if constexpr (is_same_v<_Tp, bool>)
4451 else if constexpr (is_same_v<_Tp, _CharT>)
4453 else if constexpr (is_same_v<_Tp, int>)
4455 else if constexpr (is_same_v<_Tp, unsigned>)
4457 else if constexpr (is_same_v<_Tp, long long>)
4459 else if constexpr (is_same_v<_Tp, unsigned long long>)
4461 else if constexpr (is_same_v<_Tp, float>)
4463 else if constexpr (is_same_v<_Tp, double>)
4465 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4466 else if constexpr (is_same_v<_Tp, long double>)
4469 // Don't use _Arg_ldbl for this target, it's ambiguous.
4470 else if constexpr (is_same_v<_Tp, __ibm128>)
4472 else if constexpr (is_same_v<_Tp, __ieee128>)
4473 return _Arg_ieee128;
4475 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4476 else if constexpr (is_same_v<_Tp, __float128>)
4477 return _Arg_float128;
4479 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4480 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4483 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4484 else if constexpr (is_same_v<_Tp, _Float16>)
4487 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4488 else if constexpr (is_same_v<_Tp, _Float32>)
4491 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4492 else if constexpr (is_same_v<_Tp, _Float64>)
4495 else if constexpr (is_same_v<_Tp, const _CharT*>)
4497 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4499 else if constexpr (is_same_v<_Tp, const void*>)
4501 #ifdef __SIZEOF_INT128__
4502 else if constexpr (is_same_v<_Tp, __int128>)
4504 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4507 else if constexpr (is_same_v<_Tp, handle>)
4511 template<typename _Tp>
4513 _M_set(_Tp __v) noexcept
4515 _M_type = _S_to_enum<_Tp>();
4519 template<typename _Tp>
4520 requires __format::__formattable_with<_Tp, _Context>
4522 basic_format_arg(_Tp& __v) noexcept
4524 using _Td = _Normalize<_Tp>;
4525 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4526 _M_set(_Td{__v.data(), __v.size()});
4527 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4528 && is_same_v<_CharT, wchar_t>)
4529 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4531 _M_set(static_cast<_Td>(__v));
4534 template<typename _Ctx, typename... _Argz>
4536 make_format_args(_Argz&...) noexcept;
4538 template<typename _Visitor, typename _Ctx>
4539 friend decltype(auto)
4540 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4542 template<typename _Visitor, typename _Ctx>
4543 friend decltype(auto)
4544 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4546 template<typename _Ch, typename _Tp>
4547 friend consteval __format::_Arg_t
4548 __format::__to_arg_t_enum() noexcept;
4550 [[__gnu__::__noinline__]]
4552 _M_handle_unrecognized() const;
4554 template<typename _Visitor>
4556 _M_visit(_Visitor&& __vis)
4560 using enum __format::_Arg_t;
4562 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4564 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4566 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4568 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4570 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4572 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4574 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4575 #if __glibcxx_to_chars // FIXME: need to be able to format these types!
4577 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4579 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4580 #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4582 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4583 #if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4585 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4589 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4591 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4593 #if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4595 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4597 #if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4599 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4601 #if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4603 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4605 #if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4607 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4609 #endif // __glibcxx_to_chars
4611 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4613 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4615 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4617 return std::forward<_Visitor>(__vis)(_M_val._M_handle);
4618 #ifdef __SIZEOF_INT128__
4620 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4622 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4625 // Call exported definition of _M_handle_unrecognized from
4626 // libstdc++.so, that should recognize new _Arg_t values and
4627 // return basic_format_arg, containing a handle to that value.
4628 handle __h = _M_handle_unrecognized();
4629 return std::forward<_Visitor>(__vis)(__h);
4633 template<typename _Visitor>
4635 _M_visit_user(_Visitor&& __vis)
4637 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4639 constexpr bool __user_facing = __is_one_of<_Tp,
4640 monostate, bool, _CharT,
4641 int, unsigned int, long long int, unsigned long long int,
4642 float, double, long double,
4643 const _CharT*, basic_string_view<_CharT>,
4644 const void*, handle>::value;
4645 if constexpr (__user_facing)
4646 return std::forward<_Visitor>(__vis)(__val);
4650 return std::forward<_Visitor>(__vis)(__h);
4656 template<typename _Visitor, typename _Context>
4657 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4658 inline decltype(auto)
4659 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4660 { return __arg._M_visit_user(std::forward<_Visitor>(__vis)); }
4662 /// @cond undocumented
4665 template<typename _Visitor, typename _Ctx>
4666 inline decltype(auto)
4667 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4668 { return __arg._M_visit(std::forward<_Visitor>(__vis)); }
4670 struct _WidthPrecVisitor
4672 template<typename _Tp>
4674 operator()(_Tp& __arg) const
4676 if constexpr (is_same_v<_Tp, monostate>)
4677 __format::__invalid_arg_id_in_format_string();
4678 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4679 // 3720. Restrict the valid types of arg-id for width and precision
4680 // 3721. Allow an arg-id with a value of zero for width
4681 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4683 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4684 // 3720. Restrict the valid types of arg-id for width and precision
4685 if constexpr (__is_unsigned_integer<_Tp>::value)
4687 else if constexpr (__is_signed_integer<_Tp>::value)
4691 __throw_format_error("format error: argument used for width or "
4692 "precision must be a non-negative integer");
4696 #pragma GCC diagnostic push
4697 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4698 template<typename _Context>
4700 __int_from_arg(const basic_format_arg<_Context>& __arg)
4701 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4703 // Pack _Arg_t enum values into a single 60-bit integer.
4704 template<int _Bits, size_t _Nm>
4706 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4708 __UINT64_TYPE__ __packed_types = 0;
4709 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4710 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4711 return __packed_types;
4713 } // namespace __format
4716 template<typename _Context>
4717 class basic_format_args
4719 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4720 static constexpr int _S_packed_type_mask = 0b11111;
4721 static constexpr int _S_max_packed_args = 12;
4723 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4725 template<typename... _Args>
4726 using _Store = __format::_Arg_store<_Context, _Args...>;
4728 template<typename _Ctx, typename... _Args>
4729 friend class __format::_Arg_store;
4731 using uint64_t = __UINT64_TYPE__;
4732 using _Format_arg = basic_format_arg<_Context>;
4733 using _Format_arg_val = __format::_Arg_value<_Context>;
4735 // If args are packed then the number of args is in _M_packed_size and
4736 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4737 // If args are not packed then the number of args is in _M_unpacked_size
4738 // and _M_packed_size is zero.
4739 uint64_t _M_packed_size : 4;
4740 uint64_t _M_unpacked_size : 60;
4743 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4744 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4748 _M_size() const noexcept
4749 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4751 typename __format::_Arg_t
4752 _M_type(size_t __i) const noexcept
4754 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4755 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4758 template<typename _Ctx, typename... _Args>
4760 make_format_args(_Args&...) noexcept;
4762 // An array of _Arg_t enums corresponding to _Args...
4763 template<typename... _Args>
4764 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4766 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4769 template<typename... _Args>
4770 basic_format_args(const _Store<_Args...>& __store) noexcept;
4772 [[nodiscard,__gnu__::__always_inline__]]
4773 basic_format_arg<_Context>
4774 get(size_t __i) const noexcept
4776 basic_format_arg<_Context> __arg;
4777 if (__i < _M_packed_size)
4779 __arg._M_type = _M_type(__i);
4780 __arg._M_val = _M_values[__i];
4782 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4783 __arg = _M_args[__i];
4788 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4789 // 3810. CTAD for std::basic_format_args
4790 template<typename _Context, typename... _Args>
4791 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4792 -> basic_format_args<_Context>;
4794 template<typename _Context, typename... _Args>
4796 make_format_args(_Args&... __fmt_args) noexcept;
4798 // An array of type-erased formatting arguments.
4799 template<typename _Context, typename... _Args>
4800 class __format::_Arg_store
4802 friend std::basic_format_args<_Context>;
4804 template<typename _Ctx, typename... _Argz>
4806 #if _GLIBCXX_INLINE_VERSION
4807 __8:: // Needed for PR c++/59256
4809 make_format_args(_Argz&...) noexcept;
4811 // For a sufficiently small number of arguments we only store values.
4812 // basic_format_args can get the types from the _Args pack.
4813 static constexpr bool _S_values_only
4814 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4817 = __conditional_t<_S_values_only,
4818 __format::_Arg_value<_Context>,
4819 basic_format_arg<_Context>>;
4821 _Element_t _M_args[sizeof...(_Args)];
4823 template<typename _Tp>
4825 _S_make_elt(_Tp& __v)
4827 using _Tq = remove_const_t<_Tp>;
4828 using _CharT = typename _Context::char_type;
4829 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4830 "std::formatter must be specialized for the type "
4831 "of each format arg");
4832 using __format::__formattable_with;
4833 if constexpr (is_const_v<_Tp>)
4834 if constexpr (!__formattable_with<_Tp, _Context>)
4835 if constexpr (__formattable_with<_Tq, _Context>)
4836 static_assert(__formattable_with<_Tp, _Context>,
4837 "format arg must be non-const because its "
4838 "std::formatter specialization has a "
4839 "non-const reference parameter");
4840 basic_format_arg<_Context> __arg(__v);
4841 if constexpr (_S_values_only)
4842 return __arg._M_val;
4847 template<typename... _Tp>
4848 requires (sizeof...(_Tp) == sizeof...(_Args))
4849 [[__gnu__::__always_inline__]]
4850 _Arg_store(_Tp&... __a) noexcept
4851 : _M_args{_S_make_elt(__a)...}
4855 template<typename _Context>
4856 class __format::_Arg_store<_Context>
4859 template<typename _Context>
4860 template<typename... _Args>
4862 basic_format_args<_Context>::
4863 basic_format_args(const _Store<_Args...>& __store) noexcept
4865 if constexpr (sizeof...(_Args) == 0)
4868 _M_unpacked_size = 0;
4871 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4873 // The number of packed arguments:
4874 _M_packed_size = sizeof...(_Args);
4875 // The packed type enums:
4877 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4878 // The _Arg_value objects.
4879 _M_values = __store._M_args;
4883 // No packed arguments:
4885 // The number of unpacked arguments:
4886 _M_unpacked_size = sizeof...(_Args);
4887 // The basic_format_arg objects:
4888 _M_args = __store._M_args;
4892 /// Capture formatting arguments for use by `std::vformat`.
4893 template<typename _Context = format_context, typename... _Args>
4894 [[nodiscard,__gnu__::__always_inline__]]
4896 make_format_args(_Args&... __fmt_args) noexcept
4898 using _Fmt_arg = basic_format_arg<_Context>;
4899 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4900 _Normalize<_Args>...>;
4901 return _Store(__fmt_args...);
4904 #ifdef _GLIBCXX_USE_WCHAR_T
4905 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4906 template<typename... _Args>
4907 [[nodiscard,__gnu__::__always_inline__]]
4909 make_wformat_args(_Args&... __args) noexcept
4910 { return std::make_format_args<wformat_context>(__args...); }
4913 /// @cond undocumented
4916 template<typename _Out, typename _CharT, typename _Context>
4918 __do_vformat_to(_Out, basic_string_view<_CharT>,
4919 const basic_format_args<_Context>&,
4920 const locale* = nullptr);
4922 template<typename _CharT> struct __formatter_chrono;
4924 } // namespace __format
4927 /** Context for std::format and similar functions.
4929 * A formatting context contains an output iterator and locale to use
4930 * for the formatting operations. Most programs will never need to use
4931 * this class template explicitly. For typical uses of `std::format` the
4932 * library will use the specializations `std::format_context` (for `char`)
4933 * and `std::wformat_context` (for `wchar_t`).
4935 * You are not allowed to define partial or explicit specializations of
4936 * this class template.
4940 template<typename _Out, typename _CharT>
4941 class basic_format_context
4943 static_assert( output_iterator<_Out, const _CharT&> );
4945 basic_format_args<basic_format_context> _M_args;
4947 __format::_Optional_locale _M_loc;
4949 basic_format_context(basic_format_args<basic_format_context> __args,
4951 : _M_args(__args), _M_out(std::move(__out))
4954 basic_format_context(basic_format_args<basic_format_context> __args,
4955 _Out __out, const std::locale& __loc)
4956 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4959 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4960 // 4061. Should std::basic_format_context be
4961 // default-constructible/copyable/movable?
4962 basic_format_context(const basic_format_context&) = delete;
4963 basic_format_context& operator=(const basic_format_context&) = delete;
4965 template<typename _Out2, typename _CharT2, typename _Context2>
4967 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4968 const basic_format_args<_Context2>&,
4971 friend __format::__formatter_chrono<_CharT>;
4974 ~basic_format_context() = default;
4976 using iterator = _Out;
4977 using char_type = _CharT;
4978 template<typename _Tp>
4979 using formatter_type = formatter<_Tp, _CharT>;
4982 basic_format_arg<basic_format_context>
4983 arg(size_t __id) const noexcept
4984 { return _M_args.get(__id); }
4987 std::locale locale() { return _M_loc.value(); }
4990 iterator out() { return std::move(_M_out); }
4992 void advance_to(iterator __it) { _M_out = std::move(__it); }
4995 #if _GLIBCXX_EXTERN_TEMPLATE
4996 // The defintion _M_handle_unrecognized is placed in format-inst.cc
4997 // source file, to ensure that it will not be inlined by compiler.
4998 extern template basic_format_arg<format_context>::handle
4999 basic_format_arg<format_context>::_M_handle_unrecognized() const;
5000 # ifdef _GLIBCXX_USE_WCHAR_T
5001 extern template basic_format_arg<wformat_context>::handle
5002 basic_format_arg<wformat_context>::_M_handle_unrecognized() const;
5005 template<typename _Context>
5006 typename basic_format_arg<_Context>::handle
5007 basic_format_arg<_Context>::_M_handle_unrecognized() const
5009 // If _M_type corresponds to a new value of _Arg_t introduced after
5010 // GCC 16, this function should return a handle that refers to the
5011 // union member of _M_val corresponding to that _Arg_t value.
5012 __throw_format_error("format error: unrecognized argument type");
5016 /// @cond undocumented
5019 // Abstract base class defining an interface for scanning format strings.
5020 // Scan the characters in a format string, dividing it up into strings of
5021 // ordinary characters, escape sequences, and replacement fields.
5022 // Call virtual functions for derived classes to parse format-specifiers
5023 // or write formatted output.
5024 template<typename _CharT>
5027 using iterator = typename basic_format_parse_context<_CharT>::iterator;
5029 struct _Parse_context : basic_format_parse_context<_CharT>
5031 using basic_format_parse_context<_CharT>::basic_format_parse_context;
5032 const _Arg_t* _M_types = nullptr;
5036 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
5037 : _M_pc(__str, __nargs)
5040 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
5041 constexpr iterator end() const noexcept { return _M_pc.end(); }
5046 basic_string_view<_CharT> __fmt = _M_fmt_str();
5048 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5050 _M_pc.advance_to(begin() + 1);
5051 _M_format_arg(_M_pc.next_arg_id());
5055 size_t __lbr = __fmt.find('{');
5056 size_t __rbr = __fmt.find('}');
5058 while (__fmt.size())
5060 auto __cmp = __lbr <=> __rbr;
5064 _M_pc.advance_to(end());
5069 if (__lbr + 1 == __fmt.size()
5070 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
5071 __format::__unmatched_left_brace_in_format_string();
5072 const bool __is_escape = __fmt[__lbr + 1] == '{';
5073 iterator __last = begin() + __lbr + int(__is_escape);
5074 _M_on_chars(__last);
5075 _M_pc.advance_to(__last + 1);
5076 __fmt = _M_fmt_str();
5079 if (__rbr != __fmt.npos)
5081 __lbr = __fmt.find('{');
5085 _M_on_replacement_field();
5086 __fmt = _M_fmt_str();
5087 __lbr = __fmt.find('{');
5088 __rbr = __fmt.find('}');
5093 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
5094 __format::__unmatched_right_brace_in_format_string();
5095 iterator __last = begin() + __rbr;
5096 _M_on_chars(__last);
5097 _M_pc.advance_to(__last + 1);
5098 __fmt = _M_fmt_str();
5099 if (__lbr != __fmt.npos)
5101 __rbr = __fmt.find('}');
5106 constexpr basic_string_view<_CharT>
5107 _M_fmt_str() const noexcept
5108 { return {begin(), end()}; }
5110 constexpr virtual void _M_on_chars(iterator) { }
5112 constexpr void _M_on_replacement_field()
5114 auto __next = begin();
5118 __id = _M_pc.next_arg_id();
5119 else if (*__next == ':')
5121 __id = _M_pc.next_arg_id();
5122 _M_pc.advance_to(++__next);
5126 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5127 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5128 __format::__invalid_arg_id_in_format_string();
5129 _M_pc.check_arg_id(__id = __i);
5132 _M_pc.advance_to(++__ptr);
5135 _M_pc.advance_to(__ptr);
5137 _M_format_arg(__id);
5138 if (begin() == end() || *begin() != '}')
5139 __format::__unmatched_left_brace_in_format_string();
5140 _M_pc.advance_to(begin() + 1); // Move past '}'
5143 constexpr virtual void _M_format_arg(size_t __id) = 0;
5146 // Process a format string and format the arguments in the context.
5147 template<typename _Out, typename _CharT>
5148 class _Formatting_scanner : public _Scanner<_CharT>
5151 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5152 basic_string_view<_CharT> __str)
5153 : _Scanner<_CharT>(__str), _M_fc(__fc)
5157 basic_format_context<_Out, _CharT>& _M_fc;
5159 using iterator = typename _Scanner<_CharT>::iterator;
5162 _M_on_chars(iterator __last) override
5164 basic_string_view<_CharT> __str(this->begin(), __last);
5165 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5169 _M_format_arg(size_t __id) override
5171 using _Context = basic_format_context<_Out, _CharT>;
5172 using handle = typename basic_format_arg<_Context>::handle;
5174 __format::__visit_format_arg([this](auto& __arg) {
5175 using _Type = remove_reference_t<decltype(__arg)>;
5176 using _Formatter = typename _Context::template formatter_type<_Type>;
5177 if constexpr (is_same_v<_Type, monostate>)
5178 __format::__invalid_arg_id_in_format_string();
5179 else if constexpr (is_same_v<_Type, handle>)
5180 __arg.format(this->_M_pc, this->_M_fc);
5181 else if constexpr (is_default_constructible_v<_Formatter>)
5184 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5185 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5188 static_assert(__format::__formattable_with<_Type, _Context>);
5189 }, _M_fc.arg(__id));
5193 template<typename _CharT, typename _Tp>
5195 __to_arg_t_enum() noexcept
5197 using _Context = __format::__format_context<_CharT>;
5198 using _Fmt_arg = basic_format_arg<_Context>;
5199 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5200 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5203 // Validate a format string for Args.
5204 template<typename _CharT, typename... _Args>
5205 class _Checking_scanner : public _Scanner<_CharT>
5208 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5209 "std::formatter must be specialized for each type being formatted");
5213 _Checking_scanner(basic_string_view<_CharT> __str)
5214 : _Scanner<_CharT>(__str, sizeof...(_Args))
5216 #if __cpp_lib_format >= 202305L
5217 this->_M_pc._M_types = _M_types.data();
5223 _M_format_arg(size_t __id) override
5225 if constexpr (sizeof...(_Args) != 0)
5227 if (__id < sizeof...(_Args))
5229 _M_parse_format_spec<_Args...>(__id);
5233 __builtin_unreachable();
5236 template<typename _Tp, typename... _OtherArgs>
5238 _M_parse_format_spec(size_t __id)
5242 formatter<_Tp, _CharT> __f;
5243 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5245 else if constexpr (sizeof...(_OtherArgs) != 0)
5246 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5248 __builtin_unreachable();
5251 #if __cpp_lib_format >= 202305L
5252 array<_Arg_t, sizeof...(_Args)>
5253 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5257 template<typename _CharT, unsigned = __unicode::__literal_encoding_is_unicode<_CharT>()>
5259 __do_vformat_to(_Sink_iter<_CharT> __out, basic_string_view<_CharT> __fmt,
5260 __format_context<_CharT>& __ctx)
5262 if constexpr (is_same_v<_CharT, char>)
5263 // Fast path for "{}" format strings and simple format arg types.
5264 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5266 bool __done = false;
5267 __format::__visit_format_arg([&](auto& __arg) {
5268 using _Tp = remove_cvref_t<decltype(__arg)>;
5269 if constexpr (is_same_v<_Tp, bool>)
5271 size_t __len = 4 + !__arg;
5272 const char* __chars[] = { "false", "true" };
5273 if (auto __res = __out._M_reserve(__len))
5275 __builtin_memcpy(__res.get(), __chars[__arg], __len);
5276 __res._M_bump(__len);
5280 else if constexpr (is_same_v<_Tp, char>)
5282 if (auto __res = __out._M_reserve(1))
5284 *__res.get() = __arg;
5289 else if constexpr (is_integral_v<_Tp>)
5291 make_unsigned_t<_Tp> __uval;
5292 const bool __neg = __arg < 0;
5294 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5297 const auto __n = __detail::__to_chars_len(__uval);
5298 if (auto __res = __out._M_reserve(__n + __neg))
5300 auto __ptr = __res.get();
5302 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5304 __res._M_bump(__n + __neg);
5308 else if constexpr (is_convertible_v<_Tp, string_view>)
5310 string_view __sv = __arg;
5311 if (auto __res = __out._M_reserve(__sv.size()))
5313 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5314 __res._M_bump(__sv.size());
5324 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5325 __scanner._M_scan();
5329 // The behavior of the formatters (interpretation of fill character) depends
5330 // on the literal encoding. As explicit instantiation of __do_vformat_to
5331 // instantiates formatters for types stored in basic_format_arg, we can
5332 // support only single encoding, in this case unicode. This should cover
5333 // most common use cases.
5334 #if __cplusplus <= 202002L && _GLIBCXX_EXTERN_TEMPLATE
5335 extern template _Sink_iter<char>
5336 __do_vformat_to<char, 1>(_Sink_iter<char>, string_view,
5338 # ifdef _GLIBCXX_USE_WCHAR_T
5339 extern template _Sink_iter<wchar_t>
5340 __do_vformat_to<wchar_t, 1>(_Sink_iter<wchar_t>, wstring_view,
5345 template<typename _Out, typename _CharT, typename _Context>
5347 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5348 const basic_format_args<_Context>& __args,
5349 const locale* __loc)
5351 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5353 auto __ctx = __loc == nullptr
5354 ? _Context(__args, __out)
5355 : _Context(__args, __out, *__loc);
5356 return __format::__do_vformat_to(__out, __fmt, __ctx);
5358 else if constexpr (__contiguous_char_iter<_CharT, _Out>)
5360 _Ptr_sink<_CharT> __sink(__out);
5361 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5362 return std::move(__sink)._M_finish(__out).out;
5366 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5367 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5368 return std::move(__sink)._M_finish().out;
5372 template<typename _Out, typename _CharT>
5373 inline format_to_n_result<_Out>
5374 __do_vformat_to_n(_Out __out, iter_difference_t<_Out> __n,
5375 basic_string_view<_CharT> __fmt,
5376 const type_identity_t<
5377 basic_format_args<__format_context<_CharT>>>& __args,
5378 const locale* __loc = nullptr)
5380 if constexpr (__contiguous_char_iter<_CharT, _Out>)
5382 _Ptr_sink<_CharT> __sink(__out, __n);
5383 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5384 return std::move(__sink)._M_finish(__out);
5388 _Iter_sink<_CharT, _Out> __sink(std::move(__out), __n);
5389 __format::__do_vformat_to(__sink.out(), __fmt, __args, __loc);
5390 return std::move(__sink)._M_finish();
5394 #pragma GCC diagnostic pop
5396 } // namespace __format
5399 #if __cpp_lib_format >= 202305L // >= C++26
5400 /// @cond undocumented
5401 // Common implementation of check_dynamic_spec{,_string,_integral}
5402 template<typename _CharT>
5403 template<typename... _Ts>
5405 basic_format_parse_context<_CharT>::
5406 __check_dynamic_spec(size_t __id) noexcept
5408 if (__id >= _M_num_args)
5409 __format::__invalid_arg_id_in_format_string();
5410 if constexpr (sizeof...(_Ts) != 0)
5412 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5413 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
5414 __format::_Arg_t __types[] = {
5415 __format::__to_arg_t_enum<_CharT, _Ts>()...
5417 for (auto __t : __types)
5421 __invalid_dynamic_spec("arg(id) type does not match");
5426 template<typename _CharT, typename... _Args>
5427 template<typename _Tp>
5428 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5430 basic_format_string<_CharT, _Args...>::
5431 basic_format_string(const _Tp& __s)
5434 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5436 __scanner._M_scan();
5439 // [format.functions], formatting functions
5441 template<typename _Out> requires output_iterator<_Out, const char&>
5442 [[__gnu__::__always_inline__]]
5444 vformat_to(_Out __out, string_view __fmt, format_args __args)
5445 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5447 #ifdef _GLIBCXX_USE_WCHAR_T
5448 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5449 [[__gnu__::__always_inline__]]
5451 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5452 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5455 template<typename _Out> requires output_iterator<_Out, const char&>
5456 [[__gnu__::__always_inline__]]
5458 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5461 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5464 #ifdef _GLIBCXX_USE_WCHAR_T
5465 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5466 [[__gnu__::__always_inline__]]
5468 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5469 wformat_args __args)
5471 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5477 vformat(string_view __fmt, format_args __args)
5479 __format::_Str_sink<char> __buf;
5480 std::vformat_to(__buf.out(), __fmt, __args);
5481 return std::move(__buf).get();
5484 #ifdef _GLIBCXX_USE_WCHAR_T
5487 vformat(wstring_view __fmt, wformat_args __args)
5489 __format::_Str_sink<wchar_t> __buf;
5490 std::vformat_to(__buf.out(), __fmt, __args);
5491 return std::move(__buf).get();
5497 vformat(const locale& __loc, string_view __fmt, format_args __args)
5499 __format::_Str_sink<char> __buf;
5500 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5501 return std::move(__buf).get();
5504 #ifdef _GLIBCXX_USE_WCHAR_T
5507 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5509 __format::_Str_sink<wchar_t> __buf;
5510 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5511 return std::move(__buf).get();
5515 template<typename... _Args>
5518 format(format_string<_Args...> __fmt, _Args&&... __args)
5519 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5521 #ifdef _GLIBCXX_USE_WCHAR_T
5522 template<typename... _Args>
5525 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5526 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5529 template<typename... _Args>
5532 format(const locale& __loc, format_string<_Args...> __fmt,
5535 return std::vformat(__loc, __fmt.get(),
5536 std::make_format_args(__args...));
5539 #ifdef _GLIBCXX_USE_WCHAR_T
5540 template<typename... _Args>
5543 format(const locale& __loc, wformat_string<_Args...> __fmt,
5546 return std::vformat(__loc, __fmt.get(),
5547 std::make_wformat_args(__args...));
5551 template<typename _Out, typename... _Args>
5552 requires output_iterator<_Out, const char&>
5554 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5556 return std::vformat_to(std::move(__out), __fmt.get(),
5557 std::make_format_args(__args...));
5560 #ifdef _GLIBCXX_USE_WCHAR_T
5561 template<typename _Out, typename... _Args>
5562 requires output_iterator<_Out, const wchar_t&>
5564 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5566 return std::vformat_to(std::move(__out), __fmt.get(),
5567 std::make_wformat_args(__args...));
5571 template<typename _Out, typename... _Args>
5572 requires output_iterator<_Out, const char&>
5574 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5577 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5578 std::make_format_args(__args...));
5581 #ifdef _GLIBCXX_USE_WCHAR_T
5582 template<typename _Out, typename... _Args>
5583 requires output_iterator<_Out, const wchar_t&>
5585 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5588 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5589 std::make_wformat_args(__args...));
5593 template<typename _Out, typename... _Args>
5594 requires output_iterator<_Out, const char&>
5595 inline format_to_n_result<_Out>
5596 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5597 format_string<_Args...> __fmt, _Args&&... __args)
5599 return __format::__do_vformat_to_n(
5600 std::move(__out), __n, __fmt.get(),
5601 std::make_format_args(__args...));
5604 #ifdef _GLIBCXX_USE_WCHAR_T
5605 template<typename _Out, typename... _Args>
5606 requires output_iterator<_Out, const wchar_t&>
5607 inline format_to_n_result<_Out>
5608 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5609 wformat_string<_Args...> __fmt, _Args&&... __args)
5611 return __format::__do_vformat_to_n(
5612 std::move(__out), __n, __fmt.get(),
5613 std::make_wformat_args(__args...));
5617 template<typename _Out, typename... _Args>
5618 requires output_iterator<_Out, const char&>
5619 inline format_to_n_result<_Out>
5620 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5621 format_string<_Args...> __fmt, _Args&&... __args)
5623 return __format::__do_vformat_to_n(
5624 std::move(__out), __n, __fmt.get(),
5625 std::make_format_args(__args...), &__loc);
5628 #ifdef _GLIBCXX_USE_WCHAR_T
5629 template<typename _Out, typename... _Args>
5630 requires output_iterator<_Out, const wchar_t&>
5631 inline format_to_n_result<_Out>
5632 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5633 wformat_string<_Args...> __fmt, _Args&&... __args)
5635 return __format::__do_vformat_to_n(
5636 std::move(__out), __n, __fmt.get(),
5637 std::make_wformat_args(__args...), &__loc);
5641 /// @cond undocumented
5645 template<typename _CharT>
5646 class _Counting_sink final : public _Ptr_sink<_CharT>
5649 _Counting_sink() : _Ptr_sink<_CharT>(nullptr, 0) { }
5651 [[__gnu__::__always_inline__]]
5654 { return this->_M_count + this->_M_used().size(); }
5657 template<typename _CharT>
5658 class _Counting_sink : public _Buf_sink<_CharT>
5660 size_t _M_count = 0;
5663 _M_overflow() override
5665 if (!std::is_constant_evaluated())
5666 _M_count += this->_M_used().size();
5671 _Counting_sink() = default;
5673 [[__gnu__::__always_inline__]]
5677 _Counting_sink::_M_overflow();
5682 } // namespace __format
5685 template<typename... _Args>
5688 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5690 __format::_Counting_sink<char> __buf;
5691 std::vformat_to(__buf.out(), __fmt.get(),
5692 std::make_format_args(__args...));
5693 return __buf.count();
5696 #ifdef _GLIBCXX_USE_WCHAR_T
5697 template<typename... _Args>
5700 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5702 __format::_Counting_sink<wchar_t> __buf;
5703 std::vformat_to(__buf.out(), __fmt.get(),
5704 std::make_wformat_args(__args...));
5705 return __buf.count();
5709 template<typename... _Args>
5712 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5715 __format::_Counting_sink<char> __buf;
5716 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5717 std::make_format_args(__args...));
5718 return __buf.count();
5721 #ifdef _GLIBCXX_USE_WCHAR_T
5722 template<typename... _Args>
5725 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5728 __format::_Counting_sink<wchar_t> __buf;
5729 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5730 std::make_wformat_args(__args...));
5731 return __buf.count();
5735 #if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5736 /// @cond undocumented
5737 template<typename _Tp>
5738 consteval range_format
5741 using _Ref = ranges::range_reference_t<_Tp>;
5742 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5743 return range_format::disabled;
5744 else if constexpr (requires { typename _Tp::key_type; })
5746 if constexpr (requires { typename _Tp::mapped_type; })
5748 using _Up = remove_cvref_t<_Ref>;
5749 if constexpr (__is_pair<_Up>)
5750 return range_format::map;
5751 else if constexpr (__is_specialization_of<_Up, tuple>)
5752 if constexpr (tuple_size_v<_Up> == 2)
5753 return range_format::map;
5755 return range_format::set;
5758 return range_format::sequence;
5762 /// A constant determining how a range should be formatted.
5763 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5764 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5766 /// @cond undocumented
5769 template<typename _CharT, typename _Out, typename _Callback>
5770 typename basic_format_context<_Out, _CharT>::iterator
5771 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5772 const _Spec<_CharT>& __spec,
5775 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5779 // This is required to implement formatting with padding,
5780 // as we need to format to temporary buffer, using the same iterator.
5781 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5783 const size_t __padwidth = __spec._M_get_width(__fc);
5784 if (__padwidth == 0)
5785 return __call(__fc);
5789 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5790 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5795 { _M_ctx = nullptr; }
5800 _M_ctx->advance_to(_M_out);
5804 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5805 _Sink_iter<_CharT> _M_out;
5808 _Restore_out __restore(__fc);
5809 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5810 __fc.advance_to(__sink.out());
5812 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5813 __restore._M_disarm();
5818 template<size_t _Pos, typename _Tp, typename _CharT>
5819 struct __indexed_formatter_storage
5824 basic_format_parse_context<_CharT> __pc({});
5825 if (_M_formatter.parse(__pc) != __pc.end())
5826 __format::__failed_to_parse_format_spec();
5829 template<typename _Out>
5831 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5832 basic_format_context<_Out, _CharT>& __fc,
5833 basic_string_view<_CharT> __sep) const
5835 if constexpr (_Pos != 0)
5836 __fc.advance_to(__format::__write(__fc.out(), __sep));
5837 __fc.advance_to(_M_formatter.format(__elem, __fc));
5840 [[__gnu__::__always_inline__]]
5844 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5845 _M_formatter.set_debug_format();
5849 formatter<_Tp, _CharT> _M_formatter;
5852 template<typename _CharT, typename... _Tps>
5853 class __tuple_formatter
5855 using _String_view = basic_string_view<_CharT>;
5856 using _Seps = __format::_Separators<_CharT>;
5860 set_separator(basic_string_view<_CharT> __sep) noexcept
5864 set_brackets(basic_string_view<_CharT> __open,
5865 basic_string_view<_CharT> __close) noexcept
5871 // We deviate from standard, that declares this as template accepting
5872 // unconstrained ParseContext type, which seems unimplementable.
5873 constexpr typename basic_format_parse_context<_CharT>::iterator
5874 parse(basic_format_parse_context<_CharT>& __pc)
5876 auto __first = __pc.begin();
5877 const auto __last = __pc.end();
5878 __format::_Spec<_CharT> __spec{};
5880 auto __finished = [&]
5882 if (__first != __last && *__first != '}')
5886 _M_felems._M_parse();
5887 _M_felems.set_debug_format();
5894 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5898 __first = __spec._M_parse_width(__first, __last, __pc);
5902 if (*__first == 'n')
5905 _M_open = _M_close = _String_view();
5907 else if (*__first == 'm')
5910 if constexpr (sizeof...(_Tps) == 2)
5912 _M_sep = _Seps::_S_colon();
5913 _M_open = _M_close = _String_view();
5916 __throw_format_error("format error: 'm' specifier requires range"
5917 " of pair or tuple of two elements");
5923 __format::__failed_to_parse_format_spec();
5927 template<typename _Tuple, typename _Out, size_t... _Ids>
5928 typename basic_format_context<_Out, _CharT>::iterator
5929 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5930 basic_format_context<_Out, _CharT>& __fc) const
5931 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5933 template<typename _Out>
5934 typename basic_format_context<_Out, _CharT>::iterator
5935 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5936 basic_format_context<_Out, _CharT>& __fc) const
5938 return __format::__format_padded(
5940 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5942 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5943 _M_felems._M_format(__elems..., __nfc, _M_sep);
5944 return __format::__write(__nfc.out(), _M_close);
5949 template<size_t... _Ids>
5950 struct __formatters_storage
5951 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5953 template<size_t _Id, typename _Up>
5954 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5959 (_Base<_Ids, _Tps>::_M_parse(), ...);
5962 template<typename _Out>
5964 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5965 basic_format_context<_Out, _CharT>& __fc,
5966 _String_view __sep) const
5968 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5974 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5978 template<size_t... _Ids>
5980 _S_create_storage(index_sequence<_Ids...>)
5981 -> __formatters_storage<_Ids...>;
5983 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5985 _Spec<_CharT> _M_spec{};
5986 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5987 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5988 _String_view _M_sep = _Seps::_S_comma();
5989 _Formatters _M_felems;
5992 template<typename _Tp>
5993 concept __is_map_formattable
5994 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5996 } // namespace __format
5999 // [format.tuple] Tuple formatter
6000 template<__format::__char _CharT, formattable<_CharT> _Fp,
6001 formattable<_CharT> _Sp>
6002 struct formatter<pair<_Fp, _Sp>, _CharT>
6003 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
6004 remove_cvref_t<_Sp>>
6007 using __maybe_const_pair
6008 = __conditional_t<formattable<const _Fp, _CharT>
6009 && formattable<const _Sp, _CharT>,
6010 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
6012 // We deviate from standard, that declares this as template accepting
6013 // unconstrained FormatContext type, which seems unimplementable.
6014 template<typename _Out>
6015 typename basic_format_context<_Out, _CharT>::iterator
6016 format(__maybe_const_pair& __p,
6017 basic_format_context<_Out, _CharT>& __fc) const
6018 { return this->_M_format_elems(__p.first, __p.second, __fc); }
6021 #if __glibcxx_print >= 202406L
6022 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6023 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6024 template<typename _Fp, typename _Sp>
6025 constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
6026 = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
6027 && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
6030 template<__format::__char _CharT, formattable<_CharT>... _Tps>
6031 struct formatter<tuple<_Tps...>, _CharT>
6032 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
6035 using __maybe_const_tuple
6036 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
6037 const tuple<_Tps...>, tuple<_Tps...>>;
6039 // We deviate from standard, that declares this as template accepting
6040 // unconstrained FormatContext type, which seems unimplementable.
6041 template<typename _Out>
6042 typename basic_format_context<_Out, _CharT>::iterator
6043 format(__maybe_const_tuple& __t,
6044 basic_format_context<_Out, _CharT>& __fc) const
6045 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
6048 #if __glibcxx_print >= 202406L
6049 // _GLIBCXX_RESOLVE_LIB_DEFECTS
6050 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
6051 template<typename... _Tps>
6052 constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
6053 = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
6056 // [format.range.formatter], class template range_formatter
6057 template<typename _Tp, __format::__char _CharT>
6058 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
6059 class range_formatter
6061 using _String_view = basic_string_view<_CharT>;
6062 using _Seps = __format::_Separators<_CharT>;
6066 set_separator(basic_string_view<_CharT> __sep) noexcept
6070 set_brackets(basic_string_view<_CharT> __open,
6071 basic_string_view<_CharT> __close) noexcept
6077 constexpr formatter<_Tp, _CharT>&
6078 underlying() noexcept
6081 constexpr const formatter<_Tp, _CharT>&
6082 underlying() const noexcept
6085 // We deviate from standard, that declares this as template accepting
6086 // unconstrained ParseContext type, which seems unimplementable.
6087 constexpr typename basic_format_parse_context<_CharT>::iterator
6088 parse(basic_format_parse_context<_CharT>& __pc)
6090 auto __first = __pc.begin();
6091 const auto __last = __pc.end();
6092 __format::_Spec<_CharT> __spec{};
6093 bool __no_brace = false;
6095 auto __finished = [&]
6096 { return __first == __last || *__first == '}'; };
6098 auto __finalize = [&]
6104 auto __parse_val = [&](_String_view __nfs = _String_view())
6106 basic_format_parse_context<_CharT> __npc(__nfs);
6107 if (_M_fval.parse(__npc) != __npc.end())
6108 __format::__failed_to_parse_format_spec();
6109 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
6110 _M_fval.set_debug_format();
6111 return __finalize();
6115 return __parse_val();
6117 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6119 return __parse_val();
6121 __first = __spec._M_parse_width(__first, __last, __pc);
6123 return __parse_val();
6125 if (*__first == '?')
6128 __spec._M_debug = true;
6129 if (__finished() || *__first != 's')
6130 __throw_format_error("format error: '?' is allowed only in"
6131 " combination with 's'");
6134 if (*__first == 's')
6137 if constexpr (same_as<_Tp, _CharT>)
6139 __spec._M_type = __format::_Pres_s;
6141 return __finalize();
6142 __throw_format_error("format error: element format specifier"
6143 " cannot be provided when 's' specifier is used");
6146 __throw_format_error("format error: 's' specifier requires"
6147 " range of character types");
6151 return __parse_val();
6153 if (*__first == 'n')
6156 _M_open = _M_close = _String_view();
6161 return __parse_val();
6163 if (*__first == 'm')
6165 _String_view __m(__first, 1);
6167 if constexpr (__format::__is_map_formattable<_Tp>)
6169 _M_sep = _Seps::_S_comma();
6172 _M_open = _Seps::_S_braces().substr(0, 1);
6173 _M_close = _Seps::_S_braces().substr(1, 1);
6176 return __parse_val(__m);
6177 __throw_format_error("format error: element format specifier"
6178 " cannot be provided when 'm' specifier is used");
6181 __throw_format_error("format error: 'm' specifier requires"
6182 " range of pairs or tuples of two elements");
6186 return __parse_val();
6188 if (*__first == ':')
6190 __pc.advance_to(++__first);
6191 __first = _M_fval.parse(__pc);
6195 return __finalize();
6197 __format::__failed_to_parse_format_spec();
6200 // We deviate from standard, that declares this as template accepting
6201 // unconstrained FormatContext type, which seems unimplementable.
6202 template<ranges::input_range _Rg, typename _Out>
6203 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6204 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6205 typename basic_format_context<_Out, _CharT>::iterator
6206 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6208 using _Range = remove_reference_t<_Rg>;
6209 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6210 return _M_format<const _Range>(__rg, __fc);
6212 return _M_format(__rg, __fc);
6216 template<ranges::input_range _Rg, typename _Out>
6217 typename basic_format_context<_Out, _CharT>::iterator
6218 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6220 if constexpr (same_as<_Tp, _CharT>)
6221 if (_M_spec._M_type == __format::_Pres_s)
6223 __format::__formatter_str __fstr(_M_spec);
6224 return __fstr._M_format_range(__rg, __fc);
6226 return __format::__format_padded(
6228 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6229 { return _M_format_elems(__rg, __nfc); });
6233 template<ranges::input_range _Rg, typename _Out>
6234 typename basic_format_context<_Out, _CharT>::iterator
6235 _M_format_elems(_Rg& __rg,
6236 basic_format_context<_Out, _CharT>& __fc) const
6238 auto __out = __format::__write(__fc.out(), _M_open);
6240 auto __first = ranges::begin(__rg);
6241 auto const __last = ranges::end(__rg);
6242 if (__first == __last)
6243 return __format::__write(__out, _M_close);
6245 __fc.advance_to(__out);
6246 __out = _M_fval.format(*__first, __fc);
6247 for (++__first; __first != __last; ++__first)
6249 __out = __format::__write(__out, _M_sep);
6250 __fc.advance_to(__out);
6251 __out = _M_fval.format(*__first, __fc);
6254 return __format::__write(__out, _M_close);
6257 __format::_Spec<_CharT> _M_spec{};
6258 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6259 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6260 _String_view _M_sep = _Seps::_S_comma();
6261 formatter<_Tp, _CharT> _M_fval;
6264 // In standard this is shown as inheriting from specialization of
6265 // exposition only specialization for range-default-formatter for
6266 // each range_format. We opt for simpler implementation.
6267 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6268 // specializations for maps, sets, and strings
6269 template<ranges::input_range _Rg, __format::__char _CharT>
6270 requires (format_kind<_Rg> != range_format::disabled)
6271 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6272 struct formatter<_Rg, _CharT>
6275 static const bool _S_range_format_is_string =
6276 (format_kind<_Rg> == range_format::string)
6277 || (format_kind<_Rg> == range_format::debug_string);
6278 using _Vt = remove_cvref_t<
6279 ranges::range_reference_t<
6280 __format::__maybe_const_range<_Rg, _CharT>>>;
6282 static consteval bool _S_is_correct()
6284 if constexpr (_S_range_format_is_string)
6285 static_assert(same_as<_Vt, _CharT>);
6289 static_assert(_S_is_correct());
6292 constexpr formatter() noexcept
6294 using _Seps = __format::_Separators<_CharT>;
6295 if constexpr (format_kind<_Rg> == range_format::map)
6297 static_assert(__format::__is_map_formattable<_Vt>);
6298 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6299 _Seps::_S_braces().substr(1, 1));
6300 _M_under.underlying().set_brackets({}, {});
6301 _M_under.underlying().set_separator(_Seps::_S_colon());
6303 else if constexpr (format_kind<_Rg> == range_format::set)
6304 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6305 _Seps::_S_braces().substr(1, 1));
6309 set_separator(basic_string_view<_CharT> __sep) noexcept
6310 requires (format_kind<_Rg> == range_format::sequence)
6311 { _M_under.set_separator(__sep); }
6314 set_brackets(basic_string_view<_CharT> __open,
6315 basic_string_view<_CharT> __close) noexcept
6316 requires (format_kind<_Rg> == range_format::sequence)
6317 { _M_under.set_brackets(__open, __close); }
6319 // We deviate from standard, that declares this as template accepting
6320 // unconstrained ParseContext type, which seems unimplementable.
6321 constexpr typename basic_format_parse_context<_CharT>::iterator
6322 parse(basic_format_parse_context<_CharT>& __pc)
6324 auto __res = _M_under.parse(__pc);
6325 if constexpr (format_kind<_Rg> == range_format::debug_string)
6326 _M_under.set_debug_format();
6330 // We deviate from standard, that declares this as template accepting
6331 // unconstrained FormatContext type, which seems unimplementable.
6332 template<typename _Out>
6333 typename basic_format_context<_Out, _CharT>::iterator
6334 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6335 basic_format_context<_Out, _CharT>& __fc) const
6337 if constexpr (_S_range_format_is_string)
6338 return _M_under._M_format_range(__rg, __fc);
6340 return _M_under.format(__rg, __fc);
6344 using _Formatter_under
6345 = __conditional_t<_S_range_format_is_string,
6346 __format::__formatter_str<_CharT>,
6347 range_formatter<_Vt, _CharT>>;
6348 _Formatter_under _M_under;
6351 #if __glibcxx_print >= 202406L
6352 template<ranges::input_range _Rg>
6353 requires (format_kind<_Rg> != range_format::disabled)
6354 constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6357 #endif // C++23 formatting ranges
6358 #undef _GLIBCXX_WIDEN
6360 _GLIBCXX_END_NAMESPACE_VERSION
6362 #endif // __cpp_lib_format
6363 #pragma GCC diagnostic pop
6364 #endif // _GLIBCXX_FORMAT