1// <format> Formatting -*- C++ -*-
3// Copyright The GNU Toolchain Authors.
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
25/** @file include/format
26 * This is a Standard C++ Library header.
29#ifndef _GLIBCXX_FORMAT
30#define _GLIBCXX_FORMAT 1
32#pragma GCC system_header
34#include <bits/requires_hosted.h> // for std::string
36#define __glibcxx_want_format
37#define __glibcxx_want_format_ranges
38#define __glibcxx_want_format_uchar
39#include <bits/version.h>
41#ifdef __cpp_lib_format // C++ >= 20 && HOSTED
52#include <variant> // monostate (TODO: move to bits/utility.h?)
53#include <bits/ranges_base.h> // input_range, range_reference_t
54#include <bits/ranges_util.h> // subrange
55#include <bits/ranges_algobase.h> // ranges::copy
56#include <bits/stl_iterator.h> // back_insert_iterator
57#include <bits/stl_pair.h> // __is_pair
58#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
59#include <bits/utility.h> // tuple_size_v
60#include <ext/numeric_traits.h> // __int_traits
62#if !__has_builtin(__builtin_toupper)
66namespace std _GLIBCXX_VISIBILITY(default)
68_GLIBCXX_BEGIN_NAMESPACE_VERSION
70 // [format.context], class template basic_format_context
71 template<typename _Out, typename _CharT> class basic_format_context;
73 // [format.fmt.string], class template basic_format_string
74 template<typename _CharT, typename... _Args> struct basic_format_string;
79 // Type-erased character sink.
80 template<typename _CharT> class _Sink;
81 // Output iterator that writes to a type-erase character sink.
82 template<typename _CharT>
85 template<typename _CharT>
86 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
88 template<typename _CharT>
89 struct _Runtime_format_string
91 [[__gnu__::__always_inline__]]
92 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
95 _Runtime_format_string(const _Runtime_format_string&) = delete;
96 void operator=(const _Runtime_format_string&) = delete;
99 basic_string_view<_CharT> _M_str;
101 template<typename, typename...> friend struct std::basic_format_string;
103} // namespace __format
106 using format_context = __format::__format_context<char>;
107#ifdef _GLIBCXX_USE_WCHAR_T
108 using wformat_context = __format::__format_context<wchar_t>;
111 // [format.args], class template basic_format_args
112 template<typename _Context> class basic_format_args;
113 using format_args = basic_format_args<format_context>;
114#ifdef _GLIBCXX_USE_WCHAR_T
115 using wformat_args = basic_format_args<wformat_context>;
118 // [format.arguments], arguments
119 // [format.arg], class template basic_format_arg
120 template<typename _Context>
121 class basic_format_arg;
123 /** A compile-time checked format string for the specified argument types.
125 * @since C++23 but available as an extension in C++20.
127 template<typename _CharT, typename... _Args>
128 struct basic_format_string
130 template<typename _Tp>
131 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
133 basic_format_string(const _Tp& __s);
135 [[__gnu__::__always_inline__]]
136 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
140 [[__gnu__::__always_inline__]]
141 constexpr basic_string_view<_CharT>
146 basic_string_view<_CharT> _M_str;
149 template<typename... _Args>
150 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
152#ifdef _GLIBCXX_USE_WCHAR_T
153 template<typename... _Args>
155 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
158#if __cplusplus > 202302L
159 [[__gnu__::__always_inline__]]
160 inline __format::_Runtime_format_string<char>
161 runtime_format(string_view __fmt) noexcept
164#ifdef _GLIBCXX_USE_WCHAR_T
165 [[__gnu__::__always_inline__]]
166 inline __format::_Runtime_format_string<wchar_t>
167 runtime_format(wstring_view __fmt) noexcept
172 // [format.formatter], formatter
174 /// The primary template of std::formatter is disabled.
175 template<typename _Tp, typename _CharT = char>
178 formatter() = delete; // No std::formatter specialization for this type.
179 formatter(const formatter&) = delete;
180 formatter& operator=(const formatter&) = delete;
183 // [format.error], class format_error
184 class format_error : public runtime_error
187 explicit format_error(const string& __what) : runtime_error(__what) { }
188 explicit format_error(const char* __what) : runtime_error(__what) { }
191 /// @cond undocumented
194 __throw_format_error(const char* __what)
195 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
199 // XXX use named functions for each constexpr error?
203 __unmatched_left_brace_in_format_string()
204 { __throw_format_error("format error: unmatched '{' in format string"); }
208 __unmatched_right_brace_in_format_string()
209 { __throw_format_error("format error: unmatched '}' in format string"); }
213 __conflicting_indexing_in_format_string()
214 { __throw_format_error("format error: conflicting indexing style in format string"); }
218 __invalid_arg_id_in_format_string()
219 { __throw_format_error("format error: invalid arg-id in format string"); }
223 __failed_to_parse_format_spec()
224 { __throw_format_error("format error: failed to parse format-spec"); }
225} // namespace __format
228 // [format.parse.ctx], class template basic_format_parse_context
229 template<typename _CharT> class basic_format_parse_context;
230 using format_parse_context = basic_format_parse_context<char>;
231#ifdef _GLIBCXX_USE_WCHAR_T
232 using wformat_parse_context = basic_format_parse_context<wchar_t>;
235 template<typename _CharT>
236 class basic_format_parse_context
239 using char_type = _CharT;
240 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
241 using iterator = const_iterator;
244 basic_format_parse_context(basic_string_view<_CharT> __fmt,
245 size_t __num_args = 0) noexcept
246 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
249 basic_format_parse_context(const basic_format_parse_context&) = delete;
250 void operator=(const basic_format_parse_context&) = delete;
252 constexpr const_iterator begin() const noexcept { return _M_begin; }
253 constexpr const_iterator end() const noexcept { return _M_end; }
256 advance_to(const_iterator __it) noexcept
262 if (_M_indexing == _Manual)
263 __format::__conflicting_indexing_in_format_string();
266 // _GLIBCXX_RESOLVE_LIB_DEFECTS
267 // 3825. Missing compile-time argument id check in next_arg_id
268 if (std::is_constant_evaluated())
269 if (_M_next_arg_id == _M_num_args)
270 __format::__invalid_arg_id_in_format_string();
271 return _M_next_arg_id++;
275 check_arg_id(size_t __id)
277 if (_M_indexing == _Auto)
278 __format::__conflicting_indexing_in_format_string();
279 _M_indexing = _Manual;
281 if (std::is_constant_evaluated())
282 if (__id >= _M_num_args)
283 __format::__invalid_arg_id_in_format_string();
289 enum _Indexing { _Unknown, _Manual, _Auto };
290 _Indexing _M_indexing = _Unknown;
291 size_t _M_next_arg_id = 0;
295/// @cond undocumented
296 template<typename _Tp, template<typename...> class _Class>
297 static constexpr bool __is_specialization_of = false;
298 template<template<typename...> class _Class, typename... _Args>
299 static constexpr bool __is_specialization_of<_Class<_Args...>, _Class>
304 // pre: first != last
305 template<typename _CharT>
306 constexpr pair<unsigned short, const _CharT*>
307 __parse_integer(const _CharT* __first, const _CharT* __last)
309 if (__first == __last)
310 __builtin_unreachable();
312 if constexpr (is_same_v<_CharT, char>)
314 const auto __start = __first;
315 unsigned short __val = 0;
316 // N.B. std::from_chars is not constexpr in C++20.
317 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
318 && __first != __start) [[likely]]
319 return {__val, __first};
323 constexpr int __n = 32;
325 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
326 __buf[__i] = __first[__i];
327 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
328 if (__ptr) [[likely]]
329 return {__v, __first + (__ptr - __buf)};
334 template<typename _CharT>
335 constexpr pair<unsigned short, const _CharT*>
336 __parse_arg_id(const _CharT* __first, const _CharT* __last)
338 if (__first == __last)
339 __builtin_unreachable();
342 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
344 if ('1' <= *__first && *__first <= '9')
346 const unsigned short __id = *__first - '0';
347 const auto __next = __first + 1;
348 // Optimize for most likely case of single digit arg-id.
349 if (__next == __last || !('0' <= *__next && *__next <= '9'))
350 return {__id, __next};
352 return __format::__parse_integer(__first, __last);
358 _Pres_none = 0, // Default type (not valid for integer presentation types).
359 // Presentation types for integral types (including bool and charT).
360 _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
361 // Presentation types for floating-point types.
362 _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
363 _Pres_p = 0, _Pres_P, // For pointers.
364 _Pres_s = 0, // For strings and bool.
365 _Pres_esc = 0xf, // For strings and charT.
378 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
383 _WP_none, // No width/prec specified.
384 _WP_value, // Fixed width/prec specified.
385 _WP_from_arg // Use a formatting argument for width/prec.
388 template<typename _Context>
390 __int_from_arg(const basic_format_arg<_Context>& __arg);
392 constexpr bool __is_digit(char __c)
393 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
395 constexpr bool __is_xdigit(char __c)
396 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
398 template<typename _CharT>
404 unsigned _M_localized : 1;
405 unsigned _M_zero_fill : 1;
406 _WidthPrec _M_width_kind : 2;
407 _WidthPrec _M_prec_kind : 2;
408 _Pres_type _M_type : 4;
409 unsigned _M_reserved : 1;
410 unsigned _M_reserved2 : 16;
411 unsigned short _M_width;
412 unsigned short _M_prec;
413 char32_t _M_fill = ' ';
415 using iterator = typename basic_string_view<_CharT>::iterator;
417 static constexpr _Align
418 _S_align(_CharT __c) noexcept
422 case '<': return _Align_left;
423 case '>': return _Align_right;
424 case '^': return _Align_centre;
425 default: return _Align_default;
429 // pre: __first != __last
431 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
435 using namespace __unicode;
436 if constexpr (__literal_encoding_is_unicode<_CharT>())
438 // Accept any UCS scalar value as fill character.
439 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
442 auto __beg = __uv.begin();
443 char32_t __c = *__beg++;
444 if (__is_scalar_value(__c))
445 if (auto __next = __beg.base(); __next != __last)
446 if (_Align __align = _S_align(*__next))
454 else if (__last - __first >= 2)
455 if (_Align __align = _S_align(__first[1]))
462 if (_Align __align = _S_align(__first[0]))
472 static constexpr _Sign
473 _S_sign(_CharT __c) noexcept
477 case '+': return _Sign_plus;
478 case '-': return _Sign_minus;
479 case ' ': return _Sign_space;
480 default: return _Sign_default;
484 // pre: __first != __last
486 _M_parse_sign(iterator __first, iterator) noexcept
488 if (_Sign __sign = _S_sign(*__first))
496 // pre: *__first is valid
498 _M_parse_alternate_form(iterator __first, iterator) noexcept
508 // pre: __first != __last
510 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
520 // pre: __first != __last
521 static constexpr iterator
522 _S_parse_width_or_precision(iterator __first, iterator __last,
523 unsigned short& __val, bool& __arg_id,
524 basic_format_parse_context<_CharT>& __pc)
526 if (__format::__is_digit(*__first))
528 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
530 __throw_format_error("format error: invalid width or precision "
535 else if (*__first == '{')
539 if (__first == __last)
540 __format::__unmatched_left_brace_in_format_string();
542 __val = __pc.next_arg_id();
545 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
546 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
547 __format::__invalid_arg_id_in_format_string();
549 __pc.check_arg_id(__v);
552 ++__first; // past the '}'
557 // pre: __first != __last
559 _M_parse_width(iterator __first, iterator __last,
560 basic_format_parse_context<_CharT>& __pc)
562 bool __arg_id = false;
564 __throw_format_error("format error: width must be non-zero in "
566 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
568 if (__next != __first)
569 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
573 // pre: __first != __last
575 _M_parse_precision(iterator __first, iterator __last,
576 basic_format_parse_context<_CharT>& __pc)
578 if (__first[0] != '.')
581 iterator __next = ++__first;
582 bool __arg_id = false;
583 if (__next != __last)
584 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
586 if (__next == __first)
587 __throw_format_error("format error: missing precision after '.' in "
589 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
593 // pre: __first != __last
595 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
605 template<typename _Context>
607 _M_get_width(_Context& __ctx) const
610 if (_M_width_kind == _WP_value)
612 else if (_M_width_kind == _WP_from_arg)
613 __width = __format::__int_from_arg(__ctx.arg(_M_width));
617 template<typename _Context>
619 _M_get_precision(_Context& __ctx) const
622 if (_M_prec_kind == _WP_value)
624 else if (_M_prec_kind == _WP_from_arg)
625 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
630 template<typename _Int>
632 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
636 else if (__sign == _Sign_plus)
638 else if (__sign == _Sign_space)
645 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
646 template<typename _Out, typename _CharT>
647 requires output_iterator<_Out, const _CharT&>
649 __write(_Out __out, basic_string_view<_CharT> __str)
651 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
657 for (_CharT __c : __str)
662 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
663 // pre: __align != _Align_default
664 template<typename _Out, typename _CharT>
666 __write_padded(_Out __out, basic_string_view<_CharT> __str,
667 _Align __align, size_t __nfill, char32_t __fill_char)
669 const size_t __buflen = 0x20;
670 _CharT __padding_chars[__buflen];
671 __padding_chars[0] = _CharT();
672 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
674 auto __pad = [&__padding] (size_t __n, _Out& __o) {
677 while (__n > __padding.size())
679 __o = __format::__write(std::move(__o), __padding);
680 __n -= __padding.size();
683 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
686 size_t __l, __r, __max;
687 if (__align == _Align_centre)
690 __r = __l + (__nfill & 1);
693 else if (__align == _Align_right)
706 using namespace __unicode;
707 if constexpr (__literal_encoding_is_unicode<_CharT>())
708 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
710 // Encode fill char as multiple code units of type _CharT.
711 const char32_t __arr[1]{ __fill_char };
712 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
713 basic_string<_CharT> __padstr(__v.begin(), __v.end());
714 __padding = __padstr;
716 __out = __format::__write(std::move(__out), __padding);
717 __out = __format::__write(std::move(__out), __str);
719 __out = __format::__write(std::move(__out), __padding);
723 if (__max < __buflen)
724 __padding.remove_suffix(__buflen - __max);
728 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
730 __out = __format::__write(std::move(__out), __str);
736 // Write STR to OUT, with alignment and padding as determined by SPEC.
737 // pre: __spec._M_align != _Align_default || __align != _Align_default
738 template<typename _CharT, typename _Out>
740 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
741 size_t __estimated_width,
742 basic_format_context<_Out, _CharT>& __fc,
743 const _Spec<_CharT>& __spec,
744 _Align __align = _Align_left)
746 size_t __width = __spec._M_get_width(__fc);
748 if (__width <= __estimated_width)
749 return __format::__write(__fc.out(), __str);
751 const size_t __nfill = __width - __estimated_width;
754 __align = __spec._M_align;
756 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
760 // A lightweight optional<locale>.
761 struct _Optional_locale
763 [[__gnu__::__always_inline__]]
764 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
766 _Optional_locale(const locale& __loc) noexcept
767 : _M_loc(__loc), _M_hasval(true)
770 _Optional_locale(const _Optional_locale& __l) noexcept
771 : _M_dummy(), _M_hasval(__l._M_hasval)
774 std::construct_at(&_M_loc, __l._M_loc);
778 operator=(const _Optional_locale& __l) noexcept
790 else if (__l._M_hasval)
792 std::construct_at(&_M_loc, __l._M_loc);
798 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
801 operator=(locale&& __loc) noexcept
804 _M_loc = std::move(__loc);
807 std::construct_at(&_M_loc, std::move(__loc));
818 std::construct_at(&_M_loc);
824 bool has_value() const noexcept { return _M_hasval; }
827 char _M_dummy = '\0';
830 bool _M_hasval = false;
833#ifdef _GLIBCXX_USE_WCHAR_T
834 template<typename _CharT>
835 concept __char = same_as<_CharT, char> || same_as<_CharT, wchar_t>;
837 template<typename _CharT>
838 concept __char = same_as<_CharT, char>;
841 template<__char _CharT>
842 struct __formatter_str
844 constexpr typename basic_format_parse_context<_CharT>::iterator
845 parse(basic_format_parse_context<_CharT>& __pc)
847 auto __first = __pc.begin();
848 const auto __last = __pc.end();
849 _Spec<_CharT> __spec{};
851 auto __finalize = [this, &__spec] {
855 auto __finished = [&] {
856 if (__first == __last || *__first == '}')
867 __first = __spec._M_parse_fill_and_align(__first, __last);
871 __first = __spec._M_parse_width(__first, __last, __pc);
875 __first = __spec._M_parse_precision(__first, __last, __pc);
881#if __cpp_lib_format_ranges
882 else if (*__first == '?')
884 __spec._M_type = _Pres_esc;
892 __format::__failed_to_parse_format_spec();
895 template<typename _Out>
897 format(basic_string_view<_CharT> __s,
898 basic_format_context<_Out, _CharT>& __fc) const
900 if (_M_spec._M_type == _Pres_esc)
902 // TODO: C++23 escaped string presentation
905 if (_M_spec._M_width_kind == _WP_none
906 && _M_spec._M_prec_kind == _WP_none)
907 return __format::__write(__fc.out(), __s);
909 size_t __estimated_width;
910 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
912 if (_M_spec._M_prec_kind != _WP_none)
914 size_t __prec = _M_spec._M_get_precision(__fc);
915 __estimated_width = __unicode::__truncate(__s, __prec);
918 __estimated_width = __unicode::__field_width(__s);
922 __s = __s.substr(0, _M_spec._M_get_precision(__fc));
923 __estimated_width = __s.size();
926 return __format::__write_padded_as_spec(__s, __estimated_width,
930#if __cpp_lib_format_ranges
932 set_debug_format() noexcept
933 { _M_spec._M_type = _Pres_esc; }
937 _Spec<_CharT> _M_spec{};
940 template<__char _CharT>
941 struct __formatter_int
943 // If no presentation type is specified, meaning of "none" depends
944 // whether we are formatting an integer or a char or a bool.
945 static constexpr _Pres_type _AsInteger = _Pres_d;
946 static constexpr _Pres_type _AsBool = _Pres_s;
947 static constexpr _Pres_type _AsChar = _Pres_c;
949 constexpr typename basic_format_parse_context<_CharT>::iterator
950 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
952 _Spec<_CharT> __spec{};
953 __spec._M_type = __type;
955 const auto __last = __pc.end();
956 auto __first = __pc.begin();
958 auto __finalize = [this, &__spec] {
962 auto __finished = [&] {
963 if (__first == __last || *__first == '}')
974 __first = __spec._M_parse_fill_and_align(__first, __last);
978 __first = __spec._M_parse_sign(__first, __last);
982 __first = __spec._M_parse_alternate_form(__first, __last);
986 __first = __spec._M_parse_zero_fill(__first, __last);
990 __first = __spec._M_parse_width(__first, __last, __pc);
994 __first = __spec._M_parse_locale(__first, __last);
1001 __spec._M_type = _Pres_b;
1005 __spec._M_type = _Pres_B;
1009 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1010 // 3586. format should not print bool with 'c'
1011 if (__type != _AsBool)
1013 __spec._M_type = _Pres_c;
1018 __spec._M_type = _Pres_d;
1022 __spec._M_type = _Pres_o;
1026 __spec._M_type = _Pres_x;
1030 __spec._M_type = _Pres_X;
1034 if (__type == _AsBool)
1036 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1040#if __cpp_lib_format_ranges
1042 if (__type == _AsChar)
1044 __spec._M_type = _Pres_esc;
1054 __format::__failed_to_parse_format_spec();
1057 template<typename _Tp>
1058 constexpr typename basic_format_parse_context<_CharT>::iterator
1059 _M_parse(basic_format_parse_context<_CharT>& __pc)
1061 if constexpr (is_same_v<_Tp, bool>)
1063 auto __end = _M_do_parse(__pc, _AsBool);
1064 if (_M_spec._M_type == _Pres_s)
1065 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1066 __throw_format_error("format error: format-spec contains "
1067 "invalid formatting options for "
1071 else if constexpr (__char<_Tp>)
1073 auto __end = _M_do_parse(__pc, _AsChar);
1074 if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1075 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1076 /* XXX should be invalid? || _M_spec._M_localized */)
1077 __throw_format_error("format error: format-spec contains "
1078 "invalid formatting options for "
1083 return _M_do_parse(__pc, _AsInteger);
1086 template<typename _Int, typename _Out>
1087 typename basic_format_context<_Out, _CharT>::iterator
1088 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1090 if (_M_spec._M_type == _Pres_c)
1091 return _M_format_character(_S_to_character(__i), __fc);
1093 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1094 to_chars_result __res{};
1096 string_view __base_prefix;
1097 make_unsigned_t<_Int> __u;
1099 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1103 char* __start = __buf + 3;
1104 char* const __end = __buf + sizeof(__buf);
1105 char* const __start_digits = __start;
1107 switch (_M_spec._M_type)
1111 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1112 __res = to_chars(__start, __end, __u, 2);
1116 return _M_format_character(_S_to_character(__i), __fc);
1119 // Should not reach here with _Pres_none for bool or charT, so:
1122 __res = to_chars(__start, __end, __u, 10);
1126 __base_prefix = "0";
1127 __res = to_chars(__start, __end, __u, 8);
1131 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1132 __res = to_chars(__start, __end, __u, 16);
1133 if (_M_spec._M_type == _Pres_X)
1134 for (auto __p = __start; __p != __res.ptr; ++__p)
1135#if __has_builtin(__builtin_toupper)
1136 *__p = __builtin_toupper(*__p);
1138 *__p = std::toupper(*__p);
1142 __builtin_unreachable();
1145 if (_M_spec._M_alt && __base_prefix.size())
1147 __start -= __base_prefix.size();
1148 __builtin_memcpy(__start, __base_prefix.data(),
1149 __base_prefix.size());
1151 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1153 return _M_format_int(string_view(__start, __res.ptr - __start),
1154 __start_digits - __start, __fc);
1157 template<typename _Out>
1158 typename basic_format_context<_Out, _CharT>::iterator
1159 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1161 if (_M_spec._M_type == _Pres_c)
1162 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1163 if (_M_spec._M_type != _Pres_s)
1164 return format(static_cast<unsigned char>(__i), __fc);
1166 basic_string<_CharT> __s;
1168 if (_M_spec._M_localized) [[unlikely]]
1170 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1171 __s = __i ? __np.truename() : __np.falsename();
1172 __est_width = __s.size(); // TODO Unicode-aware estimate
1176 if constexpr (is_same_v<char, _CharT>)
1177 __s = __i ? "true" : "false";
1179 __s = __i ? L"true" : L"false";
1180 __est_width = __s.size();
1183 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1187 [[__gnu__::__always_inline__]]
1189 _S_character_width(_CharT __c)
1191 // N.B. single byte cannot encode charcter of width greater than 1
1192 if constexpr (sizeof(_CharT) > 1u &&
1193 __unicode::__literal_encoding_is_unicode<_CharT>())
1194 return __unicode::__field_width(__c);
1199 template<typename _Out>
1200 typename basic_format_context<_Out, _CharT>::iterator
1201 _M_format_character(_CharT __c,
1202 basic_format_context<_Out, _CharT>& __fc) const
1204 return __format::__write_padded_as_spec({&__c, 1u},
1205 _S_character_width(__c),
1209 template<typename _Int>
1211 _S_to_character(_Int __i)
1213 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1214 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1216 if (_Traits::__min <= __i && __i <= _Traits::__max)
1217 return static_cast<_CharT>(__i);
1219 else if constexpr (is_signed_v<_Int>)
1221 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1222 return static_cast<_CharT>(__i);
1224 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1225 return static_cast<_CharT>(__i);
1226 __throw_format_error("format error: integer not representable as "
1230 template<typename _Out>
1231 typename basic_format_context<_Out, _CharT>::iterator
1232 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1233 basic_format_context<_Out, _CharT>& __fc) const
1235 size_t __width = _M_spec._M_get_width(__fc);
1237 basic_string_view<_CharT> __str;
1238 if constexpr (is_same_v<char, _CharT>)
1239 __str = __narrow_str;
1240#ifdef _GLIBCXX_USE_WCHAR_T
1243 size_t __n = __narrow_str.size();
1244 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1245 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1250 if (_M_spec._M_localized)
1252 const auto& __l = __fc.locale();
1253 if (__l.name() != "C")
1255 auto& __np = use_facet<numpunct<_CharT>>(__l);
1256 string __grp = __np.grouping();
1259 size_t __n = __str.size() - __prefix_len;
1260 auto __p = (_CharT*)__builtin_alloca(2 * __n
1263 auto __s = __str.data();
1264 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1265 __s += __prefix_len;
1266 auto __end = std::__add_grouping(__p + __prefix_len,
1267 __np.thousands_sep(),
1271 __str = {__p, size_t(__end - __p)};
1276 if (__width <= __str.size())
1277 return __format::__write(__fc.out(), __str);
1279 char32_t __fill_char = _M_spec._M_fill;
1280 _Align __align = _M_spec._M_align;
1282 size_t __nfill = __width - __str.size();
1283 auto __out = __fc.out();
1284 if (__align == _Align_default)
1286 __align = _Align_right;
1287 if (_M_spec._M_zero_fill)
1289 __fill_char = _CharT('0');
1290 // Write sign and base prefix before zero filling.
1291 if (__prefix_len != 0)
1293 __out = __format::__write(std::move(__out),
1294 __str.substr(0, __prefix_len));
1295 __str.remove_prefix(__prefix_len);
1299 __fill_char = _CharT(' ');
1301 return __format::__write_padded(std::move(__out), __str,
1302 __align, __nfill, __fill_char);
1305#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1306 template<typename _Tp>
1307 using make_unsigned_t
1308 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1309 std::make_unsigned<_Tp>,
1310 type_identity<unsigned __int128>>::type;
1312 // std::to_chars is not overloaded for int128 in strict mode.
1313 template<typename _Int>
1314 static to_chars_result
1315 to_chars(char* __first, char* __last, _Int __value, int __base)
1316 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1319 _Spec<_CharT> _M_spec{};
1322 // Decide how 128-bit floating-point types should be formatted (or not).
1323 // When supported, the typedef __format::__float128_t is the type that
1324 // format arguments should be converted to for storage in basic_format_arg.
1325 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1326 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1327 // by converting them to long double (or __ieee128 for powerpc64le).
1328 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1329 // support for _Float128, rather than formatting it as another type.
1330#undef _GLIBCXX_FORMAT_F128
1332#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1334 // Format 128-bit floating-point types using __ieee128.
1335 using __float128_t = __ieee128;
1336# define _GLIBCXX_FORMAT_F128 1
1338#ifdef __LONG_DOUBLE_IEEE128__
1339 // These overloads exist in the library, but are not declared.
1340 // Make them available as std::__format::to_chars.
1342 to_chars(char*, char*, __ibm128) noexcept
1343 __asm("_ZSt8to_charsPcS_e");
1346 to_chars(char*, char*, __ibm128, chars_format) noexcept
1347 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1350 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1351 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1352#elif __cplusplus == 202002L
1354 to_chars(char*, char*, __ieee128) noexcept
1355 __asm("_ZSt8to_charsPcS_u9__ieee128");
1358 to_chars(char*, char*, __ieee128, chars_format) noexcept
1359 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1362 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1363 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1366#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1368 // Format 128-bit floating-point types using long double.
1369 using __float128_t = long double;
1370# define _GLIBCXX_FORMAT_F128 1
1372#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1374 // Format 128-bit floating-point types using _Float128.
1375 using __float128_t = _Float128;
1376# define _GLIBCXX_FORMAT_F128 2
1378# if __cplusplus == 202002L
1379 // These overloads exist in the library, but are not declared for C++20.
1380 // Make them available as std::__format::to_chars.
1382 to_chars(char*, char*, _Float128) noexcept
1383# if _GLIBCXX_INLINE_VERSION
1384 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1386 __asm("_ZSt8to_charsPcS_DF128_");
1390 to_chars(char*, char*, _Float128, chars_format) noexcept
1391# if _GLIBCXX_INLINE_VERSION
1392 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1394 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1398 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1399# if _GLIBCXX_INLINE_VERSION
1400 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1402 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1407 using std::to_chars;
1409 // We can format a floating-point type iff it is usable with to_chars.
1410 template<typename _Tp>
1411 concept __formattable_float
1412 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1413 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1415 template<__char _CharT>
1416 struct __formatter_fp
1418 constexpr typename basic_format_parse_context<_CharT>::iterator
1419 parse(basic_format_parse_context<_CharT>& __pc)
1421 _Spec<_CharT> __spec{};
1422 const auto __last = __pc.end();
1423 auto __first = __pc.begin();
1425 auto __finalize = [this, &__spec] {
1429 auto __finished = [&] {
1430 if (__first == __last || *__first == '}')
1441 __first = __spec._M_parse_fill_and_align(__first, __last);
1445 __first = __spec._M_parse_sign(__first, __last);
1449 __first = __spec._M_parse_alternate_form(__first, __last);
1453 __first = __spec._M_parse_zero_fill(__first, __last);
1457 if (__first[0] != '.')
1459 __first = __spec._M_parse_width(__first, __last, __pc);
1464 __first = __spec._M_parse_precision(__first, __last, __pc);
1468 __first = __spec._M_parse_locale(__first, __last);
1475 __spec._M_type = _Pres_a;
1479 __spec._M_type = _Pres_A;
1483 __spec._M_type = _Pres_e;
1487 __spec._M_type = _Pres_E;
1491 __spec._M_type = _Pres_f;
1495 __spec._M_type = _Pres_F;
1499 __spec._M_type = _Pres_g;
1503 __spec._M_type = _Pres_G;
1511 __format::__failed_to_parse_format_spec();
1514 template<typename _Fp, typename _Out>
1515 typename basic_format_context<_Out, _CharT>::iterator
1516 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
1518 std::string __dynbuf;
1520 to_chars_result __res{};
1523 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
1525 __prec = _M_spec._M_get_precision(__fc);
1527 char* __start = __buf + 1; // reserve space for sign
1528 char* __end = __buf + sizeof(__buf);
1530 chars_format __fmt{};
1531 bool __upper = false;
1532 bool __trailing_zeros = false;
1535 switch (_M_spec._M_type)
1542 if (_M_spec._M_type != _Pres_A)
1544 __fmt = chars_format::hex;
1552 __fmt = chars_format::scientific;
1559 __fmt = chars_format::fixed;
1566 __trailing_zeros = true;
1568 __fmt = chars_format::general;
1572 __fmt = chars_format::general;
1575 __builtin_unreachable();
1578 // Write value into buffer using std::to_chars.
1579 auto __to_chars = [&](char* __b, char* __e) {
1581 return __format::to_chars(__b, __e, __v, __fmt, __prec);
1582 else if (__fmt != chars_format{})
1583 return __format::to_chars(__b, __e, __v, __fmt);
1585 return __format::to_chars(__b, __e, __v);
1588 // First try using stack buffer.
1589 __res = __to_chars(__start, __end);
1591 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
1593 // If the buffer is too small it's probably because of a large
1594 // precision, or a very large value in fixed format.
1595 size_t __guess = 8 + __prec;
1596 if (__fmt == chars_format::fixed) // +ddd.prec
1598 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
1599 || is_same_v<_Fp, long double>)
1601 // The number of digits to the left of the decimal point
1602 // is floor(log10(max(abs(__v),1)))+1
1604 if constexpr (is_same_v<_Fp, float>)
1605 __builtin_frexpf(__v, &__exp);
1606 else if constexpr (is_same_v<_Fp, double>)
1607 __builtin_frexp(__v, &__exp);
1608 else if constexpr (is_same_v<_Fp, long double>)
1609 __builtin_frexpl(__v, &__exp);
1611 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
1614 __guess += numeric_limits<_Fp>::max_exponent10;
1616 if (__guess <= sizeof(__buf)) [[unlikely]]
1617 __guess = sizeof(__buf) * 2;
1618 __dynbuf.reserve(__guess);
1622 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
1624 __res = __to_chars(__p + 1, __p + __n - 1);
1625 return __res.ec == errc{} ? __res.ptr - __p : 0;
1628 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
1630 __start = __dynbuf.data() + 1; // reserve space for sign
1631 __end = __dynbuf.data() + __dynbuf.size();
1633 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
1636 // Use uppercase for 'A', 'E', and 'G' formats.
1639 for (char* __p = __start; __p != __res.ptr; ++__p)
1640 *__p = std::toupper(*__p);
1643 bool __have_sign = true;
1644 // Add sign for non-negative values.
1645 if (!__builtin_signbit(__v))
1647 if (_M_spec._M_sign == _Sign_plus)
1649 else if (_M_spec._M_sign == _Sign_space)
1652 __have_sign = false;
1655 string_view __narrow_str(__start, __res.ptr - __start);
1657 // Use alternate form. Ensure decimal point is always present,
1658 // and add trailing zeros (up to precision) for g and G forms.
1659 if (_M_spec._M_alt && __builtin_isfinite(__v))
1661 string_view __s = __narrow_str;
1662 size_t __sigfigs; // Number of significant figures.
1663 size_t __z = 0; // Number of trailing zeros to add.
1664 size_t __p; // Position of the exponent character (if any).
1665 size_t __d = __s.find('.'); // Position of decimal point.
1666 if (__d != __s.npos) // Found decimal point.
1668 __p = __s.find(__expc, __d + 1);
1669 if (__p == __s.npos)
1672 // If presentation type is g or G we might need to add zeros.
1673 if (__trailing_zeros)
1675 // Find number of digits after first significant figure.
1676 if (__s[__have_sign] != '0')
1677 // A string like "D.D" or "-D.DDD"
1678 __sigfigs = __p - __have_sign - 1;
1680 // A string like "0.D" or "-0.0DD".
1681 // Safe to assume there is a non-zero digit, because
1682 // otherwise there would be no decimal point.
1683 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
1686 else // No decimal point, we need to insert one.
1688 __p = __s.find(__expc); // Find the exponent, if present.
1689 if (__p == __s.npos)
1691 __d = __p; // Position where '.' should be inserted.
1692 __sigfigs = __d - __have_sign;
1695 if (__trailing_zeros && __prec != 0)
1697 // For g and G presentation types std::to_chars produces
1698 // no more than prec significant figures. Insert this many
1699 // zeros so the result has exactly prec significant figures.
1700 __z = __prec - __sigfigs;
1703 if (size_t __extras = int(__d == __p) + __z) // How many to add.
1705 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
1707 // The stack buffer is large enough for the result.
1708 // Move exponent to make space for extra chars.
1709 __builtin_memmove(__start + __p + __extras,
1713 __start[__p++] = '.';
1714 __builtin_memset(__start + __p, '0', __z);
1715 __narrow_str = {__s.data(), __s.size() + __extras};
1717 else // Need to switch to the dynamic buffer.
1719 __dynbuf.reserve(__s.size() + __extras);
1720 if (__dynbuf.empty())
1722 __dynbuf = __s.substr(0, __p);
1726 __dynbuf.append(__z, '0');
1727 __dynbuf.append(__s.substr(__p));
1731 __dynbuf.insert(__p, __extras, '0');
1733 __dynbuf[__p] = '.';
1735 __narrow_str = __dynbuf;
1740 basic_string<_CharT> __wstr;
1741 basic_string_view<_CharT> __str;
1742 if constexpr (is_same_v<_CharT, char>)
1743 __str = __narrow_str;
1744#ifdef _GLIBCXX_USE_WCHAR_T
1747 __wstr = std::__to_wstring_numeric(__narrow_str);
1752 if (_M_spec._M_localized && __builtin_isfinite(__v))
1754 auto __s = _M_localize(__str, __expc, __fc.locale());
1756 __str = __wstr = std::move(__s);
1759 size_t __width = _M_spec._M_get_width(__fc);
1761 if (__width <= __str.size())
1762 return __format::__write(__fc.out(), __str);
1764 char32_t __fill_char = _M_spec._M_fill;
1765 _Align __align = _M_spec._M_align;
1767 size_t __nfill = __width - __str.size();
1768 auto __out = __fc.out();
1769 if (__align == _Align_default)
1771 __align = _Align_right;
1772 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
1774 __fill_char = _CharT('0');
1775 // Write sign before zero filling.
1776 if (!__format::__is_xdigit(__narrow_str[0]))
1778 *__out++ = __str[0];
1779 __str.remove_prefix(1);
1783 __fill_char = _CharT(' ');
1785 return __format::__write_padded(std::move(__out), __str,
1786 __align, __nfill, __fill_char);
1789 // Locale-specific format.
1790 basic_string<_CharT>
1791 _M_localize(basic_string_view<_CharT> __str, char __expc,
1792 const locale& __loc) const
1794 basic_string<_CharT> __lstr;
1796 if (__loc == locale::classic())
1797 return __lstr; // Nothing to do.
1799 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
1800 const _CharT __point = __np.decimal_point();
1801 const string __grp = __np.grouping();
1803 _CharT __dot, __exp;
1804 if constexpr (is_same_v<_CharT, char>)
1827 __builtin_unreachable();
1831 if (__grp.empty() && __point == __dot)
1832 return __lstr; // Locale uses '.' and no grouping.
1834 size_t __d = __str.find(__dot); // Index of radix character (if any).
1835 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
1836 if (__e == __str.npos)
1838 const size_t __r = __str.size() - __e; // Length of remainder.
1839 auto __overwrite = [&](_CharT* __p, size_t) {
1840 // Apply grouping to the digits before the radix or exponent.
1842 if (auto __c = __str.front(); __c == '-' || __c == '+' || __c == ' ')
1847 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
1848 __grp.data(), __grp.size(),
1849 __str.data() + __off,
1850 __str.data() + __e);
1851 if (__r) // If there's a fractional part or exponent
1853 if (__d != __str.npos)
1855 *__end = __point; // Add the locale's radix character.
1859 const size_t __rlen = __str.size() - __e;
1860 // Append fractional digits and/or exponent:
1861 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
1864 return (__end - __p);
1866 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
1870 _Spec<_CharT> _M_spec{};
1873} // namespace __format
1876 /// Format a character.
1877 template<__format::__char _CharT>
1878 struct formatter<_CharT, _CharT>
1880 formatter() = default;
1882 constexpr typename basic_format_parse_context<_CharT>::iterator
1883 parse(basic_format_parse_context<_CharT>& __pc)
1885 return _M_f.template _M_parse<_CharT>(__pc);
1888 template<typename _Out>
1889 typename basic_format_context<_Out, _CharT>::iterator
1890 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
1892 if (_M_f._M_spec._M_type == __format::_Pres_none
1893 || _M_f._M_spec._M_type == __format::_Pres_c)
1894 return _M_f._M_format_character(__u, __fc);
1895 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1901 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
1904#if __cpp_lib_format_ranges
1906 set_debug_format() noexcept
1907 { _M_f._M_spec._M_type = __format::_Pres_esc; }
1911 __format::__formatter_int<_CharT> _M_f;
1914#ifdef _GLIBCXX_USE_WCHAR_T
1915 /// Format a char value for wide character output.
1917 struct formatter<char, wchar_t>
1919 formatter() = default;
1921 constexpr typename basic_format_parse_context<wchar_t>::iterator
1922 parse(basic_format_parse_context<wchar_t>& __pc)
1924 return _M_f._M_parse<char>(__pc);
1927 template<typename _Out>
1928 typename basic_format_context<_Out, wchar_t>::iterator
1929 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
1931 if (_M_f._M_spec._M_type == __format::_Pres_none
1932 || _M_f._M_spec._M_type == __format::_Pres_c)
1933 return _M_f._M_format_character(__u, __fc);
1934 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
1940 return _M_f.format(static_cast<unsigned char>(__u), __fc);
1943#if __cpp_lib_format_ranges
1945 set_debug_format() noexcept
1946 { _M_f._M_spec._M_type = __format::_Pres_esc; }
1950 __format::__formatter_int<wchar_t> _M_f;
1952#endif // USE_WCHAR_T
1954 /** Format a string.
1957 template<__format::__char _CharT>
1958 struct formatter<_CharT*, _CharT>
1960 formatter() = default;
1962 [[__gnu__::__always_inline__]]
1963 constexpr typename basic_format_parse_context<_CharT>::iterator
1964 parse(basic_format_parse_context<_CharT>& __pc)
1965 { return _M_f.parse(__pc); }
1967 template<typename _Out>
1968 [[__gnu__::__nonnull__]]
1969 typename basic_format_context<_Out, _CharT>::iterator
1970 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
1971 { return _M_f.format(__u, __fc); }
1973#if __cpp_lib_format_ranges
1974 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
1978 __format::__formatter_str<_CharT> _M_f;
1981 template<__format::__char _CharT>
1982 struct formatter<const _CharT*, _CharT>
1984 formatter() = default;
1986 [[__gnu__::__always_inline__]]
1987 constexpr typename basic_format_parse_context<_CharT>::iterator
1988 parse(basic_format_parse_context<_CharT>& __pc)
1989 { return _M_f.parse(__pc); }
1991 template<typename _Out>
1992 [[__gnu__::__nonnull__]]
1993 typename basic_format_context<_Out, _CharT>::iterator
1994 format(const _CharT* __u,
1995 basic_format_context<_Out, _CharT>& __fc) const
1996 { return _M_f.format(__u, __fc); }
1998#if __cpp_lib_format_ranges
1999 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2003 __format::__formatter_str<_CharT> _M_f;
2006 template<__format::__char _CharT, size_t _Nm>
2007 struct formatter<_CharT[_Nm], _CharT>
2009 formatter() = default;
2011 [[__gnu__::__always_inline__]]
2012 constexpr typename basic_format_parse_context<_CharT>::iterator
2013 parse(basic_format_parse_context<_CharT>& __pc)
2014 { return _M_f.parse(__pc); }
2016 template<typename _Out>
2017 typename basic_format_context<_Out, _CharT>::iterator
2018 format(const _CharT (&__u)[_Nm],
2019 basic_format_context<_Out, _CharT>& __fc) const
2020 { return _M_f.format({__u, _Nm}, __fc); }
2022#if __cpp_lib_format_ranges
2023 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2027 __format::__formatter_str<_CharT> _M_f;
2030 template<typename _Traits, typename _Alloc>
2031 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2033 formatter() = default;
2035 [[__gnu__::__always_inline__]]
2036 constexpr typename basic_format_parse_context<char>::iterator
2037 parse(basic_format_parse_context<char>& __pc)
2038 { return _M_f.parse(__pc); }
2040 template<typename _Out>
2041 typename basic_format_context<_Out, char>::iterator
2042 format(const basic_string<char, _Traits, _Alloc>& __u,
2043 basic_format_context<_Out, char>& __fc) const
2044 { return _M_f.format(__u, __fc); }
2046#if __cpp_lib_format_ranges
2047 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2051 __format::__formatter_str<char> _M_f;
2054#ifdef _GLIBCXX_USE_WCHAR_T
2055 template<typename _Traits, typename _Alloc>
2056 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2058 formatter() = default;
2060 [[__gnu__::__always_inline__]]
2061 constexpr typename basic_format_parse_context<wchar_t>::iterator
2062 parse(basic_format_parse_context<wchar_t>& __pc)
2063 { return _M_f.parse(__pc); }
2065 template<typename _Out>
2066 typename basic_format_context<_Out, wchar_t>::iterator
2067 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2068 basic_format_context<_Out, wchar_t>& __fc) const
2069 { return _M_f.format(__u, __fc); }
2071#if __cpp_lib_format_ranges
2072 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2076 __format::__formatter_str<wchar_t> _M_f;
2078#endif // USE_WCHAR_T
2080 template<typename _Traits>
2081 struct formatter<basic_string_view<char, _Traits>, char>
2083 formatter() = default;
2085 [[__gnu__::__always_inline__]]
2086 constexpr typename basic_format_parse_context<char>::iterator
2087 parse(basic_format_parse_context<char>& __pc)
2088 { return _M_f.parse(__pc); }
2090 template<typename _Out>
2091 typename basic_format_context<_Out, char>::iterator
2092 format(basic_string_view<char, _Traits> __u,
2093 basic_format_context<_Out, char>& __fc) const
2094 { return _M_f.format(__u, __fc); }
2096#if __cpp_lib_format_ranges
2097 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2101 __format::__formatter_str<char> _M_f;
2104#ifdef _GLIBCXX_USE_WCHAR_T
2105 template<typename _Traits>
2106 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2108 formatter() = default;
2110 [[__gnu__::__always_inline__]]
2111 constexpr typename basic_format_parse_context<wchar_t>::iterator
2112 parse(basic_format_parse_context<wchar_t>& __pc)
2113 { return _M_f.parse(__pc); }
2115 template<typename _Out>
2116 typename basic_format_context<_Out, wchar_t>::iterator
2117 format(basic_string_view<wchar_t, _Traits> __u,
2118 basic_format_context<_Out, wchar_t>& __fc) const
2119 { return _M_f.format(__u, __fc); }
2121#if __cpp_lib_format_ranges
2122 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2126 __format::__formatter_str<wchar_t> _M_f;
2128#endif // USE_WCHAR_T
2131/// @cond undocumented
2134 // each cv-unqualified arithmetic type ArithmeticT other than
2135 // char, wchar_t, char8_t, char16_t, or char32_t
2136 template<typename _Tp>
2137 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2139#if defined __SIZEOF_INT128__
2140 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2141 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2145 template<> inline constexpr bool __is_formattable_integer<char> = false;
2146 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2147#ifdef _GLIBCXX_USE_CHAR8_T
2148 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2150 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2151 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2155 /// Format an integer.
2156 template<typename _Tp, __format::__char _CharT>
2157 requires __format::__is_formattable_integer<_Tp>
2158 struct formatter<_Tp, _CharT>
2160 formatter() = default;
2162 [[__gnu__::__always_inline__]]
2163 constexpr typename basic_format_parse_context<_CharT>::iterator
2164 parse(basic_format_parse_context<_CharT>& __pc)
2166 return _M_f.template _M_parse<_Tp>(__pc);
2169 template<typename _Out>
2170 typename basic_format_context<_Out, _CharT>::iterator
2171 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2172 { return _M_f.format(__u, __fc); }
2175 __format::__formatter_int<_CharT> _M_f;
2178#if defined __glibcxx_to_chars
2179 /// Format a floating-point value.
2180 template<__format::__formattable_float _Tp, __format::__char _CharT>
2181 struct formatter<_Tp, _CharT>
2183 formatter() = default;
2185 [[__gnu__::__always_inline__]]
2186 constexpr typename basic_format_parse_context<_CharT>::iterator
2187 parse(basic_format_parse_context<_CharT>& __pc)
2188 { return _M_f.parse(__pc); }
2190 template<typename _Out>
2191 typename basic_format_context<_Out, _CharT>::iterator
2192 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2193 { return _M_f.format(__u, __fc); }
2196 __format::__formatter_fp<_CharT> _M_f;
2199#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2200 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2201 template<__format::__char _CharT>
2202 struct formatter<long double, _CharT>
2204 formatter() = default;
2206 [[__gnu__::__always_inline__]]
2207 constexpr typename basic_format_parse_context<_CharT>::iterator
2208 parse(basic_format_parse_context<_CharT>& __pc)
2209 { return _M_f.parse(__pc); }
2211 template<typename _Out>
2212 typename basic_format_context<_Out, _CharT>::iterator
2213 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2214 { return _M_f.format((double)__u, __fc); }
2217 __format::__formatter_fp<_CharT> _M_f;
2221#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2222 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2223 template<__format::__char _CharT>
2224 struct formatter<_Float16, _CharT>
2226 formatter() = default;
2228 [[__gnu__::__always_inline__]]
2229 constexpr typename basic_format_parse_context<_CharT>::iterator
2230 parse(basic_format_parse_context<_CharT>& __pc)
2231 { return _M_f.parse(__pc); }
2233 template<typename _Out>
2234 typename basic_format_context<_Out, _CharT>::iterator
2235 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2236 { return _M_f.format((float)__u, __fc); }
2239 __format::__formatter_fp<_CharT> _M_f;
2243#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2244 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2245 template<__format::__char _CharT>
2246 struct formatter<_Float32, _CharT>
2248 formatter() = default;
2250 [[__gnu__::__always_inline__]]
2251 constexpr typename basic_format_parse_context<_CharT>::iterator
2252 parse(basic_format_parse_context<_CharT>& __pc)
2253 { return _M_f.parse(__pc); }
2255 template<typename _Out>
2256 typename basic_format_context<_Out, _CharT>::iterator
2257 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2258 { return _M_f.format((float)__u, __fc); }
2261 __format::__formatter_fp<_CharT> _M_f;
2265#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2266 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2267 template<__format::__char _CharT>
2268 struct formatter<_Float64, _CharT>
2270 formatter() = default;
2272 [[__gnu__::__always_inline__]]
2273 constexpr typename basic_format_parse_context<_CharT>::iterator
2274 parse(basic_format_parse_context<_CharT>& __pc)
2275 { return _M_f.parse(__pc); }
2277 template<typename _Out>
2278 typename basic_format_context<_Out, _CharT>::iterator
2279 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2280 { return _M_f.format((double)__u, __fc); }
2283 __format::__formatter_fp<_CharT> _M_f;
2287#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2288 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2289 template<__format::__char _CharT>
2290 struct formatter<_Float128, _CharT>
2292 formatter() = default;
2294 [[__gnu__::__always_inline__]]
2295 constexpr typename basic_format_parse_context<_CharT>::iterator
2296 parse(basic_format_parse_context<_CharT>& __pc)
2297 { return _M_f.parse(__pc); }
2299 template<typename _Out>
2300 typename basic_format_context<_Out, _CharT>::iterator
2301 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2302 { return _M_f.format((__format::__float128_t)__u, __fc); }
2305 __format::__formatter_fp<_CharT> _M_f;
2309#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2310 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2311 template<__format::__char _CharT>
2312 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2314 formatter() = default;
2316 [[__gnu__::__always_inline__]]
2317 constexpr typename basic_format_parse_context<_CharT>::iterator
2318 parse(basic_format_parse_context<_CharT>& __pc)
2319 { return _M_f.parse(__pc); }
2321 template<typename _Out>
2322 typename basic_format_context<_Out, _CharT>::iterator
2323 format(__gnu_cxx::__bfloat16_t __u,
2324 basic_format_context<_Out, _CharT>& __fc) const
2325 { return _M_f.format((float)__u, __fc); }
2328 __format::__formatter_fp<_CharT> _M_f;
2331#endif // __cpp_lib_to_chars
2333 /** Format a pointer.
2336 template<__format::__char _CharT>
2337 struct formatter<const void*, _CharT>
2339 formatter() = default;
2341 constexpr typename basic_format_parse_context<_CharT>::iterator
2342 parse(basic_format_parse_context<_CharT>& __pc)
2344 __format::_Spec<_CharT> __spec{};
2345 const auto __last = __pc.end();
2346 auto __first = __pc.begin();
2348 auto __finalize = [this, &__spec] {
2352 auto __finished = [&] {
2353 if (__first == __last || *__first == '}')
2364 __first = __spec._M_parse_fill_and_align(__first, __last);
2368// _GLIBCXX_RESOLVE_LIB_DEFECTS
2369// P2510R3 Formatting pointers
2370#if __cplusplus > 202302L || ! defined __STRICT_ANSI__
2371#define _GLIBCXX_P2518R3 1
2373#define _GLIBCXX_P2518R3 0
2377 __first = __spec._M_parse_zero_fill(__first, __last);
2382 __first = __spec._M_parse_width(__first, __last, __pc);
2384 if (__first != __last)
2386 if (*__first == 'p')
2389 else if (*__first == 'P')
2391 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2392 // P2510R3 Formatting pointers
2393 __spec._M_type = __format::_Pres_P;
2402 __format::__failed_to_parse_format_spec();
2405 template<typename _Out>
2406 typename basic_format_context<_Out, _CharT>::iterator
2407 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2409 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2410 char __buf[2 + sizeof(__v) * 2];
2411 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2413 int __n = __ptr - __buf;
2417 if (_M_spec._M_type == __format::_Pres_P)
2420 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2421#if __has_builtin(__builtin_toupper)
2422 *__p = __builtin_toupper(*__p);
2424 *__p = std::toupper(*__p);
2429 basic_string_view<_CharT> __str;
2430 if constexpr (is_same_v<_CharT, char>)
2431 __str = string_view(__buf, __n);
2432#ifdef _GLIBCXX_USE_WCHAR_T
2435 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2436 std::__to_wstring_numeric(__buf, __n, __p);
2437 __str = wstring_view(__p, __n);
2442 if (_M_spec._M_zero_fill)
2444 size_t __width = _M_spec._M_get_width(__fc);
2445 if (__width <= __str.size())
2446 return __format::__write(__fc.out(), __str);
2448 auto __out = __fc.out();
2449 // Write "0x" or "0X" prefix before zero-filling.
2450 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2451 __str.remove_prefix(2);
2452 size_t __nfill = __width - __n;
2453 return __format::__write_padded(std::move(__out), __str,
2454 __format::_Align_right,
2455 __nfill, _CharT('0'));
2459 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2460 __format::_Align_right);
2464 __format::_Spec<_CharT> _M_spec{};
2467 template<__format::__char _CharT>
2468 struct formatter<void*, _CharT>
2470 formatter() = default;
2472 [[__gnu__::__always_inline__]]
2473 constexpr typename basic_format_parse_context<_CharT>::iterator
2474 parse(basic_format_parse_context<_CharT>& __pc)
2475 { return _M_f.parse(__pc); }
2477 template<typename _Out>
2478 typename basic_format_context<_Out, _CharT>::iterator
2479 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2480 { return _M_f.format(__v, __fc); }
2483 formatter<const void*, _CharT> _M_f;
2486 template<__format::__char _CharT>
2487 struct formatter<nullptr_t, _CharT>
2489 formatter() = default;
2491 [[__gnu__::__always_inline__]]
2492 constexpr typename basic_format_parse_context<_CharT>::iterator
2493 parse(basic_format_parse_context<_CharT>& __pc)
2494 { return _M_f.parse(__pc); }
2496 template<typename _Out>
2497 typename basic_format_context<_Out, _CharT>::iterator
2498 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2499 { return _M_f.format(nullptr, __fc); }
2502 formatter<const void*, _CharT> _M_f;
2506#if defined _GLIBCXX_USE_WCHAR_T && __cpp_lib_format_ranges
2507 // _GLIBCXX_RESOLVE_LIB_DEFECTS
2508 // 3944. Formatters converting sequences of char to sequences of wchar_t
2510 namespace __format { struct __disabled; }
2512 // std::formatter<__disabled, C> uses the primary template, which is disabled.
2514 struct formatter<char*, wchar_t>
2515 : private formatter<__format::__disabled, wchar_t> { };
2517 struct formatter<const char*, wchar_t>
2518 : private formatter<__format::__disabled, wchar_t> { };
2519 template<size_t _Nm>
2520 struct formatter<char[_Nm], wchar_t>
2521 : private formatter<__format::__disabled, wchar_t> { };
2522 template<class _Traits, class _Allocator>
2523 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
2524 : private formatter<__format::__disabled, wchar_t> { };
2525 template<class _Traits>
2526 struct formatter<basic_string_view<char, _Traits>, wchar_t>
2527 : private formatter<__format::__disabled, wchar_t> { };
2530/// @cond undocumented
2533 template<typename _Tp, typename _Context,
2535 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2536 typename _ParseContext
2537 = basic_format_parse_context<typename _Context::char_type>>
2538 concept __parsable_with
2539 = semiregular<_Formatter>
2540 && requires (_Formatter __f, _ParseContext __pc)
2542 { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
2545 template<typename _Tp, typename _Context,
2547 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
2548 typename _ParseContext
2549 = basic_format_parse_context<typename _Context::char_type>>
2550 concept __formattable_with
2551 = semiregular<_Formatter>
2552 && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
2554 { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
2557 // An unspecified output iterator type used in the `formattable` concept.
2558 template<typename _CharT>
2559 using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
2561 template<typename _Tp, typename _CharT,
2562 typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
2563 concept __formattable_impl
2564 = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
2566} // namespace __format
2569// Concept std::formattable was introduced by P2286R8 "Formatting Ranges",
2570// but we can't guard it with __cpp_lib_format_ranges until we define that!
2571#if __cplusplus > 202002L
2572 // [format.formattable], concept formattable
2573 template<typename _Tp, typename _CharT>
2575 = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
2578#if __cpp_lib_format_ranges
2579 /// @cond undocumented
2582 template<typename _Rg, typename _CharT>
2583 concept __const_formattable_range
2584 = ranges::input_range<const _Rg>
2585 && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
2587 template<typename _Rg, typename _CharT>
2588 using __maybe_const_range
2589 = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
2590} // namespace __format
2592#endif // format_ranges
2594 /// An iterator after the last character written, and the number of
2595 /// characters that would have been written.
2596 template<typename _Out>
2597 struct format_to_n_result
2600 iter_difference_t<_Out> size;
2603_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
2604template<typename, typename> class vector;
2605_GLIBCXX_END_NAMESPACE_CONTAINER
2607/// @cond undocumented
2610 template<typename _CharT>
2613 _Sink<_CharT>* _M_sink = nullptr;
2616 using iterator_category = output_iterator_tag;
2617 using value_type = void;
2618 using difference_type = ptrdiff_t;
2619 using pointer = void;
2620 using reference = void;
2622 _Sink_iter() = default;
2623 _Sink_iter(const _Sink_iter&) = default;
2624 _Sink_iter& operator=(const _Sink_iter&) = default;
2626 [[__gnu__::__always_inline__]]
2628 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
2630 [[__gnu__::__always_inline__]]
2631 constexpr _Sink_iter&
2632 operator=(_CharT __c)
2634 _M_sink->_M_write(__c);
2638 [[__gnu__::__always_inline__]]
2639 constexpr _Sink_iter&
2640 operator=(basic_string_view<_CharT> __s)
2642 _M_sink->_M_write(__s);
2646 [[__gnu__::__always_inline__]]
2647 constexpr _Sink_iter&
2648 operator*() { return *this; }
2650 [[__gnu__::__always_inline__]]
2651 constexpr _Sink_iter&
2652 operator++() { return *this; }
2654 [[__gnu__::__always_inline__]]
2655 constexpr _Sink_iter
2656 operator++(int) { return *this; }
2659 _M_reserve(size_t __n) const
2660 { return _M_sink->_M_reserve(__n); }
2663 // Abstract base class for type-erased character sinks.
2664 // All formatting and output is done via this type's iterator,
2665 // to reduce the number of different template instantiations.
2666 template<typename _CharT>
2669 friend class _Sink_iter<_CharT>;
2671 span<_CharT> _M_span;
2672 typename span<_CharT>::iterator _M_next;
2674 // Called when the span is full, to make more space available.
2675 // Precondition: _M_next != _M_span.begin()
2676 // Postcondition: _M_next != _M_span.end()
2677 // TODO: remove the precondition? could make overflow handle it.
2678 virtual void _M_overflow() = 0;
2681 // Precondition: __span.size() != 0
2682 [[__gnu__::__always_inline__]]
2684 _Sink(span<_CharT> __span) noexcept
2685 : _M_span(__span), _M_next(__span.begin())
2688 // The portion of the span that has been written to.
2689 [[__gnu__::__always_inline__]]
2691 _M_used() const noexcept
2692 { return _M_span.first(_M_next - _M_span.begin()); }
2694 // The portion of the span that has not been written to.
2695 [[__gnu__::__always_inline__]]
2696 constexpr span<_CharT>
2697 _M_unused() const noexcept
2698 { return _M_span.subspan(_M_next - _M_span.begin()); }
2700 // Use the start of the span as the next write position.
2701 [[__gnu__::__always_inline__]]
2703 _M_rewind() noexcept
2704 { _M_next = _M_span.begin(); }
2706 // Replace the current output range.
2708 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
2711 _M_next = __s.begin() + __pos;
2714 // Called by the iterator for *it++ = c
2716 _M_write(_CharT __c)
2719 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
2724 _M_write(basic_string_view<_CharT> __s)
2726 span __to = _M_unused();
2727 while (__to.size() <= __s.size())
2729 __s.copy(__to.data(), __to.size());
2730 _M_next += __to.size();
2731 __s.remove_prefix(__to.size());
2737 __s.copy(__to.data(), __s.size());
2738 _M_next += __s.size();
2742 // A successful _Reservation can be used to directly write
2743 // up to N characters to the sink to avoid unwanted buffering.
2746 // True if the reservation was successful, false otherwise.
2747 explicit operator bool() const noexcept { return _M_sink; }
2748 // A pointer to write directly to the sink.
2749 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
2750 // Add n to the _M_next iterator for the sink.
2751 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
2755 // Attempt to reserve space to write n characters to the sink.
2756 // If anything is written to the reservation then there must be a call
2757 // to _M_bump(N2) before any call to another member function of *this,
2758 // where N2 is the number of characters written.
2759 virtual _Reservation
2760 _M_reserve(size_t __n)
2762 if (__n <= _M_unused().size())
2765 if (__n <= _M_span.size()) // Cannot meet the request.
2767 _M_overflow(); // Make more space available.
2768 if (__n <= _M_unused().size())
2774 // Update the next output position after writing directly to the sink.
2775 // pre: no calls to _M_write or _M_overflow since _M_reserve.
2781 _Sink(const _Sink&) = delete;
2782 _Sink& operator=(const _Sink&) = delete;
2784 [[__gnu__::__always_inline__]]
2785 constexpr _Sink_iter<_CharT>
2787 { return _Sink_iter<_CharT>(*this); }
2790 // A sink with an internal buffer. This is used to implement concrete sinks.
2791 template<typename _CharT>
2792 class _Buf_sink : public _Sink<_CharT>
2795 _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
2797 [[__gnu__::__always_inline__]]
2799 _Buf_sink() noexcept
2800 : _Sink<_CharT>(_M_buf)
2804 using _GLIBCXX_STD_C::vector;
2806 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
2807 // Writes to a buffer then appends that to the sequence when it fills up.
2808 template<typename _Seq>
2809 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
2811 using _CharT = typename _Seq::value_type;
2815 // Transfer buffer contents to the sequence, so buffer can be refilled.
2817 _M_overflow() override
2819 auto __s = this->_M_used();
2820 if (__s.empty()) [[unlikely]]
2821 return; // Nothing in the buffer to transfer to _M_seq.
2823 // If _M_reserve was called then _M_bump must have been called too.
2824 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
2826 if constexpr (__is_specialization_of<_Seq, basic_string>)
2827 _M_seq.append(__s.data(), __s.size());
2829 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
2831 // Make the whole of _M_buf available for the next write:
2835 typename _Sink<_CharT>::_Reservation
2836 _M_reserve(size_t __n) override
2838 // We might already have n characters available in this->_M_unused(),
2839 // but the whole point of this function is to be an optimization for
2840 // the std::format("{}", x) case. We want to avoid writing to _M_buf
2841 // and then copying that into a basic_string if possible, so this
2842 // function prefers to create space directly in _M_seq rather than
2845 if constexpr (__is_specialization_of<_Seq, basic_string>
2846 || __is_specialization_of<_Seq, vector>)
2848 // Flush the buffer to _M_seq first (should not be needed).
2849 if (this->_M_used().size()) [[unlikely]]
2850 _Seq_sink::_M_overflow();
2852 // Expand _M_seq to make __n new characters available:
2853 const auto __sz = _M_seq.size();
2854 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
2855 _M_seq.__resize_and_overwrite(__sz + __n,
2856 [](auto, auto __n2) {
2860 _M_seq.resize(__sz + __n);
2862 // Set _M_used() to be a span over the original part of _M_seq
2863 // and _M_unused() to be the extra capacity we just created:
2864 this->_M_reset(_M_seq, __sz);
2867 else // Try to use the base class' buffer.
2868 return _Sink<_CharT>::_M_reserve(__n);
2872 _M_bump(size_t __n) override
2874 if constexpr (__is_specialization_of<_Seq, basic_string>
2875 || __is_specialization_of<_Seq, vector>)
2877 auto __s = this->_M_used();
2878 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
2879 // Truncate the sequence to the part that was actually written to:
2880 _M_seq.resize(__s.size() + __n);
2881 // Switch back to using buffer:
2882 this->_M_reset(this->_M_buf);
2887 // TODO: for SSO string, use SSO buffer as initial span, then switch
2888 // to _M_buf if it overflows? Or even do that for all unused capacity?
2890 [[__gnu__::__always_inline__]]
2891 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
2894 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
2895 : _M_seq(std::move(__s))
2898 using _Sink<_CharT>::out;
2903 if (this->_M_used().size() != 0)
2904 _Seq_sink::_M_overflow();
2905 return std::move(_M_seq);
2908 // A writable span that views everything written to the sink.
2909 // Will be either a view over _M_seq or the used part of _M_buf.
2913 auto __s = this->_M_used();
2916 if (__s.size() != 0)
2917 _Seq_sink::_M_overflow();
2924 template<typename _CharT, typename _Alloc = allocator<_CharT>>
2926 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
2928 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
2929 // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
2931 // A sink that writes to an output iterator.
2932 // Writes to a fixed-size buffer and then flushes to the output iterator
2933 // when the buffer fills up.
2934 template<typename _CharT, typename _OutIter>
2935 class _Iter_sink : public _Buf_sink<_CharT>
2938 iter_difference_t<_OutIter> _M_max;
2941 size_t _M_count = 0;
2944 _M_overflow() override
2946 auto __s = this->_M_used();
2947 if (_M_max < 0) // No maximum.
2948 _M_out = ranges::copy(__s, std::move(_M_out)).out;
2949 else if (_M_count < static_cast<size_t>(_M_max))
2951 auto __max = _M_max - _M_count;
2952 span<_CharT> __first;
2953 if (__max < __s.size())
2954 __first = __s.first(static_cast<size_t>(__max));
2957 _M_out = ranges::copy(__first, std::move(_M_out)).out;
2960 _M_count += __s.size();
2964 [[__gnu__::__always_inline__]]
2966 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
2967 : _M_out(std::move(__out)), _M_max(__max)
2970 using _Sink<_CharT>::out;
2972 format_to_n_result<_OutIter>
2975 if (this->_M_used().size() != 0)
2976 _Iter_sink::_M_overflow();
2977 iter_difference_t<_OutIter> __count(_M_count);
2978 return { std::move(_M_out), __count };
2982 // Partial specialization for contiguous iterators.
2983 // No buffer is used, characters are written straight to the iterator.
2984 // We do not know the size of the output range, so the span size just grows
2985 // as needed. The end of the span might be an invalid pointer outside the
2986 // valid range, but we never actually call _M_span.end(). This class does
2987 // not introduce any invalid pointer arithmetic or overflows that would not
2988 // have happened anyway.
2989 template<typename _CharT, contiguous_iterator _OutIter>
2990 requires same_as<iter_value_t<_OutIter>, _CharT>
2991 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
2994 iter_difference_t<_OutIter> _M_max = -1;
2996 size_t _M_count = 0;
2998 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3002 _M_overflow() override
3004 if (this->_M_unused().size() != 0)
3005 return; // No need to switch to internal buffer yet.
3007 auto __s = this->_M_used();
3011 _M_count += __s.size();
3012 // Span was already sized for the maximum character count,
3013 // if it overflows then any further output must go to the
3014 // internal buffer, to be discarded.
3015 this->_M_reset(this->_M_buf);
3019 // No maximum character count. Just extend the span to allow
3020 // writing more characters to it.
3021 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3025 typename _Sink<_CharT>::_Reservation
3026 _M_reserve(size_t __n) final
3028 auto __avail = this->_M_unused();
3029 if (__n > __avail.size())
3032 return {}; // cannot grow
3034 auto __s = this->_M_used();
3035 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3042 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3043 span<_CharT> __buf) noexcept
3046 return __buf; // Only write to the internal buffer.
3050 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3051 || sizeof(__n) > sizeof(size_t))
3053 // __int128 or __detail::__max_diff_type
3054 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3058 return {__ptr, (size_t)__n};
3061#if __has_builtin(__builtin_dynamic_object_size)
3062 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3063 return {__ptr, __bytes / sizeof(_CharT)};
3065 // Avoid forming a pointer to a different memory page.
3066 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3067 __n = (1024 - __off) / sizeof(_CharT);
3068 if (__n > 0) [[likely]]
3069 return {__ptr, static_cast<size_t>(__n)};
3070 else // Misaligned/packed buffer of wchar_t?
3076 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3077 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3078 _M_first(__out), _M_max(__n)
3081 format_to_n_result<_OutIter>
3084 auto __s = this->_M_used();
3085 if (__s.data() == _M_buf)
3087 // Switched to internal buffer, so must have written _M_max.
3088 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3089 return { _M_first + _M_max, __count };
3091 else // Not using internal buffer yet
3093 iter_difference_t<_OutIter> __count(__s.size());
3094 return { _M_first + __count, __count };
3099 enum _Arg_t : unsigned char {
3100 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3101 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3102 _Arg_i128, _Arg_u128,
3103 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3104#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3106 _Arg_f128 = _Arg_ldbl,
3107 _Arg_ibm128 = _Arg_next_value_,
3114 template<typename _Context>
3117 using _CharT = typename _Context::char_type;
3133 unsigned long long _M_ull;
3136#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3137 long double _M_ldbl;
3139 const _CharT* _M_str;
3140 basic_string_view<_CharT> _M_sv;
3142 _HandleBase _M_handle;
3143#ifdef __SIZEOF_INT128__
3145 unsigned __int128 _M_u128;
3147#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3150#elif _GLIBCXX_FORMAT_F128 == 2
3151 __float128_t _M_f128;
3155 [[__gnu__::__always_inline__]]
3156 _Arg_value() : _M_none() { }
3159 template<typename _Tp>
3160 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3161 { _S_get<_Tp>() = __val; }
3164 template<typename _Tp, typename _Self>
3165 [[__gnu__::__always_inline__]]
3167 _S_get(_Self& __u) noexcept
3169 if constexpr (is_same_v<_Tp, bool>)
3171 else if constexpr (is_same_v<_Tp, _CharT>)
3173 else if constexpr (is_same_v<_Tp, int>)
3175 else if constexpr (is_same_v<_Tp, unsigned>)
3177 else if constexpr (is_same_v<_Tp, long long>)
3179 else if constexpr (is_same_v<_Tp, unsigned long long>)
3181 else if constexpr (is_same_v<_Tp, float>)
3183 else if constexpr (is_same_v<_Tp, double>)
3185#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3186 else if constexpr (is_same_v<_Tp, long double>)
3189 else if constexpr (is_same_v<_Tp, __ieee128>)
3191 else if constexpr (is_same_v<_Tp, __ibm128>)
3192 return __u._M_ibm128;
3194 else if constexpr (is_same_v<_Tp, const _CharT*>)
3196 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3198 else if constexpr (is_same_v<_Tp, const void*>)
3200#ifdef __SIZEOF_INT128__
3201 else if constexpr (is_same_v<_Tp, __int128>)
3203 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3206#if _GLIBCXX_FORMAT_F128 == 2
3207 else if constexpr (is_same_v<_Tp, __float128_t>)
3210 else if constexpr (derived_from<_Tp, _HandleBase>)
3211 return static_cast<_Tp&>(__u._M_handle);
3212 // Otherwise, ill-formed.
3215 template<typename _Tp>
3216 [[__gnu__::__always_inline__]]
3219 { return _S_get<_Tp>(*this); }
3221 template<typename _Tp>
3222 [[__gnu__::__always_inline__]]
3224 _M_get() const noexcept
3225 { return _S_get<_Tp>(*this); }
3227 template<typename _Tp>
3228 [[__gnu__::__always_inline__]]
3230 _M_set(_Tp __v) noexcept
3232 if constexpr (derived_from<_Tp, _HandleBase>)
3233 std::construct_at(&_M_handle, __v);
3235 _S_get<_Tp>(*this) = __v;
3239 // [format.arg.store], class template format-arg-store
3240 template<typename _Context, typename... _Args>
3243} // namespace __format
3246 template<typename _Context>
3247 class basic_format_arg
3249 using _CharT = typename _Context::char_type;
3251 template<typename _Tp>
3252 static constexpr bool __formattable
3253 = __format::__formattable_with<_Tp, _Context>;
3256 class handle : public __format::_Arg_value<_Context>::_HandleBase
3258 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3260 // Format as const if possible, to reduce instantiations.
3261 template<typename _Tp>
3262 using __maybe_const_t
3263 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3265 template<typename _Tq>
3267 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3268 _Context& __format_ctx, const void* __ptr)
3270 using _Td = remove_const_t<_Tq>;
3271 typename _Context::template formatter_type<_Td> __f;
3272 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3273 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3274 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3277 template<typename _Tp>
3279 handle(_Tp& __val) noexcept
3281 this->_M_ptr = __builtin_addressof(__val);
3282 auto __func = _S_format<__maybe_const_t<_Tp>>;
3283 this->_M_func = reinterpret_cast<void(*)()>(__func);
3286 friend class basic_format_arg<_Context>;
3289 handle(const handle&) = default;
3290 handle& operator=(const handle&) = default;
3292 [[__gnu__::__always_inline__]]
3294 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3296 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3297 _Context&, const void*);
3298 auto __f = reinterpret_cast<_Func>(this->_M_func);
3299 __f(__pc, __fc, this->_M_ptr);
3303 [[__gnu__::__always_inline__]]
3304 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3306 [[nodiscard,__gnu__::__always_inline__]]
3307 explicit operator bool() const noexcept
3308 { return _M_type != __format::_Arg_none; }
3311 template<typename _Ctx>
3312 friend class basic_format_args;
3314 template<typename _Ctx, typename... _Args>
3315 friend class __format::_Arg_store;
3317 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3319 __format::_Arg_value<_Context> _M_val;
3320 __format::_Arg_t _M_type;
3322 // Transform incoming argument type to the type stored in _Arg_value.
3323 // e.g. short -> int, std::string -> std::string_view,
3324 // char[3] -> const char*.
3325 template<typename _Tp>
3326 static consteval auto
3329 using _Td = remove_const_t<_Tp>;
3330 if constexpr (is_same_v<_Td, bool>)
3331 return type_identity<bool>();
3332 else if constexpr (is_same_v<_Td, _CharT>)
3333 return type_identity<_CharT>();
3334 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3335 return type_identity<_CharT>();
3336#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3337 else if constexpr (is_same_v<_Td, __int128>)
3338 return type_identity<__int128>();
3339 else if constexpr (is_same_v<_Td, unsigned __int128>)
3340 return type_identity<unsigned __int128>();
3342 else if constexpr (__is_signed_integer<_Td>::value)
3344 if constexpr (sizeof(_Td) <= sizeof(int))
3345 return type_identity<int>();
3346 else if constexpr (sizeof(_Td) <= sizeof(long long))
3347 return type_identity<long long>();
3349 else if constexpr (__is_unsigned_integer<_Td>::value)
3351 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3352 return type_identity<unsigned>();
3353 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3354 return type_identity<unsigned long long>();
3356 else if constexpr (is_same_v<_Td, float>)
3357 return type_identity<float>();
3358 else if constexpr (is_same_v<_Td, double>)
3359 return type_identity<double>();
3360#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3361 else if constexpr (is_same_v<_Td, long double>)
3362 return type_identity<long double>();
3364 else if constexpr (is_same_v<_Td, __ibm128>)
3365 return type_identity<__ibm128>();
3366 else if constexpr (is_same_v<_Td, __ieee128>)
3367 return type_identity<__ieee128>();
3370#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3371 else if constexpr (is_same_v<_Td, _Float16>)
3372 return type_identity<float>();
3375#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3376 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3377 return type_identity<float>();
3380#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3381 else if constexpr (is_same_v<_Td, _Float32>)
3382 return type_identity<float>();
3385#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3386 else if constexpr (is_same_v<_Td, _Float64>)
3387 return type_identity<double>();
3390#if _GLIBCXX_FORMAT_F128
3392 else if constexpr (is_same_v<_Td, _Float128>)
3393 return type_identity<__format::__float128_t>();
3395# if __SIZEOF_FLOAT128__
3396 else if constexpr (is_same_v<_Td, __float128>)
3397 return type_identity<__format::__float128_t>();
3400 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3401 || __is_specialization_of<_Td, basic_string>)
3403 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3404 return type_identity<basic_string_view<_CharT>>();
3406 return type_identity<handle>();
3408 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3409 return type_identity<const _CharT*>();
3410 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3411 return type_identity<const _CharT*>();
3412 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3413 return type_identity<const void*>();
3414 else if constexpr (is_same_v<_Td, nullptr_t>)
3415 return type_identity<const void*>();
3417 return type_identity<handle>();
3420 // Transform a formattable type to the appropriate storage type.
3421 template<typename _Tp>
3422 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3424 // Get the _Arg_t value corresponding to a normalized type.
3425 template<typename _Tp>
3426 static consteval __format::_Arg_t
3429 using namespace __format;
3430 if constexpr (is_same_v<_Tp, bool>)
3432 else if constexpr (is_same_v<_Tp, _CharT>)
3434 else if constexpr (is_same_v<_Tp, int>)
3436 else if constexpr (is_same_v<_Tp, unsigned>)
3438 else if constexpr (is_same_v<_Tp, long long>)
3440 else if constexpr (is_same_v<_Tp, unsigned long long>)
3442 else if constexpr (is_same_v<_Tp, float>)
3444 else if constexpr (is_same_v<_Tp, double>)
3446#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3447 else if constexpr (is_same_v<_Tp, long double>)
3450 // Don't use _Arg_ldbl for this target, it's ambiguous.
3451 else if constexpr (is_same_v<_Tp, __ibm128>)
3453 else if constexpr (is_same_v<_Tp, __ieee128>)
3456 else if constexpr (is_same_v<_Tp, const _CharT*>)
3458 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3460 else if constexpr (is_same_v<_Tp, const void*>)
3462#ifdef __SIZEOF_INT128__
3463 else if constexpr (is_same_v<_Tp, __int128>)
3465 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3469#if _GLIBCXX_FORMAT_F128 == 2
3470 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3473 else if constexpr (is_same_v<_Tp, handle>)
3477 template<typename _Tp>
3479 _M_set(_Tp __v) noexcept
3481 _M_type = _S_to_enum<_Tp>();
3485 template<typename _Tp>
3486 requires __format::__formattable_with<_Tp, _Context>
3488 basic_format_arg(_Tp& __v) noexcept
3490 using _Td = _Normalize<_Tp>;
3491 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3492 _M_set(_Td{__v.data(), __v.size()});
3493 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3494 && is_same_v<_CharT, wchar_t>)
3495 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3497 _M_set(static_cast<_Td>(__v));
3500 template<typename _Ctx, typename... _Argz>
3502 make_format_args(_Argz&...) noexcept;
3504 template<typename _Visitor, typename _Ctx>
3505 friend decltype(auto)
3506 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3508 template<typename _Visitor>
3510 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
3512 using namespace __format;
3516 return std::forward<_Visitor>(__vis)(_M_val._M_none);
3518 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
3520 return std::forward<_Visitor>(__vis)(_M_val._M_c);
3522 return std::forward<_Visitor>(__vis)(_M_val._M_i);
3524 return std::forward<_Visitor>(__vis)(_M_val._M_u);
3526 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
3528 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
3529#if __glibcxx_to_chars // FIXME: need to be able to format these types!
3531 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
3533 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
3534#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3536 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
3539 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3541 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
3545 return std::forward<_Visitor>(__vis)(_M_val._M_str);
3547 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
3549 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
3552 auto& __h = static_cast<handle&>(_M_val._M_handle);
3553 return std::forward<_Visitor>(__vis)(__h);
3555#ifdef __SIZEOF_INT128__
3557 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
3559 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
3562#if _GLIBCXX_FORMAT_F128 == 2
3564 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
3569 __builtin_unreachable();
3574 template<typename _Visitor, typename _Context>
3575 inline decltype(auto)
3576 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
3578 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
3581/// @cond undocumented
3584 struct _WidthPrecVisitor
3586 template<typename _Tp>
3588 operator()(_Tp& __arg) const
3590 if constexpr (is_same_v<_Tp, monostate>)
3591 __format::__invalid_arg_id_in_format_string();
3592 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3593 // 3720. Restrict the valid types of arg-id for width and precision
3594 // 3721. Allow an arg-id with a value of zero for width
3595 else if constexpr (sizeof(_Tp) <= sizeof(long long))
3597 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3598 // 3720. Restrict the valid types of arg-id for width and precision
3599 if constexpr (__is_unsigned_integer<_Tp>::value)
3601 else if constexpr (__is_signed_integer<_Tp>::value)
3605 __throw_format_error("format error: argument used for width or "
3606 "precision must be a non-negative integer");
3610 template<typename _Context>
3612 __int_from_arg(const basic_format_arg<_Context>& __arg)
3613 { return std::visit_format_arg(_WidthPrecVisitor(), __arg); }
3615 // Pack _Arg_t enum values into a single 60-bit integer.
3616 template<int _Bits, size_t _Nm>
3618 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
3620 __UINT64_TYPE__ __packed_types = 0;
3621 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
3622 __packed_types = (__packed_types << _Bits) | *__i;
3623 return __packed_types;
3625} // namespace __format
3628 template<typename _Context>
3629 class basic_format_args
3631 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
3632 static constexpr int _S_packed_type_mask = 0b11111;
3633 static constexpr int _S_max_packed_args = 12;
3635 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
3637 template<typename... _Args>
3638 using _Store = __format::_Arg_store<_Context, _Args...>;
3640 template<typename _Ctx, typename... _Args>
3641 friend class __format::_Arg_store;
3643 using uint64_t = __UINT64_TYPE__;
3644 using _Format_arg = basic_format_arg<_Context>;
3645 using _Format_arg_val = __format::_Arg_value<_Context>;
3647 // If args are packed then the number of args is in _M_packed_size and
3648 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
3649 // If args are not packed then the number of args is in _M_unpacked_size
3650 // and _M_packed_size is zero.
3651 uint64_t _M_packed_size : 4;
3652 uint64_t _M_unpacked_size : 60;
3655 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
3656 const _Format_arg* _M_args; // Active when _M_packed_size == 0
3660 _M_size() const noexcept
3661 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
3663 typename __format::_Arg_t
3664 _M_type(size_t __i) const noexcept
3666 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
3667 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
3670 template<typename _Ctx, typename... _Args>
3672 make_format_args(_Args&...) noexcept;
3674 // An array of _Arg_t enums corresponding to _Args...
3675 template<typename... _Args>
3676 static consteval array<__format::_Arg_t, sizeof...(_Args)>
3678 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
3681 template<typename... _Args>
3682 basic_format_args(const _Store<_Args...>& __store) noexcept;
3684 [[nodiscard,__gnu__::__always_inline__]]
3685 basic_format_arg<_Context>
3686 get(size_t __i) const noexcept
3688 basic_format_arg<_Context> __arg;
3689 if (__i < _M_packed_size)
3691 __arg._M_type = _M_type(__i);
3692 __arg._M_val = _M_values[__i];
3694 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
3695 __arg = _M_args[__i];
3700 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3701 // 3810. CTAD for std::basic_format_args
3702 template<typename _Context, typename... _Args>
3703 basic_format_args(__format::_Arg_store<_Context, _Args...>)
3704 -> basic_format_args<_Context>;
3706 template<typename _Context, typename... _Args>
3708 make_format_args(_Args&... __fmt_args) noexcept;
3710 // An array of type-erased formatting arguments.
3711 template<typename _Context, typename... _Args>
3712 class __format::_Arg_store
3714 friend std::basic_format_args<_Context>;
3716 template<typename _Ctx, typename... _Argz>
3718#if _GLIBCXX_INLINE_VERSION
3719 __8:: // Needed for PR c++/59256
3721 make_format_args(_Argz&...) noexcept;
3723 // For a sufficiently small number of arguments we only store values.
3724 // basic_format_args can get the types from the _Args pack.
3725 static constexpr bool _S_values_only
3726 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
3729 = __conditional_t<_S_values_only,
3730 __format::_Arg_value<_Context>,
3731 basic_format_arg<_Context>>;
3733 _Element_t _M_args[sizeof...(_Args)];
3735 template<typename _Tp>
3737 _S_make_elt(_Tp& __v)
3739 using _Tq = remove_const_t<_Tp>;
3740 using _CharT = typename _Context::char_type;
3741 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
3742 "std::formatter must be specialized for the type "
3743 "of each format arg");
3744 using __format::__formattable_with;
3745 if constexpr (is_const_v<_Tp>)
3746 if constexpr (!__formattable_with<_Tp, _Context>)
3747 if constexpr (__formattable_with<_Tq, _Context>)
3748 static_assert(__formattable_with<_Tp, _Context>,
3749 "format arg must be non-const because its "
3750 "std::formatter specialization has a "
3751 "non-const reference parameter");
3752 basic_format_arg<_Context> __arg(__v);
3753 if constexpr (_S_values_only)
3754 return __arg._M_val;
3759 template<typename... _Tp>
3760 requires (sizeof...(_Tp) == sizeof...(_Args))
3761 [[__gnu__::__always_inline__]]
3762 _Arg_store(_Tp&... __a) noexcept
3763 : _M_args{_S_make_elt(__a)...}
3767 template<typename _Context>
3768 class __format::_Arg_store<_Context>
3771 template<typename _Context>
3772 template<typename... _Args>
3774 basic_format_args<_Context>::
3775 basic_format_args(const _Store<_Args...>& __store) noexcept
3777 if constexpr (sizeof...(_Args) == 0)
3780 _M_unpacked_size = 0;
3783 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
3785 // The number of packed arguments:
3786 _M_packed_size = sizeof...(_Args);
3787 // The packed type enums:
3789 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
3790 // The _Arg_value objects.
3791 _M_values = __store._M_args;
3795 // No packed arguments:
3797 // The number of unpacked arguments:
3798 _M_unpacked_size = sizeof...(_Args);
3799 // The basic_format_arg objects:
3800 _M_args = __store._M_args;
3804 /// Capture formatting arguments for use by `std::vformat`.
3805 template<typename _Context = format_context, typename... _Args>
3806 [[nodiscard,__gnu__::__always_inline__]]
3808 make_format_args(_Args&... __fmt_args) noexcept
3810 using _Fmt_arg = basic_format_arg<_Context>;
3811 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
3812 _Normalize<_Args>...>;
3813 return _Store(__fmt_args...);
3816#ifdef _GLIBCXX_USE_WCHAR_T
3817 /// Capture formatting arguments for use by `std::vformat` (for wide output).
3818 template<typename... _Args>
3819 [[nodiscard,__gnu__::__always_inline__]]
3821 make_wformat_args(_Args&... __args) noexcept
3822 { return std::make_format_args<wformat_context>(__args...); }
3825/// @cond undocumented
3828 template<typename _Out, typename _CharT, typename _Context>
3830 __do_vformat_to(_Out, basic_string_view<_CharT>,
3831 const basic_format_args<_Context>&,
3832 const locale* = nullptr);
3833} // namespace __format
3836 /** Context for std::format and similar functions.
3838 * A formatting context contains an output iterator and locale to use
3839 * for the formatting operations. Most programs will never need to use
3840 * this class template explicitly. For typical uses of `std::format` the
3841 * library will use the specializations `std::format_context` (for `char`)
3842 * and `std::wformat_context` (for `wchar_t`).
3844 template<typename _Out, typename _CharT>
3845 class basic_format_context
3847 static_assert( output_iterator<_Out, const _CharT&> );
3849 basic_format_args<basic_format_context> _M_args;
3851 __format::_Optional_locale _M_loc;
3853 basic_format_context(basic_format_args<basic_format_context> __args,
3855 : _M_args(__args), _M_out(std::move(__out))
3858 basic_format_context(basic_format_args<basic_format_context> __args,
3859 _Out __out, const std::locale& __loc)
3860 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
3863 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3864 // 4061. Should std::basic_format_context be
3865 // default-constructible/copyable/movable?
3866 basic_format_context(const basic_format_context&) = delete;
3867 basic_format_context& operator=(const basic_format_context&) = delete;
3869 template<typename _Out2, typename _CharT2, typename _Context2>
3871 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
3872 const basic_format_args<_Context2>&,
3876 ~basic_format_context() = default;
3878 using iterator = _Out;
3879 using char_type = _CharT;
3880 template<typename _Tp>
3881 using formatter_type = formatter<_Tp, _CharT>;
3884 basic_format_arg<basic_format_context>
3885 arg(size_t __id) const noexcept
3886 { return _M_args.get(__id); }
3889 std::locale locale() { return _M_loc.value(); }
3892 iterator out() { return std::move(_M_out); }
3894 void advance_to(iterator __it) { _M_out = std::move(__it); }
3898/// @cond undocumented
3901 // Abstract base class defining an interface for scanning format strings.
3902 // Scan the characters in a format string, dividing it up into strings of
3903 // ordinary characters, escape sequences, and replacement fields.
3904 // Call virtual functions for derived classes to parse format-specifiers
3905 // or write formatted output.
3906 template<typename _CharT>
3909 using iterator = typename basic_format_parse_context<_CharT>::iterator;
3911 basic_format_parse_context<_CharT> _M_pc;
3914 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
3915 : _M_pc(__str, __nargs)
3918 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
3919 constexpr iterator end() const noexcept { return _M_pc.end(); }
3924 basic_string_view<_CharT> __fmt = _M_fmt_str();
3926 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
3928 _M_pc.advance_to(begin() + 1);
3929 _M_format_arg(_M_pc.next_arg_id());
3933 size_t __lbr = __fmt.find('{');
3934 size_t __rbr = __fmt.find('}');
3936 while (__fmt.size())
3938 auto __cmp = __lbr <=> __rbr;
3942 _M_pc.advance_to(end());
3947 if (__lbr + 1 == __fmt.size()
3948 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
3949 __format::__unmatched_left_brace_in_format_string();
3950 const bool __is_escape = __fmt[__lbr + 1] == '{';
3951 iterator __last = begin() + __lbr + int(__is_escape);
3952 _M_on_chars(__last);
3953 _M_pc.advance_to(__last + 1);
3954 __fmt = _M_fmt_str();
3957 if (__rbr != __fmt.npos)
3959 __lbr = __fmt.find('{');
3963 _M_on_replacement_field();
3964 __fmt = _M_fmt_str();
3965 __lbr = __fmt.find('{');
3966 __rbr = __fmt.find('}');
3971 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
3972 __format::__unmatched_right_brace_in_format_string();
3973 iterator __last = begin() + __rbr;
3974 _M_on_chars(__last);
3975 _M_pc.advance_to(__last + 1);
3976 __fmt = _M_fmt_str();
3977 if (__lbr != __fmt.npos)
3979 __rbr = __fmt.find('}');
3984 constexpr basic_string_view<_CharT>
3985 _M_fmt_str() const noexcept
3986 { return {begin(), end()}; }
3988 constexpr virtual void _M_on_chars(iterator) { }
3990 constexpr void _M_on_replacement_field()
3992 auto __next = begin();
3996 __id = _M_pc.next_arg_id();
3997 else if (*__next == ':')
3999 __id = _M_pc.next_arg_id();
4000 _M_pc.advance_to(++__next);
4004 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4005 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4006 __format::__invalid_arg_id_in_format_string();
4007 _M_pc.check_arg_id(__id = __i);
4010 _M_pc.advance_to(++__ptr);
4013 _M_pc.advance_to(__ptr);
4015 _M_format_arg(__id);
4016 if (begin() == end() || *begin() != '}')
4017 __format::__unmatched_left_brace_in_format_string();
4018 _M_pc.advance_to(begin() + 1); // Move past '}'
4021 constexpr virtual void _M_format_arg(size_t __id) = 0;
4024 // Process a format string and format the arguments in the context.
4025 template<typename _Out, typename _CharT>
4026 class _Formatting_scanner : public _Scanner<_CharT>
4029 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4030 basic_string_view<_CharT> __str)
4031 : _Scanner<_CharT>(__str), _M_fc(__fc)
4035 basic_format_context<_Out, _CharT>& _M_fc;
4037 using iterator = typename _Scanner<_CharT>::iterator;
4040 _M_on_chars(iterator __last) override
4042 basic_string_view<_CharT> __str(this->begin(), __last);
4043 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4047 _M_format_arg(size_t __id) override
4049 using _Context = basic_format_context<_Out, _CharT>;
4050 using handle = typename basic_format_arg<_Context>::handle;
4052 std::visit_format_arg([this](auto& __arg) {
4053 using _Type = remove_reference_t<decltype(__arg)>;
4054 using _Formatter = typename _Context::template formatter_type<_Type>;
4055 if constexpr (is_same_v<_Type, monostate>)
4056 __format::__invalid_arg_id_in_format_string();
4057 else if constexpr (is_same_v<_Type, handle>)
4058 __arg.format(this->_M_pc, this->_M_fc);
4059 else if constexpr (is_default_constructible_v<_Formatter>)
4062 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4063 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4066 static_assert(__format::__formattable_with<_Type, _Context>);
4067 }, _M_fc.arg(__id));
4071 // Validate a format string for Args.
4072 template<typename _CharT, typename... _Args>
4073 class _Checking_scanner : public _Scanner<_CharT>
4076 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4077 "std::formatter must be specialized for each type being formatted");
4081 _Checking_scanner(basic_string_view<_CharT> __str)
4082 : _Scanner<_CharT>(__str, sizeof...(_Args))
4087 _M_format_arg(size_t __id) override
4089 if constexpr (sizeof...(_Args) != 0)
4091 if (__id < sizeof...(_Args))
4093 _M_parse_format_spec<_Args...>(__id);
4097 __builtin_unreachable();
4100 template<typename _Tp, typename... _OtherArgs>
4102 _M_parse_format_spec(size_t __id)
4106 formatter<_Tp, _CharT> __f;
4107 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4109 else if constexpr (sizeof...(_OtherArgs) != 0)
4110 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4112 __builtin_unreachable();
4116 template<typename _Out, typename _CharT, typename _Context>
4118 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4119 const basic_format_args<_Context>& __args,
4120 const locale* __loc)
4122 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4123 _Sink_iter<_CharT> __sink_out;
4125 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4126 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4128 __sink_out = __sink.out();
4130 if constexpr (is_same_v<_CharT, char>)
4131 // Fast path for "{}" format strings and simple format arg types.
4132 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4134 bool __done = false;
4135 std::visit_format_arg([&](auto& __arg) {
4136 using _Tp = remove_cvref_t<decltype(__arg)>;
4137 if constexpr (is_same_v<_Tp, bool>)
4139 size_t __len = 4 + !__arg;
4140 const char* __chars[] = { "false", "true" };
4141 if (auto __res = __sink_out._M_reserve(__len))
4143 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4144 __res._M_bump(__len);
4148 else if constexpr (is_same_v<_Tp, char>)
4150 if (auto __res = __sink_out._M_reserve(1))
4152 *__res.get() = __arg;
4157 else if constexpr (is_integral_v<_Tp>)
4159 make_unsigned_t<_Tp> __uval;
4160 const bool __neg = __arg < 0;
4162 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4165 const auto __n = __detail::__to_chars_len(__uval);
4166 if (auto __res = __sink_out._M_reserve(__n + __neg))
4168 auto __ptr = __res.get();
4170 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4172 __res._M_bump(__n + __neg);
4176 else if constexpr (is_convertible_v<_Tp, string_view>)
4178 string_view __sv = __arg;
4179 if (auto __res = __sink_out._M_reserve(__sv.size()))
4181 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4182 __res._M_bump(__sv.size());
4190 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4193 return std::move(__sink)._M_finish().out;
4197 auto __ctx = __loc == nullptr
4198 ? _Context(__args, __sink_out)
4199 : _Context(__args, __sink_out, *__loc);
4200 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4201 __scanner._M_scan();
4203 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4206 return std::move(__sink)._M_finish().out;
4209} // namespace __format
4212 template<typename _CharT, typename... _Args>
4213 template<typename _Tp>
4214 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4216 basic_format_string<_CharT, _Args...>::
4217 basic_format_string(const _Tp& __s)
4220 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4222 __scanner._M_scan();
4225 // [format.functions], formatting functions
4227 template<typename _Out> requires output_iterator<_Out, const char&>
4228 [[__gnu__::__always_inline__]]
4230 vformat_to(_Out __out, string_view __fmt, format_args __args)
4231 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4233#ifdef _GLIBCXX_USE_WCHAR_T
4234 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4235 [[__gnu__::__always_inline__]]
4237 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4238 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4241 template<typename _Out> requires output_iterator<_Out, const char&>
4242 [[__gnu__::__always_inline__]]
4244 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4247 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4250#ifdef _GLIBCXX_USE_WCHAR_T
4251 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4252 [[__gnu__::__always_inline__]]
4254 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4255 wformat_args __args)
4257 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4263 vformat(string_view __fmt, format_args __args)
4265 __format::_Str_sink<char> __buf;
4266 std::vformat_to(__buf.out(), __fmt, __args);
4267 return std::move(__buf).get();
4270#ifdef _GLIBCXX_USE_WCHAR_T
4273 vformat(wstring_view __fmt, wformat_args __args)
4275 __format::_Str_sink<wchar_t> __buf;
4276 std::vformat_to(__buf.out(), __fmt, __args);
4277 return std::move(__buf).get();
4283 vformat(const locale& __loc, string_view __fmt, format_args __args)
4285 __format::_Str_sink<char> __buf;
4286 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4287 return std::move(__buf).get();
4290#ifdef _GLIBCXX_USE_WCHAR_T
4293 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4295 __format::_Str_sink<wchar_t> __buf;
4296 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4297 return std::move(__buf).get();
4301 template<typename... _Args>
4304 format(format_string<_Args...> __fmt, _Args&&... __args)
4305 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4307#ifdef _GLIBCXX_USE_WCHAR_T
4308 template<typename... _Args>
4311 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4312 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4315 template<typename... _Args>
4318 format(const locale& __loc, format_string<_Args...> __fmt,
4321 return std::vformat(__loc, __fmt.get(),
4322 std::make_format_args(__args...));
4325#ifdef _GLIBCXX_USE_WCHAR_T
4326 template<typename... _Args>
4329 format(const locale& __loc, wformat_string<_Args...> __fmt,
4332 return std::vformat(__loc, __fmt.get(),
4333 std::make_wformat_args(__args...));
4337 template<typename _Out, typename... _Args>
4338 requires output_iterator<_Out, const char&>
4340 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4342 return std::vformat_to(std::move(__out), __fmt.get(),
4343 std::make_format_args(__args...));
4346#ifdef _GLIBCXX_USE_WCHAR_T
4347 template<typename _Out, typename... _Args>
4348 requires output_iterator<_Out, const wchar_t&>
4350 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4352 return std::vformat_to(std::move(__out), __fmt.get(),
4353 std::make_wformat_args(__args...));
4357 template<typename _Out, typename... _Args>
4358 requires output_iterator<_Out, const char&>
4360 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4363 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4364 std::make_format_args(__args...));
4367#ifdef _GLIBCXX_USE_WCHAR_T
4368 template<typename _Out, typename... _Args>
4369 requires output_iterator<_Out, const wchar_t&>
4371 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4374 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4375 std::make_wformat_args(__args...));
4379 template<typename _Out, typename... _Args>
4380 requires output_iterator<_Out, const char&>
4381 inline format_to_n_result<_Out>
4382 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4383 format_string<_Args...> __fmt, _Args&&... __args)
4385 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4386 std::vformat_to(__sink.out(), __fmt.get(),
4387 std::make_format_args(__args...));
4388 return std::move(__sink)._M_finish();
4391#ifdef _GLIBCXX_USE_WCHAR_T
4392 template<typename _Out, typename... _Args>
4393 requires output_iterator<_Out, const wchar_t&>
4394 inline format_to_n_result<_Out>
4395 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4396 wformat_string<_Args...> __fmt, _Args&&... __args)
4398 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4399 std::vformat_to(__sink.out(), __fmt.get(),
4400 std::make_wformat_args(__args...));
4401 return std::move(__sink)._M_finish();
4405 template<typename _Out, typename... _Args>
4406 requires output_iterator<_Out, const char&>
4407 inline format_to_n_result<_Out>
4408 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4409 format_string<_Args...> __fmt, _Args&&... __args)
4411 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4412 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4413 std::make_format_args(__args...));
4414 return std::move(__sink)._M_finish();
4417#ifdef _GLIBCXX_USE_WCHAR_T
4418 template<typename _Out, typename... _Args>
4419 requires output_iterator<_Out, const wchar_t&>
4420 inline format_to_n_result<_Out>
4421 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4422 wformat_string<_Args...> __fmt, _Args&&... __args)
4424 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4425 std::vformat_to(__sink.out(), __loc, __fmt.get(),
4426 std::make_wformat_args(__args...));
4427 return std::move(__sink)._M_finish();
4431/// @cond undocumented
4435 template<typename _CharT>
4436 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
4439 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
4441 [[__gnu__::__always_inline__]]
4444 { return this->_M_count + this->_M_used().size(); }
4447 template<typename _CharT>
4448 class _Counting_sink : public _Buf_sink<_CharT>
4450 size_t _M_count = 0;
4453 _M_overflow() override
4455 if (!std::is_constant_evaluated())
4456 _M_count += this->_M_used().size();
4461 _Counting_sink() = default;
4463 [[__gnu__::__always_inline__]]
4467 _Counting_sink::_M_overflow();
4472} // namespace __format
4475 template<typename... _Args>
4478 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
4480 __format::_Counting_sink<char> __buf;
4481 std::vformat_to(__buf.out(), __fmt.get(),
4482 std::make_format_args(__args...));
4483 return __buf.count();
4486#ifdef _GLIBCXX_USE_WCHAR_T
4487 template<typename... _Args>
4490 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
4492 __format::_Counting_sink<wchar_t> __buf;
4493 std::vformat_to(__buf.out(), __fmt.get(),
4494 std::make_wformat_args(__args...));
4495 return __buf.count();
4499 template<typename... _Args>
4502 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
4505 __format::_Counting_sink<char> __buf;
4506 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4507 std::make_format_args(__args...));
4508 return __buf.count();
4511#ifdef _GLIBCXX_USE_WCHAR_T
4512 template<typename... _Args>
4515 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
4518 __format::_Counting_sink<wchar_t> __buf;
4519 std::vformat_to(__buf.out(), __loc, __fmt.get(),
4520 std::make_wformat_args(__args...));
4521 return __buf.count();
4525#if __cpp_lib_format_ranges
4526 // [format.range], formatting of ranges
4527 // [format.range.fmtkind], variable template format_kind
4528 enum class range_format {
4537 /// @cond undocumented
4538 template<typename _Rg>
4539 constexpr auto format_kind = not defined(format_kind<_Rg>);
4541 template<typename _Tp>
4542 consteval range_format
4545 using _Ref = ranges::range_reference_t<_Tp>;
4546 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
4547 return range_format::disabled;
4548 else if constexpr (requires { typename _Tp::key_type; })
4550 if constexpr (requires { typename _Tp::mapped_type; })
4552 using _Up = remove_cvref_t<_Ref>;
4553 if constexpr (__is_pair<_Up>)
4554 return range_format::map;
4555 else if constexpr (__is_specialization_of<_Up, tuple>)
4556 if constexpr (tuple_size_v<_Up> == 2)
4557 return range_format::map;
4559 return range_format::set;
4562 return range_format::sequence;
4566 /// A constant determining how a range should be formatted.
4567 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
4568 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
4570 // [format.range.formatter], class template range_formatter
4571 template<typename _Tp, typename _CharT = char>
4572 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
4573 class range_formatter; // TODO
4575/// @cond undocumented
4578 // [format.range.fmtdef], class template range-default-formatter
4579 template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
4580 struct __range_default_formatter; // TODO
4581} // namespace __format
4584 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
4585 // specializations for maps, sets, and strings
4586 template<ranges::input_range _Rg, typename _CharT>
4587 requires (format_kind<_Rg> != range_format::disabled)
4588 && formattable<ranges::range_reference_t<_Rg>, _CharT>
4589 struct formatter<_Rg, _CharT>
4590 : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
4592#endif // C++23 formatting ranges
4594_GLIBCXX_END_NAMESPACE_VERSION
4596#endif // __cpp_lib_format
4597#endif // _GLIBCXX_FORMAT