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;
109 // Output iterator that writes to a type-erase character sink.
110 template<typename _CharT>
113 // Output iterator that ignores the characters
114 template<typename _CharT>
117 // An unspecified output iterator type used in the `formattable` concept.
118 template<typename _CharT>
120 { using type = _Drop_iter<_CharT>; };
122 template<typename _CharT>
123 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
125 template<typename _CharT>
126 struct _Runtime_format_string
128 [[__gnu__::__always_inline__]]
129 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
132 _Runtime_format_string(const _Runtime_format_string&) = delete;
133 void operator=(const _Runtime_format_string&) = delete;
136 basic_string_view<_CharT> _M_str;
138 template<typename, typename...> friend struct std::basic_format_string;
141} // namespace __format
144 using format_context = __format::__format_context<char>;
145#ifdef _GLIBCXX_USE_WCHAR_T
146 using wformat_context = __format::__format_context<wchar_t>;
149 // [format.args], class template basic_format_args
150 template<typename _Context> class basic_format_args;
151 using format_args = basic_format_args<format_context>;
152#ifdef _GLIBCXX_USE_WCHAR_T
153 using wformat_args = basic_format_args<wformat_context>;
156 // [format.arguments], arguments
157 // [format.arg], class template basic_format_arg
158 template<typename _Context>
159 class basic_format_arg;
161 /** A compile-time checked format string for the specified argument types.
163 * @since C++23 but available as an extension in C++20.
165 template<typename _CharT, typename... _Args>
166 struct basic_format_string
168 template<typename _Tp>
169 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
171 basic_format_string(const _Tp& __s);
173 [[__gnu__::__always_inline__]]
174 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
178 [[__gnu__::__always_inline__]]
179 constexpr basic_string_view<_CharT>
184 basic_string_view<_CharT> _M_str;
187 template<typename... _Args>
188 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
190#ifdef _GLIBCXX_USE_WCHAR_T
191 template<typename... _Args>
193 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
196#if __cpp_lib_format >= 202311L // >= C++26
197 [[__gnu__::__always_inline__]]
198 inline __format::_Runtime_format_string<char>
199 runtime_format(string_view __fmt) noexcept
202#ifdef _GLIBCXX_USE_WCHAR_T
203 [[__gnu__::__always_inline__]]
204 inline __format::_Runtime_format_string<wchar_t>
205 runtime_format(wstring_view __fmt) noexcept
210 // [format.formatter], formatter
212 /// The primary template of std::formatter is disabled.
213 template<typename _Tp, typename _CharT>
216 formatter() = delete; // No std::formatter specialization for this type.
217 formatter(const formatter&) = delete;
218 formatter& operator=(const formatter&) = delete;
221 // [format.error], class format_error
222 class format_error : public runtime_error
225 explicit format_error(const string& __what) : runtime_error(__what) { }
226 explicit format_error(const char* __what) : runtime_error(__what) { }
229 /// @cond undocumented
232 __throw_format_error(const char* __what)
233 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
237 // XXX use named functions for each constexpr error?
241 __unmatched_left_brace_in_format_string()
242 { __throw_format_error("format error: unmatched '{' in format string"); }
246 __unmatched_right_brace_in_format_string()
247 { __throw_format_error("format error: unmatched '}' in format string"); }
251 __conflicting_indexing_in_format_string()
252 { __throw_format_error("format error: conflicting indexing style in format string"); }
256 __invalid_arg_id_in_format_string()
257 { __throw_format_error("format error: invalid arg-id in format string"); }
261 __failed_to_parse_format_spec()
262 { __throw_format_error("format error: failed to parse format-spec"); }
264 template<typename _CharT> class _Scanner;
266} // namespace __format
269 // [format.parse.ctx], class template basic_format_parse_context
270 template<typename _CharT> class basic_format_parse_context;
271 using format_parse_context = basic_format_parse_context<char>;
272#ifdef _GLIBCXX_USE_WCHAR_T
273 using wformat_parse_context = basic_format_parse_context<wchar_t>;
276 template<typename _CharT>
277 class basic_format_parse_context
280 using char_type = _CharT;
281 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
282 using iterator = const_iterator;
285 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
286 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
289 basic_format_parse_context(const basic_format_parse_context&) = delete;
290 void operator=(const basic_format_parse_context&) = delete;
292 constexpr const_iterator begin() const noexcept { return _M_begin; }
293 constexpr const_iterator end() const noexcept { return _M_end; }
296 advance_to(const_iterator __it) noexcept
302 if (_M_indexing == _Manual)
303 __format::__conflicting_indexing_in_format_string();
306 // _GLIBCXX_RESOLVE_LIB_DEFECTS
307 // 3825. Missing compile-time argument id check in next_arg_id
308 if (std::is_constant_evaluated())
309 if (_M_next_arg_id == _M_num_args)
310 __format::__invalid_arg_id_in_format_string();
311 return _M_next_arg_id++;
315 check_arg_id(size_t __id)
317 if (_M_indexing == _Auto)
318 __format::__conflicting_indexing_in_format_string();
319 _M_indexing = _Manual;
321 if (std::is_constant_evaluated())
322 if (__id >= _M_num_args)
323 __format::__invalid_arg_id_in_format_string();
326#if __cpp_lib_format >= 202305L
327 template<typename... _Ts>
329 check_dynamic_spec(size_t __id) noexcept
331 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
332 "template arguments for check_dynamic_spec<Ts...>(id) "
333 "must be unique and must be one of the allowed types");
335 __check_dynamic_spec<_Ts...>(__id);
340 check_dynamic_spec_integral(size_t __id) noexcept
343 __check_dynamic_spec<int, unsigned, long long,
344 unsigned long long>(__id);
349 check_dynamic_spec_string(size_t __id) noexcept
352 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
357 // True if _Tp occurs exactly once in _Ts.
358 template<typename _Tp, typename... _Ts>
359 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
361 template<typename... _Ts>
363 __valid_types_for_check_dynamic_spec()
365 // _GLIBCXX_RESOLVE_LIB_DEFECTS
366 // 4142. check_dynamic_spec should require at least one type
367 if constexpr (sizeof...(_Ts) == 0)
371 // The types in Ts... are unique. Each type in Ts... is one of
372 // bool, char_type, int, unsigned int, long long int,
373 // unsigned long long int, float, double, long double,
374 // const char_type*, basic_string_view<char_type>, or const void*.
376 = __once<bool, _Ts...>
377 + __once<char_type, _Ts...>
378 + __once<int, _Ts...>
379 + __once<unsigned int, _Ts...>
380 + __once<long long int, _Ts...>
381 + __once<unsigned long long int, _Ts...>
382 + __once<float, _Ts...>
383 + __once<double, _Ts...>
384 + __once<long double, _Ts...>
385 + __once<const char_type*, _Ts...>
386 + __once<basic_string_view<char_type>, _Ts...>
387 + __once<const void*, _Ts...>;
388 return __sum == sizeof...(_Ts);
392 template<typename... _Ts>
394 __check_dynamic_spec(size_t __id) noexcept;
396 // This must not be constexpr.
397 static void __invalid_dynamic_spec(const char*);
399 friend __format::_Scanner<_CharT>;
402 // This constructor should only be used by the implementation.
404 basic_format_parse_context(basic_string_view<_CharT> __fmt,
405 size_t __num_args) noexcept
406 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
412 enum _Indexing { _Unknown, _Manual, _Auto };
413 _Indexing _M_indexing = _Unknown;
414 size_t _M_next_arg_id = 0;
415 size_t _M_num_args = 0;
418/// @cond undocumented
419 template<typename _Tp, template<typename...> class _Class>
420 constexpr bool __is_specialization_of = false;
421 template<template<typename...> class _Class, typename... _Args>
422 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
426 // pre: first != last
427 template<typename _CharT>
428 constexpr pair<unsigned short, const _CharT*>
429 __parse_integer(const _CharT* __first, const _CharT* __last)
431 if (__first == __last)
432 __builtin_unreachable();
434 if constexpr (is_same_v<_CharT, char>)
436 const auto __start = __first;
437 unsigned short __val = 0;
438 // N.B. std::from_chars is not constexpr in C++20.
439 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
440 && __first != __start) [[likely]]
441 return {__val, __first};
445 constexpr int __n = 32;
447 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
448 __buf[__i] = __first[__i];
449 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
450 if (__ptr) [[likely]]
451 return {__v, __first + (__ptr - __buf)};
456 template<typename _CharT>
457 constexpr pair<unsigned short, const _CharT*>
458 __parse_arg_id(const _CharT* __first, const _CharT* __last)
460 if (__first == __last)
461 __builtin_unreachable();
464 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
466 if ('1' <= *__first && *__first <= '9')
468 const unsigned short __id = *__first - '0';
469 const auto __next = __first + 1;
470 // Optimize for most likely case of single digit arg-id.
471 if (__next == __last || !('0' <= *__next && *__next <= '9'))
472 return {__id, __next};
474 return __format::__parse_integer(__first, __last);
479 enum class _Pres_type : unsigned char {
480 _Pres_none = 0, // Default type (not valid for integer presentation types).
481 _Pres_s = 1, // For strings, bool, ranges
482 // Presentation types for integral types (including bool and charT).
483 _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
484 // Presentation types for floating-point types
485 _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
486 // For pointers, the value are same as hexadecimal presentations for integers
487 _Pres_p = _Pres_x, _Pres_P = _Pres_X,
490 using enum _Pres_type;
492 enum class _Sign : unsigned char {
495 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
500 enum _WidthPrec : unsigned char {
501 _WP_none, // No width/prec specified.
502 _WP_value, // Fixed width/prec specified.
503 _WP_from_arg // Use a formatting argument for width/prec.
505 using enum _WidthPrec;
507 template<typename _Context>
509 __int_from_arg(const basic_format_arg<_Context>& __arg);
511 constexpr bool __is_digit(char __c)
512 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
514 constexpr bool __is_xdigit(char __c)
515 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
517 // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
518 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
522 template<typename _CharT>
523 struct _Spec : _SpecBase
525 unsigned short _M_width;
526 unsigned short _M_prec;
527 char32_t _M_fill = ' ';
531 unsigned _M_localized : 1;
532 unsigned _M_zero_fill : 1;
533 _WidthPrec _M_width_kind : 2;
534 _WidthPrec _M_prec_kind : 2;
535 unsigned _M_debug : 1;
536 _Pres_type _M_type : 4;
537 unsigned _M_reserved : 8;
538 // This class has 8 bits of tail padding, that can be used by
541 using iterator = typename basic_string_view<_CharT>::iterator;
543 static constexpr _Align
544 _S_align(_CharT __c) noexcept
548 case '<': return _Align_left;
549 case '>': return _Align_right;
550 case '^': return _Align_centre;
551 default: return _Align_default;
555 // pre: __first != __last
557 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
558 { return _M_parse_fill_and_align(__first, __last, "{"); }
560 // pre: __first != __last
562 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
564 for (char __c : __not_fill)
565 if (*__first == static_cast<_CharT>(__c))
568 using namespace __unicode;
569 if constexpr (__literal_encoding_is_unicode<_CharT>())
571 // Accept any UCS scalar value as fill character.
572 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
575 auto __beg = __uv.begin();
576 char32_t __c = *__beg++;
577 if (__is_scalar_value(__c))
578 if (auto __next = __beg.base(); __next != __last)
579 if (_Align __align = _S_align(*__next); __align != _Align_default)
587 else if (__last - __first >= 2)
588 if (_Align __align = _S_align(__first[1]); __align != _Align_default)
595 if (_Align __align = _S_align(__first[0]); __align != _Align_default)
604 static constexpr _Sign
605 _S_sign(_CharT __c) noexcept
609 case '+': return _Sign_plus;
610 case '-': return _Sign_minus;
611 case ' ': return _Sign_space;
612 default: return _Sign_default;
616 // pre: __first != __last
618 _M_parse_sign(iterator __first, iterator) noexcept
620 if (_Sign __sign = _S_sign(*__first); __sign != _Sign_default)
628 // pre: *__first is valid
630 _M_parse_alternate_form(iterator __first, iterator) noexcept
640 // pre: __first != __last
642 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
652 // pre: __first != __last
653 static constexpr iterator
654 _S_parse_width_or_precision(iterator __first, iterator __last,
655 unsigned short& __val, bool& __arg_id,
656 basic_format_parse_context<_CharT>& __pc)
658 if (__format::__is_digit(*__first))
660 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
662 __throw_format_error("format error: invalid width or precision "
667 else if (*__first == '{')
671 if (__first == __last)
672 __format::__unmatched_left_brace_in_format_string();
674 __val = __pc.next_arg_id();
677 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
678 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
679 __format::__invalid_arg_id_in_format_string();
681 __pc.check_arg_id(__v);
684#if __cpp_lib_format >= 202305L
685 __pc.check_dynamic_spec_integral(__val);
687 ++__first; // past the '}'
692 // pre: __first != __last
694 _M_parse_width(iterator __first, iterator __last,
695 basic_format_parse_context<_CharT>& __pc)
697 bool __arg_id = false;
699 __throw_format_error("format error: width must be non-zero in "
701 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
703 if (__next != __first)
704 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
708 // pre: __first != __last
710 _M_parse_precision(iterator __first, iterator __last,
711 basic_format_parse_context<_CharT>& __pc)
713 if (__first[0] != '.')
716 iterator __next = ++__first;
717 bool __arg_id = false;
718 if (__next != __last)
719 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
721 if (__next == __first)
722 __throw_format_error("format error: missing precision after '.' in "
724 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
728 // pre: __first != __last
730 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
740 template<typename _Context>
742 _M_get_width(_Context& __ctx) const
745 if (_M_width_kind == _WP_value)
747 else if (_M_width_kind == _WP_from_arg)
748 __width = __format::__int_from_arg(__ctx.arg(_M_width));
752 template<typename _Context>
754 _M_get_precision(_Context& __ctx) const
757 if (_M_prec_kind == _WP_value)
759 else if (_M_prec_kind == _WP_from_arg)
760 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
765 template<typename _Int>
767 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
771 else if (__sign == _Sign_plus)
773 else if (__sign == _Sign_space)
780 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
781 template<typename _Out, typename _CharT>
782 requires output_iterator<_Out, const _CharT&>
784 __write(_Out __out, basic_string_view<_CharT> __str)
786 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
792 for (_CharT __c : __str)
797 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
798 // pre: __align != _Align_default
799 template<typename _Out, typename _CharT>
801 __write_padded(_Out __out, basic_string_view<_CharT> __str,
802 _Align __align, size_t __nfill, char32_t __fill_char)
804 const size_t __buflen = 0x20;
805 _CharT __padding_chars[__buflen];
806 __padding_chars[0] = _CharT();
807 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
809 auto __pad = [&__padding] (size_t __n, _Out& __o) {
812 while (__n > __padding.size())
814 __o = __format::__write(std::move(__o), __padding);
815 __n -= __padding.size();
818 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
821 size_t __l, __r, __max;
822 if (__align == _Align_centre)
825 __r = __l + (__nfill & 1);
828 else if (__align == _Align_right)
841 using namespace __unicode;
842 if constexpr (__literal_encoding_is_unicode<_CharT>())
843 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
845 // Encode fill char as multiple code units of type _CharT.
846 const char32_t __arr[1]{ __fill_char };
847 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
848 basic_string<_CharT> __padstr(__v.begin(), __v.end());
849 __padding = __padstr;
851 __out = __format::__write(std::move(__out), __padding);
852 __out = __format::__write(std::move(__out), __str);
854 __out = __format::__write(std::move(__out), __padding);
858 if (__max < __buflen)
859 __padding.remove_suffix(__buflen - __max);
863 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
865 __out = __format::__write(std::move(__out), __str);
871 // Write STR to OUT, with alignment and padding as determined by SPEC.
872 // pre: __spec._M_align != _Align_default || __align != _Align_default
873 template<typename _CharT, typename _Out>
875 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
876 size_t __estimated_width,
877 basic_format_context<_Out, _CharT>& __fc,
878 const _Spec<_CharT>& __spec,
879 _Align __align = _Align_left)
881 size_t __width = __spec._M_get_width(__fc);
883 if (__width <= __estimated_width)
884 return __format::__write(__fc.out(), __str);
886 const size_t __nfill = __width - __estimated_width;
888 if (__spec._M_align != _Align_default)
889 __align = __spec._M_align;
891 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
895 template<typename _CharT>
897 __truncate(basic_string_view<_CharT>& __s, size_t __prec)
899 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
901 if (__prec != (size_t)-1)
902 return __unicode::__truncate(__s, __prec);
904 return __unicode::__field_width(__s);
908 __s = __s.substr(0, __prec);
913 enum class _Term_char : unsigned char {
918 using enum _Term_char;
920 template<typename _CharT>
923 using _Str_view = basic_string_view<_CharT>;
927 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
931 { return _S_all().substr(0, 3); }
934 _Str_view _S_newline()
935 { return _S_all().substr(3, 3); }
938 _Str_view _S_return()
939 { return _S_all().substr(6, 3); }
942 _Str_view _S_bslash()
943 { return _S_all().substr(9, 3); }
947 { return _S_all().substr(12, 3); }
951 { return _S_all().substr(15, 3); }
955 { return _S_all().substr(18, 2); }
959 { return _S_all().substr(20, 2); }
962 _Str_view _S_term(_Term_char __term)
969 return _S_quote().substr(0, 1);
971 return _S_apos().substr(0, 1);
973 __builtin_unreachable();
977 template<typename _CharT>
980 using _Str_view = basic_string_view<_CharT>;
984 { return _GLIBCXX_WIDEN("[]{}(), : "); }
987 _Str_view _S_squares()
988 { return _S_all().substr(0, 2); }
991 _Str_view _S_braces()
992 { return _S_all().substr(2, 2); }
995 _Str_view _S_parens()
996 { return _S_all().substr(4, 2); }
1000 { return _S_all().substr(6, 2); }
1003 _Str_view _S_colon()
1004 { return _S_all().substr(8, 2); }
1007 template<typename _CharT>
1008 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1010 using _Esc = _Escapes<_CharT>;
1013 case _Esc::_S_tab()[0]:
1014 case _Esc::_S_newline()[0]:
1015 case _Esc::_S_return()[0]:
1016 case _Esc::_S_bslash()[0]:
1018 case _Esc::_S_quote()[0]:
1019 return __term == _Term_quote;
1020 case _Esc::_S_apos()[0]:
1021 return __term == _Term_apos;
1023 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1027 // @pre __c <= 0x10FFFF
1028 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1030 if (__unicode::__should_escape_category(__c))
1034 return __unicode::__grapheme_cluster_break_property(__c)
1035 == __unicode::_Gcb_property::_Gcb_Extend;
1038 using uint_least32_t = __UINT_LEAST32_TYPE__;
1039 template<typename _Out, typename _CharT>
1041 __write_escape_seq(_Out __out, uint_least32_t __val,
1042 basic_string_view<_CharT> __prefix)
1044 using _Str_view = basic_string_view<_CharT>;
1045 constexpr size_t __max = 8;
1047 const string_view __narrow(
1049 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1051 __out = __format::__write(__out, __prefix);
1052 *__out = _Separators<_CharT>::_S_braces()[0];
1054 if constexpr (is_same_v<char, _CharT>)
1055 __out = __format::__write(__out, __narrow);
1056#ifdef _GLIBCXX_USE_WCHAR_T
1059 _CharT __wbuf[__max];
1060 const size_t __n = __narrow.size();
1061 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1062 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1065 *__out = _Separators<_CharT>::_S_braces()[1];
1069 template<typename _Out, typename _CharT>
1071 __write_escaped_char(_Out __out, _CharT __c)
1073 using _UChar = make_unsigned_t<_CharT>;
1074 using _Esc = _Escapes<_CharT>;
1077 case _Esc::_S_tab()[0]:
1078 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1079 case _Esc::_S_newline()[0]:
1080 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1081 case _Esc::_S_return()[0]:
1082 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1083 case _Esc::_S_bslash()[0]:
1084 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1085 case _Esc::_S_quote()[0]:
1086 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1087 case _Esc::_S_apos()[0]:
1088 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1090 return __format::__write_escape_seq(
1091 __out, static_cast<_UChar>(__c), _Esc::_S_u());
1095 template<typename _CharT, typename _Out>
1097 __write_escaped_ascii(_Out __out,
1098 basic_string_view<_CharT> __str,
1101 using _Str_view = basic_string_view<_CharT>;
1102 auto __first = __str.begin();
1103 auto const __last = __str.end();
1104 while (__first != __last)
1106 auto __print = __first;
1107 // assume anything outside ASCII is printable
1108 while (__print != __last
1109 && !__format::__should_escape_ascii(*__print, __term))
1112 if (__print != __first)
1113 __out = __format::__write(__out, _Str_view(__first, __print));
1115 if (__print == __last)
1119 __out = __format::__write_escaped_char(__out, *__first);
1125 template<typename _CharT, typename _Out>
1127 __write_escaped_unicode(_Out __out,
1128 basic_string_view<_CharT> __str,
1131 using _Str_view = basic_string_view<_CharT>;
1132 using _UChar = make_unsigned_t<_CharT>;
1133 using _Esc = _Escapes<_CharT>;
1135 static constexpr char32_t __replace = U'\uFFFD';
1136 static constexpr _Str_view __replace_rep = []
1138 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1139 if constexpr (is_same_v<char, _CharT>)
1140 return "\xEF\xBF\xBD";
1145 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1146 auto __first = __v.begin();
1147 auto const __last = __v.end();
1149 bool __prev_esc = true;
1150 while (__first != __last)
1152 bool __esc_ascii = false;
1153 bool __esc_unicode = false;
1154 bool __esc_replace = false;
1155 auto __should_escape = [&](auto const& __it)
1159 = __format::__should_escape_ascii(*__it.base(), __term);
1160 if (__format::__should_escape_unicode(*__it, __prev_esc))
1161 return __esc_unicode = true;
1162 if (*__it == __replace)
1164 _Str_view __units(__it.base(), __it._M_units());
1165 return __esc_replace = (__units != __replace_rep);
1170 auto __print = __first;
1171 while (__print != __last && !__should_escape(__print))
1177 if (__print != __first)
1178 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1180 if (__print == __last)
1185 __out = __format::__write_escaped_char(__out, *__first.base());
1186 else if (__esc_unicode)
1187 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1188 else // __esc_replace
1189 for (_CharT __c : _Str_view(__first.base(), __first._M_units()))
1190 __out = __format::__write_escape_seq(__out,
1191 static_cast<_UChar>(__c),
1200 template<typename _CharT, typename _Out>
1202 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1204 __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1206 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1207 __out = __format::__write_escaped_unicode(__out, __str, __term);
1208 else if constexpr (is_same_v<char, _CharT>
1209 && __unicode::__literal_encoding_is_extended_ascii())
1210 __out = __format::__write_escaped_ascii(__out, __str, __term);
1212 // TODO Handle non-ascii extended encoding
1213 __out = __format::__write_escaped_ascii(__out, __str, __term);
1215 return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1218 // A lightweight optional<locale>.
1219 struct _Optional_locale
1221 [[__gnu__::__always_inline__]]
1222 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1224 _Optional_locale(const locale& __loc) noexcept
1225 : _M_loc(__loc), _M_hasval(true)
1228 _Optional_locale(const _Optional_locale& __l) noexcept
1229 : _M_dummy(), _M_hasval(__l._M_hasval)
1232 std::construct_at(&_M_loc, __l._M_loc);
1236 operator=(const _Optional_locale& __l) noexcept
1241 _M_loc = __l._M_loc;
1248 else if (__l._M_hasval)
1250 std::construct_at(&_M_loc, __l._M_loc);
1256 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1259 operator=(locale&& __loc) noexcept
1262 _M_loc = std::move(__loc);
1265 std::construct_at(&_M_loc, std::move(__loc));
1276 std::construct_at(&_M_loc);
1282 bool has_value() const noexcept { return _M_hasval; }
1285 char _M_dummy = '\0';
1288 bool _M_hasval = false;
1291 template<__char _CharT>
1292 struct __formatter_str
1294 __formatter_str() = default;
1297 __formatter_str(_Spec<_CharT> __spec) noexcept
1301 constexpr typename basic_format_parse_context<_CharT>::iterator
1302 parse(basic_format_parse_context<_CharT>& __pc)
1304 auto __first = __pc.begin();
1305 const auto __last = __pc.end();
1306 _Spec<_CharT> __spec{};
1308 auto __finalize = [this, &__spec] {
1312 auto __finished = [&] {
1313 if (__first == __last || *__first == '}')
1324 __first = __spec._M_parse_fill_and_align(__first, __last);
1328 __first = __spec._M_parse_width(__first, __last, __pc);
1332 __first = __spec._M_parse_precision(__first, __last, __pc);
1336 if (*__first == 's')
1338 __spec._M_type = _Pres_s;
1341#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1342 else if (*__first == '?')
1344 __spec._M_debug = true;
1352 __format::__failed_to_parse_format_spec();
1355 template<typename _Out>
1357 format(basic_string_view<_CharT> __s,
1358 basic_format_context<_Out, _CharT>& __fc) const
1360 if (_M_spec._M_debug)
1361 return _M_format_escaped(__s, __fc);
1363 if (_M_spec._M_width_kind == _WP_none
1364 && _M_spec._M_prec_kind == _WP_none)
1365 return __format::__write(__fc.out(), __s);
1367 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1368 const size_t __width = __format::__truncate(__s, __maxwidth);
1369 return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1372 template<typename _Out>
1374 _M_format_escaped(basic_string_view<_CharT> __s,
1375 basic_format_context<_Out, _CharT>& __fc) const
1377 const size_t __padwidth = _M_spec._M_get_width(__fc);
1378 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1379 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1381 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1382 const size_t __width = __truncate(__s, __maxwidth);
1383 // N.B. Escaping only increases width
1384 if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1385 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1387 // N.B. [tab:format.type.string] defines '?' as
1388 // Copies the escaped string ([format.string.escaped]) to the output,
1389 // so precision seem to appy to escaped string.
1390 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1391 __format::__write_escaped(__sink.out(), __s, _Term_quote);
1392 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1395#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1396 template<ranges::input_range _Rg, typename _Out>
1397 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1399 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1401 using _Range = remove_reference_t<_Rg>;
1402 using _String = basic_string<_CharT>;
1403 using _String_view = basic_string_view<_CharT>;
1404 if constexpr (!is_lvalue_reference_v<_Rg>)
1405 return _M_format_range<_Range&>(__rg, __fc);
1406 else if constexpr (!is_const_v<_Range>
1407 && __simply_formattable_range<_Range, _CharT>)
1408 return _M_format_range<const _Range&>(__rg, __fc);
1409 else if constexpr (ranges::contiguous_range<_Rg>)
1411 _String_view __str(ranges::data(__rg),
1412 size_t(ranges::distance(__rg)));
1413 return format(__str, __fc);
1415 else if (!_M_spec._M_debug)
1417 const size_t __padwidth = _M_spec._M_get_width(__fc);
1418 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1419 return ranges::copy(__rg, __fc.out()).out;
1421 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth,
1422 _M_spec._M_get_precision(__fc));
1423 ranges::copy(__rg, __sink.out());
1424 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1426 else if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
1428 const size_t __n(ranges::distance(__rg));
1430 if constexpr (!__unicode::__literal_encoding_is_unicode<_CharT>())
1431 if (size_t __max = _M_spec._M_get_precision(__fc); __n > __max)
1434 if (__w <= __format::__stackbuf_size<_CharT>)
1436 _CharT __buf[__format::__stackbuf_size<_CharT>];
1437 ranges::copy_n(ranges::begin(__rg), __w, __buf);
1438 return _M_format_escaped(_String_view(__buf, __n), __fc);
1440 else if constexpr (ranges::random_access_range<_Rg>)
1442 ranges::iterator_t<_Rg> __first = ranges::begin(__rg);
1443 ranges::subrange __sub(__first, ranges::next(__first, __w));
1444 return _M_format_escaped(_String(from_range, __sub), __fc);
1446 else if (__w <= __n)
1448 ranges::subrange __sub(
1449 counted_iterator(ranges::begin(__rg), __w),
1451 return _M_format_escaped(_String(from_range, __sub), __fc);
1453 else if constexpr (ranges::sized_range<_Rg>)
1454 return _M_format_escaped(_String(from_range, __rg), __fc);
1457 // N.B. preserve the computed size
1458 ranges::subrange __sub(__rg, __n);
1459 return _M_format_escaped(_String(from_range, __sub), __fc);
1463 return _M_format_escaped(_String(from_range, __rg), __fc);
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 enum class _Arg_t : unsigned char {
4001 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
4002 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
4003 _Arg_i128, _Arg_u128, _Arg_float128,
4004 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
4007#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4008 _Arg_ibm128 = _Arg_ldbl,
4009 _Arg_ieee128 = _Arg_float128,
4014 template<typename _Context>
4017 using _CharT = typename _Context::char_type;
4033 unsigned long long _M_ull;
4036#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
4037 long double _M_ldbl;
4040 __ieee128 _M_ieee128;
4042#ifdef __SIZEOF_FLOAT128__
4043 __float128 _M_float128;
4045 const _CharT* _M_str;
4046 basic_string_view<_CharT> _M_sv;
4048 _HandleBase _M_handle;
4049#ifdef __SIZEOF_INT128__
4051 unsigned __int128 _M_u128;
4053#ifdef __BFLT16_DIG__
4067 [[__gnu__::__always_inline__]]
4068 _Arg_value() : _M_none() { }
4071 template<typename _Tp>
4072 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
4073 { _S_get<_Tp>() = __val; }
4076 template<typename _Tp, typename _Self>
4077 [[__gnu__::__always_inline__]]
4079 _S_get(_Self& __u) noexcept
4081 if constexpr (is_same_v<_Tp, bool>)
4083 else if constexpr (is_same_v<_Tp, _CharT>)
4085 else if constexpr (is_same_v<_Tp, int>)
4087 else if constexpr (is_same_v<_Tp, unsigned>)
4089 else if constexpr (is_same_v<_Tp, long long>)
4091 else if constexpr (is_same_v<_Tp, unsigned long long>)
4093 else if constexpr (is_same_v<_Tp, float>)
4095 else if constexpr (is_same_v<_Tp, double>)
4097#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4098 else if constexpr (is_same_v<_Tp, long double>)
4101 else if constexpr (is_same_v<_Tp, __ibm128>)
4102 return __u._M_ibm128;
4103 else if constexpr (is_same_v<_Tp, __ieee128>)
4104 return __u._M_ieee128;
4106#ifdef __SIZEOF_FLOAT128__
4107 else if constexpr (is_same_v<_Tp, __float128>)
4108 return __u._M_float128;
4110 else if constexpr (is_same_v<_Tp, const _CharT*>)
4112 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4114 else if constexpr (is_same_v<_Tp, const void*>)
4116#ifdef __SIZEOF_INT128__
4117 else if constexpr (is_same_v<_Tp, __int128>)
4119 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4122#ifdef __BFLT16_DIG__
4123 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4127 else if constexpr (is_same_v<_Tp, _Float16>)
4131 else if constexpr (is_same_v<_Tp, _Float32>)
4135 else if constexpr (is_same_v<_Tp, _Float64>)
4138 else if constexpr (derived_from<_Tp, _HandleBase>)
4139 return static_cast<_Tp&>(__u._M_handle);
4140 // Otherwise, ill-formed.
4143 template<typename _Tp>
4144 [[__gnu__::__always_inline__]]
4147 { return _S_get<_Tp>(*this); }
4149 template<typename _Tp>
4150 [[__gnu__::__always_inline__]]
4152 _M_get() const noexcept
4153 { return _S_get<_Tp>(*this); }
4155 template<typename _Tp>
4156 [[__gnu__::__always_inline__]]
4158 _M_set(_Tp __v) noexcept
4160 if constexpr (derived_from<_Tp, _HandleBase>)
4161 std::construct_at(&_M_handle, __v);
4163 _S_get<_Tp>(*this) = __v;
4167 // [format.arg.store], class template format-arg-store
4168 template<typename _Context, typename... _Args>
4171 template<typename _Visitor, typename _Ctx>
4172 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4174 template<typename _Ch, typename _Tp>
4176 __to_arg_t_enum() noexcept;
4177} // namespace __format
4180 template<typename _Context>
4181 class basic_format_arg
4183 using _CharT = typename _Context::char_type;
4185 template<typename _Tp>
4186 static constexpr bool __formattable
4187 = __format::__formattable_with<_Tp, _Context>;
4190 class handle : public __format::_Arg_value<_Context>::_HandleBase
4192 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
4194 // Format as const if possible, to reduce instantiations.
4195 template<typename _Tp>
4196 using __maybe_const_t
4197 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
4199 template<typename _Tq>
4201 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4202 _Context& __format_ctx, const void* __ptr)
4204 using _Td = remove_const_t<_Tq>;
4205 typename _Context::template formatter_type<_Td> __f;
4206 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4207 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4208 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4211 template<typename _Tp>
4213 handle(_Tp& __val) noexcept
4215 this->_M_ptr = __builtin_addressof(__val);
4216 auto __func = _S_format<__maybe_const_t<_Tp>>;
4217 this->_M_func = reinterpret_cast<void(*)()>(__func);
4220 friend class basic_format_arg<_Context>;
4223 handle(const handle&) = default;
4224 handle& operator=(const handle&) = default;
4226 [[__gnu__::__always_inline__]]
4228 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4230 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4231 _Context&, const void*);
4232 auto __f = reinterpret_cast<_Func>(this->_M_func);
4233 __f(__pc, __fc, this->_M_ptr);
4237 [[__gnu__::__always_inline__]]
4238 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4240 [[nodiscard,__gnu__::__always_inline__]]
4241 explicit operator bool() const noexcept
4242 { return _M_type != __format::_Arg_none; }
4244#if __cpp_lib_format >= 202306L // >= C++26
4245 template<typename _Visitor>
4247 visit(this basic_format_arg __arg, _Visitor&& __vis)
4248 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4250 template<typename _Res, typename _Visitor>
4252 visit(this basic_format_arg __arg, _Visitor&& __vis)
4253 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4257 template<typename _Ctx>
4258 friend class basic_format_args;
4260 template<typename _Ctx, typename... _Args>
4261 friend class __format::_Arg_store;
4263 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4265 __format::_Arg_value<_Context> _M_val;
4266 __format::_Arg_t _M_type;
4268 // Transform incoming argument type to the type stored in _Arg_value.
4269 // e.g. short -> int, std::string -> std::string_view,
4270 // char[3] -> const char*.
4271 template<typename _Tp>
4272 static consteval auto
4275 using _Td = remove_const_t<_Tp>;
4276 if constexpr (is_same_v<_Td, bool>)
4277 return type_identity<bool>();
4278 else if constexpr (is_same_v<_Td, _CharT>)
4279 return type_identity<_CharT>();
4280 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4281 return type_identity<_CharT>();
4282#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4283 else if constexpr (is_same_v<_Td, __int128>)
4284 return type_identity<__int128>();
4285 else if constexpr (is_same_v<_Td, unsigned __int128>)
4286 return type_identity<unsigned __int128>();
4288 else if constexpr (__is_signed_integer<_Td>::value)
4290 if constexpr (sizeof(_Td) <= sizeof(int))
4291 return type_identity<int>();
4292 else if constexpr (sizeof(_Td) <= sizeof(long long))
4293 return type_identity<long long>();
4295 else if constexpr (__is_unsigned_integer<_Td>::value)
4297 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4298 return type_identity<unsigned>();
4299 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4300 return type_identity<unsigned long long>();
4302 else if constexpr (is_same_v<_Td, float>)
4303 return type_identity<float>();
4304 else if constexpr (is_same_v<_Td, double>)
4305 return type_identity<double>();
4306#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4307 else if constexpr (is_same_v<_Td, long double>)
4308 return type_identity<long double>();
4310 else if constexpr (is_same_v<_Td, __ibm128>)
4311 return type_identity<__ibm128>();
4312 else if constexpr (is_same_v<_Td, __ieee128>)
4313 return type_identity<__ieee128>();
4315#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4316 else if constexpr (is_same_v<_Td, __float128>)
4317 return type_identity<__float128>();
4319#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4320 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4321 return type_identity<__format::__bflt16_t>();
4323#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4324 else if constexpr (is_same_v<_Td, _Float16>)
4325 return type_identity<_Float16>();
4327#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4328 else if constexpr (is_same_v<_Td, _Float32>)
4329 return type_identity<_Float32>();
4331#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4332 else if constexpr (is_same_v<_Td, _Float64>)
4333 return type_identity<_Float64>();
4335 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4336 || __is_specialization_of<_Td, basic_string>)
4338 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4339 return type_identity<basic_string_view<_CharT>>();
4341 return type_identity<handle>();
4343 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4344 return type_identity<const _CharT*>();
4345 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4346 return type_identity<const _CharT*>();
4347 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4348 return type_identity<const void*>();
4349 else if constexpr (is_same_v<_Td, nullptr_t>)
4350 return type_identity<const void*>();
4352 return type_identity<handle>();
4355 // Transform a formattable type to the appropriate storage type.
4356 template<typename _Tp>
4357 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4359 // Get the _Arg_t value corresponding to a normalized type.
4360 template<typename _Tp>
4361 static consteval __format::_Arg_t
4364 using namespace __format;
4365 if constexpr (is_same_v<_Tp, bool>)
4367 else if constexpr (is_same_v<_Tp, _CharT>)
4369 else if constexpr (is_same_v<_Tp, int>)
4371 else if constexpr (is_same_v<_Tp, unsigned>)
4373 else if constexpr (is_same_v<_Tp, long long>)
4375 else if constexpr (is_same_v<_Tp, unsigned long long>)
4377 else if constexpr (is_same_v<_Tp, float>)
4379 else if constexpr (is_same_v<_Tp, double>)
4381#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4382 else if constexpr (is_same_v<_Tp, long double>)
4385 // Don't use _Arg_ldbl for this target, it's ambiguous.
4386 else if constexpr (is_same_v<_Tp, __ibm128>)
4388 else if constexpr (is_same_v<_Tp, __ieee128>)
4389 return _Arg_ieee128;
4391#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4392 else if constexpr (is_same_v<_Tp, __float128>)
4393 return _Arg_float128;
4395#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4396 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4399#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4400 else if constexpr (is_same_v<_Tp, _Float16>)
4403#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4404 else if constexpr (is_same_v<_Tp, _Float32>)
4407#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4408 else if constexpr (is_same_v<_Tp, _Float64>)
4411 else if constexpr (is_same_v<_Tp, const _CharT*>)
4413 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4415 else if constexpr (is_same_v<_Tp, const void*>)
4417#ifdef __SIZEOF_INT128__
4418 else if constexpr (is_same_v<_Tp, __int128>)
4420 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4423 else if constexpr (is_same_v<_Tp, handle>)
4427 template<typename _Tp>
4429 _M_set(_Tp __v) noexcept
4431 _M_type = _S_to_enum<_Tp>();
4435 template<typename _Tp>
4436 requires __format::__formattable_with<_Tp, _Context>
4438 basic_format_arg(_Tp& __v) noexcept
4440 using _Td = _Normalize<_Tp>;
4441 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4442 _M_set(_Td{__v.data(), __v.size()});
4443 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4444 && is_same_v<_CharT, wchar_t>)
4445 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4447 _M_set(static_cast<_Td>(__v));
4450 template<typename _Ctx, typename... _Argz>
4452 make_format_args(_Argz&...) noexcept;
4454 template<typename _Visitor, typename _Ctx>
4455 friend decltype(auto)
4456 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4458 template<typename _Visitor, typename _Ctx>
4459 friend decltype(auto)
4460 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4462 template<typename _Ch, typename _Tp>
4463 friend consteval __format::_Arg_t
4464 __format::__to_arg_t_enum() noexcept;
4466 template<typename _Visitor>
4468 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4470 using namespace __format;
4474 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4476 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4478 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4480 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4482 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4484 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4486 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4487#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4489 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4491 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4492#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4494 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4495#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4497 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4501 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4503 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4505#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4507 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4509#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4511 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4513#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4515 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4517#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4519 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4521#endif // __glibcxx_to_chars
4523 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4525 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4527 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4530 auto& __h = static_cast<handle&>(_M_val._M_handle);
4531 return std::forward<_Visitor>(__vis)(__h);
4533#ifdef __SIZEOF_INT128__
4535 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4537 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4540 __builtin_unreachable();
4544 template<typename _Visitor>
4546 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4548 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4550 constexpr bool __user_facing = __is_one_of<_Tp,
4551 monostate, bool, _CharT,
4552 int, unsigned int, long long int, unsigned long long int,
4553 float, double, long double,
4554 const _CharT*, basic_string_view<_CharT>,
4555 const void*, handle>::value;
4556 if constexpr (__user_facing)
4557 return std::forward<_Visitor>(__vis)(__val);
4561 return std::forward<_Visitor>(__vis)(__h);
4567 template<typename _Visitor, typename _Context>
4568 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4569 inline decltype(auto)
4570 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4572 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4575/// @cond undocumented
4578 template<typename _Visitor, typename _Ctx>
4579 inline decltype(auto)
4580 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4582 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4585 struct _WidthPrecVisitor
4587 template<typename _Tp>
4589 operator()(_Tp& __arg) const
4591 if constexpr (is_same_v<_Tp, monostate>)
4592 __format::__invalid_arg_id_in_format_string();
4593 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4594 // 3720. Restrict the valid types of arg-id for width and precision
4595 // 3721. Allow an arg-id with a value of zero for width
4596 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4598 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4599 // 3720. Restrict the valid types of arg-id for width and precision
4600 if constexpr (__is_unsigned_integer<_Tp>::value)
4602 else if constexpr (__is_signed_integer<_Tp>::value)
4606 __throw_format_error("format error: argument used for width or "
4607 "precision must be a non-negative integer");
4611#pragma GCC diagnostic push
4612#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4613 template<typename _Context>
4615 __int_from_arg(const basic_format_arg<_Context>& __arg)
4616 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4618 // Pack _Arg_t enum values into a single 60-bit integer.
4619 template<int _Bits, size_t _Nm>
4621 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4623 __UINT64_TYPE__ __packed_types = 0;
4624 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4625 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4626 return __packed_types;
4628} // namespace __format
4631 template<typename _Context>
4632 class basic_format_args
4634 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4635 static constexpr int _S_packed_type_mask = 0b11111;
4636 static constexpr int _S_max_packed_args = 12;
4638 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4640 template<typename... _Args>
4641 using _Store = __format::_Arg_store<_Context, _Args...>;
4643 template<typename _Ctx, typename... _Args>
4644 friend class __format::_Arg_store;
4646 using uint64_t = __UINT64_TYPE__;
4647 using _Format_arg = basic_format_arg<_Context>;
4648 using _Format_arg_val = __format::_Arg_value<_Context>;
4650 // If args are packed then the number of args is in _M_packed_size and
4651 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4652 // If args are not packed then the number of args is in _M_unpacked_size
4653 // and _M_packed_size is zero.
4654 uint64_t _M_packed_size : 4;
4655 uint64_t _M_unpacked_size : 60;
4658 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4659 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4663 _M_size() const noexcept
4664 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4666 typename __format::_Arg_t
4667 _M_type(size_t __i) const noexcept
4669 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4670 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4673 template<typename _Ctx, typename... _Args>
4675 make_format_args(_Args&...) noexcept;
4677 // An array of _Arg_t enums corresponding to _Args...
4678 template<typename... _Args>
4679 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4681 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4684 template<typename... _Args>
4685 basic_format_args(const _Store<_Args...>& __store) noexcept;
4687 [[nodiscard,__gnu__::__always_inline__]]
4688 basic_format_arg<_Context>
4689 get(size_t __i) const noexcept
4691 basic_format_arg<_Context> __arg;
4692 if (__i < _M_packed_size)
4694 __arg._M_type = _M_type(__i);
4695 __arg._M_val = _M_values[__i];
4697 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4698 __arg = _M_args[__i];
4703 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4704 // 3810. CTAD for std::basic_format_args
4705 template<typename _Context, typename... _Args>
4706 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4707 -> basic_format_args<_Context>;
4709 template<typename _Context, typename... _Args>
4711 make_format_args(_Args&... __fmt_args) noexcept;
4713 // An array of type-erased formatting arguments.
4714 template<typename _Context, typename... _Args>
4715 class __format::_Arg_store
4717 friend std::basic_format_args<_Context>;
4719 template<typename _Ctx, typename... _Argz>
4721#if _GLIBCXX_INLINE_VERSION
4722 __8:: // Needed for PR c++/59256
4724 make_format_args(_Argz&...) noexcept;
4726 // For a sufficiently small number of arguments we only store values.
4727 // basic_format_args can get the types from the _Args pack.
4728 static constexpr bool _S_values_only
4729 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4732 = __conditional_t<_S_values_only,
4733 __format::_Arg_value<_Context>,
4734 basic_format_arg<_Context>>;
4736 _Element_t _M_args[sizeof...(_Args)];
4738 template<typename _Tp>
4740 _S_make_elt(_Tp& __v)
4742 using _Tq = remove_const_t<_Tp>;
4743 using _CharT = typename _Context::char_type;
4744 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4745 "std::formatter must be specialized for the type "
4746 "of each format arg");
4747 using __format::__formattable_with;
4748 if constexpr (is_const_v<_Tp>)
4749 if constexpr (!__formattable_with<_Tp, _Context>)
4750 if constexpr (__formattable_with<_Tq, _Context>)
4751 static_assert(__formattable_with<_Tp, _Context>,
4752 "format arg must be non-const because its "
4753 "std::formatter specialization has a "
4754 "non-const reference parameter");
4755 basic_format_arg<_Context> __arg(__v);
4756 if constexpr (_S_values_only)
4757 return __arg._M_val;
4762 template<typename... _Tp>
4763 requires (sizeof...(_Tp) == sizeof...(_Args))
4764 [[__gnu__::__always_inline__]]
4765 _Arg_store(_Tp&... __a) noexcept
4766 : _M_args{_S_make_elt(__a)...}
4770 template<typename _Context>
4771 class __format::_Arg_store<_Context>
4774 template<typename _Context>
4775 template<typename... _Args>
4777 basic_format_args<_Context>::
4778 basic_format_args(const _Store<_Args...>& __store) noexcept
4780 if constexpr (sizeof...(_Args) == 0)
4783 _M_unpacked_size = 0;
4786 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4788 // The number of packed arguments:
4789 _M_packed_size = sizeof...(_Args);
4790 // The packed type enums:
4792 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4793 // The _Arg_value objects.
4794 _M_values = __store._M_args;
4798 // No packed arguments:
4800 // The number of unpacked arguments:
4801 _M_unpacked_size = sizeof...(_Args);
4802 // The basic_format_arg objects:
4803 _M_args = __store._M_args;
4807 /// Capture formatting arguments for use by `std::vformat`.
4808 template<typename _Context = format_context, typename... _Args>
4809 [[nodiscard,__gnu__::__always_inline__]]
4811 make_format_args(_Args&... __fmt_args) noexcept
4813 using _Fmt_arg = basic_format_arg<_Context>;
4814 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4815 _Normalize<_Args>...>;
4816 return _Store(__fmt_args...);
4819#ifdef _GLIBCXX_USE_WCHAR_T
4820 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4821 template<typename... _Args>
4822 [[nodiscard,__gnu__::__always_inline__]]
4824 make_wformat_args(_Args&... __args) noexcept
4825 { return std::make_format_args<wformat_context>(__args...); }
4828/// @cond undocumented
4831 template<typename _Out, typename _CharT, typename _Context>
4833 __do_vformat_to(_Out, basic_string_view<_CharT>,
4834 const basic_format_args<_Context>&,
4835 const locale* = nullptr);
4837 template<typename _CharT> struct __formatter_chrono;
4839} // namespace __format
4842 /** Context for std::format and similar functions.
4844 * A formatting context contains an output iterator and locale to use
4845 * for the formatting operations. Most programs will never need to use
4846 * this class template explicitly. For typical uses of `std::format` the
4847 * library will use the specializations `std::format_context` (for `char`)
4848 * and `std::wformat_context` (for `wchar_t`).
4850 * You are not allowed to define partial or explicit specializations of
4851 * this class template.
4855 template<typename _Out, typename _CharT>
4856 class basic_format_context
4858 static_assert( output_iterator<_Out, const _CharT&> );
4860 basic_format_args<basic_format_context> _M_args;
4862 __format::_Optional_locale _M_loc;
4864 basic_format_context(basic_format_args<basic_format_context> __args,
4866 : _M_args(__args), _M_out(std::move(__out))
4869 basic_format_context(basic_format_args<basic_format_context> __args,
4870 _Out __out, const std::locale& __loc)
4871 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4874 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4875 // 4061. Should std::basic_format_context be
4876 // default-constructible/copyable/movable?
4877 basic_format_context(const basic_format_context&) = delete;
4878 basic_format_context& operator=(const basic_format_context&) = delete;
4880 template<typename _Out2, typename _CharT2, typename _Context2>
4882 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4883 const basic_format_args<_Context2>&,
4886 friend __format::__formatter_chrono<_CharT>;
4889 ~basic_format_context() = default;
4891 using iterator = _Out;
4892 using char_type = _CharT;
4893 template<typename _Tp>
4894 using formatter_type = formatter<_Tp, _CharT>;
4897 basic_format_arg<basic_format_context>
4898 arg(size_t __id) const noexcept
4899 { return _M_args.get(__id); }
4902 std::locale locale() { return _M_loc.value(); }
4905 iterator out() { return std::move(_M_out); }
4907 void advance_to(iterator __it) { _M_out = std::move(__it); }
4911/// @cond undocumented
4914 // Abstract base class defining an interface for scanning format strings.
4915 // Scan the characters in a format string, dividing it up into strings of
4916 // ordinary characters, escape sequences, and replacement fields.
4917 // Call virtual functions for derived classes to parse format-specifiers
4918 // or write formatted output.
4919 template<typename _CharT>
4922 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4924 struct _Parse_context : basic_format_parse_context<_CharT>
4926 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4927 const _Arg_t* _M_types = nullptr;
4931 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4932 : _M_pc(__str, __nargs)
4935 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4936 constexpr iterator end() const noexcept { return _M_pc.end(); }
4941 basic_string_view<_CharT> __fmt = _M_fmt_str();
4943 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4945 _M_pc.advance_to(begin() + 1);
4946 _M_format_arg(_M_pc.next_arg_id());
4950 size_t __lbr = __fmt.find('{');
4951 size_t __rbr = __fmt.find('}');
4953 while (__fmt.size())
4955 auto __cmp = __lbr <=> __rbr;
4959 _M_pc.advance_to(end());
4964 if (__lbr + 1 == __fmt.size()
4965 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4966 __format::__unmatched_left_brace_in_format_string();
4967 const bool __is_escape = __fmt[__lbr + 1] == '{';
4968 iterator __last = begin() + __lbr + int(__is_escape);
4969 _M_on_chars(__last);
4970 _M_pc.advance_to(__last + 1);
4971 __fmt = _M_fmt_str();
4974 if (__rbr != __fmt.npos)
4976 __lbr = __fmt.find('{');
4980 _M_on_replacement_field();
4981 __fmt = _M_fmt_str();
4982 __lbr = __fmt.find('{');
4983 __rbr = __fmt.find('}');
4988 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4989 __format::__unmatched_right_brace_in_format_string();
4990 iterator __last = begin() + __rbr;
4991 _M_on_chars(__last);
4992 _M_pc.advance_to(__last + 1);
4993 __fmt = _M_fmt_str();
4994 if (__lbr != __fmt.npos)
4996 __rbr = __fmt.find('}');
5001 constexpr basic_string_view<_CharT>
5002 _M_fmt_str() const noexcept
5003 { return {begin(), end()}; }
5005 constexpr virtual void _M_on_chars(iterator) { }
5007 constexpr void _M_on_replacement_field()
5009 auto __next = begin();
5013 __id = _M_pc.next_arg_id();
5014 else if (*__next == ':')
5016 __id = _M_pc.next_arg_id();
5017 _M_pc.advance_to(++__next);
5021 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
5022 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
5023 __format::__invalid_arg_id_in_format_string();
5024 _M_pc.check_arg_id(__id = __i);
5027 _M_pc.advance_to(++__ptr);
5030 _M_pc.advance_to(__ptr);
5032 _M_format_arg(__id);
5033 if (begin() == end() || *begin() != '}')
5034 __format::__unmatched_left_brace_in_format_string();
5035 _M_pc.advance_to(begin() + 1); // Move past '}'
5038 constexpr virtual void _M_format_arg(size_t __id) = 0;
5041 // Process a format string and format the arguments in the context.
5042 template<typename _Out, typename _CharT>
5043 class _Formatting_scanner : public _Scanner<_CharT>
5046 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
5047 basic_string_view<_CharT> __str)
5048 : _Scanner<_CharT>(__str), _M_fc(__fc)
5052 basic_format_context<_Out, _CharT>& _M_fc;
5054 using iterator = typename _Scanner<_CharT>::iterator;
5057 _M_on_chars(iterator __last) override
5059 basic_string_view<_CharT> __str(this->begin(), __last);
5060 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
5064 _M_format_arg(size_t __id) override
5066 using _Context = basic_format_context<_Out, _CharT>;
5067 using handle = typename basic_format_arg<_Context>::handle;
5069 __format::__visit_format_arg([this](auto& __arg) {
5070 using _Type = remove_reference_t<decltype(__arg)>;
5071 using _Formatter = typename _Context::template formatter_type<_Type>;
5072 if constexpr (is_same_v<_Type, monostate>)
5073 __format::__invalid_arg_id_in_format_string();
5074 else if constexpr (is_same_v<_Type, handle>)
5075 __arg.format(this->_M_pc, this->_M_fc);
5076 else if constexpr (is_default_constructible_v<_Formatter>)
5079 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5080 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5083 static_assert(__format::__formattable_with<_Type, _Context>);
5084 }, _M_fc.arg(__id));
5088 template<typename _CharT, typename _Tp>
5090 __to_arg_t_enum() noexcept
5092 using _Context = __format::__format_context<_CharT>;
5093 using _Fmt_arg = basic_format_arg<_Context>;
5094 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5095 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5098 // Validate a format string for Args.
5099 template<typename _CharT, typename... _Args>
5100 class _Checking_scanner : public _Scanner<_CharT>
5103 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5104 "std::formatter must be specialized for each type being formatted");
5108 _Checking_scanner(basic_string_view<_CharT> __str)
5109 : _Scanner<_CharT>(__str, sizeof...(_Args))
5111#if __cpp_lib_format >= 202305L
5112 this->_M_pc._M_types = _M_types.data();
5118 _M_format_arg(size_t __id) override
5120 if constexpr (sizeof...(_Args) != 0)
5122 if (__id < sizeof...(_Args))
5124 _M_parse_format_spec<_Args...>(__id);
5128 __builtin_unreachable();
5131 template<typename _Tp, typename... _OtherArgs>
5133 _M_parse_format_spec(size_t __id)
5137 formatter<_Tp, _CharT> __f;
5138 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5140 else if constexpr (sizeof...(_OtherArgs) != 0)
5141 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5143 __builtin_unreachable();
5146#if __cpp_lib_format >= 202305L
5147 array<_Arg_t, sizeof...(_Args)>
5148 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5152 template<typename _Out, typename _CharT, typename _Context>
5154 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5155 const basic_format_args<_Context>& __args,
5156 const locale* __loc)
5158 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5159 _Sink_iter<_CharT> __sink_out;
5161 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5162 __sink_out = __out; // Already a sink iterator, safe to use post-move.
5164 __sink_out = __sink.out();
5166 if constexpr (is_same_v<_CharT, char>)
5167 // Fast path for "{}" format strings and simple format arg types.
5168 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5170 bool __done = false;
5171 __format::__visit_format_arg([&](auto& __arg) {
5172 using _Tp = remove_cvref_t<decltype(__arg)>;
5173 if constexpr (is_same_v<_Tp, bool>)
5175 size_t __len = 4 + !__arg;
5176 const char* __chars[] = { "false", "true" };
5177 if (auto __res = __sink_out._M_reserve(__len))
5179 __builtin_memcpy(__res.get(), __chars[__arg], __len);
5180 __res._M_bump(__len);
5184 else if constexpr (is_same_v<_Tp, char>)
5186 if (auto __res = __sink_out._M_reserve(1))
5188 *__res.get() = __arg;
5193 else if constexpr (is_integral_v<_Tp>)
5195 make_unsigned_t<_Tp> __uval;
5196 const bool __neg = __arg < 0;
5198 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5201 const auto __n = __detail::__to_chars_len(__uval);
5202 if (auto __res = __sink_out._M_reserve(__n + __neg))
5204 auto __ptr = __res.get();
5206 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5208 __res._M_bump(__n + __neg);
5212 else if constexpr (is_convertible_v<_Tp, string_view>)
5214 string_view __sv = __arg;
5215 if (auto __res = __sink_out._M_reserve(__sv.size()))
5217 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5218 __res._M_bump(__sv.size());
5226 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5229 return std::move(__sink)._M_finish().out;
5233 auto __ctx = __loc == nullptr
5234 ? _Context(__args, __sink_out)
5235 : _Context(__args, __sink_out, *__loc);
5236 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5237 __scanner._M_scan();
5239 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5242 return std::move(__sink)._M_finish().out;
5244#pragma GCC diagnostic pop
5246} // namespace __format
5249#if __cpp_lib_format >= 202305L // >= C++26
5250 /// @cond undocumented
5251 // Common implementation of check_dynamic_spec{,_string,_integral}
5252 template<typename _CharT>
5253 template<typename... _Ts>
5255 basic_format_parse_context<_CharT>::
5256 __check_dynamic_spec(size_t __id) noexcept
5258 if (__id >= _M_num_args)
5259 __format::__invalid_arg_id_in_format_string();
5260 if constexpr (sizeof...(_Ts) != 0)
5262 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5263 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
5264 __format::_Arg_t __types[] = {
5265 __format::__to_arg_t_enum<_CharT, _Ts>()...
5267 for (auto __t : __types)
5271 __invalid_dynamic_spec("arg(id) type does not match");
5276 template<typename _CharT, typename... _Args>
5277 template<typename _Tp>
5278 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5280 basic_format_string<_CharT, _Args...>::
5281 basic_format_string(const _Tp& __s)
5284 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5286 __scanner._M_scan();
5289 // [format.functions], formatting functions
5291 template<typename _Out> requires output_iterator<_Out, const char&>
5292 [[__gnu__::__always_inline__]]
5294 vformat_to(_Out __out, string_view __fmt, format_args __args)
5295 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5297#ifdef _GLIBCXX_USE_WCHAR_T
5298 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5299 [[__gnu__::__always_inline__]]
5301 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5302 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5305 template<typename _Out> requires output_iterator<_Out, const char&>
5306 [[__gnu__::__always_inline__]]
5308 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5311 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5314#ifdef _GLIBCXX_USE_WCHAR_T
5315 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5316 [[__gnu__::__always_inline__]]
5318 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5319 wformat_args __args)
5321 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5327 vformat(string_view __fmt, format_args __args)
5329 __format::_Str_sink<char> __buf;
5330 std::vformat_to(__buf.out(), __fmt, __args);
5331 return std::move(__buf).get();
5334#ifdef _GLIBCXX_USE_WCHAR_T
5337 vformat(wstring_view __fmt, wformat_args __args)
5339 __format::_Str_sink<wchar_t> __buf;
5340 std::vformat_to(__buf.out(), __fmt, __args);
5341 return std::move(__buf).get();
5347 vformat(const locale& __loc, string_view __fmt, format_args __args)
5349 __format::_Str_sink<char> __buf;
5350 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5351 return std::move(__buf).get();
5354#ifdef _GLIBCXX_USE_WCHAR_T
5357 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5359 __format::_Str_sink<wchar_t> __buf;
5360 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5361 return std::move(__buf).get();
5365 template<typename... _Args>
5368 format(format_string<_Args...> __fmt, _Args&&... __args)
5369 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5371#ifdef _GLIBCXX_USE_WCHAR_T
5372 template<typename... _Args>
5375 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5376 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5379 template<typename... _Args>
5382 format(const locale& __loc, format_string<_Args...> __fmt,
5385 return std::vformat(__loc, __fmt.get(),
5386 std::make_format_args(__args...));
5389#ifdef _GLIBCXX_USE_WCHAR_T
5390 template<typename... _Args>
5393 format(const locale& __loc, wformat_string<_Args...> __fmt,
5396 return std::vformat(__loc, __fmt.get(),
5397 std::make_wformat_args(__args...));
5401 template<typename _Out, typename... _Args>
5402 requires output_iterator<_Out, const char&>
5404 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5406 return std::vformat_to(std::move(__out), __fmt.get(),
5407 std::make_format_args(__args...));
5410#ifdef _GLIBCXX_USE_WCHAR_T
5411 template<typename _Out, typename... _Args>
5412 requires output_iterator<_Out, const wchar_t&>
5414 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5416 return std::vformat_to(std::move(__out), __fmt.get(),
5417 std::make_wformat_args(__args...));
5421 template<typename _Out, typename... _Args>
5422 requires output_iterator<_Out, const char&>
5424 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5427 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5428 std::make_format_args(__args...));
5431#ifdef _GLIBCXX_USE_WCHAR_T
5432 template<typename _Out, typename... _Args>
5433 requires output_iterator<_Out, const wchar_t&>
5435 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5438 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5439 std::make_wformat_args(__args...));
5443 template<typename _Out, typename... _Args>
5444 requires output_iterator<_Out, const char&>
5445 inline format_to_n_result<_Out>
5446 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5447 format_string<_Args...> __fmt, _Args&&... __args)
5449 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5450 std::vformat_to(__sink.out(), __fmt.get(),
5451 std::make_format_args(__args...));
5452 return std::move(__sink)._M_finish();
5455#ifdef _GLIBCXX_USE_WCHAR_T
5456 template<typename _Out, typename... _Args>
5457 requires output_iterator<_Out, const wchar_t&>
5458 inline format_to_n_result<_Out>
5459 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5460 wformat_string<_Args...> __fmt, _Args&&... __args)
5462 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5463 std::vformat_to(__sink.out(), __fmt.get(),
5464 std::make_wformat_args(__args...));
5465 return std::move(__sink)._M_finish();
5469 template<typename _Out, typename... _Args>
5470 requires output_iterator<_Out, const char&>
5471 inline format_to_n_result<_Out>
5472 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5473 format_string<_Args...> __fmt, _Args&&... __args)
5475 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5476 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5477 std::make_format_args(__args...));
5478 return std::move(__sink)._M_finish();
5481#ifdef _GLIBCXX_USE_WCHAR_T
5482 template<typename _Out, typename... _Args>
5483 requires output_iterator<_Out, const wchar_t&>
5484 inline format_to_n_result<_Out>
5485 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5486 wformat_string<_Args...> __fmt, _Args&&... __args)
5488 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5489 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5490 std::make_wformat_args(__args...));
5491 return std::move(__sink)._M_finish();
5495/// @cond undocumented
5499 template<typename _CharT>
5500 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5503 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5505 [[__gnu__::__always_inline__]]
5508 { return this->_M_count + this->_M_used().size(); }
5511 template<typename _CharT>
5512 class _Counting_sink : public _Buf_sink<_CharT>
5514 size_t _M_count = 0;
5517 _M_overflow() override
5519 if (!std::is_constant_evaluated())
5520 _M_count += this->_M_used().size();
5525 _Counting_sink() = default;
5527 [[__gnu__::__always_inline__]]
5531 _Counting_sink::_M_overflow();
5536} // namespace __format
5539 template<typename... _Args>
5542 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5544 __format::_Counting_sink<char> __buf;
5545 std::vformat_to(__buf.out(), __fmt.get(),
5546 std::make_format_args(__args...));
5547 return __buf.count();
5550#ifdef _GLIBCXX_USE_WCHAR_T
5551 template<typename... _Args>
5554 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5556 __format::_Counting_sink<wchar_t> __buf;
5557 std::vformat_to(__buf.out(), __fmt.get(),
5558 std::make_wformat_args(__args...));
5559 return __buf.count();
5563 template<typename... _Args>
5566 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5569 __format::_Counting_sink<char> __buf;
5570 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5571 std::make_format_args(__args...));
5572 return __buf.count();
5575#ifdef _GLIBCXX_USE_WCHAR_T
5576 template<typename... _Args>
5579 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5582 __format::_Counting_sink<wchar_t> __buf;
5583 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5584 std::make_wformat_args(__args...));
5585 return __buf.count();
5589#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5590 /// @cond undocumented
5591 template<typename _Tp>
5592 consteval range_format
5595 using _Ref = ranges::range_reference_t<_Tp>;
5596 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5597 return range_format::disabled;
5598 else if constexpr (requires { typename _Tp::key_type; })
5600 if constexpr (requires { typename _Tp::mapped_type; })
5602 using _Up = remove_cvref_t<_Ref>;
5603 if constexpr (__is_pair<_Up>)
5604 return range_format::map;
5605 else if constexpr (__is_specialization_of<_Up, tuple>)
5606 if constexpr (tuple_size_v<_Up> == 2)
5607 return range_format::map;
5609 return range_format::set;
5612 return range_format::sequence;
5616 /// A constant determining how a range should be formatted.
5617 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5618 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5620/// @cond undocumented
5623 template<typename _CharT, typename _Out, typename _Callback>
5624 typename basic_format_context<_Out, _CharT>::iterator
5625 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5626 const _Spec<_CharT>& __spec,
5629 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5633 // This is required to implement formatting with padding,
5634 // as we need to format to temporary buffer, using the same iterator.
5635 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5637 const size_t __padwidth = __spec._M_get_width(__fc);
5638 if (__padwidth == 0)
5639 return __call(__fc);
5643 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5644 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5649 { _M_ctx = nullptr; }
5654 _M_ctx->advance_to(_M_out);
5658 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5659 _Sink_iter<_CharT> _M_out;
5662 _Restore_out __restore(__fc);
5663 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5664 __fc.advance_to(__sink.out());
5666 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5667 __restore._M_disarm();
5672 template<size_t _Pos, typename _Tp, typename _CharT>
5673 struct __indexed_formatter_storage
5678 basic_format_parse_context<_CharT> __pc({});
5679 if (_M_formatter.parse(__pc) != __pc.end())
5680 __format::__failed_to_parse_format_spec();
5683 template<typename _Out>
5685 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5686 basic_format_context<_Out, _CharT>& __fc,
5687 basic_string_view<_CharT> __sep) const
5689 if constexpr (_Pos != 0)
5690 __fc.advance_to(__format::__write(__fc.out(), __sep));
5691 __fc.advance_to(_M_formatter.format(__elem, __fc));
5694 [[__gnu__::__always_inline__]]
5698 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5699 _M_formatter.set_debug_format();
5703 formatter<_Tp, _CharT> _M_formatter;
5706 template<typename _CharT, typename... _Tps>
5707 class __tuple_formatter
5709 using _String_view = basic_string_view<_CharT>;
5710 using _Seps = __format::_Separators<_CharT>;
5714 set_separator(basic_string_view<_CharT> __sep) noexcept
5718 set_brackets(basic_string_view<_CharT> __open,
5719 basic_string_view<_CharT> __close) noexcept
5725 // We deviate from standard, that declares this as template accepting
5726 // unconstrained ParseContext type, which seems unimplementable.
5727 constexpr typename basic_format_parse_context<_CharT>::iterator
5728 parse(basic_format_parse_context<_CharT>& __pc)
5730 auto __first = __pc.begin();
5731 const auto __last = __pc.end();
5732 __format::_Spec<_CharT> __spec{};
5734 auto __finished = [&]
5736 if (__first != __last && *__first != '}')
5740 _M_felems._M_parse();
5741 _M_felems.set_debug_format();
5748 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5752 __first = __spec._M_parse_width(__first, __last, __pc);
5756 if (*__first == 'n')
5759 _M_open = _M_close = _String_view();
5761 else if (*__first == 'm')
5764 if constexpr (sizeof...(_Tps) == 2)
5766 _M_sep = _Seps::_S_colon();
5767 _M_open = _M_close = _String_view();
5770 __throw_format_error("format error: 'm' specifier requires range"
5771 " of pair or tuple of two elements");
5777 __format::__failed_to_parse_format_spec();
5781 template<typename _Tuple, typename _Out, size_t... _Ids>
5782 typename basic_format_context<_Out, _CharT>::iterator
5783 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5784 basic_format_context<_Out, _CharT>& __fc) const
5785 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5787 template<typename _Out>
5788 typename basic_format_context<_Out, _CharT>::iterator
5789 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5790 basic_format_context<_Out, _CharT>& __fc) const
5792 return __format::__format_padded(
5794 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5796 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5797 _M_felems._M_format(__elems..., __nfc, _M_sep);
5798 return __format::__write(__nfc.out(), _M_close);
5803 template<size_t... _Ids>
5804 struct __formatters_storage
5805 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5807 template<size_t _Id, typename _Up>
5808 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5813 (_Base<_Ids, _Tps>::_M_parse(), ...);
5816 template<typename _Out>
5818 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5819 basic_format_context<_Out, _CharT>& __fc,
5820 _String_view __sep) const
5822 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5828 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5832 template<size_t... _Ids>
5834 _S_create_storage(index_sequence<_Ids...>)
5835 -> __formatters_storage<_Ids...>;
5837 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5839 _Spec<_CharT> _M_spec{};
5840 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5841 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5842 _String_view _M_sep = _Seps::_S_comma();
5843 _Formatters _M_felems;
5846 template<typename _Tp>
5847 concept __is_map_formattable
5848 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5850} // namespace __format
5853 // [format.tuple] Tuple formatter
5854 template<__format::__char _CharT, formattable<_CharT> _Fp,
5855 formattable<_CharT> _Sp>
5856 struct formatter<pair<_Fp, _Sp>, _CharT>
5857 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5858 remove_cvref_t<_Sp>>
5861 using __maybe_const_pair
5862 = __conditional_t<formattable<const _Fp, _CharT>
5863 && formattable<const _Sp, _CharT>,
5864 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5866 // We deviate from standard, that declares this as template accepting
5867 // unconstrained FormatContext type, which seems unimplementable.
5868 template<typename _Out>
5869 typename basic_format_context<_Out, _CharT>::iterator
5870 format(__maybe_const_pair& __p,
5871 basic_format_context<_Out, _CharT>& __fc) const
5872 { return this->_M_format_elems(__p.first, __p.second, __fc); }
5875#if __glibcxx_print >= 202406L
5876 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5877 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
5878 template<typename _Fp, typename _Sp>
5879 constexpr bool enable_nonlocking_formatter_optimization<pair<_Fp, _Sp>>
5880 = enable_nonlocking_formatter_optimization<remove_cvref_t<_Fp>>
5881 && enable_nonlocking_formatter_optimization<remove_cvref_t<_Sp>>;
5884 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5885 struct formatter<tuple<_Tps...>, _CharT>
5886 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5889 using __maybe_const_tuple
5890 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5891 const tuple<_Tps...>, tuple<_Tps...>>;
5893 // We deviate from standard, that declares this as template accepting
5894 // unconstrained FormatContext type, which seems unimplementable.
5895 template<typename _Out>
5896 typename basic_format_context<_Out, _CharT>::iterator
5897 format(__maybe_const_tuple& __t,
5898 basic_format_context<_Out, _CharT>& __fc) const
5899 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5902#if __glibcxx_print >= 202406L
5903 // _GLIBCXX_RESOLVE_LIB_DEFECTS
5904 // 4399. enable_nonlocking_formatter_optimization for pair and tuple needs remove_cvref_t
5905 template<typename... _Tps>
5906 constexpr bool enable_nonlocking_formatter_optimization<tuple<_Tps...>>
5907 = (enable_nonlocking_formatter_optimization<remove_cvref_t<_Tps>> && ...);
5910 // [format.range.formatter], class template range_formatter
5911 template<typename _Tp, __format::__char _CharT>
5912 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
5913 class range_formatter
5915 using _String_view = basic_string_view<_CharT>;
5916 using _Seps = __format::_Separators<_CharT>;
5920 set_separator(basic_string_view<_CharT> __sep) noexcept
5924 set_brackets(basic_string_view<_CharT> __open,
5925 basic_string_view<_CharT> __close) noexcept
5931 constexpr formatter<_Tp, _CharT>&
5932 underlying() noexcept
5935 constexpr const formatter<_Tp, _CharT>&
5936 underlying() const noexcept
5939 // We deviate from standard, that declares this as template accepting
5940 // unconstrained ParseContext type, which seems unimplementable.
5941 constexpr typename basic_format_parse_context<_CharT>::iterator
5942 parse(basic_format_parse_context<_CharT>& __pc)
5944 auto __first = __pc.begin();
5945 const auto __last = __pc.end();
5946 __format::_Spec<_CharT> __spec{};
5947 bool __no_brace = false;
5949 auto __finished = [&]
5950 { return __first == __last || *__first == '}'; };
5952 auto __finalize = [&]
5958 auto __parse_val = [&](_String_view __nfs = _String_view())
5960 basic_format_parse_context<_CharT> __npc(__nfs);
5961 if (_M_fval.parse(__npc) != __npc.end())
5962 __format::__failed_to_parse_format_spec();
5963 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
5964 _M_fval.set_debug_format();
5965 return __finalize();
5969 return __parse_val();
5971 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5973 return __parse_val();
5975 __first = __spec._M_parse_width(__first, __last, __pc);
5977 return __parse_val();
5979 if (*__first == '?')
5982 __spec._M_debug = true;
5983 if (__finished() || *__first != 's')
5984 __throw_format_error("format error: '?' is allowed only in"
5985 " combination with 's'");
5988 if (*__first == 's')
5991 if constexpr (same_as<_Tp, _CharT>)
5993 __spec._M_type = __format::_Pres_s;
5995 return __finalize();
5996 __throw_format_error("format error: element format specifier"
5997 " cannot be provided when 's' specifier is used");
6000 __throw_format_error("format error: 's' specifier requires"
6001 " range of character types");
6005 return __parse_val();
6007 if (*__first == 'n')
6010 _M_open = _M_close = _String_view();
6015 return __parse_val();
6017 if (*__first == 'm')
6019 _String_view __m(__first, 1);
6021 if constexpr (__format::__is_map_formattable<_Tp>)
6023 _M_sep = _Seps::_S_comma();
6026 _M_open = _Seps::_S_braces().substr(0, 1);
6027 _M_close = _Seps::_S_braces().substr(1, 1);
6030 return __parse_val(__m);
6031 __throw_format_error("format error: element format specifier"
6032 " cannot be provided when 'm' specifier is used");
6035 __throw_format_error("format error: 'm' specifier requires"
6036 " range of pairs or tuples of two elements");
6040 return __parse_val();
6042 if (*__first == ':')
6044 __pc.advance_to(++__first);
6045 __first = _M_fval.parse(__pc);
6049 return __finalize();
6051 __format::__failed_to_parse_format_spec();
6054 // We deviate from standard, that declares this as template accepting
6055 // unconstrained FormatContext type, which seems unimplementable.
6056 template<ranges::input_range _Rg, typename _Out>
6057 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
6058 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
6059 typename basic_format_context<_Out, _CharT>::iterator
6060 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
6062 using _Range = remove_reference_t<_Rg>;
6063 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
6064 return _M_format<const _Range>(__rg, __fc);
6066 return _M_format(__rg, __fc);
6070 template<ranges::input_range _Rg, typename _Out>
6071 typename basic_format_context<_Out, _CharT>::iterator
6072 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
6074 if constexpr (same_as<_Tp, _CharT>)
6075 if (_M_spec._M_type == __format::_Pres_s)
6077 __format::__formatter_str __fstr(_M_spec);
6078 return __fstr._M_format_range(__rg, __fc);
6080 return __format::__format_padded(
6082 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
6083 { return _M_format_elems(__rg, __nfc); });
6087 template<ranges::input_range _Rg, typename _Out>
6088 typename basic_format_context<_Out, _CharT>::iterator
6089 _M_format_elems(_Rg& __rg,
6090 basic_format_context<_Out, _CharT>& __fc) const
6092 auto __out = __format::__write(__fc.out(), _M_open);
6094 auto __first = ranges::begin(__rg);
6095 auto const __last = ranges::end(__rg);
6096 if (__first == __last)
6097 return __format::__write(__out, _M_close);
6099 __fc.advance_to(__out);
6100 __out = _M_fval.format(*__first, __fc);
6101 for (++__first; __first != __last; ++__first)
6103 __out = __format::__write(__out, _M_sep);
6104 __fc.advance_to(__out);
6105 __out = _M_fval.format(*__first, __fc);
6108 return __format::__write(__out, _M_close);
6111 __format::_Spec<_CharT> _M_spec{};
6112 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6113 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6114 _String_view _M_sep = _Seps::_S_comma();
6115 formatter<_Tp, _CharT> _M_fval;
6118 // In standard this is shown as inheriting from specialization of
6119 // exposition only specialization for range-default-formatter for
6120 // each range_format. We opt for simpler implementation.
6121 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
6122 // specializations for maps, sets, and strings
6123 template<ranges::input_range _Rg, __format::__char _CharT>
6124 requires (format_kind<_Rg> != range_format::disabled)
6125 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6126 struct formatter<_Rg, _CharT>
6129 static const bool _S_range_format_is_string =
6130 (format_kind<_Rg> == range_format::string)
6131 || (format_kind<_Rg> == range_format::debug_string);
6132 using _Vt = remove_cvref_t<
6133 ranges::range_reference_t<
6134 __format::__maybe_const_range<_Rg, _CharT>>>;
6136 static consteval bool _S_is_correct()
6138 if constexpr (_S_range_format_is_string)
6139 static_assert(same_as<_Vt, _CharT>);
6143 static_assert(_S_is_correct());
6146 constexpr formatter() noexcept
6148 using _Seps = __format::_Separators<_CharT>;
6149 if constexpr (format_kind<_Rg> == range_format::map)
6151 static_assert(__format::__is_map_formattable<_Vt>);
6152 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6153 _Seps::_S_braces().substr(1, 1));
6154 _M_under.underlying().set_brackets({}, {});
6155 _M_under.underlying().set_separator(_Seps::_S_colon());
6157 else if constexpr (format_kind<_Rg> == range_format::set)
6158 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6159 _Seps::_S_braces().substr(1, 1));
6163 set_separator(basic_string_view<_CharT> __sep) noexcept
6164 requires (format_kind<_Rg> == range_format::sequence)
6165 { _M_under.set_separator(__sep); }
6168 set_brackets(basic_string_view<_CharT> __open,
6169 basic_string_view<_CharT> __close) noexcept
6170 requires (format_kind<_Rg> == range_format::sequence)
6171 { _M_under.set_brackets(__open, __close); }
6173 // We deviate from standard, that declares this as template accepting
6174 // unconstrained ParseContext type, which seems unimplementable.
6175 constexpr typename basic_format_parse_context<_CharT>::iterator
6176 parse(basic_format_parse_context<_CharT>& __pc)
6178 auto __res = _M_under.parse(__pc);
6179 if constexpr (format_kind<_Rg> == range_format::debug_string)
6180 _M_under.set_debug_format();
6184 // We deviate from standard, that declares this as template accepting
6185 // unconstrained FormatContext type, which seems unimplementable.
6186 template<typename _Out>
6187 typename basic_format_context<_Out, _CharT>::iterator
6188 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6189 basic_format_context<_Out, _CharT>& __fc) const
6191 if constexpr (_S_range_format_is_string)
6192 return _M_under._M_format_range(__rg, __fc);
6194 return _M_under.format(__rg, __fc);
6198 using _Formatter_under
6199 = __conditional_t<_S_range_format_is_string,
6200 __format::__formatter_str<_CharT>,
6201 range_formatter<_Vt, _CharT>>;
6202 _Formatter_under _M_under;
6205#if __glibcxx_print >= 202406L
6206 template<ranges::input_range _Rg>
6207 requires (format_kind<_Rg> != range_format::disabled)
6208 constexpr bool enable_nonlocking_formatter_optimization<_Rg> = false;
6211#endif // C++23 formatting ranges
6212#undef _GLIBCXX_WIDEN
6214_GLIBCXX_END_NAMESPACE_VERSION
6216#endif // __cpp_lib_format
6217#pragma GCC diagnostic pop
6218#endif // _GLIBCXX_FORMAT