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 <variant> // monostate (TODO: move to bits/utility.h?)
55#include <bits/ranges_base.h> // input_range, range_reference_t
56#include <bits/ranges_util.h> // subrange
57#include <bits/ranges_algobase.h> // ranges::copy
58#include <bits/stl_iterator.h> // back_insert_iterator
59#include <bits/stl_pair.h> // __is_pair
60#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
61#include <bits/utility.h> // tuple_size_v
62#include <ext/numeric_traits.h> // __int_traits
64#if !__has_builtin(__builtin_toupper)
68#pragma GCC diagnostic push
69#pragma GCC diagnostic ignored "-Wpedantic" // __int128
70#pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
72namespace std _GLIBCXX_VISIBILITY(default)
74_GLIBCXX_BEGIN_NAMESPACE_VERSION
76 // [format.context], class template basic_format_context
77 template<typename _Out, typename _CharT> class basic_format_context;
79 // [format.fmt.string], class template basic_format_string
80 template<typename _CharT, typename... _Args> struct basic_format_string;
85 // Type-erased character sink.
86 template<typename _CharT> class _Sink;
87 // Output iterator that writes to a type-erase character sink.
88 template<typename _CharT>
91 template<typename _CharT>
92 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
94 template<typename _CharT>
95 struct _Runtime_format_string
97 [[__gnu__::__always_inline__]]
98 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
101 _Runtime_format_string(const _Runtime_format_string&) = delete;
102 void operator=(const _Runtime_format_string&) = delete;
105 basic_string_view<_CharT> _M_str;
107 template<typename, typename...> friend struct std::basic_format_string;
109} // namespace __format
112 using format_context = __format::__format_context<char>;
113#ifdef _GLIBCXX_USE_WCHAR_T
114 using wformat_context = __format::__format_context<wchar_t>;
117 // [format.args], class template basic_format_args
118 template<typename _Context> class basic_format_args;
119 using format_args = basic_format_args<format_context>;
120#ifdef _GLIBCXX_USE_WCHAR_T
121 using wformat_args = basic_format_args<wformat_context>;
124 // [format.arguments], arguments
125 // [format.arg], class template basic_format_arg
126 template<typename _Context>
127 class basic_format_arg;
129 /** A compile-time checked format string for the specified argument types.
131 * @since C++23 but available as an extension in C++20.
133 template<typename _CharT, typename... _Args>
134 struct basic_format_string
136 template<typename _Tp>
137 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
139 basic_format_string(const _Tp& __s);
141 [[__gnu__::__always_inline__]]
142 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
146 [[__gnu__::__always_inline__]]
147 constexpr basic_string_view<_CharT>
152 basic_string_view<_CharT> _M_str;
155 template<typename... _Args>
156 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
158#ifdef _GLIBCXX_USE_WCHAR_T
159 template<typename... _Args>
161 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
164#if __cpp_lib_format >= 202311L // >= C++26
165 [[__gnu__::__always_inline__]]
166 inline __format::_Runtime_format_string<char>
167 runtime_format(string_view __fmt) noexcept
170#ifdef _GLIBCXX_USE_WCHAR_T
171 [[__gnu__::__always_inline__]]
172 inline __format::_Runtime_format_string<wchar_t>
173 runtime_format(wstring_view __fmt) noexcept
178 // [format.formatter], formatter
180 /// The primary template of std::formatter is disabled.
181 template<typename _Tp, typename _CharT = char>
184 formatter() = delete; // No std::formatter specialization for this type.
185 formatter(const formatter&) = delete;
186 formatter& operator=(const formatter&) = delete;
189 // [format.error], class format_error
190 class format_error : public runtime_error
193 explicit format_error(const string& __what) : runtime_error(__what) { }
194 explicit format_error(const char* __what) : runtime_error(__what) { }
197 /// @cond undocumented
200 __throw_format_error(const char* __what)
201 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
205 // XXX use named functions for each constexpr error?
209 __unmatched_left_brace_in_format_string()
210 { __throw_format_error("format error: unmatched '{' in format string"); }
214 __unmatched_right_brace_in_format_string()
215 { __throw_format_error("format error: unmatched '}' in format string"); }
219 __conflicting_indexing_in_format_string()
220 { __throw_format_error("format error: conflicting indexing style in format string"); }
224 __invalid_arg_id_in_format_string()
225 { __throw_format_error("format error: invalid arg-id in format string"); }
229 __failed_to_parse_format_spec()
230 { __throw_format_error("format error: failed to parse format-spec"); }
232 template<typename _CharT> class _Scanner;
234} // namespace __format
237 // [format.parse.ctx], class template basic_format_parse_context
238 template<typename _CharT> class basic_format_parse_context;
239 using format_parse_context = basic_format_parse_context<char>;
240#ifdef _GLIBCXX_USE_WCHAR_T
241 using wformat_parse_context = basic_format_parse_context<wchar_t>;
244 template<typename _CharT>
245 class basic_format_parse_context
248 using char_type = _CharT;
249 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
250 using iterator = const_iterator;
253 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
254 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
257 basic_format_parse_context(const basic_format_parse_context&) = delete;
258 void operator=(const basic_format_parse_context&) = delete;
260 constexpr const_iterator begin() const noexcept { return _M_begin; }
261 constexpr const_iterator end() const noexcept { return _M_end; }
264 advance_to(const_iterator __it) noexcept
270 if (_M_indexing == _Manual)
271 __format::__conflicting_indexing_in_format_string();
274 // _GLIBCXX_RESOLVE_LIB_DEFECTS
275 // 3825. Missing compile-time argument id check in next_arg_id
276 if (std::is_constant_evaluated())
277 if (_M_next_arg_id == _M_num_args)
278 __format::__invalid_arg_id_in_format_string();
279 return _M_next_arg_id++;
283 check_arg_id(size_t __id)
285 if (_M_indexing == _Auto)
286 __format::__conflicting_indexing_in_format_string();
287 _M_indexing = _Manual;
289 if (std::is_constant_evaluated())
290 if (__id >= _M_num_args)
291 __format::__invalid_arg_id_in_format_string();
294#if __cpp_lib_format >= 202305L
295 template<typename... _Ts>
297 check_dynamic_spec(size_t __id) noexcept;
300 check_dynamic_spec_integral(size_t __id) noexcept
302 check_dynamic_spec<int, unsigned, long long, unsigned long long>(__id);
306 check_dynamic_spec_string(size_t __id) noexcept
308 check_dynamic_spec<const char_type*, basic_string_view<_CharT>>(__id);
312 // Check the Mandates: condition for check_dynamic_spec<Ts...>(n)
313 template<typename... _Ts>
314 static consteval bool
315 __check_dynamic_spec_types()
317 if constexpr (sizeof...(_Ts))
320 (is_same_v<bool, _Ts> + ...),
321 (is_same_v<_CharT, _Ts> + ...),
322 (is_same_v<int, _Ts> + ...),
323 (is_same_v<unsigned, _Ts> + ...),
324 (is_same_v<long long, _Ts> + ...),
325 (is_same_v<unsigned long long, _Ts> + ...),
326 (is_same_v<float, _Ts> + ...),
327 (is_same_v<double, _Ts> + ...),
328 (is_same_v<long double, _Ts> + ...),
329 (is_same_v<const _CharT*, _Ts> + ...),
330 (is_same_v<basic_string_view<_CharT>, _Ts> + ...),
331 (is_same_v<const void*, _Ts> + ...)
334 for (int __c : __counts)
338 __invalid_dynamic_spec("non-unique template argument type");
340 if (__sum != sizeof...(_Ts))
341 __invalid_dynamic_spec("disallowed template argument type");
346 // This must not be constexpr.
347 static void __invalid_dynamic_spec(const char*);
349 friend __format::_Scanner<_CharT>;
352 // This constructor should only be used by the implementation.
354 basic_format_parse_context(basic_string_view<_CharT> __fmt,
355 size_t __num_args) noexcept
356 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
362 enum _Indexing { _Unknown, _Manual, _Auto };
363 _Indexing _M_indexing = _Unknown;
364 size_t _M_next_arg_id = 0;
365 size_t _M_num_args = 0;
368/// @cond undocumented
369 template<typename _Tp, template<typename...> class _Class>
370 constexpr bool __is_specialization_of = false;
371 template<template<typename...> class _Class, typename... _Args>
372 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
376 // pre: first != last
377 template<typename _CharT>
378 constexpr pair<unsigned short, const _CharT*>
379 __parse_integer(const _CharT* __first, const _CharT* __last)
381 if (__first == __last)
382 __builtin_unreachable();
384 if constexpr (is_same_v<_CharT, char>)
386 const auto __start = __first;
387 unsigned short __val = 0;
388 // N.B. std::from_chars is not constexpr in C++20.
389 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
390 && __first != __start) [[likely]]
391 return {__val, __first};
395 constexpr int __n = 32;
397 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
398 __buf[__i] = __first[__i];
399 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
400 if (__ptr) [[likely]]
401 return {__v, __first + (__ptr - __buf)};
406 template<typename _CharT>
407 constexpr pair<unsigned short, const _CharT*>
408 __parse_arg_id(const _CharT* __first, const _CharT* __last)
410 if (__first == __last)
411 __builtin_unreachable();
414 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
416 if ('1' <= *__first && *__first <= '9')
418 const unsigned short __id = *__first - '0';
419 const auto __next = __first + 1;
420 // Optimize for most likely case of single digit arg-id.
421 if (__next == __last || !('0' <= *__next && *__next <= '9'))
422 return {__id, __next};
424 return __format::__parse_integer(__first, __last);
430 _Pres_none = 0, // Default type (not valid for integer presentation types).
431 // Presentation types for integral types (including bool and charT).
432 _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
433 // Presentation types for floating-point types.
434 _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
435 _Pres_p = 0, _Pres_P, // For pointers.
436 _Pres_s = 0, // For strings and bool.
437 _Pres_esc = 0xf, // For strings and charT.
450 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
455 _WP_none, // No width/prec specified.
456 _WP_value, // Fixed width/prec specified.
457 _WP_from_arg // Use a formatting argument for width/prec.
460 template<typename _Context>
462 __int_from_arg(const basic_format_arg<_Context>& __arg);
464 constexpr bool __is_digit(char __c)
465 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
467 constexpr bool __is_xdigit(char __c)
468 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
470 template<typename _CharT>
476 unsigned _M_localized : 1;
477 unsigned _M_zero_fill : 1;
478 _WidthPrec _M_width_kind : 2;
479 _WidthPrec _M_prec_kind : 2;
480 _Pres_type _M_type : 4;
481 unsigned _M_reserved : 1;
482 unsigned _M_reserved2 : 16;
483 unsigned short _M_width;
484 unsigned short _M_prec;
485 char32_t _M_fill = ' ';
487 using iterator = typename basic_string_view<_CharT>::iterator;
489 static constexpr _Align
490 _S_align(_CharT __c) noexcept
494 case '<': return _Align_left;
495 case '>': return _Align_right;
496 case '^': return _Align_centre;
497 default: return _Align_default;
501 // pre: __first != __last
503 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
507 using namespace __unicode;
508 if constexpr (__literal_encoding_is_unicode<_CharT>())
510 // Accept any UCS scalar value as fill character.
511 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
514 auto __beg = __uv.begin();
515 char32_t __c = *__beg++;
516 if (__is_scalar_value(__c))
517 if (auto __next = __beg.base(); __next != __last)
518 if (_Align __align = _S_align(*__next))
526 else if (__last - __first >= 2)
527 if (_Align __align = _S_align(__first[1]))
534 if (_Align __align = _S_align(__first[0]))
544 static constexpr _Sign
545 _S_sign(_CharT __c) noexcept
549 case '+': return _Sign_plus;
550 case '-': return _Sign_minus;
551 case ' ': return _Sign_space;
552 default: return _Sign_default;
556 // pre: __first != __last
558 _M_parse_sign(iterator __first, iterator) noexcept
560 if (_Sign __sign = _S_sign(*__first))
568 // pre: *__first is valid
570 _M_parse_alternate_form(iterator __first, iterator) noexcept
580 // pre: __first != __last
582 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
592 // pre: __first != __last
593 static constexpr iterator
594 _S_parse_width_or_precision(iterator __first, iterator __last,
595 unsigned short& __val, bool& __arg_id,
596 basic_format_parse_context<_CharT>& __pc)
598 if (__format::__is_digit(*__first))
600 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
602 __throw_format_error("format error: invalid width or precision "
607 else if (*__first == '{')
611 if (__first == __last)
612 __format::__unmatched_left_brace_in_format_string();
614 __val = __pc.next_arg_id();
617 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
618 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
619 __format::__invalid_arg_id_in_format_string();
621 __pc.check_arg_id(__v);
624#if __cpp_lib_format >= 202305L
625 __pc.check_dynamic_spec_integral(__val);
627 ++__first; // past the '}'
632 // pre: __first != __last
634 _M_parse_width(iterator __first, iterator __last,
635 basic_format_parse_context<_CharT>& __pc)
637 bool __arg_id = false;
639 __throw_format_error("format error: width must be non-zero in "
641 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
643 if (__next != __first)
644 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
648 // pre: __first != __last
650 _M_parse_precision(iterator __first, iterator __last,
651 basic_format_parse_context<_CharT>& __pc)
653 if (__first[0] != '.')
656 iterator __next = ++__first;
657 bool __arg_id = false;
658 if (__next != __last)
659 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
661 if (__next == __first)
662 __throw_format_error("format error: missing precision after '.' in "
664 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
668 // pre: __first != __last
670 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
680 template<typename _Context>
682 _M_get_width(_Context& __ctx) const
685 if (_M_width_kind == _WP_value)
687 else if (_M_width_kind == _WP_from_arg)
688 __width = __format::__int_from_arg(__ctx.arg(_M_width));
692 template<typename _Context>
694 _M_get_precision(_Context& __ctx) const
697 if (_M_prec_kind == _WP_value)
699 else if (_M_prec_kind == _WP_from_arg)
700 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
705 template<typename _Int>
707 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
711 else if (__sign == _Sign_plus)
713 else if (__sign == _Sign_space)
720 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
721 template<typename _Out, typename _CharT>
722 requires output_iterator<_Out, const _CharT&>
724 __write(_Out __out, basic_string_view<_CharT> __str)
726 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
732 for (_CharT __c : __str)
737 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
738 // pre: __align != _Align_default
739 template<typename _Out, typename _CharT>
741 __write_padded(_Out __out, basic_string_view<_CharT> __str,
742 _Align __align, size_t __nfill, char32_t __fill_char)
744 const size_t __buflen = 0x20;
745 _CharT __padding_chars[__buflen];
746 __padding_chars[0] = _CharT();
747 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
749 auto __pad = [&__padding] (size_t __n, _Out& __o) {
752 while (__n > __padding.size())
754 __o = __format::__write(std::move(__o), __padding);
755 __n -= __padding.size();
758 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
761 size_t __l, __r, __max;
762 if (__align == _Align_centre)
765 __r = __l + (__nfill & 1);
768 else if (__align == _Align_right)
781 using namespace __unicode;
782 if constexpr (__literal_encoding_is_unicode<_CharT>())
783 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
785 // Encode fill char as multiple code units of type _CharT.
786 const char32_t __arr[1]{ __fill_char };
787 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
788 basic_string<_CharT> __padstr(__v.begin(), __v.end());
789 __padding = __padstr;
791 __out = __format::__write(std::move(__out), __padding);
792 __out = __format::__write(std::move(__out), __str);
794 __out = __format::__write(std::move(__out), __padding);
798 if (__max < __buflen)
799 __padding.remove_suffix(__buflen - __max);
803 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
805 __out = __format::__write(std::move(__out), __str);
811 // Write STR to OUT, with alignment and padding as determined by SPEC.
812 // pre: __spec._M_align != _Align_default || __align != _Align_default
813 template<typename _CharT, typename _Out>
815 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
816 size_t __estimated_width,
817 basic_format_context<_Out, _CharT>& __fc,
818 const _Spec<_CharT>& __spec,
819 _Align __align = _Align_left)
821 size_t __width = __spec._M_get_width(__fc);
823 if (__width <= __estimated_width)
824 return __format::__write(__fc.out(), __str);
826 const size_t __nfill = __width - __estimated_width;
829 __align = __spec._M_align;
831 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
835 // A lightweight optional<locale>.
836 struct _Optional_locale
838 [[__gnu__::__always_inline__]]
839 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
841 _Optional_locale(const locale& __loc) noexcept
842 : _M_loc(__loc), _M_hasval(true)
845 _Optional_locale(const _Optional_locale& __l) noexcept
846 : _M_dummy(), _M_hasval(__l._M_hasval)
849 std::construct_at(&_M_loc, __l._M_loc);
853 operator=(const _Optional_locale& __l) noexcept
865 else if (__l._M_hasval)
867 std::construct_at(&_M_loc, __l._M_loc);
873 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
876 operator=(locale&& __loc) noexcept
879 _M_loc = std::move(__loc);
882 std::construct_at(&_M_loc, std::move(__loc));
893 std::construct_at(&_M_loc);
899 bool has_value() const noexcept { return _M_hasval; }
902 char _M_dummy = '\0';
905 bool _M_hasval = false;
908#ifdef _GLIBCXX_USE_WCHAR_T
909 template<typename _CharT>
910 concept __char = same_as<_CharT, char> || same_as<_CharT, wchar_t>;
912 template<typename _CharT>
913 concept __char = same_as<_CharT, char>;
916 template<__char _CharT>
917 struct __formatter_str
919 constexpr typename basic_format_parse_context<_CharT>::iterator
920 parse(basic_format_parse_context<_CharT>& __pc)
922 auto __first = __pc.begin();
923 const auto __last = __pc.end();
924 _Spec<_CharT> __spec{};
926 auto __finalize = [this, &__spec] {
930 auto __finished = [&] {
931 if (__first == __last || *__first == '}')
942 __first = __spec._M_parse_fill_and_align(__first, __last);
946 __first = __spec._M_parse_width(__first, __last, __pc);
950 __first = __spec._M_parse_precision(__first, __last, __pc);
956#if __cpp_lib_format_ranges
957 else if (*__first == '?')
959 __spec._M_type = _Pres_esc;
967 __format::__failed_to_parse_format_spec();
970 template<typename _Out>
972 format(basic_string_view<_CharT> __s,
973 basic_format_context<_Out, _CharT>& __fc) const
975 if (_M_spec._M_type == _Pres_esc)
977 // TODO: C++23 escaped string presentation
980 if (_M_spec._M_width_kind == _WP_none
981 && _M_spec._M_prec_kind == _WP_none)
982 return __format::__write(__fc.out(), __s);
984 size_t __estimated_width;
985 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
987 if (_M_spec._M_prec_kind != _WP_none)
989 size_t __prec = _M_spec._M_get_precision(__fc);
990 __estimated_width = __unicode::__truncate(__s, __prec);
993 __estimated_width = __unicode::__field_width(__s);
997 __s = __s.substr(0, _M_spec._M_get_precision(__fc));
998 __estimated_width = __s.size();
1001 return __format::__write_padded_as_spec(__s, __estimated_width,
1005#if __cpp_lib_format_ranges
1007 set_debug_format() noexcept
1008 { _M_spec._M_type = _Pres_esc; }
1012 _Spec<_CharT> _M_spec{};
1015 template<__char _CharT>
1016 struct __formatter_int
1018 // If no presentation type is specified, meaning of "none" depends
1019 // whether we are formatting an integer or a char or a bool.
1020 static constexpr _Pres_type _AsInteger = _Pres_d;
1021 static constexpr _Pres_type _AsBool = _Pres_s;
1022 static constexpr _Pres_type _AsChar = _Pres_c;
1024 constexpr typename basic_format_parse_context<_CharT>::iterator
1025 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1027 _Spec<_CharT> __spec{};
1028 __spec._M_type = __type;
1030 const auto __last = __pc.end();
1031 auto __first = __pc.begin();
1033 auto __finalize = [this, &__spec] {
1037 auto __finished = [&] {
1038 if (__first == __last || *__first == '}')
1049 __first = __spec._M_parse_fill_and_align(__first, __last);
1053 __first = __spec._M_parse_sign(__first, __last);
1057 __first = __spec._M_parse_alternate_form(__first, __last);
1061 __first = __spec._M_parse_zero_fill(__first, __last);
1065 __first = __spec._M_parse_width(__first, __last, __pc);
1069 __first = __spec._M_parse_locale(__first, __last);
1076 __spec._M_type = _Pres_b;
1080 __spec._M_type = _Pres_B;
1084 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1085 // 3586. format should not print bool with 'c'
1086 if (__type != _AsBool)
1088 __spec._M_type = _Pres_c;
1093 __spec._M_type = _Pres_d;
1097 __spec._M_type = _Pres_o;
1101 __spec._M_type = _Pres_x;
1105 __spec._M_type = _Pres_X;
1109 if (__type == _AsBool)
1111 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1115#if __cpp_lib_format_ranges
1117 if (__type == _AsChar)
1119 __spec._M_type = _Pres_esc;
1129 __format::__failed_to_parse_format_spec();
1132 template<typename _Tp>
1133 constexpr typename basic_format_parse_context<_CharT>::iterator
1134 _M_parse(basic_format_parse_context<_CharT>& __pc)
1136 if constexpr (is_same_v<_Tp, bool>)
1138 auto __end = _M_do_parse(__pc, _AsBool);
1139 if (_M_spec._M_type == _Pres_s)
1140 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1141 __throw_format_error("format error: format-spec contains "
1142 "invalid formatting options for "
1146 else if constexpr (__char<_Tp>)
1148 auto __end = _M_do_parse(__pc, _AsChar);
1149 if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1150 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1151 /* XXX should be invalid? || _M_spec._M_localized */)
1152 __throw_format_error("format error: format-spec contains "
1153 "invalid formatting options for "
1158 return _M_do_parse(__pc, _AsInteger);
1161 template<typename _Int, typename _Out>
1162 typename basic_format_context<_Out, _CharT>::iterator
1163 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1165 if (_M_spec._M_type == _Pres_c)
1166 return _M_format_character(_S_to_character(__i), __fc);
1168 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1169 to_chars_result __res{};
1171 string_view __base_prefix;
1172 make_unsigned_t<_Int> __u;
1174 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1178 char* __start = __buf + 3;
1179 char* const __end = __buf + sizeof(__buf);
1180 char* const __start_digits = __start;
1182 switch (_M_spec._M_type)
1186 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1187 __res = to_chars(__start, __end, __u, 2);
1191 return _M_format_character(_S_to_character(__i), __fc);
1194 // Should not reach here with _Pres_none for bool or charT, so:
1197 __res = to_chars(__start, __end, __u, 10);
1201 __base_prefix = "0";
1202 __res = to_chars(__start, __end, __u, 8);
1206 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1207 __res = to_chars(__start, __end, __u, 16);
1208 if (_M_spec._M_type == _Pres_X)
1209 for (auto __p = __start; __p != __res.ptr; ++__p)
1210#if __has_builtin(__builtin_toupper)
1211 *__p = __builtin_toupper(*__p);
1213 *__p = std::toupper(*__p);
1217 __builtin_unreachable();
1220 if (_M_spec._M_alt && __base_prefix.size())
1222 __start -= __base_prefix.size();
1223 __builtin_memcpy(__start, __base_prefix.data(),
1224 __base_prefix.size());
1226 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1228 return _M_format_int(string_view(__start, __res.ptr - __start),
1229 __start_digits - __start, __fc);
1232 template<typename _Out>
1233 typename basic_format_context<_Out, _CharT>::iterator
1234 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1236 if (_M_spec._M_type == _Pres_c)
1237 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1238 if (_M_spec._M_type != _Pres_s)
1239 return format(static_cast<unsigned char>(__i), __fc);
1241 basic_string<_CharT> __s;
1243 if (_M_spec._M_localized) [[unlikely]]
1245 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1246 __s = __i ? __np.truename() : __np.falsename();
1247 __est_width = __s.size(); // TODO Unicode-aware estimate
1251 if constexpr (is_same_v<char, _CharT>)
1252 __s = __i ? "true" : "false";
1254 __s = __i ? L"true" : L"false";
1255 __est_width = __s.size();
1258 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1262 template<typename _Out>
1263 typename basic_format_context<_Out, _CharT>::iterator
1264 _M_format_character(_CharT __c,
1265 basic_format_context<_Out, _CharT>& __fc) const
1267 return __format::__write_padded_as_spec({&__c, 1u}, 1, __fc, _M_spec);
1270 template<typename _Int>
1272 _S_to_character(_Int __i)
1274 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1275 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1277 if (_Traits::__min <= __i && __i <= _Traits::__max)
1278 return static_cast<_CharT>(__i);
1280 else if constexpr (is_signed_v<_Int>)
1282 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1283 return static_cast<_CharT>(__i);
1285 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1286 return static_cast<_CharT>(__i);
1287 __throw_format_error("format error: integer not representable as "
1291 template<typename _Out>
1292 typename basic_format_context<_Out, _CharT>::iterator
1293 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1294 basic_format_context<_Out, _CharT>& __fc) const
1296 size_t __width = _M_spec._M_get_width(__fc);
1298 basic_string_view<_CharT> __str;
1299 if constexpr (is_same_v<char, _CharT>)
1300 __str = __narrow_str;
1301#ifdef _GLIBCXX_USE_WCHAR_T
1304 size_t __n = __narrow_str.size();
1305 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1306 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1311 if (_M_spec._M_localized)
1313 const auto& __l = __fc.locale();
1314 if (__l.name() != "C")
1316 auto& __np = use_facet<numpunct<_CharT>>(__l);
1317 string __grp = __np.grouping();
1320 size_t __n = __str.size() - __prefix_len;
1321 auto __p = (_CharT*)__builtin_alloca(2 * __n
1324 auto __s = __str.data();
1325 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1326 __s += __prefix_len;
1327 auto __end = std::__add_grouping(__p + __prefix_len,
1328 __np.thousands_sep(),
1332 __str = {__p, size_t(__end - __p)};
1337 if (__width <= __str.size())
1338 return __format::__write(__fc.out(), __str);
1340 char32_t __fill_char = _M_spec._M_fill;
1341 _Align __align = _M_spec._M_align;
1343 size_t __nfill = __width - __str.size();
1344 auto __out = __fc.out();
1345 if (__align == _Align_default)
1347 __align = _Align_right;
1348 if (_M_spec._M_zero_fill)
1350 __fill_char = _CharT('0');
1351 // Write sign and base prefix before zero filling.
1352 if (__prefix_len != 0)
1354 __out = __format::__write(std::move(__out),
1355 __str.substr(0, __prefix_len));
1356 __str.remove_prefix(__prefix_len);
1360 __fill_char = _CharT(' ');
1362 return __format::__write_padded(std::move(__out), __str,
1363 __align, __nfill, __fill_char);
1366#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1367 template<typename _Tp>
1368 using make_unsigned_t
1369 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1370 std::make_unsigned<_Tp>,
1371 type_identity<unsigned __int128>>::type;
1373 // std::to_chars is not overloaded for int128 in strict mode.
1374 template<typename _Int>
1375 static to_chars_result
1376 to_chars(char* __first, char* __last, _Int __value, int __base)
1377 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1380 _Spec<_CharT> _M_spec{};
1383 // Decide how 128-bit floating-point types should be formatted (or not).
1384 // When supported, the typedef __format::__float128_t is the type that
1385 // format arguments should be converted to for storage in basic_format_arg.
1386 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1387 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1388 // by converting them to long double (or __ieee128 for powerpc64le).
1389 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1390 // support for _Float128, rather than formatting it as another type.
1391#undef _GLIBCXX_FORMAT_F128
1393#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1395 // Format 128-bit floating-point types using __ieee128.
1396 using __float128_t = __ieee128;
1397# define _GLIBCXX_FORMAT_F128 1
1399#ifdef __LONG_DOUBLE_IEEE128__
1400 // These overloads exist in the library, but are not declared.
1401 // Make them available as std::__format::to_chars.
1403 to_chars(char*, char*, __ibm128) noexcept
1404 __asm("_ZSt8to_charsPcS_e");
1407 to_chars(char*, char*, __ibm128, chars_format) noexcept
1408 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1411 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1412 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1413#elif __cplusplus == 202002L
1415 to_chars(char*, char*, __ieee128) noexcept
1416 __asm("_ZSt8to_charsPcS_u9__ieee128");
1419 to_chars(char*, char*, __ieee128, chars_format) noexcept
1420 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1423 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1424 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1427#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1429 // Format 128-bit floating-point types using long double.
1430 using __float128_t = long double;
1431# define _GLIBCXX_FORMAT_F128 1
1433#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1435 // Format 128-bit floating-point types using _Float128.
1436 using __float128_t = _Float128;
1437# define _GLIBCXX_FORMAT_F128 2
1439# if __cplusplus == 202002L
1440 // These overloads exist in the library, but are not declared for C++20.
1441 // Make them available as std::__format::to_chars.
1443 to_chars(char*, char*, _Float128) noexcept
1444# if _GLIBCXX_INLINE_VERSION
1445 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1447 __asm("_ZSt8to_charsPcS_DF128_");
1451 to_chars(char*, char*, _Float128, chars_format) noexcept
1452# if _GLIBCXX_INLINE_VERSION
1453 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1455 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1459 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1460# if _GLIBCXX_INLINE_VERSION
1461 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1463 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1468 using std::to_chars;
1470 // We can format a floating-point type iff it is usable with to_chars.
1471 template<typename _Tp>
1472 concept __formattable_float
1473 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1474 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1476 template<__char _CharT>
1477 struct __formatter_fp
1479 constexpr typename basic_format_parse_context<_CharT>::iterator
1480 parse(basic_format_parse_context<_CharT>& __pc)
1482 _Spec<_CharT> __spec{};
1483 const auto __last = __pc.end();
1484 auto __first = __pc.begin();
1486 auto __finalize = [this, &__spec] {
1490 auto __finished = [&] {
1491 if (__first == __last || *__first == '}')
1502 __first = __spec._M_parse_fill_and_align(__first, __last);
1506 __first = __spec._M_parse_sign(__first, __last);
1510 __first = __spec._M_parse_alternate_form(__first, __last);
1514 __first = __spec._M_parse_zero_fill(__first, __last);
1518 if (__first[0] != '.')
1520 __first = __spec._M_parse_width(__first, __last, __pc);
1525 __first = __spec._M_parse_precision(__first, __last, __pc);
1529 __first = __spec._M_parse_locale(__first, __last);
1536 __spec._M_type = _Pres_a;
1540 __spec._M_type = _Pres_A;
1544 __spec._M_type = _Pres_e;
1548 __spec._M_type = _Pres_E;
1552 __spec._M_type = _Pres_f;
1556 __spec._M_type = _Pres_F;
1560 __spec._M_type = _Pres_g;
1564 __spec._M_type = _Pres_G;
1572 __format::__failed_to_parse_format_spec();
1575 template<typename _Fp, typename _Out>
1576 typename basic_format_context<_Out, _CharT>::iterator
1577 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
1579 std::string __dynbuf;
1581 to_chars_result __res{};
1584 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
1586 __prec = _M_spec._M_get_precision(__fc);
1588 char* __start = __buf + 1; // reserve space for sign
1589 char* __end = __buf + sizeof(__buf);
1591 chars_format __fmt{};
1592 bool __upper = false;
1593 bool __trailing_zeros = false;
1596 switch (_M_spec._M_type)
1603 if (_M_spec._M_type != _Pres_A)
1605 __fmt = chars_format::hex;
1613 __fmt = chars_format::scientific;
1620 __fmt = chars_format::fixed;
1627 __trailing_zeros = true;
1629 __fmt = chars_format::general;
1633 __fmt = chars_format::general;
1636 __builtin_unreachable();
1639 // Write value into buffer using std::to_chars.
1640 auto __to_chars = [&](char* __b, char* __e) {
1642 return __format::to_chars(__b, __e, __v, __fmt, __prec);
1643 else if (__fmt != chars_format{})
1644 return __format::to_chars(__b, __e, __v, __fmt);
1646 return __format::to_chars(__b, __e, __v);
1649 // First try using stack buffer.
1650 __res = __to_chars(__start, __end);
1652 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
1654 // If the buffer is too small it's probably because of a large
1655 // precision, or a very large value in fixed format.
1656 size_t __guess = 8 + __prec;
1657 if (__fmt == chars_format::fixed) // +ddd.prec
1659 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
1660 || is_same_v<_Fp, long double>)
1662 // The number of digits to the left of the decimal point
1663 // is floor(log10(max(abs(__v),1)))+1
1665 if constexpr (is_same_v<_Fp, float>)
1666 __builtin_frexpf(__v, &__exp);
1667 else if constexpr (is_same_v<_Fp, double>)
1668 __builtin_frexp(__v, &__exp);
1669 else if constexpr (is_same_v<_Fp, long double>)
1670 __builtin_frexpl(__v, &__exp);
1672 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
1675 __guess += numeric_limits<_Fp>::max_exponent10;
1677 if (__guess <= sizeof(__buf)) [[unlikely]]
1678 __guess = sizeof(__buf) * 2;
1679 __dynbuf.reserve(__guess);
1683 // Mangling of this lambda, and thus resize_and_overwrite
1684 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
1685 // <format> was new in G++ 13, and is experimental, that
1687 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
1689 __res = __to_chars(__p + 1, __p + __n - 1);
1690 return __res.ec == errc{} ? __res.ptr - __p : 0;
1693 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
1695 __start = __dynbuf.data() + 1; // reserve space for sign
1696 __end = __dynbuf.data() + __dynbuf.size();
1698 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
1701 // Use uppercase for 'A', 'E', and 'G' formats.
1704 for (char* __p = __start; __p != __res.ptr; ++__p)
1705 *__p = std::toupper(*__p);
1708 bool __have_sign = true;
1709 // Add sign for non-negative values.
1710 if (!__builtin_signbit(__v))
1712 if (_M_spec._M_sign == _Sign_plus)
1714 else if (_M_spec._M_sign == _Sign_space)
1717 __have_sign = false;
1720 string_view __narrow_str(__start, __res.ptr - __start);
1722 // Use alternate form. Ensure decimal point is always present,
1723 // and add trailing zeros (up to precision) for g and G forms.
1724 if (_M_spec._M_alt && __builtin_isfinite(__v))
1726 string_view __s = __narrow_str;
1727 size_t __sigfigs; // Number of significant figures.
1728 size_t __z = 0; // Number of trailing zeros to add.
1729 size_t __p; // Position of the exponent character (if any).
1730 size_t __d = __s.find('.'); // Position of decimal point.
1731 if (__d != __s.npos) // Found decimal point.
1733 __p = __s.find(__expc, __d + 1);
1734 if (__p == __s.npos)
1737 // If presentation type is g or G we might need to add zeros.
1738 if (__trailing_zeros)
1740 // Find number of digits after first significant figure.
1741 if (__s[__have_sign] != '0')
1742 // A string like "D.D" or "-D.DDD"
1743 __sigfigs = __p - __have_sign - 1;
1745 // A string like "0.D" or "-0.0DD".
1746 // Safe to assume there is a non-zero digit, because
1747 // otherwise there would be no decimal point.
1748 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
1751 else // No decimal point, we need to insert one.
1753 __p = __s.find(__expc); // Find the exponent, if present.
1754 if (__p == __s.npos)
1756 __d = __p; // Position where '.' should be inserted.
1757 __sigfigs = __d - __have_sign;
1760 if (__trailing_zeros && __prec != 0)
1762 // For g and G presentation types std::to_chars produces
1763 // no more than prec significant figures. Insert this many
1764 // zeros so the result has exactly prec significant figures.
1765 __z = __prec - __sigfigs;
1768 if (size_t __extras = int(__d == __p) + __z) // How many to add.
1770 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
1772 // The stack buffer is large enough for the result.
1773 // Move exponent to make space for extra chars.
1774 __builtin_memmove(__start + __p + __extras,
1778 __start[__p++] = '.';
1779 __builtin_memset(__start + __p, '0', __z);
1780 __narrow_str = {__s.data(), __s.size() + __extras};
1782 else // Need to switch to the dynamic buffer.
1784 __dynbuf.reserve(__s.size() + __extras);
1785 if (__dynbuf.empty())
1787 __dynbuf = __s.substr(0, __p);
1791 __dynbuf.append(__z, '0');
1792 __dynbuf.append(__s.substr(__p));
1796 __dynbuf.insert(__p, __extras, '0');
1798 __dynbuf[__p] = '.';
1800 __narrow_str = __dynbuf;
1805 basic_string<_CharT> __wstr;
1806 basic_string_view<_CharT> __str;
1807 if constexpr (is_same_v<_CharT, char>)
1808 __str = __narrow_str;
1809#ifdef _GLIBCXX_USE_WCHAR_T
1812 __wstr = std::__to_wstring_numeric(__narrow_str);
1817 if (_M_spec._M_localized && __builtin_isfinite(__v))
1819 __wstr = _M_localize(__str, __expc, __fc.locale());
1820 if (!__wstr.empty())
1824 size_t __width = _M_spec._M_get_width(__fc);
1826 if (__width <= __str.size())
1827 return __format::__write(__fc.out(), __str);
1829 char32_t __fill_char = _M_spec._M_fill;
1830 _Align __align = _M_spec._M_align;
1832 size_t __nfill = __width - __str.size();
1833 auto __out = __fc.out();
1834 if (__align == _Align_default)
1836 __align = _Align_right;
1837 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
1839 __fill_char = _CharT('0');
1840 // Write sign before zero filling.
1841 if (!__format::__is_xdigit(__narrow_str[0]))
1843 *__out++ = __str[0];
1844 __str.remove_prefix(1);
1848 __fill_char = _CharT(' ');
1850 return __format::__write_padded(std::move(__out), __str,
1851 __align, __nfill, __fill_char);
1854 // Locale-specific format.
1855 basic_string<_CharT>
1856 _M_localize(basic_string_view<_CharT> __str, char __expc,
1857 const locale& __loc) const
1859 basic_string<_CharT> __lstr;
1861 if (__loc == locale::classic())
1862 return __lstr; // Nothing to do.
1864 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1865 const _CharT __point = __np.decimal_point();
1866 const string __grp = __np.grouping();
1868 _CharT __dot, __exp;
1869 if constexpr (is_same_v<_CharT, char>)
1892 __builtin_unreachable();
1896 if (__grp.empty() && __point == __dot)
1897 return __lstr; // Locale uses '.' and no grouping.
1899 size_t __d = __str.find(__dot); // Index of radix character (if any).
1900 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
1901 if (__e == __str.npos)
1903 const size_t __r = __str.size() - __e; // Length of remainder.
1904 auto __overwrite = [&](_CharT* __p, size_t) {
1905 // Apply grouping to the digits before the radix or exponent.
1906 auto __end = std::__add_grouping(__p, __np.thousands_sep(),
1907 __grp.data(), __grp.size(),
1908 __str.data(), __str.data() + __e);
1909 if (__r) // If there's a fractional part or exponent
1911 if (__d != __str.npos)
1913 *__end = __point; // Add the locale's radix character.
1917 const size_t __rlen = __str.size() - __e;
1918 // Append fractional digits and/or exponent:
1919 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
1922 return (__end - __p);
1924 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
1928 _Spec<_CharT> _M_spec{};
1931} // namespace __format
1934 /// Format a character.
1935 template<__format::__char _CharT>
1936 struct formatter<_CharT, _CharT>
1938 formatter() = default;
1940 constexpr typename basic_format_parse_context<_CharT>::iterator
1941 parse(basic_format_parse_context<_CharT>& __pc)
1943 return _M_f.template _M_parse<_CharT>(__pc);
1946 template<typename _Out>
1947 typename basic_format_context<_Out, _CharT>::iterator
1948 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
1950 if (_M_f._M_spec._M_type == __format::_Pres_none
1951 || _M_f._M_spec._M_type == __format::_Pres_c)
1952 return _M_f._M_format_character(__u, __fc);
1953 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1959 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
1962#if __cpp_lib_format_ranges
1964 set_debug_format() noexcept
1965 { _M_f._M_spec._M_type = __format::_Pres_esc; }
1969 __format::__formatter_int<_CharT> _M_f;
1972#ifdef _GLIBCXX_USE_WCHAR_T
1973 /// Format a char value for wide character output.
1975 struct formatter<char, wchar_t>
1977 formatter() = default;
1979 constexpr typename basic_format_parse_context<wchar_t>::iterator
1980 parse(basic_format_parse_context<wchar_t>& __pc)
1982 return _M_f._M_parse<char>(__pc);
1985 template<typename _Out>
1986 typename basic_format_context<_Out, wchar_t>::iterator
1987 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
1989 if (_M_f._M_spec._M_type == __format::_Pres_none
1990 || _M_f._M_spec._M_type == __format::_Pres_c)
1991 return _M_f._M_format_character(__u, __fc);
1992 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1998 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2001#if __cpp_lib_format_ranges
2003 set_debug_format() noexcept
2004 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2008 __format::__formatter_int<wchar_t> _M_f;
2010#endif // USE_WCHAR_T
2012 /** Format a string.
2015 template<__format::__char _CharT>
2016 struct formatter<_CharT*, _CharT>
2018 formatter() = default;
2020 [[__gnu__::__always_inline__]]
2021 constexpr typename basic_format_parse_context<_CharT>::iterator
2022 parse(basic_format_parse_context<_CharT>& __pc)
2023 { return _M_f.parse(__pc); }
2025 template<typename _Out>
2026 [[__gnu__::__nonnull__]]
2027 typename basic_format_context<_Out, _CharT>::iterator
2028 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2029 { return _M_f.format(__u, __fc); }
2031#if __cpp_lib_format_ranges
2032 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2036 __format::__formatter_str<_CharT> _M_f;
2039 template<__format::__char _CharT>
2040 struct formatter<const _CharT*, _CharT>
2042 formatter() = default;
2044 [[__gnu__::__always_inline__]]
2045 constexpr typename basic_format_parse_context<_CharT>::iterator
2046 parse(basic_format_parse_context<_CharT>& __pc)
2047 { return _M_f.parse(__pc); }
2049 template<typename _Out>
2050 [[__gnu__::__nonnull__]]
2051 typename basic_format_context<_Out, _CharT>::iterator
2052 format(const _CharT* __u,
2053 basic_format_context<_Out, _CharT>& __fc) const
2054 { return _M_f.format(__u, __fc); }
2056#if __cpp_lib_format_ranges
2057 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2061 __format::__formatter_str<_CharT> _M_f;
2064 template<__format::__char _CharT, size_t _Nm>
2065 struct formatter<_CharT[_Nm], _CharT>
2067 formatter() = default;
2069 [[__gnu__::__always_inline__]]
2070 constexpr typename basic_format_parse_context<_CharT>::iterator
2071 parse(basic_format_parse_context<_CharT>& __pc)
2072 { return _M_f.parse(__pc); }
2074 template<typename _Out>
2075 typename basic_format_context<_Out, _CharT>::iterator
2076 format(const _CharT (&__u)[_Nm],
2077 basic_format_context<_Out, _CharT>& __fc) const
2078 { return _M_f.format({__u, _Nm}, __fc); }
2080#if __cpp_lib_format_ranges
2081 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2085 __format::__formatter_str<_CharT> _M_f;
2088 template<typename _Traits, typename _Alloc>
2089 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2091 formatter() = default;
2093 [[__gnu__::__always_inline__]]
2094 constexpr typename basic_format_parse_context<char>::iterator
2095 parse(basic_format_parse_context<char>& __pc)
2096 { return _M_f.parse(__pc); }
2098 template<typename _Out>
2099 typename basic_format_context<_Out, char>::iterator
2100 format(const basic_string<char, _Traits, _Alloc>& __u,
2101 basic_format_context<_Out, char>& __fc) const
2102 { return _M_f.format(__u, __fc); }
2104#if __cpp_lib_format_ranges
2105 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2109 __format::__formatter_str<char> _M_f;
2112#ifdef _GLIBCXX_USE_WCHAR_T
2113 template<typename _Traits, typename _Alloc>
2114 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2116 formatter() = default;
2118 [[__gnu__::__always_inline__]]
2119 constexpr typename basic_format_parse_context<wchar_t>::iterator
2120 parse(basic_format_parse_context<wchar_t>& __pc)
2121 { return _M_f.parse(__pc); }
2123 template<typename _Out>
2124 typename basic_format_context<_Out, wchar_t>::iterator
2125 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2126 basic_format_context<_Out, wchar_t>& __fc) const
2127 { return _M_f.format(__u, __fc); }
2129#if __cpp_lib_format_ranges
2130 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2134 __format::__formatter_str<wchar_t> _M_f;
2136#endif // USE_WCHAR_T
2138 template<typename _Traits>
2139 struct formatter<basic_string_view<char, _Traits>, char>
2141 formatter() = default;
2143 [[__gnu__::__always_inline__]]
2144 constexpr typename basic_format_parse_context<char>::iterator
2145 parse(basic_format_parse_context<char>& __pc)
2146 { return _M_f.parse(__pc); }
2148 template<typename _Out>
2149 typename basic_format_context<_Out, char>::iterator
2150 format(basic_string_view<char, _Traits> __u,
2151 basic_format_context<_Out, char>& __fc) const
2152 { return _M_f.format(__u, __fc); }
2154#if __cpp_lib_format_ranges
2155 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2159 __format::__formatter_str<char> _M_f;
2162#ifdef _GLIBCXX_USE_WCHAR_T
2163 template<typename _Traits>
2164 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2166 formatter() = default;
2168 [[__gnu__::__always_inline__]]
2169 constexpr typename basic_format_parse_context<wchar_t>::iterator
2170 parse(basic_format_parse_context<wchar_t>& __pc)
2171 { return _M_f.parse(__pc); }
2173 template<typename _Out>
2174 typename basic_format_context<_Out, wchar_t>::iterator
2175 format(basic_string_view<wchar_t, _Traits> __u,
2176 basic_format_context<_Out, wchar_t>& __fc) const
2177 { return _M_f.format(__u, __fc); }
2179#if __cpp_lib_format_ranges
2180 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2184 __format::__formatter_str<wchar_t> _M_f;
2186#endif // USE_WCHAR_T
2189/// @cond undocumented
2192 // each cv-unqualified arithmetic type ArithmeticT other than
2193 // char, wchar_t, char8_t, char16_t, or char32_t
2194 template<typename _Tp>
2195 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2197#if defined __SIZEOF_INT128__
2198 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2199 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2203 template<> inline constexpr bool __is_formattable_integer<char> = false;
2204 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2205#ifdef _GLIBCXX_USE_CHAR8_T
2206 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2208 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2209 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2213 /// Format an integer.
2214 template<typename _Tp, __format::__char _CharT>
2215 requires __format::__is_formattable_integer<_Tp>
2216 struct formatter<_Tp, _CharT>
2218 formatter() = default;
2220 [[__gnu__::__always_inline__]]
2221 constexpr typename basic_format_parse_context<_CharT>::iterator
2222 parse(basic_format_parse_context<_CharT>& __pc)
2224 return _M_f.template _M_parse<_Tp>(__pc);
2227 template<typename _Out>
2228 typename basic_format_context<_Out, _CharT>::iterator
2229 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2230 { return _M_f.format(__u, __fc); }
2233 __format::__formatter_int<_CharT> _M_f;
2236#if defined __glibcxx_to_chars
2237 /// Format a floating-point value.
2238 template<__format::__formattable_float _Tp, __format::__char _CharT>
2239 struct formatter<_Tp, _CharT>
2241 formatter() = default;
2243 [[__gnu__::__always_inline__]]
2244 constexpr typename basic_format_parse_context<_CharT>::iterator
2245 parse(basic_format_parse_context<_CharT>& __pc)
2246 { return _M_f.parse(__pc); }
2248 template<typename _Out>
2249 typename basic_format_context<_Out, _CharT>::iterator
2250 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2251 { return _M_f.format(__u, __fc); }
2254 __format::__formatter_fp<_CharT> _M_f;
2257#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2258 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2259 template<__format::__char _CharT>
2260 struct formatter<long double, _CharT>
2262 formatter() = default;
2264 [[__gnu__::__always_inline__]]
2265 constexpr typename basic_format_parse_context<_CharT>::iterator
2266 parse(basic_format_parse_context<_CharT>& __pc)
2267 { return _M_f.parse(__pc); }
2269 template<typename _Out>
2270 typename basic_format_context<_Out, _CharT>::iterator
2271 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2272 { return _M_f.format((double)__u, __fc); }
2275 __format::__formatter_fp<_CharT> _M_f;
2279#ifdef __STDCPP_FLOAT16_T__
2280 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2281 template<__format::__char _CharT>
2282 struct formatter<_Float16, _CharT>
2284 formatter() = default;
2286 [[__gnu__::__always_inline__]]
2287 constexpr typename basic_format_parse_context<_CharT>::iterator
2288 parse(basic_format_parse_context<_CharT>& __pc)
2289 { return _M_f.parse(__pc); }
2291 template<typename _Out>
2292 typename basic_format_context<_Out, _CharT>::iterator
2293 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2294 { return _M_f.format((float)__u, __fc); }
2297 __format::__formatter_fp<_CharT> _M_f;
2301#if defined(__FLT32_DIG__)
2302 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2303 template<__format::__char _CharT>
2304 struct formatter<_Float32, _CharT>
2306 formatter() = default;
2308 [[__gnu__::__always_inline__]]
2309 constexpr typename basic_format_parse_context<_CharT>::iterator
2310 parse(basic_format_parse_context<_CharT>& __pc)
2311 { return _M_f.parse(__pc); }
2313 template<typename _Out>
2314 typename basic_format_context<_Out, _CharT>::iterator
2315 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2316 { return _M_f.format((float)__u, __fc); }
2319 __format::__formatter_fp<_CharT> _M_f;
2323#if defined(__FLT64_DIG__)
2324 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2325 template<__format::__char _CharT>
2326 struct formatter<_Float64, _CharT>
2328 formatter() = default;
2330 [[__gnu__::__always_inline__]]
2331 constexpr typename basic_format_parse_context<_CharT>::iterator
2332 parse(basic_format_parse_context<_CharT>& __pc)
2333 { return _M_f.parse(__pc); }
2335 template<typename _Out>
2336 typename basic_format_context<_Out, _CharT>::iterator
2337 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2338 { return _M_f.format((double)__u, __fc); }
2341 __format::__formatter_fp<_CharT> _M_f;
2345#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2346 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2347 template<__format::__char _CharT>
2348 struct formatter<_Float128, _CharT>
2350 formatter() = default;
2352 [[__gnu__::__always_inline__]]
2353 constexpr typename basic_format_parse_context<_CharT>::iterator
2354 parse(basic_format_parse_context<_CharT>& __pc)
2355 { return _M_f.parse(__pc); }
2357 template<typename _Out>
2358 typename basic_format_context<_Out, _CharT>::iterator
2359 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2360 { return _M_f.format((__format::__float128_t)__u, __fc); }
2363 __format::__formatter_fp<_CharT> _M_f;
2367#ifdef __STDCPP_BFLOAT16_T__
2368 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2369 template<__format::__char _CharT>
2370 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2372 formatter() = default;
2374 [[__gnu__::__always_inline__]]
2375 constexpr typename basic_format_parse_context<_CharT>::iterator
2376 parse(basic_format_parse_context<_CharT>& __pc)
2377 { return _M_f.parse(__pc); }
2379 template<typename _Out>
2380 typename basic_format_context<_Out, _CharT>::iterator
2381 format(__gnu_cxx::__bfloat16_t __u,
2382 basic_format_context<_Out, _CharT>& __fc) const
2383 { return _M_f.format((float)__u, __fc); }
2386 __format::__formatter_fp<_CharT> _M_f;
2389#endif // __cpp_lib_to_chars
2391 /** Format a pointer.
2394 template<__format::__char _CharT>
2395 struct formatter<const void*, _CharT>
2397 formatter() = default;
2399 constexpr typename basic_format_parse_context<_CharT>::iterator
2400 parse(basic_format_parse_context<_CharT>& __pc)
2402 __format::_Spec<_CharT> __spec{};
2403 const auto __last = __pc.end();
2404 auto __first = __pc.begin();
2406 auto __finalize = [this, &__spec] {
2410 auto __finished = [&] {
2411 if (__first == __last || *__first == '}')
2422 __first = __spec._M_parse_fill_and_align(__first, __last);
2426// _GLIBCXX_RESOLVE_LIB_DEFECTS
2427// P2510R3 Formatting pointers
2428#if __glibcxx_format >= 202304L
2429 __first = __spec._M_parse_zero_fill(__first, __last);
2434 __first = __spec._M_parse_width(__first, __last, __pc);
2436 if (__first != __last)
2438 if (*__first == 'p')
2440#if __glibcxx_format >= 202304L
2441 else if (*__first == 'P')
2443 __spec._M_type = __format::_Pres_P;
2452 __format::__failed_to_parse_format_spec();
2455 template<typename _Out>
2456 typename basic_format_context<_Out, _CharT>::iterator
2457 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2459 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2460 char __buf[2 + sizeof(__v) * 2];
2461 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2463 int __n = __ptr - __buf;
2466#if __glibcxx_format >= 202304L
2467 if (_M_spec._M_type == __format::_Pres_P)
2470 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2471#if __has_builtin(__builtin_toupper)
2472 *__p = __builtin_toupper(*__p);
2474 *__p = std::toupper(*__p);
2479 basic_string_view<_CharT> __str;
2480 if constexpr (is_same_v<_CharT, char>)
2481 __str = string_view(__buf, __n);
2482#ifdef _GLIBCXX_USE_WCHAR_T
2485 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2486 std::__to_wstring_numeric(__buf, __n, __p);
2487 __str = wstring_view(__p, __n);
2491#if __glibcxx_format >= 202304L
2492 if (_M_spec._M_zero_fill)
2494 size_t __width = _M_spec._M_get_width(__fc);
2495 if (__width <= __str.size())
2496 return __format::__write(__fc.out(), __str);
2498 auto __out = __fc.out();
2499 // Write "0x" or "0X" prefix before zero-filling.
2500 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2501 __str.remove_prefix(2);
2502 size_t __nfill = __width - __n;
2503 return __format::__write_padded(std::move(__out), __str,
2504 __format::_Align_right,
2505 __nfill, _CharT('0'));
2509 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2510 __format::_Align_right);
2514 __format::_Spec<_CharT> _M_spec{};
2517 template<__format::__char _CharT>
2518 struct formatter<void*, _CharT>
2520 formatter() = default;
2522 [[__gnu__::__always_inline__]]
2523 constexpr typename basic_format_parse_context<_CharT>::iterator
2524 parse(basic_format_parse_context<_CharT>& __pc)
2525 { return _M_f.parse(__pc); }
2527 template<typename _Out>
2528 typename basic_format_context<_Out, _CharT>::iterator
2529 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2530 { return _M_f.format(__v, __fc); }
2533 formatter<const void*, _CharT> _M_f;
2536 template<__format::__char _CharT>
2537 struct formatter<nullptr_t, _CharT>
2539 formatter() = default;
2541 [[__gnu__::__always_inline__]]
2542 constexpr typename basic_format_parse_context<_CharT>::iterator
2543 parse(basic_format_parse_context<_CharT>& __pc)
2544 { return _M_f.parse(__pc); }
2546 template<typename _Out>
2547 typename basic_format_context<_Out, _CharT>::iterator
2548 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2549 { return _M_f.format(nullptr, __fc); }
2552 formatter<const void*, _CharT> _M_f;
2556#if defined _GLIBCXX_USE_WCHAR_T && __cpp_lib_format_ranges
2557 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2558 // 3944. Formatters converting sequences of char to sequences of wchar_t
2560 namespace __format { struct __disabled; }
2562 // std::formatter<__disabled, C> uses the primary template, which is disabled.
2564 struct formatter<char*, wchar_t>
2565 : private formatter<__format::__disabled, wchar_t> { };
2567 struct formatter<const char*, wchar_t>
2568 : private formatter<__format::__disabled, wchar_t> { };
2569 template<size_t _Nm>
2570 struct formatter<char[_Nm], wchar_t>
2571 : private formatter<__format::__disabled, wchar_t> { };
2572 template<class _Traits, class _Allocator>
2573 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
2574 : private formatter<__format::__disabled, wchar_t> { };
2575 template<class _Traits>
2576 struct formatter<basic_string_view<char, _Traits>, wchar_t>
2577 : private formatter<__format::__disabled, wchar_t> { };
2580/// @cond undocumented
2583 template<typename _Tp, typename _Context,
2585 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2586 typename _ParseContext
2587 = basic_format_parse_context<typename _Context::char_type>>
2588 concept __parsable_with
2589 = semiregular<_Formatter>
2590 && requires (_Formatter __f, _ParseContext __pc)
2592 { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
2595 template<typename _Tp, typename _Context,
2597 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2598 typename _ParseContext
2599 = basic_format_parse_context<typename _Context::char_type>>
2600 concept __formattable_with
2601 = semiregular<_Formatter>
2602 && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
2604 { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
2607 // An unspecified output iterator type used in the `formattable` concept.
2608 template<typename _CharT>
2609 using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
2611 template<typename _Tp, typename _CharT,
2612 typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
2613 concept __formattable_impl
2614 = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
2616} // namespace __format
2619// Concept std::formattable was introduced by P2286R8 "Formatting Ranges",
2620// but we can't guard it with __cpp_lib_format_ranges until we define that!
2621#if __cplusplus > 202002L
2622 // [format.formattable], concept formattable
2623 template<typename _Tp, typename _CharT>
2625 = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
2628#if __cpp_lib_format_ranges
2629 /// @cond undocumented
2632 template<typename _Rg, typename _CharT>
2633 concept __const_formattable_range
2634 = ranges::input_range<const _Rg>
2635 && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
2637 template<typename _Rg, typename _CharT>
2638 using __maybe_const_range
2639 = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
2640} // namespace __format
2642#endif // format_ranges
2644 /// An iterator after the last character written, and the number of
2645 /// characters that would have been written.
2646 template<typename _Out>
2647 struct format_to_n_result
2650 iter_difference_t<_Out> size;
2653_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
2654template<typename, typename> class vector;
2655_GLIBCXX_END_NAMESPACE_CONTAINER
2657/// @cond undocumented
2660 template<typename _CharT>
2663 _Sink<_CharT>* _M_sink = nullptr;
2666 using iterator_category = output_iterator_tag;
2667 using value_type = void;
2668 using difference_type = ptrdiff_t;
2669 using pointer = void;
2670 using reference = void;
2672 _Sink_iter() = default;
2673 _Sink_iter(const _Sink_iter&) = default;
2674 _Sink_iter& operator=(const _Sink_iter&) = default;
2676 [[__gnu__::__always_inline__]]
2678 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
2680 [[__gnu__::__always_inline__]]
2681 constexpr _Sink_iter&
2682 operator=(_CharT __c)
2684 _M_sink->_M_write(__c);
2688 [[__gnu__::__always_inline__]]
2689 constexpr _Sink_iter&
2690 operator=(basic_string_view<_CharT> __s)
2692 _M_sink->_M_write(__s);
2696 [[__gnu__::__always_inline__]]
2697 constexpr _Sink_iter&
2698 operator*() { return *this; }
2700 [[__gnu__::__always_inline__]]
2701 constexpr _Sink_iter&
2702 operator++() { return *this; }
2704 [[__gnu__::__always_inline__]]
2705 constexpr _Sink_iter
2706 operator++(int) { return *this; }
2709 _M_reserve(size_t __n) const
2710 { return _M_sink->_M_reserve(__n); }
2713 // Abstract base class for type-erased character sinks.
2714 // All formatting and output is done via this type's iterator,
2715 // to reduce the number of different template instantiations.
2716 template<typename _CharT>
2719 friend class _Sink_iter<_CharT>;
2721 span<_CharT> _M_span;
2722 typename span<_CharT>::iterator _M_next;
2724 // Called when the span is full, to make more space available.
2725 // Precondition: _M_next != _M_span.begin()
2726 // Postcondition: _M_next != _M_span.end()
2727 // TODO: remove the precondition? could make overflow handle it.
2728 virtual void _M_overflow() = 0;
2731 // Precondition: __span.size() != 0
2732 [[__gnu__::__always_inline__]]
2734 _Sink(span<_CharT> __span) noexcept
2735 : _M_span(__span), _M_next(__span.begin())
2738 // The portion of the span that has been written to.
2739 [[__gnu__::__always_inline__]]
2741 _M_used() const noexcept
2742 { return _M_span.first(_M_next - _M_span.begin()); }
2744 // The portion of the span that has not been written to.
2745 [[__gnu__::__always_inline__]]
2746 constexpr span<_CharT>
2747 _M_unused() const noexcept
2748 { return _M_span.subspan(_M_next - _M_span.begin()); }
2750 // Use the start of the span as the next write position.
2751 [[__gnu__::__always_inline__]]
2753 _M_rewind() noexcept
2754 { _M_next = _M_span.begin(); }
2756 // Replace the current output range.
2758 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
2761 _M_next = __s.begin() + __pos;
2764 // Called by the iterator for *it++ = c
2766 _M_write(_CharT __c)
2769 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
2774 _M_write(basic_string_view<_CharT> __s)
2776 span __to = _M_unused();
2777 while (__to.size() <= __s.size())
2779 __s.copy(__to.data(), __to.size());
2780 _M_next += __to.size();
2781 __s.remove_prefix(__to.size());
2787 __s.copy(__to.data(), __s.size());
2788 _M_next += __s.size();
2792 // A successful _Reservation can be used to directly write
2793 // up to N characters to the sink to avoid unwanted buffering.
2796 // True if the reservation was successful, false otherwise.
2797 explicit operator bool() const noexcept { return _M_sink; }
2798 // A pointer to write directly to the sink.
2799 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
2800 // Add n to the _M_next iterator for the sink.
2801 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
2805 // Attempt to reserve space to write n characters to the sink.
2806 // If anything is written to the reservation then there must be a call
2807 // to _M_bump(N2) before any call to another member function of *this,
2808 // where N2 is the number of characters written.
2809 virtual _Reservation
2810 _M_reserve(size_t __n)
2812 if (__n <= _M_unused().size())
2815 if (__n <= _M_span.size()) // Cannot meet the request.
2817 _M_overflow(); // Make more space available.
2818 if (__n <= _M_unused().size())
2824 // Update the next output position after writing directly to the sink.
2825 // pre: no calls to _M_write or _M_overflow since _M_reserve.
2831 _Sink(const _Sink&) = delete;
2832 _Sink& operator=(const _Sink&) = delete;
2834 [[__gnu__::__always_inline__]]
2835 constexpr _Sink_iter<_CharT>
2837 { return _Sink_iter<_CharT>(*this); }
2840 // A sink with an internal buffer. This is used to implement concrete sinks.
2841 template<typename _CharT>
2842 class _Buf_sink : public _Sink<_CharT>
2845 _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
2847 [[__gnu__::__always_inline__]]
2849 _Buf_sink() noexcept
2850 : _Sink<_CharT>(_M_buf)
2854 using _GLIBCXX_STD_C::vector;
2856 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
2857 // Writes to a buffer then appends that to the sequence when it fills up.
2858 template<typename _Seq>
2859 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
2861 using _CharT = typename _Seq::value_type;
2865 // Transfer buffer contents to the sequence, so buffer can be refilled.
2867 _M_overflow() override
2869 auto __s = this->_M_used();
2870 if (__s.empty()) [[unlikely]]
2871 return; // Nothing in the buffer to transfer to _M_seq.
2873 // If _M_reserve was called then _M_bump must have been called too.
2874 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
2876 if constexpr (__is_specialization_of<_Seq, basic_string>)
2877 _M_seq.append(__s.data(), __s.size());
2879 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
2881 // Make the whole of _M_buf available for the next write:
2885 typename _Sink<_CharT>::_Reservation
2886 _M_reserve(size_t __n) override
2888 // We might already have n characters available in this->_M_unused(),
2889 // but the whole point of this function is to be an optimization for
2890 // the std::format("{}", x) case. We want to avoid writing to _M_buf
2891 // and then copying that into a basic_string if possible, so this
2892 // function prefers to create space directly in _M_seq rather than
2895 if constexpr (__is_specialization_of<_Seq, basic_string>
2896 || __is_specialization_of<_Seq, vector>)
2898 // Flush the buffer to _M_seq first (should not be needed).
2899 if (this->_M_used().size()) [[unlikely]]
2900 _Seq_sink::_M_overflow();
2902 // Expand _M_seq to make __n new characters available:
2903 const auto __sz = _M_seq.size();
2904 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
2905 _M_seq.__resize_and_overwrite(__sz + __n,
2906 [](auto, auto __n2) {
2910 _M_seq.resize(__sz + __n);
2912 // Set _M_used() to be a span over the original part of _M_seq
2913 // and _M_unused() to be the extra capacity we just created:
2914 this->_M_reset(_M_seq, __sz);
2917 else // Try to use the base class' buffer.
2918 return _Sink<_CharT>::_M_reserve(__n);
2922 _M_bump(size_t __n) override
2924 if constexpr (__is_specialization_of<_Seq, basic_string>
2925 || __is_specialization_of<_Seq, vector>)
2927 auto __s = this->_M_used();
2928 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
2929 // Truncate the sequence to the part that was actually written to:
2930 _M_seq.resize(__s.size() + __n);
2931 // Switch back to using buffer:
2932 this->_M_reset(this->_M_buf);
2937 // TODO: for SSO string, use SSO buffer as initial span, then switch
2938 // to _M_buf if it overflows? Or even do that for all unused capacity?
2940 [[__gnu__::__always_inline__]]
2941 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
2944 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
2945 : _M_seq(std::move(__s))
2948 using _Sink<_CharT>::out;
2953 if (this->_M_used().size() != 0)
2954 _Seq_sink::_M_overflow();
2955 return std::move(_M_seq);
2958 // A writable span that views everything written to the sink.
2959 // Will be either a view over _M_seq or the used part of _M_buf.
2963 auto __s = this->_M_used();
2966 if (__s.size() != 0)
2967 _Seq_sink::_M_overflow();
2974 template<typename _CharT, typename _Alloc = allocator<_CharT>>
2976 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
2978 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
2979 // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
2981 // A sink that writes to an output iterator.
2982 // Writes to a fixed-size buffer and then flushes to the output iterator
2983 // when the buffer fills up.
2984 template<typename _CharT, typename _OutIter>
2985 class _Iter_sink : public _Buf_sink<_CharT>
2988 iter_difference_t<_OutIter> _M_max;
2991 size_t _M_count = 0;
2994 _M_overflow() override
2996 auto __s = this->_M_used();
2997 if (_M_max < 0) // No maximum.
2998 _M_out = ranges::copy(__s, std::move(_M_out)).out;
2999 else if (_M_count < static_cast<size_t>(_M_max))
3001 auto __max = _M_max - _M_count;
3002 span<_CharT> __first;
3003 if (__max < __s.size())
3004 __first = __s.first(static_cast<size_t>(__max));
3007 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3010 _M_count += __s.size();
3014 [[__gnu__::__always_inline__]]
3016 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3017 : _M_out(std::move(__out)), _M_max(__max)
3020 using _Sink<_CharT>::out;
3022 format_to_n_result<_OutIter>
3025 if (this->_M_used().size() != 0)
3026 _Iter_sink::_M_overflow();
3027 iter_difference_t<_OutIter> __count(_M_count);
3028 return { std::move(_M_out), __count };
3032 // Partial specialization for contiguous iterators.
3033 // No buffer is used, characters are written straight to the iterator.
3034 // We do not know the size of the output range, so the span size just grows
3035 // as needed. The end of the span might be an invalid pointer outside the
3036 // valid range, but we never actually call _M_span.end(). This class does
3037 // not introduce any invalid pointer arithmetic or overflows that would not
3038 // have happened anyway.
3039 template<typename _CharT, contiguous_iterator _OutIter>
3040 requires same_as<iter_value_t<_OutIter>, _CharT>
3041 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3044 iter_difference_t<_OutIter> _M_max = -1;
3046 size_t _M_count = 0;
3048 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3052 _M_overflow() override
3054 if (this->_M_unused().size() != 0)
3055 return; // No need to switch to internal buffer yet.
3057 auto __s = this->_M_used();
3061 _M_count += __s.size();
3062 // Span was already sized for the maximum character count,
3063 // if it overflows then any further output must go to the
3064 // internal buffer, to be discarded.
3065 this->_M_reset(this->_M_buf);
3069 // No maximum character count. Just extend the span to allow
3070 // writing more characters to it.
3071 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3075 typename _Sink<_CharT>::_Reservation
3076 _M_reserve(size_t __n) final
3078 auto __avail = this->_M_unused();
3079 if (__n > __avail.size())
3082 return {}; // cannot grow
3084 auto __s = this->_M_used();
3085 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3092 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3093 span<_CharT> __buf) noexcept
3096 return __buf; // Only write to the internal buffer.
3100 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3101 || sizeof(__n) > sizeof(size_t))
3103 // __int128 or __detail::__max_diff_type
3104 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3108 return {__ptr, (size_t)__n};
3111#if __has_builtin(__builtin_dynamic_object_size)
3112 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3113 return {__ptr, __bytes / sizeof(_CharT)};
3115 // Avoid forming a pointer to a different memory page.
3116 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3117 __n = (1024 - __off) / sizeof(_CharT);
3118 if (__n > 0) [[likely]]
3119 return {__ptr, static_cast<size_t>(__n)};
3120 else // Misaligned/packed buffer of wchar_t?
3126 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3127 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3128 _M_first(__out), _M_max(__n)
3131 format_to_n_result<_OutIter>
3134 auto __s = this->_M_used();
3135 if (__s.data() == _M_buf)
3137 // Switched to internal buffer, so must have written _M_max.
3138 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3139 return { _M_first + _M_max, __count };
3141 else // Not using internal buffer yet
3143 iter_difference_t<_OutIter> __count(__s.size());
3144 return { _M_first + __count, __count };
3149 enum _Arg_t : unsigned char {
3150 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3151 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3152 _Arg_i128, _Arg_u128,
3153 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3154#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3156 _Arg_f128 = _Arg_ldbl,
3157 _Arg_ibm128 = _Arg_next_value_,
3164 template<typename _Context>
3167 using _CharT = typename _Context::char_type;
3183 unsigned long long _M_ull;
3186#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3187 long double _M_ldbl;
3189 const _CharT* _M_str;
3190 basic_string_view<_CharT> _M_sv;
3192 _HandleBase _M_handle;
3193#ifdef __SIZEOF_INT128__
3195 unsigned __int128 _M_u128;
3197#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3200#elif _GLIBCXX_FORMAT_F128 == 2
3201 __float128_t _M_f128;
3205 [[__gnu__::__always_inline__]]
3206 _Arg_value() : _M_none() { }
3209 template<typename _Tp>
3210 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3211 { _S_get<_Tp>() = __val; }
3214 template<typename _Tp, typename _Self>
3215 [[__gnu__::__always_inline__]]
3217 _S_get(_Self& __u) noexcept
3219 if constexpr (is_same_v<_Tp, bool>)
3221 else if constexpr (is_same_v<_Tp, _CharT>)
3223 else if constexpr (is_same_v<_Tp, int>)
3225 else if constexpr (is_same_v<_Tp, unsigned>)
3227 else if constexpr (is_same_v<_Tp, long long>)
3229 else if constexpr (is_same_v<_Tp, unsigned long long>)
3231 else if constexpr (is_same_v<_Tp, float>)
3233 else if constexpr (is_same_v<_Tp, double>)
3235#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3236 else if constexpr (is_same_v<_Tp, long double>)
3239 else if constexpr (is_same_v<_Tp, __ieee128>)
3241 else if constexpr (is_same_v<_Tp, __ibm128>)
3242 return __u._M_ibm128;
3244 else if constexpr (is_same_v<_Tp, const _CharT*>)
3246 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3248 else if constexpr (is_same_v<_Tp, const void*>)
3250#ifdef __SIZEOF_INT128__
3251 else if constexpr (is_same_v<_Tp, __int128>)
3253 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3256#if _GLIBCXX_FORMAT_F128 == 2
3257 else if constexpr (is_same_v<_Tp, __float128_t>)
3260 else if constexpr (derived_from<_Tp, _HandleBase>)
3261 return static_cast<_Tp&>(__u._M_handle);
3262 // Otherwise, ill-formed.
3265 template<typename _Tp>
3266 [[__gnu__::__always_inline__]]
3269 { return _S_get<_Tp>(*this); }
3271 template<typename _Tp>
3272 [[__gnu__::__always_inline__]]
3274 _M_get() const noexcept
3275 { return _S_get<_Tp>(*this); }
3277 template<typename _Tp>
3278 [[__gnu__::__always_inline__]]
3280 _M_set(_Tp __v) noexcept
3282 if constexpr (derived_from<_Tp, _HandleBase>)
3283 std::construct_at(&_M_handle, __v);
3285 _S_get<_Tp>(*this) = __v;
3289 // [format.arg.store], class template format-arg-store
3290 template<typename _Context, typename... _Args>
3293 template<typename _Ch, typename _Tp>
3295 __to_arg_t_enum() noexcept;
3297} // namespace __format
3300 template<typename _Context>
3301 class basic_format_arg
3303 using _CharT = typename _Context::char_type;
3305 template<typename _Tp>
3306 static constexpr bool __formattable
3307 = __format::__formattable_with<_Tp, _Context>;
3310 class handle : public __format::_Arg_value<_Context>::_HandleBase
3312 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3314 // Format as const if possible, to reduce instantiations.
3315 template<typename _Tp>
3316 using __maybe_const_t
3317 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3319 template<typename _Tq>
3321 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3322 _Context& __format_ctx, const void* __ptr)
3324 using _Td = remove_const_t<_Tq>;
3325 typename _Context::template formatter_type<_Td> __f;
3326 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3327 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3328 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3331 template<typename _Tp>
3333 handle(_Tp& __val) noexcept
3335 this->_M_ptr = __builtin_addressof(__val);
3336 auto __func = _S_format<__maybe_const_t<_Tp>>;
3337 this->_M_func = reinterpret_cast<void(*)()>(__func);
3340 friend class basic_format_arg<_Context>;
3343 handle(const handle&) = default;
3344 handle& operator=(const handle&) = default;
3346 [[__gnu__::__always_inline__]]
3348 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3350 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3351 _Context&, const void*);
3352 auto __f = reinterpret_cast<_Func>(this->_M_func);
3353 __f(__pc, __fc, this->_M_ptr);
3357 [[__gnu__::__always_inline__]]
3358 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3360 [[nodiscard,__gnu__::__always_inline__]]
3361 explicit operator bool() const noexcept
3362 { return _M_type != __format::_Arg_none; }
3364#if __cpp_lib_format >= 202306L // >= C++26
3365 template<typename _Visitor>
3367 visit(this basic_format_arg __arg, _Visitor&& __vis)
3368 { return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type); }
3370 template<typename _Res, typename _Visitor>
3372 visit(this basic_format_arg __arg, _Visitor&& __vis)
3373 { return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type); }
3377 template<typename _Ctx>
3378 friend class basic_format_args;
3380 template<typename _Ctx, typename... _Args>
3381 friend class __format::_Arg_store;
3383 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3385 __format::_Arg_value<_Context> _M_val;
3386 __format::_Arg_t _M_type;
3388 // Transform incoming argument type to the type stored in _Arg_value.
3389 // e.g. short -> int, std::string -> std::string_view,
3390 // char[3] -> const char*.
3391 template<typename _Tp>
3392 static consteval auto
3395 using _Td = remove_const_t<_Tp>;
3396 if constexpr (is_same_v<_Td, bool>)
3397 return type_identity<bool>();
3398 else if constexpr (is_same_v<_Td, _CharT>)
3399 return type_identity<_CharT>();
3400 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3401 return type_identity<_CharT>();
3402#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3403 else if constexpr (is_same_v<_Td, __int128>)
3404 return type_identity<__int128>();
3405 else if constexpr (is_same_v<_Td, unsigned __int128>)
3406 return type_identity<unsigned __int128>();
3408 else if constexpr (__is_signed_integer<_Td>::value)
3410 if constexpr (sizeof(_Td) <= sizeof(int))
3411 return type_identity<int>();
3412 else if constexpr (sizeof(_Td) <= sizeof(long long))
3413 return type_identity<long long>();
3415 else if constexpr (__is_unsigned_integer<_Td>::value)
3417 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3418 return type_identity<unsigned>();
3419 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3420 return type_identity<unsigned long long>();
3422 else if constexpr (is_same_v<_Td, float>)
3423 return type_identity<float>();
3424 else if constexpr (is_same_v<_Td, double>)
3425 return type_identity<double>();
3426#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3427 else if constexpr (is_same_v<_Td, long double>)
3428 return type_identity<long double>();
3430 else if constexpr (is_same_v<_Td, __ibm128>)
3431 return type_identity<__ibm128>();
3432 else if constexpr (is_same_v<_Td, __ieee128>)
3433 return type_identity<__ieee128>();
3436#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3437 else if constexpr (is_same_v<_Td, _Float16>)
3438 return type_identity<float>();
3441#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3442 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3443 return type_identity<float>();
3447 else if constexpr (is_same_v<_Td, _Float32>)
3448# ifdef _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3449 return type_identity<float>();
3451 return type_identity<_Float32>();
3455 else if constexpr (is_same_v<_Td, _Float64>)
3456# ifdef _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3457 return type_identity<double>();
3459 return type_identity<_Float64>();
3462#if _GLIBCXX_FORMAT_F128
3464 else if constexpr (is_same_v<_Td, _Float128>)
3465 return type_identity<__format::__float128_t>();
3467# if __SIZEOF_FLOAT128__
3468 else if constexpr (is_same_v<_Td, __float128>)
3469 return type_identity<__format::__float128_t>();
3472 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3473 || __is_specialization_of<_Td, basic_string>)
3475 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3476 return type_identity<basic_string_view<_CharT>>();
3478 return type_identity<handle>();
3480 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3481 return type_identity<const _CharT*>();
3482 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3483 return type_identity<const _CharT*>();
3484 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3485 return type_identity<const void*>();
3486 else if constexpr (is_same_v<_Td, nullptr_t>)
3487 return type_identity<const void*>();
3489 return type_identity<handle>();
3492 // Transform a formattable type to the appropriate storage type.
3493 template<typename _Tp>
3494 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3496 // Get the _Arg_t value corresponding to a normalized type.
3497 template<typename _Tp>
3498 static consteval __format::_Arg_t
3501 using namespace __format;
3502 if constexpr (is_same_v<_Tp, bool>)
3504 else if constexpr (is_same_v<_Tp, _CharT>)
3506 else if constexpr (is_same_v<_Tp, int>)
3508 else if constexpr (is_same_v<_Tp, unsigned>)
3510 else if constexpr (is_same_v<_Tp, long long>)
3512 else if constexpr (is_same_v<_Tp, unsigned long long>)
3514 else if constexpr (is_same_v<_Tp, float>)
3516 else if constexpr (is_same_v<_Tp, double>)
3518#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3519 else if constexpr (is_same_v<_Tp, long double>)
3522 // Don't use _Arg_ldbl for this target, it's ambiguous.
3523 else if constexpr (is_same_v<_Tp, __ibm128>)
3525 else if constexpr (is_same_v<_Tp, __ieee128>)
3528 else if constexpr (is_same_v<_Tp, const _CharT*>)
3530 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3532 else if constexpr (is_same_v<_Tp, const void*>)
3534#ifdef __SIZEOF_INT128__
3535 else if constexpr (is_same_v<_Tp, __int128>)
3537 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3541 // N.B. some of these types will never actually be used here,
3542 // because they get normalized to a standard floating-point type.
3543#if defined __FLT32_DIG__ && ! _GLIBCXX_FLOAT_IS_IEEE_BINARY32
3544 else if constexpr (is_same_v<_Tp, _Float32>)
3547#if defined __FLT64_DIG__ && ! _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
3548 else if constexpr (is_same_v<_Tp, _Float64>)
3551#if _GLIBCXX_FORMAT_F128 == 2
3552 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3555 else if constexpr (is_same_v<_Tp, handle>)
3559 template<typename _Tp>
3561 _M_set(_Tp __v) noexcept
3563 _M_type = _S_to_enum<_Tp>();
3567 template<typename _Tp>
3568 requires __format::__formattable_with<_Tp, _Context>
3570 basic_format_arg(_Tp& __v) noexcept
3572 using _Td = _Normalize<_Tp>;
3573 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3574 _M_set(_Td{__v.data(), __v.size()});
3575 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3576 && is_same_v<_CharT, wchar_t>)
3577 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3579 _M_set(static_cast<_Td>(__v));
3582 template<typename _Ctx, typename... _Argz>
3584 make_format_args(_Argz&...) noexcept;
3586 template<typename _Visitor, typename _Ctx>
3587 friend decltype(auto)
3588 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3590 template<typename _Ch, typename _Tp>
3591 friend consteval __format::_Arg_t
3592 __format::__to_arg_t_enum() noexcept;
3594 template<typename _Visitor>
3596 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
3598 using namespace __format;
3602 return std::forward<_Visitor>(__vis)(_M_val._M_none);
3604 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
3606 return std::forward<_Visitor>(__vis)(_M_val._M_c);
3608 return std::forward<_Visitor>(__vis)(_M_val._M_i);
3610 return std::forward<_Visitor>(__vis)(_M_val._M_u);
3612 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
3614 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
3615#if __glibcxx_to_chars // FIXME: need to be able to format these types!
3617 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
3619 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
3620#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3622 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
3625 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3627 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
3631 return std::forward<_Visitor>(__vis)(_M_val._M_str);
3633 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
3635 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
3638 auto& __h = static_cast<handle&>(_M_val._M_handle);
3639 return std::forward<_Visitor>(__vis)(__h);
3641#ifdef __SIZEOF_INT128__
3643 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
3645 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
3648#if _GLIBCXX_FORMAT_F128 == 2
3650 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3655 __builtin_unreachable();
3660 template<typename _Visitor, typename _Context>
3661 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
3662 inline decltype(auto)
3663 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
3665 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
3668/// @cond undocumented
3671 struct _WidthPrecVisitor
3673 template<typename _Tp>
3675 operator()(_Tp& __arg) const
3677 if constexpr (is_same_v<_Tp, monostate>)
3678 __format::__invalid_arg_id_in_format_string();
3679 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3680 // 3720. Restrict the valid types of arg-id for width and precision
3681 // 3721. Allow an arg-id with a value of zero for width
3682 else if constexpr (sizeof(_Tp) <= sizeof(long long))
3684 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3685 // 3720. Restrict the valid types of arg-id for width and precision
3686 if constexpr (__is_unsigned_integer<_Tp>::value)
3688 else if constexpr (__is_signed_integer<_Tp>::value)
3692 __throw_format_error("format error: argument used for width or "
3693 "precision must be a non-negative integer");
3697#pragma GCC diagnostic push
3698#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
3699 template<typename _Context>
3701 __int_from_arg(const basic_format_arg<_Context>& __arg)
3702 { return std::visit_format_arg(_WidthPrecVisitor(), __arg); }
3704 // Pack _Arg_t enum values into a single 60-bit integer.
3705 template<int _Bits, size_t _Nm>
3707 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
3709 __UINT64_TYPE__ __packed_types = 0;
3710 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
3711 __packed_types = (__packed_types << _Bits) | *__i;
3712 return __packed_types;
3714} // namespace __format
3717 template<typename _Context>
3718 class basic_format_args
3720 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
3721 static constexpr int _S_packed_type_mask = 0b11111;
3722 static constexpr int _S_max_packed_args = 12;
3724 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
3726 template<typename... _Args>
3727 using _Store = __format::_Arg_store<_Context, _Args...>;
3729 template<typename _Ctx, typename... _Args>
3730 friend class __format::_Arg_store;
3732 using uint64_t = __UINT64_TYPE__;
3733 using _Format_arg = basic_format_arg<_Context>;
3734 using _Format_arg_val = __format::_Arg_value<_Context>;
3736 // If args are packed then the number of args is in _M_packed_size and
3737 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
3738 // If args are not packed then the number of args is in _M_unpacked_size
3739 // and _M_packed_size is zero.
3740 uint64_t _M_packed_size : 4;
3741 uint64_t _M_unpacked_size : 60;
3744 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
3745 const _Format_arg* _M_args; // Active when _M_packed_size == 0
3749 _M_size() const noexcept
3750 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
3752 typename __format::_Arg_t
3753 _M_type(size_t __i) const noexcept
3755 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
3756 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
3759 template<typename _Ctx, typename... _Args>
3761 make_format_args(_Args&...) noexcept;
3763 // An array of _Arg_t enums corresponding to _Args...
3764 template<typename... _Args>
3765 static consteval array<__format::_Arg_t, sizeof...(_Args)>
3767 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
3770 template<typename... _Args>
3771 basic_format_args(const _Store<_Args...>& __store) noexcept;
3773 [[nodiscard,__gnu__::__always_inline__]]
3774 basic_format_arg<_Context>
3775 get(size_t __i) const noexcept
3777 basic_format_arg<_Context> __arg;
3778 if (__i < _M_packed_size)
3780 __arg._M_type = _M_type(__i);
3781 __arg._M_val = _M_values[__i];
3783 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
3784 __arg = _M_args[__i];
3789 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3790 // 3810. CTAD for std::basic_format_args
3791 template<typename _Context, typename... _Args>
3792 basic_format_args(__format::_Arg_store<_Context, _Args...>)
3793 -> basic_format_args<_Context>;
3795 template<typename _Context, typename... _Args>
3797 make_format_args(_Args&... __fmt_args) noexcept;
3799 // An array of type-erased formatting arguments.
3800 template<typename _Context, typename... _Args>
3801 class __format::_Arg_store
3803 friend std::basic_format_args<_Context>;
3805 template<typename _Ctx, typename... _Argz>
3807#if _GLIBCXX_INLINE_VERSION
3808 __8:: // Needed for PR c++/59256
3810 make_format_args(_Argz&...) noexcept;
3812 // For a sufficiently small number of arguments we only store values.
3813 // basic_format_args can get the types from the _Args pack.
3814 static constexpr bool _S_values_only
3815 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
3818 = __conditional_t<_S_values_only,
3819 __format::_Arg_value<_Context>,
3820 basic_format_arg<_Context>>;
3822 _Element_t _M_args[sizeof...(_Args)];
3824 template<typename _Tp>
3826 _S_make_elt(_Tp& __v)
3828 using _Tq = remove_const_t<_Tp>;
3829 using _CharT = typename _Context::char_type;
3830 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
3831 "std::formatter must be specialized for the type "
3832 "of each format arg");
3833 using __format::__formattable_with;
3834 if constexpr (is_const_v<_Tp>)
3835 if constexpr (!__formattable_with<_Tp, _Context>)
3836 if constexpr (__formattable_with<_Tq, _Context>)
3837 static_assert(__formattable_with<_Tp, _Context>,
3838 "format arg must be non-const because its "
3839 "std::formatter specialization has a "
3840 "non-const reference parameter");
3841 basic_format_arg<_Context> __arg(__v);
3842 if constexpr (_S_values_only)
3843 return __arg._M_val;
3848 template<typename... _Tp>
3849 requires (sizeof...(_Tp) == sizeof...(_Args))
3850 [[__gnu__::__always_inline__]]
3851 _Arg_store(_Tp&... __a) noexcept
3852 : _M_args{_S_make_elt(__a)...}
3856 template<typename _Context>
3857 class __format::_Arg_store<_Context>
3860 template<typename _Context>
3861 template<typename... _Args>
3863 basic_format_args<_Context>::
3864 basic_format_args(const _Store<_Args...>& __store) noexcept
3866 if constexpr (sizeof...(_Args) == 0)
3869 _M_unpacked_size = 0;
3872 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
3874 // The number of packed arguments:
3875 _M_packed_size = sizeof...(_Args);
3876 // The packed type enums:
3878 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
3879 // The _Arg_value objects.
3880 _M_values = __store._M_args;
3884 // No packed arguments:
3886 // The number of unpacked arguments:
3887 _M_unpacked_size = sizeof...(_Args);
3888 // The basic_format_arg objects:
3889 _M_args = __store._M_args;
3893 /// Capture formatting arguments for use by `std::vformat`.
3894 template<typename _Context = format_context, typename... _Args>
3895 [[nodiscard,__gnu__::__always_inline__]]
3897 make_format_args(_Args&... __fmt_args) noexcept
3899 using _Fmt_arg = basic_format_arg<_Context>;
3900 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
3901 _Normalize<_Args>...>;
3902 return _Store(__fmt_args...);
3905#ifdef _GLIBCXX_USE_WCHAR_T
3906 /// Capture formatting arguments for use by `std::vformat` (for wide output).
3907 template<typename... _Args>
3908 [[nodiscard,__gnu__::__always_inline__]]
3910 make_wformat_args(_Args&... __args) noexcept
3911 { return std::make_format_args<wformat_context>(__args...); }
3914/// @cond undocumented
3917 template<typename _Out, typename _CharT, typename _Context>
3919 __do_vformat_to(_Out, basic_string_view<_CharT>,
3920 const basic_format_args<_Context>&,
3921 const locale* = nullptr);
3923 template<typename _CharT> struct __formatter_chrono;
3925} // namespace __format
3928 /** Context for std::format and similar functions.
3930 * A formatting context contains an output iterator and locale to use
3931 * for the formatting operations. Most programs will never need to use
3932 * this class template explicitly. For typical uses of `std::format` the
3933 * library will use the specializations `std::format_context` (for `char`)
3934 * and `std::wformat_context` (for `wchar_t`).
3936 * You are not allowed to define partial or explicit specializations of
3937 * this class template.
3941 template<typename _Out, typename _CharT>
3942 class basic_format_context
3944 static_assert( output_iterator<_Out, const _CharT&> );
3946 basic_format_args<basic_format_context> _M_args;
3948 __format::_Optional_locale _M_loc;
3950 basic_format_context(basic_format_args<basic_format_context> __args,
3952 : _M_args(__args), _M_out(std::move(__out))
3955 basic_format_context(basic_format_args<basic_format_context> __args,
3956 _Out __out, const std::locale& __loc)
3957 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
3960 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3961 // 4061. Should std::basic_format_context be
3962 // default-constructible/copyable/movable?
3963 basic_format_context(const basic_format_context&) = delete;
3964 basic_format_context& operator=(const basic_format_context&) = delete;
3966 template<typename _Out2, typename _CharT2, typename _Context2>
3968 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
3969 const basic_format_args<_Context2>&,
3972 friend __format::__formatter_chrono<_CharT>;
3975 ~basic_format_context() = default;
3977 using iterator = _Out;
3978 using char_type = _CharT;
3979 template<typename _Tp>
3980 using formatter_type = formatter<_Tp, _CharT>;
3983 basic_format_arg<basic_format_context>
3984 arg(size_t __id) const noexcept
3985 { return _M_args.get(__id); }
3988 std::locale locale() { return _M_loc.value(); }
3991 iterator out() { return std::move(_M_out); }
3993 void advance_to(iterator __it) { _M_out = std::move(__it); }
3997/// @cond undocumented
4000 // Abstract base class defining an interface for scanning format strings.
4001 // Scan the characters in a format string, dividing it up into strings of
4002 // ordinary characters, escape sequences, and replacement fields.
4003 // Call virtual functions for derived classes to parse format-specifiers
4004 // or write formatted output.
4005 template<typename _CharT>
4008 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4010 struct _Parse_context : basic_format_parse_context<_CharT>
4012 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4013 const _Arg_t* _M_types = nullptr;
4017 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = -1)
4018 : _M_pc(__str, __nargs)
4021 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4022 constexpr iterator end() const noexcept { return _M_pc.end(); }
4027 basic_string_view<_CharT> __fmt = _M_fmt_str();
4029 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4031 _M_pc.advance_to(begin() + 1);
4032 _M_format_arg(_M_pc.next_arg_id());
4036 size_t __lbr = __fmt.find('{');
4037 size_t __rbr = __fmt.find('}');
4039 while (__fmt.size())
4041 auto __cmp = __lbr <=> __rbr;
4045 _M_pc.advance_to(end());
4050 if (__lbr + 1 == __fmt.size()
4051 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4052 __format::__unmatched_left_brace_in_format_string();
4053 const bool __is_escape = __fmt[__lbr + 1] == '{';
4054 iterator __last = begin() + __lbr + int(__is_escape);
4055 _M_on_chars(__last);
4056 _M_pc.advance_to(__last + 1);
4057 __fmt = _M_fmt_str();
4060 if (__rbr != __fmt.npos)
4062 __lbr = __fmt.find('{');
4066 _M_on_replacement_field();
4067 __fmt = _M_fmt_str();
4068 __lbr = __fmt.find('{');
4069 __rbr = __fmt.find('}');
4074 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4075 __format::__unmatched_right_brace_in_format_string();
4076 iterator __last = begin() + __rbr;
4077 _M_on_chars(__last);
4078 _M_pc.advance_to(__last + 1);
4079 __fmt = _M_fmt_str();
4080 if (__lbr != __fmt.npos)
4082 __rbr = __fmt.find('}');
4087 constexpr basic_string_view<_CharT>
4088 _M_fmt_str() const noexcept
4089 { return {begin(), end()}; }
4091 constexpr virtual void _M_on_chars(iterator) { }
4093 constexpr void _M_on_replacement_field()
4095 auto __next = begin();
4099 __id = _M_pc.next_arg_id();
4100 else if (*__next == ':')
4102 __id = _M_pc.next_arg_id();
4103 _M_pc.advance_to(++__next);
4107 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4108 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4109 __format::__invalid_arg_id_in_format_string();
4110 _M_pc.check_arg_id(__id = __i);
4113 _M_pc.advance_to(++__ptr);
4116 _M_pc.advance_to(__ptr);
4118 _M_format_arg(__id);
4119 if (begin() == end() || *begin() != '}')
4120 __format::__unmatched_left_brace_in_format_string();
4121 _M_pc.advance_to(begin() + 1); // Move past '}'
4124 constexpr virtual void _M_format_arg(size_t __id) = 0;
4127 // Process a format string and format the arguments in the context.
4128 template<typename _Out, typename _CharT>
4129 class _Formatting_scanner : public _Scanner<_CharT>
4132 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4133 basic_string_view<_CharT> __str)
4134 : _Scanner<_CharT>(__str), _M_fc(__fc)
4138 basic_format_context<_Out, _CharT>& _M_fc;
4140 using iterator = typename _Scanner<_CharT>::iterator;
4143 _M_on_chars(iterator __last) override
4145 basic_string_view<_CharT> __str(this->begin(), __last);
4146 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4150 _M_format_arg(size_t __id) override
4152 using _Context = basic_format_context<_Out, _CharT>;
4153 using handle = typename basic_format_arg<_Context>::handle;
4155 std::visit_format_arg([this](auto& __arg) {
4156 using _Type = remove_reference_t<decltype(__arg)>;
4157 using _Formatter = typename _Context::template formatter_type<_Type>;
4158 if constexpr (is_same_v<_Type, monostate>)
4159 __format::__invalid_arg_id_in_format_string();
4160 else if constexpr (is_same_v<_Type, handle>)
4161 __arg.format(this->_M_pc, this->_M_fc);
4162 else if constexpr (is_default_constructible_v<_Formatter>)
4165 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4166 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4169 static_assert(__format::__formattable_with<_Type, _Context>);
4170 }, _M_fc.arg(__id));
4174 template<typename _CharT, typename _Tp>
4176 __to_arg_t_enum() noexcept
4178 using _Context = __format::__format_context<_CharT>;
4179 using _Fmt_arg = basic_format_arg<_Context>;
4180 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4181 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4184 // Validate a format string for Args.
4185 template<typename _CharT, typename... _Args>
4186 class _Checking_scanner : public _Scanner<_CharT>
4189 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4190 "std::formatter must be specialized for each type being formatted");
4194 _Checking_scanner(basic_string_view<_CharT> __str)
4195 : _Scanner<_CharT>(__str, sizeof...(_Args))
4197#if __cpp_lib_format >= 202305L
4198 this->_M_pc._M_types = _M_types.data();
4204 _M_format_arg(size_t __id) override
4206 if constexpr (sizeof...(_Args) != 0)
4208 if (__id < sizeof...(_Args))
4210 _M_parse_format_spec<_Args...>(__id);
4214 __builtin_unreachable();
4217 template<typename _Tp, typename... _OtherArgs>
4219 _M_parse_format_spec(size_t __id)
4223 formatter<_Tp, _CharT> __f;
4224 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4226 else if constexpr (sizeof...(_OtherArgs) != 0)
4227 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4229 __builtin_unreachable();
4232#if __cpp_lib_format >= 202305L
4233 array<_Arg_t, sizeof...(_Args)>
4234 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
4238 template<typename _Out, typename _CharT, typename _Context>
4240 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4241 const basic_format_args<_Context>& __args,
4242 const locale* __loc)
4244 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4245 _Sink_iter<_CharT> __sink_out;
4247 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4248 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4250 __sink_out = __sink.out();
4252 if constexpr (is_same_v<_CharT, char>)
4253 // Fast path for "{}" format strings and simple format arg types.
4254 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4256 bool __done = false;
4257 std::visit_format_arg([&](auto& __arg) {
4258 using _Tp = remove_cvref_t<decltype(__arg)>;
4259 if constexpr (is_same_v<_Tp, bool>)
4261 size_t __len = 4 + !__arg;
4262 const char* __chars[] = { "false", "true" };
4263 if (auto __res = __sink_out._M_reserve(__len))
4265 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4266 __res._M_bump(__len);
4270 else if constexpr (is_same_v<_Tp, char>)
4272 if (auto __res = __sink_out._M_reserve(1))
4274 *__res.get() = __arg;
4279 else if constexpr (is_integral_v<_Tp>)
4281 make_unsigned_t<_Tp> __uval;
4282 const bool __neg = __arg < 0;
4284 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4287 const auto __n = __detail::__to_chars_len(__uval);
4288 if (auto __res = __sink_out._M_reserve(__n + __neg))
4290 auto __ptr = __res.get();
4292 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4294 __res._M_bump(__n + __neg);
4298 else if constexpr (is_convertible_v<_Tp, string_view>)
4300 string_view __sv = __arg;
4301 if (auto __res = __sink_out._M_reserve(__sv.size()))
4303 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4304 __res._M_bump(__sv.size());
4312 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4315 return std::move(__sink)._M_finish().out;
4319 auto __ctx = __loc == nullptr
4320 ? _Context(__args, __sink_out)
4321 : _Context(__args, __sink_out, *__loc);
4322 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4323 __scanner._M_scan();
4325 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4328 return std::move(__sink)._M_finish().out;
4330#pragma GCC diagnostic pop
4332} // namespace __format
4335#if __cpp_lib_format >= 202305L
4336 template<typename _CharT>
4337 template<typename... _Ts>
4339 basic_format_parse_context<_CharT>::check_dynamic_spec(size_t __id) noexcept
4341 // This call enforces the Mandates: condition that _Ts contains valid
4342 // types and each type appears at most once. It could be a static_assert
4343 // but this way failures give better diagnostics, due to calling the
4344 // non-constexpr __invalid_dynamic_spec function.
4346 constexpr bool __ok = __check_dynamic_spec_types<_Ts...>();
4349 if (__id >= _M_num_args)
4350 __format::__invalid_arg_id_in_format_string();
4351 if constexpr (sizeof...(_Ts) != 0)
4353 using _Parse_context = __format::_Scanner<_CharT>::_Parse_context;
4354 auto __arg = static_cast<_Parse_context*>(this)->_M_types[__id];
4355 __format::_Arg_t __types[] = {
4356 __format::__to_arg_t_enum<_CharT, _Ts>()...
4358 for (auto __t : __types)
4362 __invalid_dynamic_spec("arg(id) type does not match");
4367 template<typename _CharT, typename... _Args>
4368 template<typename _Tp>
4369 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4371 basic_format_string<_CharT, _Args...>::
4372 basic_format_string(const _Tp& __s)
4375 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4377 __scanner._M_scan();
4380 // [format.functions], formatting functions
4382 template<typename _Out> requires output_iterator<_Out, const char&>
4383 [[__gnu__::__always_inline__]]
4385 vformat_to(_Out __out, string_view __fmt, format_args __args)
4386 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4388#ifdef _GLIBCXX_USE_WCHAR_T
4389 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4390 [[__gnu__::__always_inline__]]
4392 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4393 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4396 template<typename _Out> requires output_iterator<_Out, const char&>
4397 [[__gnu__::__always_inline__]]
4399 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4402 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4405#ifdef _GLIBCXX_USE_WCHAR_T
4406 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4407 [[__gnu__::__always_inline__]]
4409 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4410 wformat_args __args)
4412 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4418 vformat(string_view __fmt, format_args __args)
4420 __format::_Str_sink<char> __buf;
4421 std::vformat_to(__buf.out(), __fmt, __args);
4422 return std::move(__buf).get();
4425#ifdef _GLIBCXX_USE_WCHAR_T
4428 vformat(wstring_view __fmt, wformat_args __args)
4430 __format::_Str_sink<wchar_t> __buf;
4431 std::vformat_to(__buf.out(), __fmt, __args);
4432 return std::move(__buf).get();
4438 vformat(const locale& __loc, string_view __fmt, format_args __args)
4440 __format::_Str_sink<char> __buf;
4441 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4442 return std::move(__buf).get();
4445#ifdef _GLIBCXX_USE_WCHAR_T
4448 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4450 __format::_Str_sink<wchar_t> __buf;
4451 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4452 return std::move(__buf).get();
4456 template<typename... _Args>
4459 format(format_string<_Args...> __fmt, _Args&&... __args)
4460 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4462#ifdef _GLIBCXX_USE_WCHAR_T
4463 template<typename... _Args>
4466 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4467 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4470 template<typename... _Args>
4473 format(const locale& __loc, format_string<_Args...> __fmt,
4476 return std::vformat(__loc, __fmt.get(),
4477 std::make_format_args(__args...));
4480#ifdef _GLIBCXX_USE_WCHAR_T
4481 template<typename... _Args>
4484 format(const locale& __loc, wformat_string<_Args...> __fmt,
4487 return std::vformat(__loc, __fmt.get(),
4488 std::make_wformat_args(__args...));
4492 template<typename _Out, typename... _Args>
4493 requires output_iterator<_Out, const char&>
4495 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4497 return std::vformat_to(std::move(__out), __fmt.get(),
4498 std::make_format_args(__args...));
4501#ifdef _GLIBCXX_USE_WCHAR_T
4502 template<typename _Out, typename... _Args>
4503 requires output_iterator<_Out, const wchar_t&>
4505 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4507 return std::vformat_to(std::move(__out), __fmt.get(),
4508 std::make_wformat_args(__args...));
4512 template<typename _Out, typename... _Args>
4513 requires output_iterator<_Out, const char&>
4515 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4518 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4519 std::make_format_args(__args...));
4522#ifdef _GLIBCXX_USE_WCHAR_T
4523 template<typename _Out, typename... _Args>
4524 requires output_iterator<_Out, const wchar_t&>
4526 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4529 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4530 std::make_wformat_args(__args...));
4534 template<typename _Out, typename... _Args>
4535 requires output_iterator<_Out, const char&>
4536 inline format_to_n_result<_Out>
4537 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4538 format_string<_Args...> __fmt, _Args&&... __args)
4540 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4541 std::vformat_to(__sink.out(), __fmt.get(),
4542 std::make_format_args(__args...));
4543 return std::move(__sink)._M_finish();
4546#ifdef _GLIBCXX_USE_WCHAR_T
4547 template<typename _Out, typename... _Args>
4548 requires output_iterator<_Out, const wchar_t&>
4549 inline format_to_n_result<_Out>
4550 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4551 wformat_string<_Args...> __fmt, _Args&&... __args)
4553 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4554 std::vformat_to(__sink.out(), __fmt.get(),
4555 std::make_wformat_args(__args...));
4556 return std::move(__sink)._M_finish();
4560 template<typename _Out, typename... _Args>
4561 requires output_iterator<_Out, const char&>
4562 inline format_to_n_result<_Out>
4563 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4564 format_string<_Args...> __fmt, _Args&&... __args)
4566 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4567 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4568 std::make_format_args(__args...));
4569 return std::move(__sink)._M_finish();
4572#ifdef _GLIBCXX_USE_WCHAR_T
4573 template<typename _Out, typename... _Args>
4574 requires output_iterator<_Out, const wchar_t&>
4575 inline format_to_n_result<_Out>
4576 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4577 wformat_string<_Args...> __fmt, _Args&&... __args)
4579 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4580 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4581 std::make_wformat_args(__args...));
4582 return std::move(__sink)._M_finish();
4586/// @cond undocumented
4590 template<typename _CharT>
4591 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
4594 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
4596 [[__gnu__::__always_inline__]]
4599 { return this->_M_count + this->_M_used().size(); }
4602 template<typename _CharT>
4603 class _Counting_sink : public _Buf_sink<_CharT>
4605 size_t _M_count = 0;
4608 _M_overflow() override
4610 if (!std::is_constant_evaluated())
4611 _M_count += this->_M_used().size();
4616 _Counting_sink() = default;
4618 [[__gnu__::__always_inline__]]
4622 _Counting_sink::_M_overflow();
4627} // namespace __format
4630 template<typename... _Args>
4633 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
4635 __format::_Counting_sink<char> __buf;
4636 std::vformat_to(__buf.out(), __fmt.get(),
4637 std::make_format_args(__args...));
4638 return __buf.count();
4641#ifdef _GLIBCXX_USE_WCHAR_T
4642 template<typename... _Args>
4645 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
4647 __format::_Counting_sink<wchar_t> __buf;
4648 std::vformat_to(__buf.out(), __fmt.get(),
4649 std::make_wformat_args(__args...));
4650 return __buf.count();
4654 template<typename... _Args>
4657 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
4660 __format::_Counting_sink<char> __buf;
4661 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4662 std::make_format_args(__args...));
4663 return __buf.count();
4666#ifdef _GLIBCXX_USE_WCHAR_T
4667 template<typename... _Args>
4670 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
4673 __format::_Counting_sink<wchar_t> __buf;
4674 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4675 std::make_wformat_args(__args...));
4676 return __buf.count();
4680#if __cpp_lib_format_ranges
4681 // [format.range], formatting of ranges
4682 // [format.range.fmtkind], variable template format_kind
4683 enum class range_format {
4692 /// @cond undocumented
4693 template<typename _Rg>
4694 constexpr auto format_kind = not defined(format_kind<_Rg>);
4696 template<typename _Tp>
4697 consteval range_format
4700 using _Ref = ranges::range_reference_t<_Tp>;
4701 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
4702 return range_format::disabled;
4703 else if constexpr (requires { typename _Tp::key_type; })
4705 if constexpr (requires { typename _Tp::mapped_type; })
4707 using _Up = remove_cvref_t<_Ref>;
4708 if constexpr (__is_pair<_Up>)
4709 return range_format::map;
4710 else if constexpr (__is_specialization_of<_Up, tuple>)
4711 if constexpr (tuple_size_v<_Up> == 2)
4712 return range_format::map;
4714 return range_format::set;
4717 return range_format::sequence;
4721 /// A constant determining how a range should be formatted.
4722 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
4723 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
4725 // [format.range.formatter], class template range_formatter
4726 template<typename _Tp, typename _CharT = char>
4727 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
4728 class range_formatter; // TODO
4730/// @cond undocumented
4733 // [format.range.fmtdef], class template range-default-formatter
4734 template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
4735 struct __range_default_formatter; // TODO
4736} // namespace __format
4739 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
4740 // specializations for maps, sets, and strings
4741 template<ranges::input_range _Rg, typename _CharT>
4742 requires (format_kind<_Rg> != range_format::disabled)
4743 && formattable<ranges::range_reference_t<_Rg>, _CharT>
4744 struct formatter<_Rg, _CharT>
4745 : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
4747#endif // C++23 formatting ranges
4749_GLIBCXX_END_NAMESPACE_VERSION
4751#endif // __cpp_lib_format
4752#pragma GCC diagnostic pop
4753#endif // _GLIBCXX_FORMAT