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
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#include <bits/version.h>
43#ifdef __cpp_lib_format // C++ >= 20 && HOSTED
54#include <bits/monostate.h>
55#include <bits/formatfwd.h>
56#include <bits/ranges_base.h> // input_range, range_reference_t
57#include <bits/ranges_util.h> // subrange
58#include <bits/ranges_algobase.h> // ranges::copy
59#include <bits/stl_iterator.h> // counted_iterator
60#include <bits/stl_pair.h> // __is_pair
61#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
62#include <bits/utility.h> // tuple_size_v
63#include <ext/numeric_traits.h> // __int_traits
65#if !__has_builtin(__builtin_toupper)
69#pragma GCC diagnostic push
70#pragma GCC diagnostic ignored "-Wpedantic" // __int128
71#pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
73namespace std _GLIBCXX_VISIBILITY(default)
75_GLIBCXX_BEGIN_NAMESPACE_VERSION
77 // [format.fmt.string], class template basic_format_string
78 template<typename _CharT, typename... _Args> struct basic_format_string;
83 // STATICALLY-WIDEN, see C++20 [time.general]
84 // It doesn't matter for format strings (which can only be char or wchar_t)
85 // but this returns the narrow string for anything that isn't wchar_t. This
86 // is done because const char* can be inserted into any ostream type, and
87 // will be widened at runtime if necessary.
88 template<typename _CharT>
90 _Widen(const char* __narrow, const wchar_t* __wide)
92 if constexpr (is_same_v<_CharT, wchar_t>)
97#define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
98#define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
100 // Size for stack located buffer
101 template<typename _CharT>
102 constexpr size_t __stackbuf_size = 32 * sizeof(void*) / sizeof(_CharT);
104 // Type-erased character sinks.
105 template<typename _CharT> class _Sink;
106 template<typename _CharT> class _Fixedbuf_sink;
107 template<typename _Out, typename _CharT> class _Padding_sink;
108 template<typename _Out, typename _CharT> class _Escaping_sink;
110 // Output iterator that writes to a type-erase character sink.
111 template<typename _CharT>
114 // Output iterator that ignores the characters
115 template<typename _CharT>
118 // An unspecified output iterator type used in the `formattable` concept.
119 template<typename _CharT>
121 { using type = _Drop_iter<_CharT>; };
123 template<typename _CharT>
124 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
126 template<typename _CharT>
127 struct _Runtime_format_string
129 [[__gnu__::__always_inline__]]
130 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
133 _Runtime_format_string(const _Runtime_format_string&) = delete;
134 void operator=(const _Runtime_format_string&) = delete;
137 basic_string_view<_CharT> _M_str;
139 template<typename, typename...> friend struct std::basic_format_string;
142} // namespace __format
145 using format_context = __format::__format_context<char>;
146#ifdef _GLIBCXX_USE_WCHAR_T
147 using wformat_context = __format::__format_context<wchar_t>;
150 // [format.args], class template basic_format_args
151 template<typename _Context> class basic_format_args;
152 using format_args = basic_format_args<format_context>;
153#ifdef _GLIBCXX_USE_WCHAR_T
154 using wformat_args = basic_format_args<wformat_context>;
157 // [format.arguments], arguments
158 // [format.arg], class template basic_format_arg
159 template<typename _Context>
160 class basic_format_arg;
162 /** A compile-time checked format string for the specified argument types.
164 * @since C++23 but available as an extension in C++20.
166 template<typename _CharT, typename... _Args>
167 struct basic_format_string
169 template<typename _Tp>
170 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
172 basic_format_string(const _Tp& __s);
174 [[__gnu__::__always_inline__]]
175 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
179 [[__gnu__::__always_inline__]]
180 constexpr basic_string_view<_CharT>
185 basic_string_view<_CharT> _M_str;
188 template<typename... _Args>
189 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
191#ifdef _GLIBCXX_USE_WCHAR_T
192 template<typename... _Args>
194 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
197#if __cpp_lib_format >= 202311L // >= C++26
198 [[__gnu__::__always_inline__]]
199 inline __format::_Runtime_format_string<char>
200 runtime_format(string_view __fmt) noexcept
203#ifdef _GLIBCXX_USE_WCHAR_T
204 [[__gnu__::__always_inline__]]
205 inline __format::_Runtime_format_string<wchar_t>
206 runtime_format(wstring_view __fmt) noexcept
211 // [format.formatter], formatter
213 /// The primary template of std::formatter is disabled.
214 template<typename _Tp, typename _CharT>
217 formatter() = delete; // No std::formatter specialization for this type.
218 formatter(const formatter&) = delete;
219 formatter& operator=(const formatter&) = delete;
222 // [format.error], class format_error
223 class format_error : public runtime_error
226 explicit format_error(const string& __what) : runtime_error(__what) { }
227 explicit format_error(const char* __what) : runtime_error(__what) { }
230 /// @cond undocumented
233 __throw_format_error(const char* __what)
234 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
238 // XXX use named functions for each constexpr error?
242 __unmatched_left_brace_in_format_string()
243 { __throw_format_error("format error: unmatched '{' in format string"); }
247 __unmatched_right_brace_in_format_string()
248 { __throw_format_error("format error: unmatched '}' in format string"); }
252 __conflicting_indexing_in_format_string()
253 { __throw_format_error("format error: conflicting indexing style in format string"); }
257 __invalid_arg_id_in_format_string()
258 { __throw_format_error("format error: invalid arg-id in format string"); }
262 __failed_to_parse_format_spec()
263 { __throw_format_error("format error: failed to parse format-spec"); }
265 template<typename _CharT> class _Scanner;
267} // namespace __format
270 // [format.parse.ctx], class template basic_format_parse_context
271 template<typename _CharT> class basic_format_parse_context;
272 using format_parse_context = basic_format_parse_context<char>;
273#ifdef _GLIBCXX_USE_WCHAR_T
274 using wformat_parse_context = basic_format_parse_context<wchar_t>;
277 template<typename _CharT>
278 class basic_format_parse_context
281 using char_type = _CharT;
282 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
283 using iterator = const_iterator;
286 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
287 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
290 basic_format_parse_context(const basic_format_parse_context&) = delete;
291 void operator=(const basic_format_parse_context&) = delete;
293 constexpr const_iterator begin() const noexcept { return _M_begin; }
294 constexpr const_iterator end() const noexcept { return _M_end; }
297 advance_to(const_iterator __it) noexcept
303 if (_M_indexing == _Manual)
304 __format::__conflicting_indexing_in_format_string();
307 // _GLIBCXX_RESOLVE_LIB_DEFECTS
308 // 3825. Missing compile-time argument id check in next_arg_id
309 if (std::is_constant_evaluated())
310 if (_M_next_arg_id == _M_num_args)
311 __format::__invalid_arg_id_in_format_string();
312 return _M_next_arg_id++;
316 check_arg_id(size_t __id)
318 if (_M_indexing == _Auto)
319 __format::__conflicting_indexing_in_format_string();
320 _M_indexing = _Manual;
322 if (std::is_constant_evaluated())
323 if (__id >= _M_num_args)
324 __format::__invalid_arg_id_in_format_string();
327#if __cpp_lib_format >= 202305L
328 template<typename... _Ts>
330 check_dynamic_spec(size_t __id) noexcept
332 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
333 "template arguments for check_dynamic_spec<Ts...>(id) "
334 "must be unique and must be one of the allowed types");
336 __check_dynamic_spec<_Ts...>(__id);
341 check_dynamic_spec_integral(size_t __id) noexcept
344 __check_dynamic_spec<int, unsigned, long long,
345 unsigned long long>(__id);
350 check_dynamic_spec_string(size_t __id) noexcept
353 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
358 // True if _Tp occurs exactly once in _Ts.
359 template<typename _Tp, typename... _Ts>
360 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
362 template<typename... _Ts>
364 __valid_types_for_check_dynamic_spec()
366 // _GLIBCXX_RESOLVE_LIB_DEFECTS
367 // 4142. check_dynamic_spec should require at least one type
368 if constexpr (sizeof...(_Ts) == 0)
372 // The types in Ts... are unique. Each type in Ts... is one of
373 // bool, char_type, int, unsigned int, long long int,
374 // unsigned long long int, float, double, long double,
375 // const char_type*, basic_string_view<char_type>, or const void*.
377 = __once<bool, _Ts...>
378 + __once<char_type, _Ts...>
379 + __once<int, _Ts...>
380 + __once<unsigned int, _Ts...>
381 + __once<long long int, _Ts...>
382 + __once<unsigned long long int, _Ts...>
383 + __once<float, _Ts...>
384 + __once<double, _Ts...>
385 + __once<long double, _Ts...>
386 + __once<const char_type*, _Ts...>
387 + __once<basic_string_view<char_type>, _Ts...>
388 + __once<const void*, _Ts...>;
389 return __sum == sizeof...(_Ts);
393 template<typename... _Ts>
395 __check_dynamic_spec(size_t __id) noexcept;
397 // This must not be constexpr.
398 static void __invalid_dynamic_spec(const char*);
400 friend __format::_Scanner<_CharT>;
403 // This constructor should only be used by the implementation.
405 basic_format_parse_context(basic_string_view<_CharT> __fmt,
406 size_t __num_args) noexcept
407 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
413 enum _Indexing { _Unknown, _Manual, _Auto };
414 _Indexing _M_indexing = _Unknown;
415 size_t _M_next_arg_id = 0;
416 size_t _M_num_args = 0;
419/// @cond undocumented
420 template<typename _Tp, template<typename...> class _Class>
421 constexpr bool __is_specialization_of = false;
422 template<template<typename...> class _Class, typename... _Args>
423 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
427 // pre: first != last
428 template<typename _CharT>
429 constexpr pair<unsigned short, const _CharT*>
430 __parse_integer(const _CharT* __first, const _CharT* __last)
432 if (__first == __last)
433 __builtin_unreachable();
435 if constexpr (is_same_v<_CharT, char>)
437 const auto __start = __first;
438 unsigned short __val = 0;
439 // N.B. std::from_chars is not constexpr in C++20.
440 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
441 && __first != __start) [[likely]]
442 return {__val, __first};
446 constexpr int __n = 32;
448 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
449 __buf[__i] = __first[__i];
450 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
451 if (__ptr) [[likely]]
452 return {__v, __first + (__ptr - __buf)};
457 template<typename _CharT>
458 constexpr pair<unsigned short, const _CharT*>
459 __parse_arg_id(const _CharT* __first, const _CharT* __last)
461 if (__first == __last)
462 __builtin_unreachable();
465 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
467 if ('1' <= *__first && *__first <= '9')
469 const unsigned short __id = *__first - '0';
470 const auto __next = __first + 1;
471 // Optimize for most likely case of single digit arg-id.
472 if (__next == __last || !('0' <= *__next && *__next <= '9'))
473 return {__id, __next};
475 return __format::__parse_integer(__first, __last);
480 enum class _Pres_type : unsigned char {
481 _Pres_none = 0, // Default type (not valid for integer presentation types).
482 _Pres_s = 1, // For strings, bool, ranges
483 // Presentation types for integral types (including bool and charT).
484 _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
485 // Presentation types for floating-point types
486 _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
487 // For pointers, the value are same as hexadecimal presentations for integers
488 _Pres_p = _Pres_x, _Pres_P = _Pres_X,
491 using enum _Pres_type;
493 enum class _Sign : unsigned char {
496 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
501 enum _WidthPrec : unsigned char {
502 _WP_none, // No width/prec specified.
503 _WP_value, // Fixed width/prec specified.
504 _WP_from_arg // Use a formatting argument for width/prec.
506 using enum _WidthPrec;
508 template<typename _Context>
510 __int_from_arg(const basic_format_arg<_Context>& __arg);
512 constexpr bool __is_digit(char __c)
513 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
515 constexpr bool __is_xdigit(char __c)
516 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
518 // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
519 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
523 template<typename _CharT>
524 struct _Spec : _SpecBase
526 unsigned short _M_width;
527 unsigned short _M_prec;
528 char32_t _M_fill = ' ';
532 unsigned _M_localized : 1;
533 unsigned _M_zero_fill : 1;
534 _WidthPrec _M_width_kind : 2;
535 _WidthPrec _M_prec_kind : 2;
536 unsigned _M_debug : 1;
537 _Pres_type _M_type : 4;
538 unsigned _M_reserved : 8;
539 // This class has 8 bits of tail padding, that can be used by
542 using iterator = typename basic_string_view<_CharT>::iterator;
544 static constexpr _Align
545 _S_align(_CharT __c) noexcept
549 case '<': return _Align_left;
550 case '>': return _Align_right;
551 case '^': return _Align_centre;
552 default: return _Align_default;
556 // pre: __first != __last
558 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
559 { return _M_parse_fill_and_align(__first, __last, "{"); }
561 // pre: __first != __last
563 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
565 for (char __c : __not_fill)
566 if (*__first == static_cast<_CharT>(__c))
569 using namespace __unicode;
570 if constexpr (__literal_encoding_is_unicode<_CharT>())
572 // Accept any UCS scalar value as fill character.
573 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
576 auto __beg = __uv.begin();
577 char32_t __c = *__beg++;
578 if (__is_scalar_value(__c))
579 if (auto __next = __beg.base(); __next != __last)
580 if (_Align __align = _S_align(*__next); __align != _Align_default)
588 else if (__last - __first >= 2)
589 if (_Align __align = _S_align(__first[1]); __align != _Align_default)
596 if (_Align __align = _S_align(__first[0]); __align != _Align_default)
605 static constexpr _Sign
606 _S_sign(_CharT __c) noexcept
610 case '+': return _Sign_plus;
611 case '-': return _Sign_minus;
612 case ' ': return _Sign_space;
613 default: return _Sign_default;
617 // pre: __first != __last
619 _M_parse_sign(iterator __first, iterator) noexcept
621 if (_Sign __sign = _S_sign(*__first); __sign != _Sign_default)
629 // pre: *__first is valid
631 _M_parse_alternate_form(iterator __first, iterator) noexcept
641 // pre: __first != __last
643 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
653 // pre: __first != __last
654 static constexpr iterator
655 _S_parse_width_or_precision(iterator __first, iterator __last,
656 unsigned short& __val, bool& __arg_id,
657 basic_format_parse_context<_CharT>& __pc)
659 if (__format::__is_digit(*__first))
661 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
663 __throw_format_error("format error: invalid width or precision "
668 else if (*__first == '{')
672 if (__first == __last)
673 __format::__unmatched_left_brace_in_format_string();
675 __val = __pc.next_arg_id();
678 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
679 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
680 __format::__invalid_arg_id_in_format_string();
682 __pc.check_arg_id(__v);
685#if __cpp_lib_format >= 202305L
686 __pc.check_dynamic_spec_integral(__val);
688 ++__first; // past the '}'
693 // pre: __first != __last
695 _M_parse_width(iterator __first, iterator __last,
696 basic_format_parse_context<_CharT>& __pc)
698 bool __arg_id = false;
700 __throw_format_error("format error: width must be non-zero in "
702 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
704 if (__next != __first)
705 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
709 // pre: __first != __last
711 _M_parse_precision(iterator __first, iterator __last,
712 basic_format_parse_context<_CharT>& __pc)
714 if (__first[0] != '.')
717 iterator __next = ++__first;
718 bool __arg_id = false;
719 if (__next != __last)
720 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
722 if (__next == __first)
723 __throw_format_error("format error: missing precision after '.' in "
725 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
729 // pre: __first != __last
731 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
741 template<typename _Context>
743 _M_get_width(_Context& __ctx) const
746 if (_M_width_kind == _WP_value)
748 else if (_M_width_kind == _WP_from_arg)
749 __width = __format::__int_from_arg(__ctx.arg(_M_width));
753 template<typename _Context>
755 _M_get_precision(_Context& __ctx) const
758 if (_M_prec_kind == _WP_value)
760 else if (_M_prec_kind == _WP_from_arg)
761 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
766 template<typename _Int>
768 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
772 else if (__sign == _Sign_plus)
774 else if (__sign == _Sign_space)
781 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
782 template<typename _Out, typename _CharT>
783 requires output_iterator<_Out, const _CharT&>
785 __write(_Out __out, basic_string_view<_CharT> __str)
787 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
793 for (_CharT __c : __str)
798 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
799 // pre: __align != _Align_default
800 template<typename _Out, typename _CharT>
802 __write_padded(_Out __out, basic_string_view<_CharT> __str,
803 _Align __align, size_t __nfill, char32_t __fill_char)
805 const size_t __buflen = 0x20;
806 _CharT __padding_chars[__buflen];
807 __padding_chars[0] = _CharT();
808 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
810 auto __pad = [&__padding] (size_t __n, _Out& __o) {
813 while (__n > __padding.size())
815 __o = __format::__write(std::move(__o), __padding);
816 __n -= __padding.size();
819 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
822 size_t __l, __r, __max;
823 if (__align == _Align_centre)
826 __r = __l + (__nfill & 1);
829 else if (__align == _Align_right)
842 using namespace __unicode;
843 if constexpr (__literal_encoding_is_unicode<_CharT>())
844 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
846 // Encode fill char as multiple code units of type _CharT.
847 const char32_t __arr[1]{ __fill_char };
848 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
849 basic_string<_CharT> __padstr(__v.begin(), __v.end());
850 __padding = __padstr;
852 __out = __format::__write(std::move(__out), __padding);
853 __out = __format::__write(std::move(__out), __str);
855 __out = __format::__write(std::move(__out), __padding);
859 if (__max < __buflen)
860 __padding.remove_suffix(__buflen - __max);
864 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
866 __out = __format::__write(std::move(__out), __str);
872 // Write STR to OUT, with alignment and padding as determined by SPEC.
873 // pre: __spec._M_align != _Align_default || __align != _Align_default
874 template<typename _CharT, typename _Out>
876 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
877 size_t __estimated_width,
878 basic_format_context<_Out, _CharT>& __fc,
879 const _Spec<_CharT>& __spec,
880 _Align __align = _Align_left)
882 size_t __width = __spec._M_get_width(__fc);
884 if (__width <= __estimated_width)
885 return __format::__write(__fc.out(), __str);
887 const size_t __nfill = __width - __estimated_width;
889 if (__spec._M_align != _Align_default)
890 __align = __spec._M_align;
892 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
896 template<typename _CharT>
898 __truncate(basic_string_view<_CharT>& __s, size_t __prec)
900 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
902 if (__prec != (size_t)-1)
903 return __unicode::__truncate(__s, __prec);
905 return __unicode::__field_width(__s);
909 __s = __s.substr(0, __prec);
914 enum class _Term_char : unsigned char {
919 using enum _Term_char;
921 template<typename _CharT>
924 using _Str_view = basic_string_view<_CharT>;
928 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
932 { return _S_all().substr(0, 3); }
935 _Str_view _S_newline()
936 { return _S_all().substr(3, 3); }
939 _Str_view _S_return()
940 { return _S_all().substr(6, 3); }
943 _Str_view _S_bslash()
944 { return _S_all().substr(9, 3); }
948 { return _S_all().substr(12, 3); }
952 { return _S_all().substr(15, 3); }
956 { return _S_all().substr(18, 2); }
960 { return _S_all().substr(20, 2); }
963 _Str_view _S_term(_Term_char __term)
970 return _S_quote().substr(0, 1);
972 return _S_apos().substr(0, 1);
974 __builtin_unreachable();
978 template<typename _CharT>
981 using _Str_view = basic_string_view<_CharT>;
985 { return _GLIBCXX_WIDEN("[]{}(), : "); }
988 _Str_view _S_squares()
989 { return _S_all().substr(0, 2); }
992 _Str_view _S_braces()
993 { return _S_all().substr(2, 2); }
996 _Str_view _S_parens()
997 { return _S_all().substr(4, 2); }
1000 _Str_view _S_comma()
1001 { return _S_all().substr(6, 2); }
1004 _Str_view _S_colon()
1005 { return _S_all().substr(8, 2); }
1008 template<typename _CharT>
1009 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1011 using _Esc = _Escapes<_CharT>;
1014 case _Esc::_S_tab()[0]:
1015 case _Esc::_S_newline()[0]:
1016 case _Esc::_S_return()[0]:
1017 case _Esc::_S_bslash()[0]:
1019 case _Esc::_S_quote()[0]:
1020 return __term == _Term_quote;
1021 case _Esc::_S_apos()[0]:
1022 return __term == _Term_apos;
1024 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1028 // @pre __c <= 0x10FFFF
1029 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1031 if (__unicode::__should_escape_category(__c))
1035 return __unicode::__grapheme_cluster_break_property(__c)
1036 == __unicode::_Gcb_property::_Gcb_Extend;
1039 using uint_least32_t = __UINT_LEAST32_TYPE__;
1040 template<typename _Out, typename _CharT>
1042 __write_escape_seq(_Out __out, uint_least32_t __val,
1043 basic_string_view<_CharT> __prefix)
1045 using _Str_view = basic_string_view<_CharT>;
1046 constexpr size_t __max = 8;
1048 const string_view __narrow(
1050 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1052 __out = __format::__write(__out, __prefix);
1053 *__out = _Separators<_CharT>::_S_braces()[0];
1055 if constexpr (is_same_v<char, _CharT>)
1056 __out = __format::__write(__out, __narrow);
1057#ifdef _GLIBCXX_USE_WCHAR_T
1060 _CharT __wbuf[__max];
1061 const size_t __n = __narrow.size();
1062 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1063 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1066 *__out = _Separators<_CharT>::_S_braces()[1];
1070 template<typename _Out, typename _CharT>
1072 __write_escape_seqs(_Out __out, basic_string_view<_CharT> __units)
1074 using _UChar = make_unsigned_t<_CharT>;
1075 for (_CharT __c : __units)
1076 __out = __format::__write_escape_seq(
1077 __out, static_cast<_UChar>(__c), _Escapes<_CharT>::_S_x());
1081 template<typename _Out, typename _CharT>
1083 __write_escaped_char(_Out __out, _CharT __c)
1085 using _UChar = make_unsigned_t<_CharT>;
1086 using _Esc = _Escapes<_CharT>;
1089 case _Esc::_S_tab()[0]:
1090 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1091 case _Esc::_S_newline()[0]:
1092 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1093 case _Esc::_S_return()[0]:
1094 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1095 case _Esc::_S_bslash()[0]:
1096 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1097 case _Esc::_S_quote()[0]:
1098 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1099 case _Esc::_S_apos()[0]:
1100 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1102 return __format::__write_escape_seq(
1103 __out, static_cast<_UChar>(__c), _Esc::_S_u());
1107 template<typename _CharT, typename _Out>
1109 __write_escaped_ascii(_Out __out,
1110 basic_string_view<_CharT> __str,
1113 using _Str_view = basic_string_view<_CharT>;
1114 auto __first = __str.begin();
1115 auto const __last = __str.end();
1116 while (__first != __last)
1118 auto __print = __first;
1119 // assume anything outside ASCII is printable
1120 while (__print != __last
1121 && !__format::__should_escape_ascii(*__print, __term))
1124 if (__print != __first)
1125 __out = __format::__write(__out, _Str_view(__first, __print));
1127 if (__print == __last)
1131 __out = __format::__write_escaped_char(__out, *__first);
1137 template<typename _CharT, typename _Out>
1139 __write_escaped_unicode_part(_Out __out, basic_string_view<_CharT>& __str,
1140 bool& __prev_esc, _Term_char __term)
1142 using _Str_view = basic_string_view<_CharT>;
1143 using _Esc = _Escapes<_CharT>;
1145 static constexpr char32_t __replace = U'\uFFFD';
1146 static constexpr _Str_view __replace_rep = []
1148 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1149 if constexpr (is_same_v<char, _CharT>)
1150 return "\xEF\xBF\xBD";
1155 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1158 auto __first = __v.begin();
1159 auto const __last = __v.end();
1160 while (__first != __last)
1162 bool __esc_ascii = false;
1163 bool __esc_unicode = false;
1164 bool __esc_replace = false;
1165 auto __should_escape = [&](auto const& __it)
1169 = __format::__should_escape_ascii(*__it.base(), __term);
1170 if (__format::__should_escape_unicode(*__it, __prev_esc))
1171 return __esc_unicode = true;
1172 if (*__it == __replace)
1174 _Str_view __units(__it.base(), __it._M_units());
1175 return __esc_replace = (__units != __replace_rep);
1180 auto __print = __first;
1181 while (__print != __last && !__should_escape(__print))
1187 if (__print != __first)
1188 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1190 if (__print == __last)
1195 __out = __format::__write_escaped_char(__out, *__first.base());
1196 else if (__esc_unicode)
1197 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1199 else if (_Str_view __units(__first.base(), __first._M_units());
1200 __units.end() != __last.base())
1201 __out = __format::__write_escape_seqs(__out, __units);
1215 template<typename _CharT, typename _Out>
1217 __write_escaped_unicode(_Out __out, basic_string_view<_CharT> __str,
1220 bool __prev_escape = true;
1221 __out = __format::__write_escaped_unicode_part(__out, __str,
1222 __prev_escape, __term);
1223 __out = __format::__write_escape_seqs(__out, __str);
1227 template<typename _CharT, typename _Out>
1229 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1231 __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1233 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1234 __out = __format::__write_escaped_unicode(__out, __str, __term);
1235 else if constexpr (is_same_v<char, _CharT>
1236 && __unicode::__literal_encoding_is_extended_ascii())
1237 __out = __format::__write_escaped_ascii(__out, __str, __term);
1239 // TODO Handle non-ascii extended encoding
1240 __out = __format::__write_escaped_ascii(__out, __str, __term);
1242 return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1245 // A lightweight optional<locale>.
1246 struct _Optional_locale
1248 [[__gnu__::__always_inline__]]
1249 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1251 _Optional_locale(const locale& __loc) noexcept
1252 : _M_loc(__loc), _M_hasval(true)
1255 _Optional_locale(const _Optional_locale& __l) noexcept
1256 : _M_dummy(), _M_hasval(__l._M_hasval)
1259 std::construct_at(&_M_loc, __l._M_loc);
1263 operator=(const _Optional_locale& __l) noexcept
1268 _M_loc = __l._M_loc;
1275 else if (__l._M_hasval)
1277 std::construct_at(&_M_loc, __l._M_loc);
1283 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1286 operator=(locale&& __loc) noexcept
1289 _M_loc = std::move(__loc);
1292 std::construct_at(&_M_loc, std::move(__loc));
1303 std::construct_at(&_M_loc);
1309 bool has_value() const noexcept { return _M_hasval; }
1312 char _M_dummy = '\0';
1315 bool _M_hasval = false;
1318 template<__char _CharT>
1319 struct __formatter_str
1321 __formatter_str() = default;
1324 __formatter_str(_Spec<_CharT> __spec) noexcept
1328 constexpr typename basic_format_parse_context<_CharT>::iterator
1329 parse(basic_format_parse_context<_CharT>& __pc)
1331 auto __first = __pc.begin();
1332 const auto __last = __pc.end();
1333 _Spec<_CharT> __spec{};
1335 auto __finalize = [this, &__spec] {
1339 auto __finished = [&] {
1340 if (__first == __last || *__first == '}')
1351 __first = __spec._M_parse_fill_and_align(__first, __last);
1355 __first = __spec._M_parse_width(__first, __last, __pc);
1359 __first = __spec._M_parse_precision(__first, __last, __pc);
1363 if (*__first == 's')
1365 __spec._M_type = _Pres_s;
1368#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1369 else if (*__first == '?')
1371 __spec._M_debug = true;
1379 __format::__failed_to_parse_format_spec();
1382 template<typename _Out>
1384 format(basic_string_view<_CharT> __s,
1385 basic_format_context<_Out, _CharT>& __fc) const
1387 if (_M_spec._M_debug)
1388 return _M_format_escaped(__s, __fc);
1390 if (_M_spec._M_width_kind == _WP_none
1391 && _M_spec._M_prec_kind == _WP_none)
1392 return __format::__write(__fc.out(), __s);
1394 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1395 const size_t __width = __format::__truncate(__s, __maxwidth);
1396 return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1399 template<typename _Out>
1401 _M_format_escaped(basic_string_view<_CharT> __s,
1402 basic_format_context<_Out, _CharT>& __fc) const
1404 const size_t __padwidth = _M_spec._M_get_width(__fc);
1405 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1406 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1408 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1409 const size_t __width = __truncate(__s, __maxwidth);
1410 // N.B. Escaping only increases width
1411 if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1412 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1414 // N.B. [tab:format.type.string] defines '?' as
1415 // Copies the escaped string ([format.string.escaped]) to the output,
1416 // so precision seem to appy to escaped string.
1417 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1418 __format::__write_escaped(__sink.out(), __s, _Term_quote);
1419 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1422#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1423 template<ranges::input_range _Rg, typename _Out>
1424 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1426 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1428 using _Range = remove_reference_t<_Rg>;
1429 using _String = basic_string<_CharT>;
1430 using _String_view = basic_string_view<_CharT>;
1431 if constexpr (!is_lvalue_reference_v<_Rg>)
1432 return _M_format_range<_Range&>(__rg, __fc);
1433 else if constexpr (!is_const_v<_Range>
1434 && __simply_formattable_range<_Range, _CharT>)
1435 return _M_format_range<const _Range&>(__rg, __fc);
1436 else if constexpr (ranges::contiguous_range<_Rg>)
1438 _String_view __str(ranges::data(__rg),
1439 size_t(ranges::distance(__rg)));
1440 return format(__str, __fc);
1444 auto __handle_debug = [this, &__rg]<typename _NOut>(_NOut __nout)
1446 if (!_M_spec._M_debug)
1447 return ranges::copy(__rg, std::move(__nout)).out;
1449 _Escaping_sink<_NOut, _CharT>
1450 __sink(std::move(__nout), _Term_quote);
1451 ranges::copy(__rg, __sink.out());
1452 return __sink._M_finish();
1455 const size_t __padwidth = _M_spec._M_get_width(__fc);
1456 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1457 return __handle_debug(__fc.out());
1459 _Padding_sink<_Out, _CharT>
1460 __sink(__fc.out(), __padwidth, _M_spec._M_get_precision(__fc));
1461 __handle_debug(__sink.out());
1462 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1467 set_debug_format() noexcept
1468 { _M_spec._M_debug = true; }
1472 _Spec<_CharT> _M_spec{};
1475 template<__char _CharT>
1476 struct __formatter_int
1478 // If no presentation type is specified, meaning of "none" depends
1479 // whether we are formatting an integer or a char or a bool.
1480 static constexpr _Pres_type _AsInteger = _Pres_d;
1481 static constexpr _Pres_type _AsBool = _Pres_s;
1482 static constexpr _Pres_type _AsChar = _Pres_c;
1484 __formatter_int() = default;
1487 __formatter_int(_Spec<_CharT> __spec) noexcept
1490 if (_M_spec._M_type == _Pres_none)
1491 _M_spec._M_type = _Pres_d;
1494 constexpr typename basic_format_parse_context<_CharT>::iterator
1495 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1497 _Spec<_CharT> __spec{};
1498 __spec._M_type = __type;
1500 const auto __last = __pc.end();
1501 auto __first = __pc.begin();
1503 auto __finalize = [this, &__spec] {
1507 auto __finished = [&] {
1508 if (__first == __last || *__first == '}')
1519 __first = __spec._M_parse_fill_and_align(__first, __last);
1523 __first = __spec._M_parse_sign(__first, __last);
1527 __first = __spec._M_parse_alternate_form(__first, __last);
1531 __first = __spec._M_parse_zero_fill(__first, __last);
1535 __first = __spec._M_parse_width(__first, __last, __pc);
1539 __first = __spec._M_parse_locale(__first, __last);
1546 __spec._M_type = _Pres_b;
1550 __spec._M_type = _Pres_B;
1554 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1555 // 3586. format should not print bool with 'c'
1556 if (__type != _AsBool)
1558 __spec._M_type = _Pres_c;
1563 __spec._M_type = _Pres_d;
1567 __spec._M_type = _Pres_o;
1571 __spec._M_type = _Pres_x;
1575 __spec._M_type = _Pres_X;
1579 if (__type == _AsBool)
1581 __spec._M_type = _Pres_s; // same meaning as "none" for bool
1585#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1587 if (__type == _AsChar)
1589 __spec._M_debug = true;
1599 __format::__failed_to_parse_format_spec();
1602 template<typename _Tp>
1603 constexpr typename basic_format_parse_context<_CharT>::iterator
1604 _M_parse(basic_format_parse_context<_CharT>& __pc)
1606 if constexpr (is_same_v<_Tp, bool>)
1608 auto __end = _M_do_parse(__pc, _AsBool);
1609 if (_M_spec._M_type == _Pres_s)
1610 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1611 || _M_spec._M_zero_fill)
1612 __throw_format_error("format error: format-spec contains "
1613 "invalid formatting options for "
1617 else if constexpr (__char<_Tp>)
1619 auto __end = _M_do_parse(__pc, _AsChar);
1620 if (_M_spec._M_type == _Pres_c)
1621 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1622 || _M_spec._M_zero_fill
1623 /* XXX should be invalid? || _M_spec._M_localized */)
1624 __throw_format_error("format error: format-spec contains "
1625 "invalid formatting options for "
1630 return _M_do_parse(__pc, _AsInteger);
1633 template<typename _Int, typename _Out>
1634 typename basic_format_context<_Out, _CharT>::iterator
1635 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1637 if (_M_spec._M_type == _Pres_c)
1638 return _M_format_character(_S_to_character(__i), __fc);
1640 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1641 to_chars_result __res{};
1643 string_view __base_prefix;
1644 make_unsigned_t<_Int> __u;
1646 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1650 char* __start = __buf + 3;
1651 char* const __end = __buf + sizeof(__buf);
1652 char* const __start_digits = __start;
1654 switch (_M_spec._M_type)
1658 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1659 __res = to_chars(__start, __end, __u, 2);
1663 return _M_format_character(_S_to_character(__i), __fc);
1666 // Should not reach here with _Pres_none for bool or charT, so:
1669 __res = to_chars(__start, __end, __u, 10);
1673 __base_prefix = "0";
1674 __res = to_chars(__start, __end, __u, 8);
1678 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1679 __res = to_chars(__start, __end, __u, 16);
1680 if (_M_spec._M_type == _Pres_X)
1681 for (auto __p = __start; __p != __res.ptr; ++__p)
1682#if __has_builtin(__builtin_toupper)
1683 *__p = __builtin_toupper(*__p);
1685 *__p = std::toupper(*__p);
1689 __builtin_unreachable();
1692 if (_M_spec._M_alt && __base_prefix.size())
1694 __start -= __base_prefix.size();
1695 __builtin_memcpy(__start, __base_prefix.data(),
1696 __base_prefix.size());
1698 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1700 return _M_format_int(string_view(__start, __res.ptr - __start),
1701 __start_digits - __start, __fc);
1704 template<typename _Out>
1705 typename basic_format_context<_Out, _CharT>::iterator
1706 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1708 if (_M_spec._M_type == _Pres_c)
1709 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1710 if (_M_spec._M_type != _Pres_s)
1711 return format(static_cast<unsigned char>(__i), __fc);
1713 basic_string<_CharT> __s;
1715 if (_M_spec._M_localized) [[unlikely]]
1717 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1718 __s = __i ? __np.truename() : __np.falsename();
1719 __est_width = __s.size(); // TODO Unicode-aware estimate
1723 if constexpr (is_same_v<char, _CharT>)
1724 __s = __i ? "true" : "false";
1726 __s = __i ? L"true" : L"false";
1727 __est_width = __s.size();
1730 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1734 template<typename _Out>
1735 typename basic_format_context<_Out, _CharT>::iterator
1736 _M_format_character(_CharT __c,
1737 basic_format_context<_Out, _CharT>& __fc) const
1739 basic_string_view<_CharT> __in(&__c, 1u);
1740 size_t __width = 1u;
1741 // N.B. single byte cannot encode character of width greater than 1
1742 if constexpr (sizeof(_CharT) > 1u &&
1743 __unicode::__literal_encoding_is_unicode<_CharT>())
1744 __width = __unicode::__field_width(__c);
1746 if (!_M_spec._M_debug)
1747 return __format::__write_padded_as_spec(__in, __width,
1751 if (_M_spec._M_get_width(__fc) <= __width)
1752 return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1755 _Fixedbuf_sink<_CharT> __sink(__buf);
1756 __format::__write_escaped(__sink.out(), __in, _Term_apos);
1758 __in = __sink.view();
1759 if (__in[1] == _Escapes<_CharT>::_S_bslash()[0]) // escape sequence
1760 __width = __in.size();
1761 return __format::__write_padded_as_spec(__in, __width,
1765 template<typename _Int>
1767 _S_to_character(_Int __i)
1769 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1770 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1772 if (_Traits::__min <= __i && __i <= _Traits::__max)
1773 return static_cast<_CharT>(__i);
1775 else if constexpr (is_signed_v<_Int>)
1777 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1778 return static_cast<_CharT>(__i);
1780 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1781 return static_cast<_CharT>(__i);
1782 __throw_format_error("format error: integer not representable as "
1786 template<typename _Out>
1787 typename basic_format_context<_Out, _CharT>::iterator
1788 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1789 basic_format_context<_Out, _CharT>& __fc) const
1791 size_t __width = _M_spec._M_get_width(__fc);
1793 basic_string_view<_CharT> __str;
1794 if constexpr (is_same_v<char, _CharT>)
1795 __str = __narrow_str;
1796#ifdef _GLIBCXX_USE_WCHAR_T
1799 size_t __n = __narrow_str.size();
1800 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1801 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1806 if (_M_spec._M_localized)
1808 const auto& __l = __fc.locale();
1809 if (__l.name() != "C")
1811 auto& __np = use_facet<numpunct<_CharT>>(__l);
1812 string __grp = __np.grouping();
1815 size_t __n = __str.size() - __prefix_len;
1816 auto __p = (_CharT*)__builtin_alloca(2 * __n
1819 auto __s = __str.data();
1820 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1821 __s += __prefix_len;
1822 auto __end = std::__add_grouping(__p + __prefix_len,
1823 __np.thousands_sep(),
1827 __str = {__p, size_t(__end - __p)};
1832 if (__width <= __str.size())
1833 return __format::__write(__fc.out(), __str);
1835 char32_t __fill_char = _M_spec._M_fill;
1836 _Align __align = _M_spec._M_align;
1838 size_t __nfill = __width - __str.size();
1839 auto __out = __fc.out();
1840 if (__align == _Align_default)
1842 __align = _Align_right;
1843 if (_M_spec._M_zero_fill)
1845 __fill_char = _CharT('0');
1846 // Write sign and base prefix before zero filling.
1847 if (__prefix_len != 0)
1849 __out = __format::__write(std::move(__out),
1850 __str.substr(0, __prefix_len));
1851 __str.remove_prefix(__prefix_len);
1855 __fill_char = _CharT(' ');
1857 return __format::__write_padded(std::move(__out), __str,
1858 __align, __nfill, __fill_char);
1861 _Spec<_CharT> _M_spec{};
1864#ifdef __BFLT16_DIG__
1865 using __bflt16_t = decltype(0.0bf16);
1868 // Decide how 128-bit floating-point types should be formatted (or not).
1869 // When supported, the typedef __format::__flt128_t is the type that format
1870 // arguments should be converted to before passing them to __formatter_fp.
1871 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1872 // The __float128, _Float128 will be formatted by converting them to:
1873 // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1874 // long double when _GLIBCXX_FORMAT_F128=2,
1875 // _Float128 when _GLIBCXX_FORMAT_F128=3.
1876#undef _GLIBCXX_FORMAT_F128
1878#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1880 // Format 128-bit floating-point types using __ieee128.
1881 using __flt128_t = __ieee128;
1882# define _GLIBCXX_FORMAT_F128 1
1884#ifdef __LONG_DOUBLE_IEEE128__
1885 // These overloads exist in the library, but are not declared.
1886 // Make them available as std::__format::to_chars.
1888 to_chars(char*, char*, __ibm128) noexcept
1889 __asm("_ZSt8to_charsPcS_e");
1892 to_chars(char*, char*, __ibm128, chars_format) noexcept
1893 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1896 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1897 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1898#elif __cplusplus == 202002L
1900 to_chars(char*, char*, __ieee128) noexcept
1901 __asm("_ZSt8to_charsPcS_u9__ieee128");
1904 to_chars(char*, char*, __ieee128, chars_format) noexcept
1905 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1908 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1909 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1912#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1914 // Format 128-bit floating-point types using long double.
1915 using __flt128_t = long double;
1916# define _GLIBCXX_FORMAT_F128 2
1918#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1920 // Format 128-bit floating-point types using _Float128.
1921 using __flt128_t = _Float128;
1922# define _GLIBCXX_FORMAT_F128 3
1924# if __cplusplus == 202002L
1925 // These overloads exist in the library, but are not declared for C++20.
1926 // Make them available as std::__format::to_chars.
1928 to_chars(char*, char*, _Float128) noexcept
1929# if _GLIBCXX_INLINE_VERSION
1930 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1932 __asm("_ZSt8to_charsPcS_DF128_");
1936 to_chars(char*, char*, _Float128, chars_format) noexcept
1937# if _GLIBCXX_INLINE_VERSION
1938 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1940 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1944 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1945# if _GLIBCXX_INLINE_VERSION
1946 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1948 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1953 using std::to_chars;
1955 // We can format a floating-point type iff it is usable with to_chars.
1956 template<typename _Tp>
1957 concept __formattable_float
1958 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1959 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1961 template<__char _CharT>
1962 struct __formatter_fp
1964 constexpr typename basic_format_parse_context<_CharT>::iterator
1965 parse(basic_format_parse_context<_CharT>& __pc)
1967 _Spec<_CharT> __spec{};
1968 const auto __last = __pc.end();
1969 auto __first = __pc.begin();
1971 auto __finalize = [this, &__spec] {
1975 auto __finished = [&] {
1976 if (__first == __last || *__first == '}')
1987 __first = __spec._M_parse_fill_and_align(__first, __last);
1991 __first = __spec._M_parse_sign(__first, __last);
1995 __first = __spec._M_parse_alternate_form(__first, __last);
1999 __first = __spec._M_parse_zero_fill(__first, __last);
2003 if (__first[0] != '.')
2005 __first = __spec._M_parse_width(__first, __last, __pc);
2010 __first = __spec._M_parse_precision(__first, __last, __pc);
2014 __first = __spec._M_parse_locale(__first, __last);
2021 __spec._M_type = _Pres_a;
2025 __spec._M_type = _Pres_A;
2029 __spec._M_type = _Pres_e;
2033 __spec._M_type = _Pres_E;
2037 __spec._M_type = _Pres_f;
2041 __spec._M_type = _Pres_F;
2045 __spec._M_type = _Pres_g;
2049 __spec._M_type = _Pres_G;
2057 __format::__failed_to_parse_format_spec();
2060 template<typename _Fp, typename _Out>
2061 typename basic_format_context<_Out, _CharT>::iterator
2062 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2064 std::string __dynbuf;
2066 to_chars_result __res{};
2069 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2071 __prec = _M_spec._M_get_precision(__fc);
2073 char* __start = __buf + 1; // reserve space for sign
2074 char* __end = __buf + sizeof(__buf);
2076 chars_format __fmt{};
2077 bool __upper = false;
2078 bool __trailing_zeros = false;
2081 switch (_M_spec._M_type)
2088 if (_M_spec._M_type != _Pres_A)
2090 __fmt = chars_format::hex;
2098 __fmt = chars_format::scientific;
2105 __fmt = chars_format::fixed;
2112 __trailing_zeros = true;
2114 __fmt = chars_format::general;
2118 __fmt = chars_format::general;
2121 __builtin_unreachable();
2124 // Write value into buffer using std::to_chars.
2125 auto __to_chars = [&](char* __b, char* __e) {
2127 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2128 else if (__fmt != chars_format{})
2129 return __format::to_chars(__b, __e, __v, __fmt);
2131 return __format::to_chars(__b, __e, __v);
2134 // First try using stack buffer.
2135 __res = __to_chars(__start, __end);
2137 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2139 // If the buffer is too small it's probably because of a large
2140 // precision, or a very large value in fixed format.
2141 size_t __guess = 8 + __prec;
2142 if (__fmt == chars_format::fixed) // +ddd.prec
2144 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2145 || is_same_v<_Fp, long double>)
2147 // The number of digits to the left of the decimal point
2148 // is floor(log10(max(abs(__v),1)))+1
2150 if constexpr (is_same_v<_Fp, float>)
2151 __builtin_frexpf(__v, &__exp);
2152 else if constexpr (is_same_v<_Fp, double>)
2153 __builtin_frexp(__v, &__exp);
2154 else if constexpr (is_same_v<_Fp, long double>)
2155 __builtin_frexpl(__v, &__exp);
2157 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2160 __guess += numeric_limits<_Fp>::max_exponent10;
2162 if (__guess <= sizeof(__buf)) [[unlikely]]
2163 __guess = sizeof(__buf) * 2;
2164 __dynbuf.reserve(__guess);
2168 // Mangling of this lambda, and thus resize_and_overwrite
2169 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2170 // <format> was new in G++ 13, and is experimental, that
2172 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
2174 __res = __to_chars(__p + 1, __p + __n - 1);
2175 return __res.ec == errc{} ? __res.ptr - __p : 0;
2178 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2180 __start = __dynbuf.data() + 1; // reserve space for sign
2181 __end = __dynbuf.data() + __dynbuf.size();
2183 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2186 // Use uppercase for 'A', 'E', and 'G' formats.
2189 for (char* __p = __start; __p != __res.ptr; ++__p)
2190 *__p = std::toupper(*__p);
2193 bool __have_sign = true;
2194 // Add sign for non-negative values.
2195 if (!__builtin_signbit(__v))
2197 if (_M_spec._M_sign == _Sign_plus)
2199 else if (_M_spec._M_sign == _Sign_space)
2202 __have_sign = false;
2205 string_view __narrow_str(__start, __res.ptr - __start);
2207 // Use alternate form. Ensure decimal point is always present,
2208 // and add trailing zeros (up to precision) for g and G forms.
2209 if (_M_spec._M_alt && __builtin_isfinite(__v))
2211 string_view __s = __narrow_str;
2212 size_t __sigfigs; // Number of significant figures.
2213 size_t __z = 0; // Number of trailing zeros to add.
2214 size_t __p; // Position of the exponent character (if any).
2215 size_t __d = __s.find('.'); // Position of decimal point.
2216 if (__d != __s.npos) // Found decimal point.
2218 __p = __s.find(__expc, __d + 1);
2219 if (__p == __s.npos)
2222 // If presentation type is g or G we might need to add zeros.
2223 if (__trailing_zeros)
2225 // Find number of digits after first significant figure.
2226 if (__s[__have_sign] != '0')
2227 // A string like "D.D" or "-D.DDD"
2228 __sigfigs = __p - __have_sign - 1;
2230 // A string like "0.D" or "-0.0DD".
2231 // Safe to assume there is a non-zero digit, because
2232 // otherwise there would be no decimal point.
2233 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2236 else // No decimal point, we need to insert one.
2238 __p = __s.find(__expc); // Find the exponent, if present.
2239 if (__p == __s.npos)
2241 __d = __p; // Position where '.' should be inserted.
2242 __sigfigs = __d - __have_sign;
2245 if (__trailing_zeros && __prec != 0)
2247 // For g and G presentation types std::to_chars produces
2248 // no more than prec significant figures. Insert this many
2249 // zeros so the result has exactly prec significant figures.
2250 __z = __prec - __sigfigs;
2253 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2255 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2257 // The stack buffer is large enough for the result.
2258 // Move exponent to make space for extra chars.
2259 __builtin_memmove(__start + __p + __extras,
2263 __start[__p++] = '.';
2264 __builtin_memset(__start + __p, '0', __z);
2265 __narrow_str = {__s.data(), __s.size() + __extras};
2267 else // Need to switch to the dynamic buffer.
2269 __dynbuf.reserve(__s.size() + __extras);
2270 if (__dynbuf.empty())
2272 __dynbuf = __s.substr(0, __p);
2276 __dynbuf.append(__z, '0');
2277 __dynbuf.append(__s.substr(__p));
2281 __dynbuf.insert(__p, __extras, '0');
2283 __dynbuf[__p] = '.';
2285 __narrow_str = __dynbuf;
2290 basic_string<_CharT> __wstr;
2291 basic_string_view<_CharT> __str;
2292 if constexpr (is_same_v<_CharT, char>)
2293 __str = __narrow_str;
2294#ifdef _GLIBCXX_USE_WCHAR_T
2297 __wstr = std::__to_wstring_numeric(__narrow_str);
2302 if (_M_spec._M_localized && __builtin_isfinite(__v))
2304 auto __s = _M_localize(__str, __expc, __fc.locale());
2306 __str = __wstr = std::move(__s);
2309 size_t __width = _M_spec._M_get_width(__fc);
2311 if (__width <= __str.size())
2312 return __format::__write(__fc.out(), __str);
2314 char32_t __fill_char = _M_spec._M_fill;
2315 _Align __align = _M_spec._M_align;
2317 size_t __nfill = __width - __str.size();
2318 auto __out = __fc.out();
2319 if (__align == _Align_default)
2321 __align = _Align_right;
2322 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2324 __fill_char = _CharT('0');
2325 // Write sign before zero filling.
2326 if (!__format::__is_xdigit(__narrow_str[0]))
2328 *__out++ = __str[0];
2329 __str.remove_prefix(1);
2333 __fill_char = _CharT(' ');
2335 return __format::__write_padded(std::move(__out), __str,
2336 __align, __nfill, __fill_char);
2339 // Locale-specific format.
2340 basic_string<_CharT>
2341 _M_localize(basic_string_view<_CharT> __str, char __expc,
2342 const locale& __loc) const
2344 basic_string<_CharT> __lstr;
2346 if (__loc == locale::classic())
2347 return __lstr; // Nothing to do.
2349 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2350 const _CharT __point = __np.decimal_point();
2351 const string __grp = __np.grouping();
2353 _CharT __dot, __exp;
2354 if constexpr (is_same_v<_CharT, char>)
2377 __builtin_unreachable();
2381 if (__grp.empty() && __point == __dot)
2382 return __lstr; // Locale uses '.' and no grouping.
2384 size_t __d = __str.find(__dot); // Index of radix character (if any).
2385 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2386 if (__e == __str.npos)
2388 const size_t __r = __str.size() - __e; // Length of remainder.
2389 auto __overwrite = [&](_CharT* __p, size_t) {
2390 // Apply grouping to the digits before the radix or exponent.
2392 if (auto __c = __str.front(); __c == '-' || __c == '+' || __c == ' ')
2397 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
2398 __grp.data(), __grp.size(),
2399 __str.data() + __off,
2400 __str.data() + __e);
2401 if (__r) // If there's a fractional part or exponent
2403 if (__d != __str.npos)
2405 *__end = __point; // Add the locale's radix character.
2409 const size_t __rlen = __str.size() - __e;
2410 // Append fractional digits and/or exponent:
2411 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2414 return (__end - __p);
2416 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2420 _Spec<_CharT> _M_spec{};
2423 template<__format::__char _CharT>
2424 struct __formatter_ptr
2426 __formatter_ptr() = default;
2429 __formatter_ptr(_Spec<_CharT> __spec) noexcept
2431 { _M_set_default(_Pres_p); }
2433 constexpr typename basic_format_parse_context<_CharT>::iterator
2434 parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type = _Pres_p)
2436 __format::_Spec<_CharT> __spec{};
2437 const auto __last = __pc.end();
2438 auto __first = __pc.begin();
2440 auto __finalize = [this, &__spec, __type] {
2442 _M_set_default(__type);
2445 auto __finished = [&] {
2446 if (__first == __last || *__first == '}')
2457 __first = __spec._M_parse_fill_and_align(__first, __last);
2461// _GLIBCXX_RESOLVE_LIB_DEFECTS
2462// P2510R3 Formatting pointers
2463#if __glibcxx_format >= 202304L
2464 __first = __spec._M_parse_zero_fill(__first, __last);
2469 __first = __spec._M_parse_width(__first, __last, __pc);
2473 if (*__first == 'p')
2475 __spec._M_type = _Pres_p;
2476 _M_spec._M_alt = !_M_spec._M_alt;
2479#if __glibcxx_format >= 202304L
2480 else if (*__first == 'P')
2482 __spec._M_type = _Pres_P;
2483 _M_spec._M_alt = !_M_spec._M_alt;
2491 __format::__failed_to_parse_format_spec();
2494 template<typename _Out>
2495 typename basic_format_context<_Out, _CharT>::iterator
2496 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2498 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2499 char __buf[2 + sizeof(__v) * 2];
2500 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2502 int __n = __ptr - __buf;
2505#if __glibcxx_format >= 202304L
2506 if (_M_spec._M_type == __format::_Pres_P)
2509 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2510#if __has_builtin(__builtin_toupper)
2511 *__p = __builtin_toupper(*__p);
2513 *__p = std::toupper(*__p);
2518 basic_string_view<_CharT> __str;
2519 if constexpr (is_same_v<_CharT, char>)
2520 __str = string_view(__buf, __n);
2521#ifdef _GLIBCXX_USE_WCHAR_T
2524 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2525 std::__to_wstring_numeric(__buf, __n, __p);
2526 __str = wstring_view(__p, __n);
2530#if __glibcxx_format >= 202304L
2531 if (_M_spec._M_zero_fill)
2533 size_t __width = _M_spec._M_get_width(__fc);
2534 if (__width <= __str.size())
2535 return __format::__write(__fc.out(), __str);
2537 auto __out = __fc.out();
2538 // Write "0x" or "0X" prefix before zero-filling.
2539 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2540 __str.remove_prefix(2);
2541 size_t __nfill = __width - __n;
2542 return __format::__write_padded(std::move(__out), __str,
2543 __format::_Align_right,
2544 __nfill, _CharT('0'));
2548 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2549 __format::_Align_right);
2553 [[__gnu__::__always_inline__]]
2555 _M_set_default(_Pres_type __type)
2557 if (_M_spec._M_type == _Pres_none && __type != _Pres_none)
2559 _M_spec._M_type = __type;
2560 _M_spec._M_alt = !_M_spec._M_alt;
2564 __format::_Spec<_CharT> _M_spec{};
2567} // namespace __format
2570 /// Format a character.
2571 template<__format::__char _CharT>
2572 struct formatter<_CharT, _CharT>
2574 formatter() = default;
2576 constexpr typename basic_format_parse_context<_CharT>::iterator
2577 parse(basic_format_parse_context<_CharT>& __pc)
2579 return _M_f.template _M_parse<_CharT>(__pc);
2582 template<typename _Out>
2583 typename basic_format_context<_Out, _CharT>::iterator
2584 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2586 if (_M_f._M_spec._M_type == __format::_Pres_c)
2587 return _M_f._M_format_character(__u, __fc);
2589 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2592#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2594 set_debug_format() noexcept
2595 { _M_f._M_spec._M_debug = true; }
2599 __format::__formatter_int<_CharT> _M_f;
2602#if __glibcxx_print >= 202403L
2603 template<__format::__char _CharT>
2604 constexpr bool enable_nonlocking_formatter_optimization<_CharT> = true;
2607#ifdef _GLIBCXX_USE_WCHAR_T
2608 /// Format a char value for wide character output.
2610 struct formatter<char, wchar_t>
2612 formatter() = default;
2614 constexpr typename basic_format_parse_context<wchar_t>::iterator
2615 parse(basic_format_parse_context<wchar_t>& __pc)
2617 return _M_f._M_parse<char>(__pc);
2620 template<typename _Out>
2621 typename basic_format_context<_Out, wchar_t>::iterator
2622 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2624 if (_M_f._M_spec._M_type == __format::_Pres_c)
2625 return _M_f._M_format_character(__u, __fc);
2627 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2630#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2632 set_debug_format() noexcept
2633 { _M_f._M_spec._M_debug = true; }
2637 __format::__formatter_int<wchar_t> _M_f;
2639#endif // USE_WCHAR_T
2641 /** Format a string.
2644 template<__format::__char _CharT>
2645 struct formatter<_CharT*, _CharT>
2647 formatter() = default;
2649 [[__gnu__::__always_inline__]]
2650 constexpr typename basic_format_parse_context<_CharT>::iterator
2651 parse(basic_format_parse_context<_CharT>& __pc)
2652 { return _M_f.parse(__pc); }
2654 template<typename _Out>
2655 [[__gnu__::__nonnull__]]
2656 typename basic_format_context<_Out, _CharT>::iterator
2657 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2658 { return _M_f.format(__u, __fc); }
2660#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2661 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2665 __format::__formatter_str<_CharT> _M_f;
2668#if __glibcxx_print >= 202403L
2669 template<__format::__char _CharT>
2670 constexpr bool enable_nonlocking_formatter_optimization<_CharT*> = true;
2673 template<__format::__char _CharT>
2674 struct formatter<const _CharT*, _CharT>
2676 formatter() = default;
2678 [[__gnu__::__always_inline__]]
2679 constexpr typename basic_format_parse_context<_CharT>::iterator
2680 parse(basic_format_parse_context<_CharT>& __pc)
2681 { return _M_f.parse(__pc); }
2683 template<typename _Out>
2684 [[__gnu__::__nonnull__]]
2685 typename basic_format_context<_Out, _CharT>::iterator
2686 format(const _CharT* __u,
2687 basic_format_context<_Out, _CharT>& __fc) const
2688 { return _M_f.format(__u, __fc); }
2690#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2691 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2695 __format::__formatter_str<_CharT> _M_f;
2698#if __glibcxx_print >= 202403L
2699 template<__format::__char _CharT>
2701 enable_nonlocking_formatter_optimization<const _CharT*> = true;
2704 template<__format::__char _CharT, size_t _Nm>
2705 struct formatter<_CharT[_Nm], _CharT>
2707 formatter() = default;
2709 [[__gnu__::__always_inline__]]
2710 constexpr typename basic_format_parse_context<_CharT>::iterator
2711 parse(basic_format_parse_context<_CharT>& __pc)
2712 { return _M_f.parse(__pc); }
2714 template<typename _Out>
2715 typename basic_format_context<_Out, _CharT>::iterator
2716 format(const _CharT (&__u)[_Nm],
2717 basic_format_context<_Out, _CharT>& __fc) const
2718 { return _M_f.format({__u, _Nm}, __fc); }
2720#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2721 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2725 __format::__formatter_str<_CharT> _M_f;
2728#if __glibcxx_print >= 202403L
2729 template<__format::__char _CharT, size_t _Nm>
2730 constexpr bool enable_nonlocking_formatter_optimization<_CharT[_Nm]> = true;
2733 template<typename _Traits, typename _Alloc>
2734 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2736 formatter() = default;
2738 [[__gnu__::__always_inline__]]
2739 constexpr typename basic_format_parse_context<char>::iterator
2740 parse(basic_format_parse_context<char>& __pc)
2741 { return _M_f.parse(__pc); }
2743 template<typename _Out>
2744 typename basic_format_context<_Out, char>::iterator
2745 format(const basic_string<char, _Traits, _Alloc>& __u,
2746 basic_format_context<_Out, char>& __fc) const
2747 { return _M_f.format(__u, __fc); }
2749#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2750 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2754 __format::__formatter_str<char> _M_f;
2757#if __glibcxx_print >= 202403L
2758 template<typename _Tr, typename _Alloc>
2760 enable_nonlocking_formatter_optimization<basic_string<char, _Tr, _Alloc>>
2764#ifdef _GLIBCXX_USE_WCHAR_T
2765 template<typename _Traits, typename _Alloc>
2766 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2768 formatter() = default;
2770 [[__gnu__::__always_inline__]]
2771 constexpr typename basic_format_parse_context<wchar_t>::iterator
2772 parse(basic_format_parse_context<wchar_t>& __pc)
2773 { return _M_f.parse(__pc); }
2775 template<typename _Out>
2776 typename basic_format_context<_Out, wchar_t>::iterator
2777 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2778 basic_format_context<_Out, wchar_t>& __fc) const
2779 { return _M_f.format(__u, __fc); }
2781#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2782 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2786 __format::__formatter_str<wchar_t> _M_f;
2789#if __glibcxx_print >= 202403L
2790 template<typename _Tr, typename _Alloc>
2792 enable_nonlocking_formatter_optimization<basic_string<wchar_t, _Tr, _Alloc>>
2796#endif // USE_WCHAR_T
2798 template<typename _Traits>
2799 struct formatter<basic_string_view<char, _Traits>, char>
2801 formatter() = default;
2803 [[__gnu__::__always_inline__]]
2804 constexpr typename basic_format_parse_context<char>::iterator
2805 parse(basic_format_parse_context<char>& __pc)
2806 { return _M_f.parse(__pc); }
2808 template<typename _Out>
2809 typename basic_format_context<_Out, char>::iterator
2810 format(basic_string_view<char, _Traits> __u,
2811 basic_format_context<_Out, char>& __fc) const
2812 { return _M_f.format(__u, __fc); }
2814#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2815 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2819 __format::__formatter_str<char> _M_f;
2822#if __glibcxx_print >= 202403L
2823 template<typename _Tr>
2825 enable_nonlocking_formatter_optimization<basic_string_view<char, _Tr>>
2829#ifdef _GLIBCXX_USE_WCHAR_T
2830 template<typename _Traits>
2831 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2833 formatter() = default;
2835 [[__gnu__::__always_inline__]]
2836 constexpr typename basic_format_parse_context<wchar_t>::iterator
2837 parse(basic_format_parse_context<wchar_t>& __pc)
2838 { return _M_f.parse(__pc); }
2840 template<typename _Out>
2841 typename basic_format_context<_Out, wchar_t>::iterator
2842 format(basic_string_view<wchar_t, _Traits> __u,
2843 basic_format_context<_Out, wchar_t>& __fc) const
2844 { return _M_f.format(__u, __fc); }
2846#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2847 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2851 __format::__formatter_str<wchar_t> _M_f;
2854#if __glibcxx_print >= 202403L
2855 template<typename _Tr>
2857 enable_nonlocking_formatter_optimization<basic_string_view<wchar_t, _Tr>>
2860#endif // USE_WCHAR_T
2863/// @cond undocumented
2866 // each cv-unqualified arithmetic type ArithmeticT other than
2867 // char, wchar_t, char8_t, char16_t, or char32_t
2868 template<typename _Tp>
2869 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2871#if defined __SIZEOF_INT128__
2872 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2873 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2877 template<> inline constexpr bool __is_formattable_integer<char> = false;
2878 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2879#ifdef _GLIBCXX_USE_CHAR8_T
2880 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2882 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2883 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2885 template<typename _Tp>
2886 concept __formattable_integer = __is_formattable_integer<_Tp>;
2890 /// Format an integer.
2891 template<__format::__formattable_integer _Tp, __format::__char _CharT>
2892 struct formatter<_Tp, _CharT>
2894 formatter() = default;
2896 [[__gnu__::__always_inline__]]
2897 constexpr typename basic_format_parse_context<_CharT>::iterator
2898 parse(basic_format_parse_context<_CharT>& __pc)
2900 return _M_f.template _M_parse<_Tp>(__pc);
2903 template<typename _Out>
2904 typename basic_format_context<_Out, _CharT>::iterator
2905 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2906 { return _M_f.format(__u, __fc); }
2909 __format::__formatter_int<_CharT> _M_f;
2912#if __glibcxx_print >= 202403L
2913 template<__format::__formattable_integer _Tp>
2915 enable_nonlocking_formatter_optimization<_Tp> = true;
2918#if defined __glibcxx_to_chars
2919 /// Format a floating-point value.
2920 template<__format::__formattable_float _Tp, __format::__char _CharT>
2921 struct formatter<_Tp, _CharT>
2923 formatter() = default;
2925 [[__gnu__::__always_inline__]]
2926 constexpr typename basic_format_parse_context<_CharT>::iterator
2927 parse(basic_format_parse_context<_CharT>& __pc)
2928 { return _M_f.parse(__pc); }
2930 template<typename _Out>
2931 typename basic_format_context<_Out, _CharT>::iterator
2932 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2933 { return _M_f.format(__u, __fc); }
2936 __format::__formatter_fp<_CharT> _M_f;
2939#if __glibcxx_print >= 202403L
2940 template<__format::__formattable_float _Tp>
2942 enable_nonlocking_formatter_optimization<_Tp> = true;
2945#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2946 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2947 template<__format::__char _CharT>
2948 struct formatter<long double, _CharT>
2950 formatter() = default;
2952 [[__gnu__::__always_inline__]]
2953 constexpr typename basic_format_parse_context<_CharT>::iterator
2954 parse(basic_format_parse_context<_CharT>& __pc)
2955 { return _M_f.parse(__pc); }
2957 template<typename _Out>
2958 typename basic_format_context<_Out, _CharT>::iterator
2959 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2960 { return _M_f.format((double)__u, __fc); }
2963 __format::__formatter_fp<_CharT> _M_f;
2967#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2968 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2969 template<__format::__char _CharT>
2970 struct formatter<_Float16, _CharT>
2972 formatter() = default;
2974 [[__gnu__::__always_inline__]]
2975 constexpr typename basic_format_parse_context<_CharT>::iterator
2976 parse(basic_format_parse_context<_CharT>& __pc)
2977 { return _M_f.parse(__pc); }
2979 template<typename _Out>
2980 typename basic_format_context<_Out, _CharT>::iterator
2981 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2982 { return _M_f.format((float)__u, __fc); }
2985 __format::__formatter_fp<_CharT> _M_f;
2989#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2990 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2991 template<__format::__char _CharT>
2992 struct formatter<_Float32, _CharT>
2994 formatter() = default;
2996 [[__gnu__::__always_inline__]]
2997 constexpr typename basic_format_parse_context<_CharT>::iterator
2998 parse(basic_format_parse_context<_CharT>& __pc)
2999 { return _M_f.parse(__pc); }
3001 template<typename _Out>
3002 typename basic_format_context<_Out, _CharT>::iterator
3003 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
3004 { return _M_f.format((float)__u, __fc); }
3007 __format::__formatter_fp<_CharT> _M_f;
3011#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3012 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
3013 template<__format::__char _CharT>
3014 struct formatter<_Float64, _CharT>
3016 formatter() = default;
3018 [[__gnu__::__always_inline__]]
3019 constexpr typename basic_format_parse_context<_CharT>::iterator
3020 parse(basic_format_parse_context<_CharT>& __pc)
3021 { return _M_f.parse(__pc); }
3023 template<typename _Out>
3024 typename basic_format_context<_Out, _CharT>::iterator
3025 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
3026 { return _M_f.format((double)__u, __fc); }
3029 __format::__formatter_fp<_CharT> _M_f;
3033#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
3034 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
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(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
3056 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
3057 // when long double is not 128bit IEEE type.
3058 template<__format::__char _CharT>
3059 struct formatter<__float128, _CharT>
3061 formatter() = default;
3063 [[__gnu__::__always_inline__]]
3064 constexpr typename basic_format_parse_context<_CharT>::iterator
3065 parse(basic_format_parse_context<_CharT>& __pc)
3066 { return _M_f.parse(__pc); }
3068 template<typename _Out>
3069 typename basic_format_context<_Out, _CharT>::iterator
3070 format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3071 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3074 __format::__formatter_fp<_CharT> _M_f;
3078#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3079 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3080 template<__format::__char _CharT>
3081 struct formatter<__format::__bflt16_t, _CharT>
3083 formatter() = default;
3085 [[__gnu__::__always_inline__]]
3086 constexpr typename basic_format_parse_context<_CharT>::iterator
3087 parse(basic_format_parse_context<_CharT>& __pc)
3088 { return _M_f.parse(__pc); }
3090 template<typename _Out>
3091 typename basic_format_context<_Out, _CharT>::iterator
3092 format(__gnu_cxx::__bfloat16_t __u,
3093 basic_format_context<_Out, _CharT>& __fc) const
3094 { return _M_f.format((float)__u, __fc); }
3097 __format::__formatter_fp<_CharT> _M_f;
3100#endif // __cpp_lib_to_chars
3102 /** Format a pointer.
3105 template<__format::__char _CharT>
3106 struct formatter<const void*, _CharT>
3108 formatter() = default;
3110 constexpr typename basic_format_parse_context<_CharT>::iterator
3111 parse(basic_format_parse_context<_CharT>& __pc)
3112 { return _M_f.parse(__pc); }
3114 template<typename _Out>
3115 typename basic_format_context<_Out, _CharT>::iterator
3116 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3117 { return _M_f.format(__v, __fc); }
3120 __format::__formatter_ptr<_CharT> _M_f;
3123#if __glibcxx_print >= 202403L
3125 inline constexpr bool
3126 enable_nonlocking_formatter_optimization<const void*> = true;
3129 template<__format::__char _CharT>
3130 struct formatter<void*, _CharT>
3132 formatter() = default;
3134 [[__gnu__::__always_inline__]]
3135 constexpr typename basic_format_parse_context<_CharT>::iterator
3136 parse(basic_format_parse_context<_CharT>& __pc)
3137 { return _M_f.parse(__pc); }
3139 template<typename _Out>
3140 typename basic_format_context<_Out, _CharT>::iterator
3141 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3142 { return _M_f.format(__v, __fc); }
3145 __format::__formatter_ptr<_CharT> _M_f;
3148#if __glibcxx_print >= 202403l
3150 inline constexpr bool
3151 enable_nonlocking_formatter_optimization<void*> = true;
3154 template<__format::__char _CharT>
3155 struct formatter<nullptr_t, _CharT>
3157 formatter() = default;
3159 [[__gnu__::__always_inline__]]
3160 constexpr typename basic_format_parse_context<_CharT>::iterator
3161 parse(basic_format_parse_context<_CharT>& __pc)
3162 { return _M_f.parse(__pc); }
3164 template<typename _Out>
3165 typename basic_format_context<_Out, _CharT>::iterator
3166 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3167 { return _M_f.format(nullptr, __fc); }
3170 __format::__formatter_ptr<_CharT> _M_f;
3174#if __glibcxx_print >= 202403L
3176 inline constexpr bool
3177 enable_nonlocking_formatter_optimization<nullptr_t> = true;
3180#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3181 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3182 // 3944. Formatters converting sequences of char to sequences of wchar_t
3184 struct __formatter_disabled
3186 __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3187 __formatter_disabled(const __formatter_disabled&) = delete;
3188 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3192 struct formatter<char*, wchar_t>
3193 : private __formatter_disabled { };
3195 struct formatter<const char*, wchar_t>
3196 : private __formatter_disabled { };
3197 template<size_t _Nm>
3198 struct formatter<char[_Nm], wchar_t>
3199 : private __formatter_disabled { };
3200 template<class _Traits, class _Allocator>
3201 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3202 : private __formatter_disabled { };
3203 template<class _Traits>
3204 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3205 : private __formatter_disabled { };
3208 /// An iterator after the last character written, and the number of
3209 /// characters that would have been written.
3210 template<typename _Out>
3211 struct format_to_n_result
3214 iter_difference_t<_Out> size;
3217_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3218template<typename, typename> class vector;
3219_GLIBCXX_END_NAMESPACE_CONTAINER
3221/// @cond undocumented
3224 template<typename _CharT>
3228 using iterator_category = output_iterator_tag;
3229 using value_type = void;
3230 using difference_type = ptrdiff_t;
3231 using pointer = void;
3232 using reference = void;
3234 _Drop_iter() = default;
3235 _Drop_iter(const _Drop_iter&) = default;
3236 _Drop_iter& operator=(const _Drop_iter&) = default;
3238 [[__gnu__::__always_inline__]]
3239 constexpr _Drop_iter&
3240 operator=(_CharT __c)
3243 [[__gnu__::__always_inline__]]
3244 constexpr _Drop_iter&
3245 operator=(basic_string_view<_CharT> __s)
3248 [[__gnu__::__always_inline__]]
3249 constexpr _Drop_iter&
3250 operator*() { return *this; }
3252 [[__gnu__::__always_inline__]]
3253 constexpr _Drop_iter&
3254 operator++() { return *this; }
3256 [[__gnu__::__always_inline__]]
3257 constexpr _Drop_iter
3258 operator++(int) { return *this; }
3261 template<typename _CharT>
3264 _Sink<_CharT>* _M_sink = nullptr;
3267 using iterator_category = output_iterator_tag;
3268 using value_type = void;
3269 using difference_type = ptrdiff_t;
3270 using pointer = void;
3271 using reference = void;
3273 _Sink_iter() = default;
3274 _Sink_iter(const _Sink_iter&) = default;
3275 _Sink_iter& operator=(const _Sink_iter&) = default;
3277 [[__gnu__::__always_inline__]]
3279 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3281 [[__gnu__::__always_inline__]]
3282 constexpr _Sink_iter&
3283 operator=(_CharT __c)
3285 _M_sink->_M_write(__c);
3289 [[__gnu__::__always_inline__]]
3290 constexpr _Sink_iter&
3291 operator=(basic_string_view<_CharT> __s)
3293 _M_sink->_M_write(__s);
3297 [[__gnu__::__always_inline__]]
3298 constexpr _Sink_iter&
3299 operator*() { return *this; }
3301 [[__gnu__::__always_inline__]]
3302 constexpr _Sink_iter&
3303 operator++() { return *this; }
3305 [[__gnu__::__always_inline__]]
3306 constexpr _Sink_iter
3307 operator++(int) { return *this; }
3310 _M_reserve(size_t __n) const
3311 { return _M_sink->_M_reserve(__n); }
3314 _M_discarding() const
3315 { return _M_sink->_M_discarding(); }
3318 // Abstract base class for type-erased character sinks.
3319 // All formatting and output is done via this type's iterator,
3320 // to reduce the number of different template instantiations.
3321 template<typename _CharT>
3324 friend class _Sink_iter<_CharT>;
3326 span<_CharT> _M_span;
3327 typename span<_CharT>::iterator _M_next;
3329 // Called when the span is full, to make more space available.
3330 // Precondition: _M_next != _M_span.begin()
3331 // Postcondition: _M_next != _M_span.end()
3332 // TODO: remove the precondition? could make overflow handle it.
3333 virtual void _M_overflow() = 0;
3336 // Precondition: __span.size() != 0
3337 [[__gnu__::__always_inline__]]
3339 _Sink(span<_CharT> __span) noexcept
3340 : _M_span(__span), _M_next(__span.begin())
3343 // The portion of the span that has been written to.
3344 [[__gnu__::__always_inline__]]
3346 _M_used() const noexcept
3347 { return _M_span.first(_M_next - _M_span.begin()); }
3349 // The portion of the span that has not been written to.
3350 [[__gnu__::__always_inline__]]
3351 constexpr span<_CharT>
3352 _M_unused() const noexcept
3353 { return _M_span.subspan(_M_next - _M_span.begin()); }
3355 // Use the start of the span as the next write position.
3356 [[__gnu__::__always_inline__]]
3358 _M_rewind() noexcept
3359 { _M_next = _M_span.begin(); }
3361 // Replace the current output range.
3363 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3366 _M_next = __s.begin() + __pos;
3369 // Called by the iterator for *it++ = c
3371 _M_write(_CharT __c)
3374 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3379 _M_write(basic_string_view<_CharT> __s)
3381 span __to = _M_unused();
3382 while (__to.size() <= __s.size())
3384 __s.copy(__to.data(), __to.size());
3385 _M_next += __to.size();
3386 __s.remove_prefix(__to.size());
3392 __s.copy(__to.data(), __s.size());
3393 _M_next += __s.size();
3397 // A successful _Reservation can be used to directly write
3398 // up to N characters to the sink to avoid unwanted buffering.
3401 // True if the reservation was successful, false otherwise.
3402 explicit operator bool() const noexcept { return _M_sink; }
3403 // A pointer to write directly to the sink.
3404 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3405 // Add n to the _M_next iterator for the sink.
3406 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3410 // Attempt to reserve space to write n characters to the sink.
3411 // If anything is written to the reservation then there must be a call
3412 // to _M_bump(N2) before any call to another member function of *this,
3413 // where N2 is the number of characters written.
3414 virtual _Reservation
3415 _M_reserve(size_t __n)
3417 if (__n <= _M_unused().size())
3420 if (__n <= _M_span.size()) // Cannot meet the request.
3422 _M_overflow(); // Make more space available.
3423 if (__n <= _M_unused().size())
3429 // Update the next output position after writing directly to the sink.
3430 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3435 // Returns true if the _Sink is discarding incoming characters.
3437 _M_discarding() const
3441 _Sink(const _Sink&) = delete;
3442 _Sink& operator=(const _Sink&) = delete;
3444 [[__gnu__::__always_inline__]]
3445 constexpr _Sink_iter<_CharT>
3447 { return _Sink_iter<_CharT>(*this); }
3451 template<typename _CharT>
3452 class _Fixedbuf_sink final : public _Sink<_CharT>
3455 _M_overflow() override
3457 __glibcxx_assert(false);
3462 [[__gnu__::__always_inline__]]
3464 _Fixedbuf_sink(span<_CharT> __buf)
3465 : _Sink<_CharT>(__buf)
3468 constexpr basic_string_view<_CharT>
3471 auto __s = this->_M_used();
3472 return basic_string_view<_CharT>(__s.data(), __s.size());
3476 // A sink with an internal buffer. This is used to implement concrete sinks.
3477 template<typename _CharT>
3478 class _Buf_sink : public _Sink<_CharT>
3481 _CharT _M_buf[__stackbuf_size<_CharT>];
3483 [[__gnu__::__always_inline__]]
3485 _Buf_sink() noexcept
3486 : _Sink<_CharT>(_M_buf)
3490 using _GLIBCXX_STD_C::vector;
3492 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3493 // Writes to a buffer then appends that to the sequence when it fills up.
3494 template<typename _Seq>
3495 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3497 using _CharT = typename _Seq::value_type;
3501 // Transfer buffer contents to the sequence, so buffer can be refilled.
3503 _M_overflow() override
3505 auto __s = this->_M_used();
3506 if (__s.empty()) [[unlikely]]
3507 return; // Nothing in the buffer to transfer to _M_seq.
3509 // If _M_reserve was called then _M_bump must have been called too.
3510 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3512 if constexpr (__is_specialization_of<_Seq, basic_string>)
3513 _M_seq.append(__s.data(), __s.size());
3515 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3517 // Make the whole of _M_buf available for the next write:
3521 typename _Sink<_CharT>::_Reservation
3522 _M_reserve(size_t __n) override
3524 // We might already have n characters available in this->_M_unused(),
3525 // but the whole point of this function is to be an optimization for
3526 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3527 // and then copying that into a basic_string if possible, so this
3528 // function prefers to create space directly in _M_seq rather than
3531 if constexpr (__is_specialization_of<_Seq, basic_string>
3532 || __is_specialization_of<_Seq, vector>)
3534 // Flush the buffer to _M_seq first (should not be needed).
3535 if (this->_M_used().size()) [[unlikely]]
3536 _Seq_sink::_M_overflow();
3538 // Expand _M_seq to make __n new characters available:
3539 const auto __sz = _M_seq.size();
3540 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3541 _M_seq.__resize_and_overwrite(__sz + __n,
3542 [](auto, auto __n2) {
3546 _M_seq.resize(__sz + __n);
3548 // Set _M_used() to be a span over the original part of _M_seq
3549 // and _M_unused() to be the extra capacity we just created:
3550 this->_M_reset(_M_seq, __sz);
3553 else // Try to use the base class' buffer.
3554 return _Sink<_CharT>::_M_reserve(__n);
3558 _M_bump(size_t __n) override
3560 if constexpr (__is_specialization_of<_Seq, basic_string>
3561 || __is_specialization_of<_Seq, vector>)
3563 auto __s = this->_M_used();
3564 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3565 // Truncate the sequence to the part that was actually written to:
3566 _M_seq.resize(__s.size() + __n);
3567 // Switch back to using buffer:
3568 this->_M_reset(this->_M_buf);
3572 void _M_trim(span<const _CharT> __s)
3573 requires __is_specialization_of<_Seq, basic_string>
3575 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3576 || __s.data() == _M_seq.data());
3577 if (__s.data() == _M_seq.data())
3578 _M_seq.resize(__s.size());
3580 this->_M_reset(this->_M_buf, __s.size());
3584 // TODO: for SSO string, use SSO buffer as initial span, then switch
3585 // to _M_buf if it overflows? Or even do that for all unused capacity?
3587 [[__gnu__::__always_inline__]]
3588 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3591 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3592 : _M_seq(std::move(__s))
3595 using _Sink<_CharT>::out;
3600 if (this->_M_used().size() != 0)
3601 _Seq_sink::_M_overflow();
3602 return std::move(_M_seq);
3605 // A writable span that views everything written to the sink.
3606 // Will be either a view over _M_seq or the used part of _M_buf.
3610 auto __s = this->_M_used();
3613 if (__s.size() != 0)
3614 _Seq_sink::_M_overflow();
3620 basic_string_view<_CharT>
3623 auto __span = _M_span();
3624 return basic_string_view<_CharT>(__span.data(), __span.size());
3628 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3630 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3632 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3633 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3634 // Writes to a fixed-size buffer and then flushes to the output iterator
3635 // when the buffer fills up.
3636 template<typename _CharT, typename _OutIter>
3637 class _Iter_sink : public _Buf_sink<_CharT>
3640 iter_difference_t<_OutIter> _M_max;
3643 size_t _M_count = 0;
3646 _M_overflow() override
3648 auto __s = this->_M_used();
3649 if (_M_max < 0) // No maximum.
3650 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3651 else if (_M_count < static_cast<size_t>(_M_max))
3653 auto __max = _M_max - _M_count;
3654 span<_CharT> __first;
3655 if (__max < __s.size())
3656 __first = __s.first(static_cast<size_t>(__max));
3659 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3662 _M_count += __s.size();
3666 _M_discarding() const override
3668 // format_to_n return total number of characters, that would be written,
3669 // see C++20 [format.functions] p20
3674 [[__gnu__::__always_inline__]]
3676 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3677 : _M_out(std::move(__out)), _M_max(__max)
3680 using _Sink<_CharT>::out;
3682 format_to_n_result<_OutIter>
3685 if (this->_M_used().size() != 0)
3686 _Iter_sink::_M_overflow();
3687 iter_difference_t<_OutIter> __count(_M_count);
3688 return { std::move(_M_out), __count };
3692 // Partial specialization for contiguous iterators.
3693 // No buffer is used, characters are written straight to the iterator.
3694 // We do not know the size of the output range, so the span size just grows
3695 // as needed. The end of the span might be an invalid pointer outside the
3696 // valid range, but we never actually call _M_span.end(). This class does
3697 // not introduce any invalid pointer arithmetic or overflows that would not
3698 // have happened anyway.
3699 template<typename _CharT, contiguous_iterator _OutIter>
3700 requires same_as<iter_value_t<_OutIter>, _CharT>
3701 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3704 iter_difference_t<_OutIter> _M_max = -1;
3706 size_t _M_count = 0;
3708 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3712 _M_overflow() override
3714 if (this->_M_unused().size() != 0)
3715 return; // No need to switch to internal buffer yet.
3717 auto __s = this->_M_used();
3721 _M_count += __s.size();
3722 // Span was already sized for the maximum character count,
3723 // if it overflows then any further output must go to the
3724 // internal buffer, to be discarded.
3725 this->_M_reset(this->_M_buf);
3729 // No maximum character count. Just extend the span to allow
3730 // writing more characters to it.
3731 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3736 _M_discarding() const override
3738 // format_to_n return total number of characters, that would be written,
3739 // see C++20 [format.functions] p20
3743 typename _Sink<_CharT>::_Reservation
3744 _M_reserve(size_t __n) final
3746 auto __avail = this->_M_unused();
3747 if (__n > __avail.size())
3750 return {}; // cannot grow
3752 auto __s = this->_M_used();
3753 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3760 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3761 span<_CharT> __buf) noexcept
3764 return __buf; // Only write to the internal buffer.
3768 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3769 || sizeof(__n) > sizeof(size_t))
3771 // __int128 or __detail::__max_diff_type
3772 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3776 return {__ptr, (size_t)__n};
3779#if __has_builtin(__builtin_dynamic_object_size)
3780 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3781 return {__ptr, __bytes / sizeof(_CharT)};
3783 // Avoid forming a pointer to a different memory page.
3784 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3785 __n = (1024 - __off) / sizeof(_CharT);
3786 if (__n > 0) [[likely]]
3787 return {__ptr, static_cast<size_t>(__n)};
3788 else // Misaligned/packed buffer of wchar_t?
3794 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3795 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3796 _M_first(__out), _M_max(__n)
3799 format_to_n_result<_OutIter>
3802 auto __s = this->_M_used();
3803 if (__s.data() == _M_buf)
3805 // Switched to internal buffer, so must have written _M_max.
3806 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3807 return { _M_first + _M_max, __count };
3809 else // Not using internal buffer yet
3811 iter_difference_t<_OutIter> __count(__s.size());
3812 return { _M_first + __count, __count };
3817 // A sink for handling the padded outputs (_M_padwidth) or truncated
3818 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3819 // until sufficient number of characters is written. After that if sequence
3820 // is longer than _M_padwidth it's written to _M_out, and further writes are
3822 // * buffered and forwarded to _M_out, if below _M_maxwidth,
3823 // * ignored otherwise
3824 // If field width of written sequence is no greater than _M_padwidth, the
3825 // sequence is written during _M_finish call.
3826 template<typename _Out, typename _CharT>
3827 class _Padding_sink : public _Str_sink<_CharT>
3832 size_t _M_printwidth;
3834 [[__gnu__::__always_inline__]]
3837 { return _M_printwidth >= _M_maxwidth; }
3839 [[__gnu__::__always_inline__]]
3841 _M_buffering() const
3843 if (_M_printwidth < _M_padwidth)
3845 if (_M_maxwidth != (size_t)-1)
3846 return _M_printwidth < _M_maxwidth;
3851 _M_sync_discarding()
3853 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3854 if (_M_out._M_discarding())
3855 _M_maxwidth = _M_printwidth;
3861 span<_CharT> __new = this->_M_used();
3862 basic_string_view<_CharT> __str(__new.data(), __new.size());
3863 _M_out = __format::__write(std::move(_M_out), __str);
3864 _M_sync_discarding();
3871 auto __str = this->view();
3872 // Compute actual field width, possibly truncated.
3873 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3875 this->_M_trim(__str);
3879 // We have more characters than padidng, no padding is needed,
3880 // write direclty to _M_out.
3881 if (_M_printwidth >= _M_padwidth)
3883 _M_out = __format::__write(std::move(_M_out), __str);
3884 _M_sync_discarding();
3886 // We reached _M_maxwidth that is smaller than _M_padwidth.
3887 // Store the prefix sequence in _M_seq, and free _M_buf.
3889 _Str_sink<_CharT>::_M_overflow();
3891 // Use internal buffer for writes to _M_out.
3892 this->_M_reset(this->_M_buf);
3897 _M_update(size_t __new)
3899 _M_printwidth += __new;
3900 // Compute estimated width, to see if is not reduced.
3901 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3902 return _M_force_update();
3907 _M_overflow() override
3909 // Ignore characters in buffer, and override it.
3912 // Write buffer to _M_out, and override it.
3913 else if (!_M_buffering())
3915 // Update written count, and if input still should be buffered,
3916 // flush the to _M_seq.
3917 else if (_M_update(this->_M_used().size()))
3918 _Str_sink<_CharT>::_M_overflow();
3922 _M_discarding() const override
3923 { return _M_ignoring(); }
3925 typename _Sink<_CharT>::_Reservation
3926 _M_reserve(size_t __n) override
3928 // Ignore characters in buffer, if any.
3931 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3932 if (!_M_buffering())
3934 // Write pending characters if any
3935 if (!this->_M_used().empty())
3937 // Try to reserve from _M_out sink.
3938 if (auto __reserved = _M_out._M_reserve(__n))
3941 return _Sink<_CharT>::_M_reserve(__n);
3945 _M_bump(size_t __n) override
3947 // Ignore the written characters.
3950 // If reservation was made directy sink associated _M_out,
3951 // _M_bump will be called on that sink.
3952 _Sink<_CharT>::_M_bump(__n);
3958 [[__gnu__::__always_inline__]]
3960 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
3961 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
3962 _M_out(std::move(__out)), _M_printwidth(0)
3963 { _M_sync_discarding(); }
3965 [[__gnu__::__always_inline__]]
3967 _Padding_sink(_Out __out, size_t __padwidth)
3968 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
3972 _M_finish(_Align __align, char32_t __fill_char)
3974 // Handle any characters in the buffer.
3975 if (auto __rem = this->_M_used().size())
3979 else if (!_M_buffering())
3985 if (!_M_buffering() || !_M_force_update())
3986 // Characters were already written to _M_out.
3987 if (_M_printwidth >= _M_padwidth)
3988 return std::move(_M_out);
3990 const auto __str = this->view();
3991 if (_M_printwidth >= _M_padwidth)
3992 return __format::__write(std::move(_M_out), __str);
3994 const size_t __nfill = _M_padwidth - _M_printwidth;
3995 return __format::__write_padded(std::move(_M_out), __str,
3996 __align, __nfill, __fill_char);
4000 template<typename _Out, typename _CharT>
4001 class _Escaping_sink : public _Buf_sink<_CharT>
4003 using _Esc = _Escapes<_CharT>;
4006 _Term_char _M_term : 2;
4007 unsigned _M_prev_escape : 1;
4008 unsigned _M_out_discards : 1;
4011 _M_sync_discarding()
4013 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4014 _M_out_discards = _M_out._M_discarding();
4020 span<_CharT> __bytes = this->_M_used();
4021 basic_string_view<_CharT> __str(__bytes.data(), __bytes.size());
4024 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4026 bool __prev_escape = _M_prev_escape;
4027 _M_out = __format::__write_escaped_unicode_part(
4028 std::move(_M_out), __str, __prev_escape, _M_term);
4029 _M_prev_escape = __prev_escape;
4031 __rem = __str.size();
4032 if (__rem > 0 && __str.data() != this->_M_buf) [[unlikely]]
4033 ranges::move(__str, this->_M_buf);
4036 _M_out = __format::__write_escaped_ascii(
4037 std::move(_M_out), __str, _M_term);
4039 this->_M_reset(this->_M_buf, __rem);
4040 _M_sync_discarding();
4044 _M_overflow() override
4046 if (_M_out_discards)
4053 _M_discarding() const override
4054 { return _M_out_discards; }
4057 [[__gnu__::__always_inline__]]
4059 _Escaping_sink(_Out __out, _Term_char __term)
4060 : _M_out(std::move(__out)), _M_term(__term),
4061 _M_prev_escape(true), _M_out_discards(false)
4063 _M_out = __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4064 _M_sync_discarding();
4070 if (_M_out_discards)
4071 return std::move(_M_out);
4073 if (!this->_M_used().empty())
4076 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
4077 if (auto __rem = this->_M_used(); !__rem.empty())
4079 basic_string_view<_CharT> __str(__rem.data(), __rem.size());
4080 _M_out = __format::__write_escape_seqs(std::move(_M_out), __str);
4083 return __format::__write(std::move(_M_out), _Esc::_S_term(_M_term));
4087 enum class _Arg_t : unsigned char {
4088 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
4089 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
4090 _Arg_i128, _Arg_u128, _Arg_float128,
4091 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
4094#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4095 _Arg_ibm128 = _Arg_ldbl,
4096 _Arg_ieee128 = _Arg_float128,
4101 template<typename _Context>
4104 using _CharT = typename _Context::char_type;
4120 unsigned long long _M_ull;
4123#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4124 long double _M_ldbl;
4127 __ieee128 _M_ieee128;
4129#ifdef __SIZEOF_FLOAT128__
4130 __float128 _M_float128;
4132 const _CharT* _M_str;
4133 basic_string_view<_CharT> _M_sv;
4135 _HandleBase _M_handle;
4136#ifdef __SIZEOF_INT128__
4138 unsigned __int128 _M_u128;
4140#ifdef __BFLT16_DIG__
4154 [[__gnu__::__always_inline__]]
4155 _Arg_value() : _M_none() { }
4158 template<typename _Tp>
4159 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4160 { _S_get<_Tp>() = __val; }
4163 template<typename _Tp, typename _Self>
4164 [[__gnu__::__always_inline__]]
4166 _S_get(_Self& __u) noexcept
4168 if constexpr (is_same_v<_Tp, bool>)
4170 else if constexpr (is_same_v<_Tp, _CharT>)
4172 else if constexpr (is_same_v<_Tp, int>)
4174 else if constexpr (is_same_v<_Tp, unsigned>)
4176 else if constexpr (is_same_v<_Tp, long long>)
4178 else if constexpr (is_same_v<_Tp, unsigned long long>)
4180 else if constexpr (is_same_v<_Tp, float>)
4182 else if constexpr (is_same_v<_Tp, double>)
4184#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4185 else if constexpr (is_same_v<_Tp, long double>)
4188 else if constexpr (is_same_v<_Tp, __ibm128>)
4189 return __u._M_ibm128;
4190 else if constexpr (is_same_v<_Tp, __ieee128>)
4191 return __u._M_ieee128;
4193#ifdef __SIZEOF_FLOAT128__
4194 else if constexpr (is_same_v<_Tp, __float128>)
4195 return __u._M_float128;
4197 else if constexpr (is_same_v<_Tp, const _CharT*>)
4199 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4201 else if constexpr (is_same_v<_Tp, const void*>)
4203#ifdef __SIZEOF_INT128__
4204 else if constexpr (is_same_v<_Tp, __int128>)
4206 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4209#ifdef __BFLT16_DIG__
4210 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4214 else if constexpr (is_same_v<_Tp, _Float16>)
4218 else if constexpr (is_same_v<_Tp, _Float32>)
4222 else if constexpr (is_same_v<_Tp, _Float64>)
4225 else if constexpr (derived_from<_Tp, _HandleBase>)
4226 return static_cast<_Tp&>(__u._M_handle);
4227 // Otherwise, ill-formed.
4230 template<typename _Tp>
4231 [[__gnu__::__always_inline__]]
4234 { return _S_get<_Tp>(*this); }
4236 template<typename _Tp>
4237 [[__gnu__::__always_inline__]]
4239 _M_get() const noexcept
4240 { return _S_get<_Tp>(*this); }
4242 template<typename _Tp>
4243 [[__gnu__::__always_inline__]]
4245 _M_set(_Tp __v) noexcept
4247 if constexpr (derived_from<_Tp, _HandleBase>)
4248 std::construct_at(&_M_handle, __v);
4250 _S_get<_Tp>(*this) = __v;
4254 // [format.arg.store], class template format-arg-store
4255 template<typename _Context, typename... _Args>
4258 template<typename _Visitor, typename _Ctx>
4259 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4261 template<typename _Ch, typename _Tp>
4263 __to_arg_t_enum() noexcept;
4264} // namespace __format
4267 template<typename _Context>
4268 class basic_format_arg
4270 using _CharT = typename _Context::char_type;
4272 template<typename _Tp>
4273 static constexpr bool __formattable
4274 = __format::__formattable_with<_Tp, _Context>;
4277 class handle : public __format::_Arg_value<_Context>::_HandleBase
4279 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
4281 // Format as const if possible, to reduce instantiations.
4282 template<typename _Tp>
4283 using __maybe_const_t
4284 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
4286 template<typename _Tq>
4288 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4289 _Context& __format_ctx, const void* __ptr)
4291 using _Td = remove_const_t<_Tq>;
4292 typename _Context::template formatter_type<_Td> __f;
4293 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4294 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4295 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4298 template<typename _Tp>
4300 handle(_Tp& __val) noexcept
4302 this->_M_ptr = __builtin_addressof(__val);
4303 auto __func = _S_format<__maybe_const_t<_Tp>>;
4304 this->_M_func = reinterpret_cast<void(*)()>(__func);
4307 friend class basic_format_arg<_Context>;
4310 handle(const handle&) = default;
4311 handle& operator=(const handle&) = default;
4313 [[__gnu__::__always_inline__]]
4315 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4317 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4318 _Context&, const void*);
4319 auto __f = reinterpret_cast<_Func>(this->_M_func);
4320 __f(__pc, __fc, this->_M_ptr);
4324 [[__gnu__::__always_inline__]]
4325 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4327 [[nodiscard,__gnu__::__always_inline__]]
4328 explicit operator bool() const noexcept
4329 { return _M_type != __format::_Arg_none; }
4331#if __cpp_lib_format >= 202306L // >= C++26
4332 template<typename _Visitor>
4334 visit(this basic_format_arg __arg, _Visitor&& __vis)
4335 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4337 template<typename _Res, typename _Visitor>
4339 visit(this basic_format_arg __arg, _Visitor&& __vis)
4340 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4344 template<typename _Ctx>
4345 friend class basic_format_args;
4347 template<typename _Ctx, typename... _Args>
4348 friend class __format::_Arg_store;
4350 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4352 __format::_Arg_value<_Context> _M_val;
4353 __format::_Arg_t _M_type;
4355 // Transform incoming argument type to the type stored in _Arg_value.
4356 // e.g. short -> int, std::string -> std::string_view,
4357 // char[3] -> const char*.
4358 template<typename _Tp>
4359 static consteval auto
4362 using _Td = remove_const_t<_Tp>;
4363 if constexpr (is_same_v<_Td, bool>)
4364 return type_identity<bool>();
4365 else if constexpr (is_same_v<_Td, _CharT>)
4366 return type_identity<_CharT>();
4367 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4368 return type_identity<_CharT>();
4369#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4370 else if constexpr (is_same_v<_Td, __int128>)
4371 return type_identity<__int128>();
4372 else if constexpr (is_same_v<_Td, unsigned __int128>)
4373 return type_identity<unsigned __int128>();
4375 else if constexpr (__is_signed_integer<_Td>::value)
4377 if constexpr (sizeof(_Td) <= sizeof(int))
4378 return type_identity<int>();
4379 else if constexpr (sizeof(_Td) <= sizeof(long long))
4380 return type_identity<long long>();
4382 else if constexpr (__is_unsigned_integer<_Td>::value)
4384 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4385 return type_identity<unsigned>();
4386 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4387 return type_identity<unsigned long long>();
4389 else if constexpr (is_same_v<_Td, float>)
4390 return type_identity<float>();
4391 else if constexpr (is_same_v<_Td, double>)
4392 return type_identity<double>();
4393#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4394 else if constexpr (is_same_v<_Td, long double>)
4395 return type_identity<long double>();
4397 else if constexpr (is_same_v<_Td, __ibm128>)
4398 return type_identity<__ibm128>();
4399 else if constexpr (is_same_v<_Td, __ieee128>)
4400 return type_identity<__ieee128>();
4402#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4403 else if constexpr (is_same_v<_Td, __float128>)
4404 return type_identity<__float128>();
4406#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4407 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4408 return type_identity<__format::__bflt16_t>();
4410#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4411 else if constexpr (is_same_v<_Td, _Float16>)
4412 return type_identity<_Float16>();
4414#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4415 else if constexpr (is_same_v<_Td, _Float32>)
4416 return type_identity<_Float32>();
4418#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4419 else if constexpr (is_same_v<_Td, _Float64>)
4420 return type_identity<_Float64>();
4422 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4423 || __is_specialization_of<_Td, basic_string>)
4425 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4426 return type_identity<basic_string_view<_CharT>>();
4428 return type_identity<handle>();
4430 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4431 return type_identity<const _CharT*>();
4432 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4433 return type_identity<const _CharT*>();
4434 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4435 return type_identity<const void*>();
4436 else if constexpr (is_same_v<_Td, nullptr_t>)
4437 return type_identity<const void*>();
4439 return type_identity<handle>();
4442 // Transform a formattable type to the appropriate storage type.
4443 template<typename _Tp>
4444 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4446 // Get the _Arg_t value corresponding to a normalized type.
4447 template<typename _Tp>
4448 static consteval __format::_Arg_t
4451 using namespace __format;
4452 if constexpr (is_same_v<_Tp, bool>)
4454 else if constexpr (is_same_v<_Tp, _CharT>)
4456 else if constexpr (is_same_v<_Tp, int>)
4458 else if constexpr (is_same_v<_Tp, unsigned>)
4460 else if constexpr (is_same_v<_Tp, long long>)
4462 else if constexpr (is_same_v<_Tp, unsigned long long>)
4464 else if constexpr (is_same_v<_Tp, float>)
4466 else if constexpr (is_same_v<_Tp, double>)
4468#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4469 else if constexpr (is_same_v<_Tp, long double>)
4472 // Don't use _Arg_ldbl for this target, it's ambiguous.
4473 else if constexpr (is_same_v<_Tp, __ibm128>)
4475 else if constexpr (is_same_v<_Tp, __ieee128>)
4476 return _Arg_ieee128;
4478#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4479 else if constexpr (is_same_v<_Tp, __float128>)
4480 return _Arg_float128;
4482#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4483 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4486#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4487 else if constexpr (is_same_v<_Tp, _Float16>)
4490#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4491 else if constexpr (is_same_v<_Tp, _Float32>)
4494#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4495 else if constexpr (is_same_v<_Tp, _Float64>)
4498 else if constexpr (is_same_v<_Tp, const _CharT*>)
4500 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4502 else if constexpr (is_same_v<_Tp, const void*>)
4504#ifdef __SIZEOF_INT128__
4505 else if constexpr (is_same_v<_Tp, __int128>)
4507 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4510 else if constexpr (is_same_v<_Tp, handle>)
4514 template<typename _Tp>
4516 _M_set(_Tp __v) noexcept
4518 _M_type = _S_to_enum<_Tp>();
4522 template<typename _Tp>
4523 requires __format::__formattable_with<_Tp, _Context>
4525 basic_format_arg(_Tp& __v) noexcept
4527 using _Td = _Normalize<_Tp>;
4528 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4529 _M_set(_Td{__v.data(), __v.size()});
4530 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4531 && is_same_v<_CharT, wchar_t>)
4532 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4534 _M_set(static_cast<_Td>(__v));
4537 template<typename _Ctx, typename... _Argz>
4539 make_format_args(_Argz&...) noexcept;
4541 template<typename _Visitor, typename _Ctx>
4542 friend decltype(auto)
4543 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4545 template<typename _Visitor, typename _Ctx>
4546 friend decltype(auto)
4547 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4549 template<typename _Ch, typename _Tp>
4550 friend consteval __format::_Arg_t
4551 __format::__to_arg_t_enum() noexcept;
4553 template<typename _Visitor>
4555 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4557 using namespace __format;
4561 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4563 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4565 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4567 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4569 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4571 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4573 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4574#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4576 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4578 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4579#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4581 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4582#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4584 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4588 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4590 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4592#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4594 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4596#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4598 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4600#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4602 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4604#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4606 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4608#endif // __glibcxx_to_chars
4610 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4612 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4614 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4617 auto& __h = static_cast<handle&>(_M_val._M_handle);
4618 return std::forward<_Visitor>(__vis)(__h);
4620#ifdef __SIZEOF_INT128__
4622 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4624 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4627 __builtin_unreachable();
4631 template<typename _Visitor>
4633 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4635 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4637 constexpr bool __user_facing = __is_one_of<_Tp,
4638 monostate, bool, _CharT,
4639 int, unsigned int, long long int, unsigned long long int,
4640 float, double, long double,
4641 const _CharT*, basic_string_view<_CharT>,
4642 const void*, handle>::value;
4643 if constexpr (__user_facing)
4644 return std::forward<_Visitor>(__vis)(__val);
4648 return std::forward<_Visitor>(__vis)(__h);
4654 template<typename _Visitor, typename _Context>
4655 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4656 inline decltype(auto)
4657 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4659 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4662/// @cond undocumented
4665 template<typename _Visitor, typename _Ctx>
4666 inline decltype(auto)
4667 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4669 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4672 struct _WidthPrecVisitor
4674 template<typename _Tp>
4676 operator()(_Tp& __arg) const
4678 if constexpr (is_same_v<_Tp, monostate>)
4679 __format::__invalid_arg_id_in_format_string();
4680 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4681 // 3720. Restrict the valid types of arg-id for width and precision
4682 // 3721. Allow an arg-id with a value of zero for width
4683 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4685 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4686 // 3720. Restrict the valid types of arg-id for width and precision
4687 if constexpr (__is_unsigned_integer<_Tp>::value)
4689 else if constexpr (__is_signed_integer<_Tp>::value)
4693 __throw_format_error("format error: argument used for width or "
4694 "precision must be a non-negative integer");
4698#pragma GCC diagnostic push
4699#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4700 template<typename _Context>
4702 __int_from_arg(const basic_format_arg<_Context>& __arg)
4703 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4705 // Pack _Arg_t enum values into a single 60-bit integer.
4706 template<int _Bits, size_t _Nm>
4708 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4710 __UINT64_TYPE__ __packed_types = 0;
4711 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4712 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4713 return __packed_types;
4715} // namespace __format
4718 template<typename _Context>
4719 class basic_format_args
4721 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4722 static constexpr int _S_packed_type_mask = 0b11111;
4723 static constexpr int _S_max_packed_args = 12;
4725 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4727 template<typename... _Args>
4728 using _Store = __format::_Arg_store<_Context, _Args...>;
4730 template<typename _Ctx, typename... _Args>
4731 friend class __format::_Arg_store;
4733 using uint64_t = __UINT64_TYPE__;
4734 using _Format_arg = basic_format_arg<_Context>;
4735 using _Format_arg_val = __format::_Arg_value<_Context>;
4737 // If args are packed then the number of args is in _M_packed_size and
4738 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4739 // If args are not packed then the number of args is in _M_unpacked_size
4740 // and _M_packed_size is zero.
4741 uint64_t _M_packed_size : 4;
4742 uint64_t _M_unpacked_size : 60;
4745 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4746 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4750 _M_size() const noexcept
4751 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4753 typename __format::_Arg_t
4754 _M_type(size_t __i) const noexcept
4756 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4757 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4760 template<typename _Ctx, typename... _Args>
4762 make_format_args(_Args&...) noexcept;
4764 // An array of _Arg_t enums corresponding to _Args...
4765 template<typename... _Args>
4766 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4768 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4771 template<typename... _Args>
4772 basic_format_args(const _Store<_Args...>& __store) noexcept;
4774 [[nodiscard,__gnu__::__always_inline__]]
4775 basic_format_arg<_Context>
4776 get(size_t __i) const noexcept
4778 basic_format_arg<_Context> __arg;
4779 if (__i < _M_packed_size)
4781 __arg._M_type = _M_type(__i);
4782 __arg._M_val = _M_values[__i];
4784 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4785 __arg = _M_args[__i];
4790 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4791 // 3810. CTAD for std::basic_format_args
4792 template<typename _Context, typename... _Args>
4793 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4794 -> basic_format_args<_Context>;
4796 template<typename _Context, typename... _Args>
4798 make_format_args(_Args&... __fmt_args) noexcept;
4800 // An array of type-erased formatting arguments.
4801 template<typename _Context, typename... _Args>
4802 class __format::_Arg_store
4804 friend std::basic_format_args<_Context>;
4806 template<typename _Ctx, typename... _Argz>
4808#if _GLIBCXX_INLINE_VERSION
4809 __8:: // Needed for PR c++/59256
4811 make_format_args(_Argz&...) noexcept;
4813 // For a sufficiently small number of arguments we only store values.
4814 // basic_format_args can get the types from the _Args pack.
4815 static constexpr bool _S_values_only
4816 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4819 = __conditional_t<_S_values_only,
4820 __format::_Arg_value<_Context>,
4821 basic_format_arg<_Context>>;
4823 _Element_t _M_args[sizeof...(_Args)];
4825 template<typename _Tp>
4827 _S_make_elt(_Tp& __v)
4829 using _Tq = remove_const_t<_Tp>;
4830 using _CharT = typename _Context::char_type;
4831 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4832 "std::formatter must be specialized for the type "
4833 "of each format arg");
4834 using __format::__formattable_with;
4835 if constexpr (is_const_v<_Tp>)
4836 if constexpr (!__formattable_with<_Tp, _Context>)
4837 if constexpr (__formattable_with<_Tq, _Context>)
4838 static_assert(__formattable_with<_Tp, _Context>,
4839 "format arg must be non-const because its "
4840 "std::formatter specialization has a "
4841 "non-const reference parameter");
4842 basic_format_arg<_Context> __arg(__v);
4843 if constexpr (_S_values_only)
4844 return __arg._M_val;
4849 template<typename... _Tp>
4850 requires (sizeof...(_Tp) == sizeof...(_Args))
4851 [[__gnu__::__always_inline__]]
4852 _Arg_store(_Tp&... __a) noexcept
4853 : _M_args{_S_make_elt(__a)...}
4857 template<typename _Context>
4858 class __format::_Arg_store<_Context>
4861 template<typename _Context>
4862 template<typename... _Args>
4864 basic_format_args<_Context>::
4865 basic_format_args(const _Store<_Args...>& __store) noexcept
4867 if constexpr (sizeof...(_Args) == 0)
4870 _M_unpacked_size = 0;
4873 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4875 // The number of packed arguments:
4876 _M_packed_size = sizeof...(_Args);
4877 // The packed type enums:
4879 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4880 // The _Arg_value objects.
4881 _M_values = __store._M_args;
4885 // No packed arguments:
4887 // The number of unpacked arguments:
4888 _M_unpacked_size = sizeof...(_Args);
4889 // The basic_format_arg objects:
4890 _M_args = __store._M_args;
4894 /// Capture formatting arguments for use by `std::vformat`.
4895 template<typename _Context = format_context, typename... _Args>
4896 [[nodiscard,__gnu__::__always_inline__]]
4898 make_format_args(_Args&... __fmt_args) noexcept
4900 using _Fmt_arg = basic_format_arg<_Context>;
4901 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4902 _Normalize<_Args>...>;
4903 return _Store(__fmt_args...);
4906#ifdef _GLIBCXX_USE_WCHAR_T
4907 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4908 template<typename... _Args>
4909 [[nodiscard,__gnu__::__always_inline__]]
4911 make_wformat_args(_Args&... __args) noexcept
4912 { return std::make_format_args<wformat_context>(__args...); }
4915/// @cond undocumented
4918 template<typename _Out, typename _CharT, typename _Context>
4920 __do_vformat_to(_Out, basic_string_view<_CharT>,
4921 const basic_format_args<_Context>&,
4922 const locale* = nullptr);
4924 template<typename _CharT> struct __formatter_chrono;
4926} // namespace __format
4929 /** Context for std::format and similar functions.
4931 * A formatting context contains an output iterator and locale to use
4932 * for the formatting operations. Most programs will never need to use
4933 * this class template explicitly. For typical uses of `std::format` the
4934 * library will use the specializations `std::format_context` (for `char`)
4935 * and `std::wformat_context` (for `wchar_t`).
4937 * You are not allowed to define partial or explicit specializations of
4938 * this class template.
4942 template<typename _Out, typename _CharT>
4943 class basic_format_context
4945 static_assert( output_iterator<_Out, const _CharT&> );
4947 basic_format_args<basic_format_context> _M_args;
4949 __format::_Optional_locale _M_loc;
4951 basic_format_context(basic_format_args<basic_format_context> __args,
4953 : _M_args(__args), _M_out(std::move(__out))
4956 basic_format_context(basic_format_args<basic_format_context> __args,
4957 _Out __out, const std::locale& __loc)
4958 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4961 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4962 // 4061. Should std::basic_format_context be
4963 // default-constructible/copyable/movable?
4964 basic_format_context(const basic_format_context&) = delete;
4965 basic_format_context& operator=(const basic_format_context&) = delete;
4967 template<typename _Out2, typename _CharT2, typename _Context2>
4969 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4970 const basic_format_args<_Context2>&,
4973 friend __format::__formatter_chrono<_CharT>;
4976 ~basic_format_context() = default;
4978 using iterator = _Out;
4979 using char_type = _CharT;
4980 template<typename _Tp>
4981 using formatter_type = formatter<_Tp, _CharT>;
4984 basic_format_arg<basic_format_context>
4985 arg(size_t __id) const noexcept
4986 { return _M_args.get(__id); }
4989 std::locale locale() { return _M_loc.value(); }
4992 iterator out() { return std::move(_M_out); }
4994 void advance_to(iterator __it) { _M_out = std::move(__it); }
4998/// @cond undocumented
5001 // Abstract base class defining an interface for scanning format strings.
5002 // Scan the characters in a format string, dividing it up into strings of
5003 // ordinary characters, escape sequences, and replacement fields.
5004 // Call virtual functions for derived classes to parse format-specifiers
5005 // or write formatted output.
5006 template<typename _CharT>
5009 using iterator = typename basic_format_parse_context<_CharT>::iterator;
5011 struct _Parse_context : basic_format_parse_context<_CharT>
5013 using basic_format_parse_context<_CharT>::basic_format_parse_context;
5014 const _Arg_t* _M_types = nullptr;
5018 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
5019 : _M_pc(__str, __nargs)
5022 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
5023 constexpr iterator end() const noexcept { return _M_pc.end(); }
5028 basic_string_view<_CharT> __fmt = _M_fmt_str();
5030 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5032 _M_pc.advance_to(begin() + 1);
5033 _M_format_arg(_M_pc.next_arg_id());
5037 size_t __lbr = __fmt.find('{');
5038 size_t __rbr = __fmt.find('}');
5040 while (__fmt.size())
5042 auto __cmp = __lbr <=> __rbr;
5046 _M_pc.advance_to(end());
5051 if (__lbr + 1 == __fmt.size()
5052 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
5053 __format::__unmatched_left_brace_in_format_string();
5054 const bool __is_escape = __fmt[__lbr + 1] == '{';
5055 iterator __last = begin() + __lbr + int(__is_escape);
5056 _M_on_chars(__last);
5057 _M_pc.advance_to(__last + 1);
5058 __fmt = _M_fmt_str();
5061 if (__rbr != __fmt.npos)
5063 __lbr = __fmt.find('{');
5067 _M_on_replacement_field();
5068 __fmt = _M_fmt_str();
5069 __lbr = __fmt.find('{');
5070 __rbr = __fmt.find('}');
5075 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
5076 __format::__unmatched_right_brace_in_format_string();
5077 iterator __last = begin() + __rbr;
5078 _M_on_chars(__last);
5079 _M_pc.advance_to(__last + 1);
5080 __fmt = _M_fmt_str();
5081 if (__lbr != __fmt.npos)
5083 __rbr = __fmt.find('}');
5088 constexpr basic_string_view<_CharT>
5089 _M_fmt_str() const noexcept
5090 { return {begin(), end()}; }
5092 constexpr virtual void _M_on_chars(iterator) { }
5094 constexpr void _M_on_replacement_field()
5096 auto __next = begin();
5100 __id = _M_pc.next_arg_id();
5101 else if (*__next == ':')
5103 __id = _M_pc.next_arg_id();
5104 _M_pc.advance_to(++__next);
5108 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5109 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5110 __format::__invalid_arg_id_in_format_string();
5111 _M_pc.check_arg_id(__id = __i);
5114 _M_pc.advance_to(++__ptr);
5117 _M_pc.advance_to(__ptr);
5119 _M_format_arg(__id);
5120 if (begin() == end() || *begin() != '}')
5121 __format::__unmatched_left_brace_in_format_string();
5122 _M_pc.advance_to(begin() + 1); // Move past '}'
5125 constexpr virtual void _M_format_arg(size_t __id) = 0;
5128 // Process a format string and format the arguments in the context.
5129 template<typename _Out, typename _CharT>
5130 class _Formatting_scanner : public _Scanner<_CharT>
5133 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5134 basic_string_view<_CharT> __str)
5135 : _Scanner<_CharT>(__str), _M_fc(__fc)
5139 basic_format_context<_Out, _CharT>& _M_fc;
5141 using iterator = typename _Scanner<_CharT>::iterator;
5144 _M_on_chars(iterator __last) override
5146 basic_string_view<_CharT> __str(this->begin(), __last);
5147 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5151 _M_format_arg(size_t __id) override
5153 using _Context = basic_format_context<_Out, _CharT>;
5154 using handle = typename basic_format_arg<_Context>::handle;
5156 __format::__visit_format_arg([this](auto& __arg) {
5157 using _Type = remove_reference_t<decltype(__arg)>;
5158 using _Formatter = typename _Context::template formatter_type<_Type>;
5159 if constexpr (is_same_v<_Type, monostate>)
5160 __format::__invalid_arg_id_in_format_string();
5161 else if constexpr (is_same_v<_Type, handle>)
5162 __arg.format(this->_M_pc, this->_M_fc);
5163 else if constexpr (is_default_constructible_v<_Formatter>)
5166 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5167 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5170 static_assert(__format::__formattable_with<_Type, _Context>);
5171 }, _M_fc.arg(__id));
5175 template<typename _CharT, typename _Tp>
5177 __to_arg_t_enum() noexcept
5179 using _Context = __format::__format_context<_CharT>;
5180 using _Fmt_arg = basic_format_arg<_Context>;
5181 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5182 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5185 // Validate a format string for Args.
5186 template<typename _CharT, typename... _Args>
5187 class _Checking_scanner : public _Scanner<_CharT>
5190 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5191 "std::formatter must be specialized for each type being formatted");
5195 _Checking_scanner(basic_string_view<_CharT> __str)
5196 : _Scanner<_CharT>(__str, sizeof...(_Args))
5198#if __cpp_lib_format >= 202305L
5199 this->_M_pc._M_types = _M_types.data();
5205 _M_format_arg(size_t __id) override
5207 if constexpr (sizeof...(_Args) != 0)
5209 if (__id < sizeof...(_Args))
5211 _M_parse_format_spec<_Args...>(__id);
5215 __builtin_unreachable();
5218 template<typename _Tp, typename... _OtherArgs>
5220 _M_parse_format_spec(size_t __id)
5224 formatter<_Tp, _CharT> __f;
5225 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5227 else if constexpr (sizeof...(_OtherArgs) != 0)
5228 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5230 __builtin_unreachable();
5233#if __cpp_lib_format >= 202305L
5234 array<_Arg_t, sizeof...(_Args)>
5235 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5239 template<typename _Out, typename _CharT, typename _Context>
5241 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5242 const basic_format_args<_Context>& __args,
5243 const locale* __loc)
5245 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5246 _Sink_iter<_CharT> __sink_out;
5248 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5249 __sink_out = __out; // Already a sink iterator, safe to use post-move.
5251 __sink_out = __sink.out();
5253 if constexpr (is_same_v<_CharT, char>)
5254 // Fast path for "{}" format strings and simple format arg types.
5255 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5257 bool __done = false;
5258 __format::__visit_format_arg([&](auto& __arg) {
5259 using _Tp = remove_cvref_t<decltype(__arg)>;
5260 if constexpr (is_same_v<_Tp, bool>)
5262 size_t __len = 4 + !__arg;
5263 const char* __chars[] = { "false", "true" };
5264 if (auto __res = __sink_out._M_reserve(__len))
5266 __builtin_memcpy(__res.get(), __chars[__arg], __len);
5267 __res._M_bump(__len);
5271 else if constexpr (is_same_v<_Tp, char>)
5273 if (auto __res = __sink_out._M_reserve(1))
5275 *__res.get() = __arg;
5280 else if constexpr (is_integral_v<_Tp>)
5282 make_unsigned_t<_Tp> __uval;
5283 const bool __neg = __arg < 0;
5285 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5288 const auto __n = __detail::__to_chars_len(__uval);
5289 if (auto __res = __sink_out._M_reserve(__n + __neg))
5291 auto __ptr = __res.get();
5293 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5295 __res._M_bump(__n + __neg);
5299 else if constexpr (is_convertible_v<_Tp, string_view>)
5301 string_view __sv = __arg;
5302 if (auto __res = __sink_out._M_reserve(__sv.size()))
5304 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5305 __res._M_bump(__sv.size());
5313 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5316 return std::move(__sink)._M_finish().out;
5320 auto __ctx = __loc == nullptr
5321 ? _Context(__args, __sink_out)
5322 : _Context(__args, __sink_out, *__loc);
5323 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5324 __scanner._M_scan();
5326 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5329 return std::move(__sink)._M_finish().out;
5331#pragma GCC diagnostic pop
5333} // namespace __format
5336#if __cpp_lib_format >= 202305L // >= C++26
5337 /// @cond undocumented
5338 // Common implementation of check_dynamic_spec{,_string,_integral}
5339 template<typename _CharT>
5340 template<typename... _Ts>
5342 basic_format_parse_context<_CharT>::
5343 __check_dynamic_spec(size_t __id) noexcept
5345 if (__id >= _M_num_args)
5346 __format::__invalid_arg_id_in_format_string();
5347 if constexpr (sizeof...(_Ts) != 0)
5349 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5350 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
5351 __format::_Arg_t __types[] = {
5352 __format::__to_arg_t_enum<_CharT, _Ts>()...
5354 for (auto __t : __types)
5358 __invalid_dynamic_spec("arg(id) type does not match");
5363 template<typename _CharT, typename... _Args>
5364 template<typename _Tp>
5365 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5367 basic_format_string<_CharT, _Args...>::
5368 basic_format_string(const _Tp& __s)
5371 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5373 __scanner._M_scan();
5376 // [format.functions], formatting functions
5378 template<typename _Out> requires output_iterator<_Out, const char&>
5379 [[__gnu__::__always_inline__]]
5381 vformat_to(_Out __out, string_view __fmt, format_args __args)
5382 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5384#ifdef _GLIBCXX_USE_WCHAR_T
5385 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5386 [[__gnu__::__always_inline__]]
5388 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5389 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5392 template<typename _Out> requires output_iterator<_Out, const char&>
5393 [[__gnu__::__always_inline__]]
5395 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5398 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5401#ifdef _GLIBCXX_USE_WCHAR_T
5402 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5403 [[__gnu__::__always_inline__]]
5405 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5406 wformat_args __args)
5408 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5414 vformat(string_view __fmt, format_args __args)
5416 __format::_Str_sink<char> __buf;
5417 std::vformat_to(__buf.out(), __fmt, __args);
5418 return std::move(__buf).get();
5421#ifdef _GLIBCXX_USE_WCHAR_T
5424 vformat(wstring_view __fmt, wformat_args __args)
5426 __format::_Str_sink<wchar_t> __buf;
5427 std::vformat_to(__buf.out(), __fmt, __args);
5428 return std::move(__buf).get();
5434 vformat(const locale& __loc, string_view __fmt, format_args __args)
5436 __format::_Str_sink<char> __buf;
5437 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5438 return std::move(__buf).get();
5441#ifdef _GLIBCXX_USE_WCHAR_T
5444 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5446 __format::_Str_sink<wchar_t> __buf;
5447 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5448 return std::move(__buf).get();
5452 template<typename... _Args>
5455 format(format_string<_Args...> __fmt, _Args&&... __args)
5456 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5458#ifdef _GLIBCXX_USE_WCHAR_T
5459 template<typename... _Args>
5462 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5463 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5466 template<typename... _Args>
5469 format(const locale& __loc, format_string<_Args...> __fmt,
5472 return std::vformat(__loc, __fmt.get(),
5473 std::make_format_args(__args...));
5476#ifdef _GLIBCXX_USE_WCHAR_T
5477 template<typename... _Args>
5480 format(const locale& __loc, wformat_string<_Args...> __fmt,
5483 return std::vformat(__loc, __fmt.get(),
5484 std::make_wformat_args(__args...));
5488 template<typename _Out, typename... _Args>
5489 requires output_iterator<_Out, const char&>
5491 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5493 return std::vformat_to(std::move(__out), __fmt.get(),
5494 std::make_format_args(__args...));
5497#ifdef _GLIBCXX_USE_WCHAR_T
5498 template<typename _Out, typename... _Args>
5499 requires output_iterator<_Out, const wchar_t&>
5501 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5503 return std::vformat_to(std::move(__out), __fmt.get(),
5504 std::make_wformat_args(__args...));
5508 template<typename _Out, typename... _Args>
5509 requires output_iterator<_Out, const char&>
5511 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5514 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5515 std::make_format_args(__args...));
5518#ifdef _GLIBCXX_USE_WCHAR_T
5519 template<typename _Out, typename... _Args>
5520 requires output_iterator<_Out, const wchar_t&>
5522 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5525 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5526 std::make_wformat_args(__args...));
5530 template<typename _Out, typename... _Args>
5531 requires output_iterator<_Out, const char&>
5532 inline format_to_n_result<_Out>
5533 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5534 format_string<_Args...> __fmt, _Args&&... __args)
5536 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5537 std::vformat_to(__sink.out(), __fmt.get(),
5538 std::make_format_args(__args...));
5539 return std::move(__sink)._M_finish();
5542#ifdef _GLIBCXX_USE_WCHAR_T
5543 template<typename _Out, typename... _Args>
5544 requires output_iterator<_Out, const wchar_t&>
5545 inline format_to_n_result<_Out>
5546 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5547 wformat_string<_Args...> __fmt, _Args&&... __args)
5549 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5550 std::vformat_to(__sink.out(), __fmt.get(),
5551 std::make_wformat_args(__args...));
5552 return std::move(__sink)._M_finish();
5556 template<typename _Out, typename... _Args>
5557 requires output_iterator<_Out, const char&>
5558 inline format_to_n_result<_Out>
5559 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5560 format_string<_Args...> __fmt, _Args&&... __args)
5562 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5563 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5564 std::make_format_args(__args...));
5565 return std::move(__sink)._M_finish();
5568#ifdef _GLIBCXX_USE_WCHAR_T
5569 template<typename _Out, typename... _Args>
5570 requires output_iterator<_Out, const wchar_t&>
5571 inline format_to_n_result<_Out>
5572 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5573 wformat_string<_Args...> __fmt, _Args&&... __args)
5575 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5576 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5577 std::make_wformat_args(__args...));
5578 return std::move(__sink)._M_finish();
5582/// @cond undocumented
5586 template<typename _CharT>
5587 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5590 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5592 [[__gnu__::__always_inline__]]
5595 { return this->_M_count + this->_M_used().size(); }
5598 template<typename _CharT>
5599 class _Counting_sink : public _Buf_sink<_CharT>
5601 size_t _M_count = 0;
5604 _M_overflow() override
5606 if (!std::is_constant_evaluated())
5607 _M_count += this->_M_used().size();
5612 _Counting_sink() = default;
5614 [[__gnu__::__always_inline__]]
5618 _Counting_sink::_M_overflow();
5623} // namespace __format
5626 template<typename... _Args>
5629 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5631 __format::_Counting_sink<char> __buf;
5632 std::vformat_to(__buf.out(), __fmt.get(),
5633 std::make_format_args(__args...));
5634 return __buf.count();
5637#ifdef _GLIBCXX_USE_WCHAR_T
5638 template<typename... _Args>
5641 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5643 __format::_Counting_sink<wchar_t> __buf;
5644 std::vformat_to(__buf.out(), __fmt.get(),
5645 std::make_wformat_args(__args...));
5646 return __buf.count();
5650 template<typename... _Args>
5653 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5656 __format::_Counting_sink<char> __buf;
5657 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5658 std::make_format_args(__args...));
5659 return __buf.count();
5662#ifdef _GLIBCXX_USE_WCHAR_T
5663 template<typename... _Args>
5666 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5669 __format::_Counting_sink<wchar_t> __buf;
5670 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5671 std::make_wformat_args(__args...));
5672 return __buf.count();
5676#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5677 /// @cond undocumented
5678 template<typename _Tp>
5679 consteval range_format
5682 using _Ref = ranges::range_reference_t<_Tp>;
5683 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5684 return range_format::disabled;
5685 else if constexpr (requires { typename _Tp::key_type; })
5687 if constexpr (requires { typename _Tp::mapped_type; })
5689 using _Up = remove_cvref_t<_Ref>;
5690 if constexpr (__is_pair<_Up>)
5691 return range_format::map;
5692 else if constexpr (__is_specialization_of<_Up, tuple>)
5693 if constexpr (tuple_size_v<_Up> == 2)
5694 return range_format::map;
5696 return range_format::set;
5699 return range_format::sequence;
5703 /// A constant determining how a range should be formatted.
5704 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5705 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5707/// @cond undocumented
5710 template<typename _CharT, typename _Out, typename _Callback>
5711 typename basic_format_context<_Out, _CharT>::iterator
5712 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5713 const _Spec<_CharT>& __spec,
5716 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5720 // This is required to implement formatting with padding,
5721 // as we need to format to temporary buffer, using the same iterator.
5722 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5724 const size_t __padwidth = __spec._M_get_width(__fc);
5725 if (__padwidth == 0)
5726 return __call(__fc);
5730 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5731 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5736 { _M_ctx = nullptr; }
5741 _M_ctx->advance_to(_M_out);
5745 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5746 _Sink_iter<_CharT> _M_out;
5749 _Restore_out __restore(__fc);
5750 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5751 __fc.advance_to(__sink.out());
5753 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5754 __restore._M_disarm();
5759 template<size_t _Pos, typename _Tp, typename _CharT>
5760 struct __indexed_formatter_storage
5765 basic_format_parse_context<_CharT> __pc({});
5766 if (_M_formatter.parse(__pc) != __pc.end())
5767 __format::__failed_to_parse_format_spec();
5770 template<typename _Out>
5772 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5773 basic_format_context<_Out, _CharT>& __fc,
5774 basic_string_view<_CharT> __sep) const
5776 if constexpr (_Pos != 0)
5777 __fc.advance_to(__format::__write(__fc.out(), __sep));
5778 __fc.advance_to(_M_formatter.format(__elem, __fc));
5781 [[__gnu__::__always_inline__]]
5785 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5786 _M_formatter.set_debug_format();
5790 formatter<_Tp, _CharT> _M_formatter;
5793 template<typename _CharT, typename... _Tps>
5794 class __tuple_formatter
5796 using _String_view = basic_string_view<_CharT>;
5797 using _Seps = __format::_Separators<_CharT>;
5801 set_separator(basic_string_view<_CharT> __sep) noexcept
5805 set_brackets(basic_string_view<_CharT> __open,
5806 basic_string_view<_CharT> __close) noexcept
5812 // We deviate from standard, that declares this as template accepting
5813 // unconstrained ParseContext type, which seems unimplementable.
5814 constexpr typename basic_format_parse_context<_CharT>::iterator
5815 parse(basic_format_parse_context<_CharT>& __pc)
5817 auto __first = __pc.begin();
5818 const auto __last = __pc.end();
5819 __format::_Spec<_CharT> __spec{};
5821 auto __finished = [&]
5823 if (__first != __last && *__first != '}')
5827 _M_felems._M_parse();
5828 _M_felems.set_debug_format();
5835 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5839 __first = __spec._M_parse_width(__first, __last, __pc);
5843 if (*__first == 'n')
5846 _M_open = _M_close = _String_view();
5848 else if (*__first == 'm')
5851 if constexpr (sizeof...(_Tps) == 2)
5853 _M_sep = _Seps::_S_colon();
5854 _M_open = _M_close = _String_view();
5857 __throw_format_error("format error: 'm' specifier requires range"
5858 " of pair or tuple of two elements");
5864 __format::__failed_to_parse_format_spec();
5868 template<typename _Tuple, typename _Out, size_t... _Ids>
5869 typename basic_format_context<_Out, _CharT>::iterator
5870 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5871 basic_format_context<_Out, _CharT>& __fc) const
5872 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5874 template<typename _Out>
5875 typename basic_format_context<_Out, _CharT>::iterator
5876 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5877 basic_format_context<_Out, _CharT>& __fc) const
5879 return __format::__format_padded(
5881 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5883 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5884 _M_felems._M_format(__elems..., __nfc, _M_sep);
5885 return __format::__write(__nfc.out(), _M_close);
5890 template<size_t... _Ids>
5891 struct __formatters_storage
5892 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5894 template<size_t _Id, typename _Up>
5895 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5900 (_Base<_Ids, _Tps>::_M_parse(), ...);
5903 template<typename _Out>
5905 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5906 basic_format_context<_Out, _CharT>& __fc,
5907 _String_view __sep) const
5909 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5915 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5919 template<size_t... _Ids>
5921 _S_create_storage(index_sequence<_Ids...>)
5922 -> __formatters_storage<_Ids...>;
5924 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5926 _Spec<_CharT> _M_spec{};
5927 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5928 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5929 _String_view _M_sep = _Seps::_S_comma();
5930 _Formatters _M_felems;
5933 template<typename _Tp>
5934 concept __is_map_formattable
5935 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5937} // namespace __format
5940 // [format.tuple] Tuple formatter
5941 template<__format::__char _CharT, formattable<_CharT> _Fp,
5942 formattable<_CharT> _Sp>
5943 struct formatter<pair<_Fp, _Sp>, _CharT>
5944 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5945 remove_cvref_t<_Sp>>
5948 using __maybe_const_pair
5949 = __conditional_t<formattable<const _Fp, _CharT>
5950 && formattable<const _Sp, _CharT>,
5951 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5953 // We deviate from standard, that declares this as template accepting
5954 // unconstrained FormatContext type, which seems unimplementable.
5955 template<typename _Out>
5956 typename basic_format_context<_Out, _CharT>::iterator
5957 format(__maybe_const_pair& __p,
5958 basic_format_context<_Out, _CharT>& __fc) const
5959 { return this->_M_format_elems(__p.first, __p.second, __fc); }
5962#if __glibcxx_print >= 202406L
5963 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5964 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
5965 template<typename _Fp, typename _Sp>
5966 constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
5967 = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
5968 && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
5971 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5972 struct formatter<tuple<_Tps...>, _CharT>
5973 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5976 using __maybe_const_tuple
5977 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5978 const tuple<_Tps...>, tuple<_Tps...>>;
5980 // We deviate from standard, that declares this as template accepting
5981 // unconstrained FormatContext type, which seems unimplementable.
5982 template<typename _Out>
5983 typename basic_format_context<_Out, _CharT>::iterator
5984 format(__maybe_const_tuple& __t,
5985 basic_format_context<_Out, _CharT>& __fc) const
5986 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5989#if __glibcxx_print >= 202406L
5990 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5991 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
5992 template<typename... _Tps>
5993 constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
5994 = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
5997 // [format.range.formatter], class template range_formatter
5998 template<typename _Tp, __format::__char _CharT>
5999 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
6000 class range_formatter
6002 using _String_view = basic_string_view<_CharT>;
6003 using _Seps = __format::_Separators<_CharT>;
6007 set_separator(basic_string_view<_CharT> __sep) noexcept
6011 set_brackets(basic_string_view<_CharT> __open,
6012 basic_string_view<_CharT> __close) noexcept
6018 constexpr formatter<_Tp, _CharT>&
6019 underlying() noexcept
6022 constexpr const formatter<_Tp, _CharT>&
6023 underlying() const noexcept
6026 // We deviate from standard, that declares this as template accepting
6027 // unconstrained ParseContext type, which seems unimplementable.
6028 constexpr typename basic_format_parse_context<_CharT>::iterator
6029 parse(basic_format_parse_context<_CharT>& __pc)
6031 auto __first = __pc.begin();
6032 const auto __last = __pc.end();
6033 __format::_Spec<_CharT> __spec{};
6034 bool __no_brace = false;
6036 auto __finished = [&]
6037 { return __first == __last || *__first == '}'; };
6039 auto __finalize = [&]
6045 auto __parse_val = [&](_String_view __nfs = _String_view())
6047 basic_format_parse_context<_CharT> __npc(__nfs);
6048 if (_M_fval.parse(__npc) != __npc.end())
6049 __format::__failed_to_parse_format_spec();
6050 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
6051 _M_fval.set_debug_format();
6052 return __finalize();
6056 return __parse_val();
6058 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
6060 return __parse_val();
6062 __first = __spec._M_parse_width(__first, __last, __pc);
6064 return __parse_val();
6066 if (*__first == '?')
6069 __spec._M_debug = true;
6070 if (__finished() || *__first != 's')
6071 __throw_format_error("format error: '?' is allowed only in"
6072 " combination with 's'");
6075 if (*__first == 's')
6078 if constexpr (same_as<_Tp, _CharT>)
6080 __spec._M_type = __format::_Pres_s;
6082 return __finalize();
6083 __throw_format_error("format error: element format specifier"
6084 " cannot be provided when 's' specifier is used");
6087 __throw_format_error("format error: 's' specifier requires"
6088 " range of character types");
6092 return __parse_val();
6094 if (*__first == 'n')
6097 _M_open = _M_close = _String_view();
6102 return __parse_val();
6104 if (*__first == 'm')
6106 _String_view __m(__first, 1);
6108 if constexpr (__format::__is_map_formattable<_Tp>)
6110 _M_sep = _Seps::_S_comma();
6113 _M_open = _Seps::_S_braces().substr(0, 1);
6114 _M_close = _Seps::_S_braces().substr(1, 1);
6117 return __parse_val(__m);
6118 __throw_format_error("format error: element format specifier"
6119 " cannot be provided when 'm' specifier is used");
6122 __throw_format_error("format error: 'm' specifier requires"
6123 " range of pairs or tuples of two elements");
6127 return __parse_val();
6129 if (*__first == ':')
6131 __pc.advance_to(++__first);
6132 __first = _M_fval.parse(__pc);
6136 return __finalize();
6138 __format::__failed_to_parse_format_spec();
6141 // We deviate from standard, that declares this as template accepting
6142 // unconstrained FormatContext type, which seems unimplementable.
6143 template<ranges::input_range _Rg, typename _Out>
6144 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6145 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6146 typename basic_format_context<_Out, _CharT>::iterator
6147 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6149 using _Range = remove_reference_t<_Rg>;
6150 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6151 return _M_format<const _Range>(__rg, __fc);
6153 return _M_format(__rg, __fc);
6157 template<ranges::input_range _Rg, typename _Out>
6158 typename basic_format_context<_Out, _CharT>::iterator
6159 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6161 if constexpr (same_as<_Tp, _CharT>)
6162 if (_M_spec._M_type == __format::_Pres_s)
6164 __format::__formatter_str __fstr(_M_spec);
6165 return __fstr._M_format_range(__rg, __fc);
6167 return __format::__format_padded(
6169 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6170 { return _M_format_elems(__rg, __nfc); });
6174 template<ranges::input_range _Rg, typename _Out>
6175 typename basic_format_context<_Out, _CharT>::iterator
6176 _M_format_elems(_Rg& __rg,
6177 basic_format_context<_Out, _CharT>& __fc) const
6179 auto __out = __format::__write(__fc.out(), _M_open);
6181 auto __first = ranges::begin(__rg);
6182 auto const __last = ranges::end(__rg);
6183 if (__first == __last)
6184 return __format::__write(__out, _M_close);
6186 __fc.advance_to(__out);
6187 __out = _M_fval.format(*__first, __fc);
6188 for (++__first; __first != __last; ++__first)
6190 __out = __format::__write(__out, _M_sep);
6191 __fc.advance_to(__out);
6192 __out = _M_fval.format(*__first, __fc);
6195 return __format::__write(__out, _M_close);
6198 __format::_Spec<_CharT> _M_spec{};
6199 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6200 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6201 _String_view _M_sep = _Seps::_S_comma();
6202 formatter<_Tp, _CharT> _M_fval;
6205 // In standard this is shown as inheriting from specialization of
6206 // exposition only specialization for range-default-formatter for
6207 // each range_format. We opt for simpler implementation.
6208 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6209 // specializations for maps, sets, and strings
6210 template<ranges::input_range _Rg, __format::__char _CharT>
6211 requires (format_kind<_Rg> != range_format::disabled)
6212 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6213 struct formatter<_Rg, _CharT>
6216 static const bool _S_range_format_is_string =
6217 (format_kind<_Rg> == range_format::string)
6218 || (format_kind<_Rg> == range_format::debug_string);
6219 using _Vt = remove_cvref_t<
6220 ranges::range_reference_t<
6221 __format::__maybe_const_range<_Rg, _CharT>>>;
6223 static consteval bool _S_is_correct()
6225 if constexpr (_S_range_format_is_string)
6226 static_assert(same_as<_Vt, _CharT>);
6230 static_assert(_S_is_correct());
6233 constexpr formatter() noexcept
6235 using _Seps = __format::_Separators<_CharT>;
6236 if constexpr (format_kind<_Rg> == range_format::map)
6238 static_assert(__format::__is_map_formattable<_Vt>);
6239 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6240 _Seps::_S_braces().substr(1, 1));
6241 _M_under.underlying().set_brackets({}, {});
6242 _M_under.underlying().set_separator(_Seps::_S_colon());
6244 else if constexpr (format_kind<_Rg> == range_format::set)
6245 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6246 _Seps::_S_braces().substr(1, 1));
6250 set_separator(basic_string_view<_CharT> __sep) noexcept
6251 requires (format_kind<_Rg> == range_format::sequence)
6252 { _M_under.set_separator(__sep); }
6255 set_brackets(basic_string_view<_CharT> __open,
6256 basic_string_view<_CharT> __close) noexcept
6257 requires (format_kind<_Rg> == range_format::sequence)
6258 { _M_under.set_brackets(__open, __close); }
6260 // We deviate from standard, that declares this as template accepting
6261 // unconstrained ParseContext type, which seems unimplementable.
6262 constexpr typename basic_format_parse_context<_CharT>::iterator
6263 parse(basic_format_parse_context<_CharT>& __pc)
6265 auto __res = _M_under.parse(__pc);
6266 if constexpr (format_kind<_Rg> == range_format::debug_string)
6267 _M_under.set_debug_format();
6271 // We deviate from standard, that declares this as template accepting
6272 // unconstrained FormatContext type, which seems unimplementable.
6273 template<typename _Out>
6274 typename basic_format_context<_Out, _CharT>::iterator
6275 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6276 basic_format_context<_Out, _CharT>& __fc) const
6278 if constexpr (_S_range_format_is_string)
6279 return _M_under._M_format_range(__rg, __fc);
6281 return _M_under.format(__rg, __fc);
6285 using _Formatter_under
6286 = __conditional_t<_S_range_format_is_string,
6287 __format::__formatter_str<_CharT>,
6288 range_formatter<_Vt, _CharT>>;
6289 _Formatter_under _M_under;
6292#if __glibcxx_print >= 202406L
6293 template<ranges::input_range _Rg>
6294 requires (format_kind<_Rg> != range_format::disabled)
6295 constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6298#endif // C++23 formatting ranges
6299#undef _GLIBCXX_WIDEN
6301_GLIBCXX_END_NAMESPACE_VERSION
6303#endif // __cpp_lib_format
6304#pragma GCC diagnostic pop
6305#endif // _GLIBCXX_FORMAT