1// <format> Formatting -*- C++ -*-
3// Copyright The GNU Toolchain Authors.
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
25/** @file include/format
26 * This is a Standard C++ Library header.
29#ifndef _GLIBCXX_FORMAT
30#define _GLIBCXX_FORMAT 1
33#pragma GCC system_header
36#include <bits/requires_hosted.h> // for std::string
38#define __glibcxx_want_format
39#define __glibcxx_want_format_ranges
40#define __glibcxx_want_format_uchar
41#include <bits/version.h>
43#ifdef __cpp_lib_format // C++ >= 20 && HOSTED
54#include <bits/monostate.h>
55#include <bits/formatfwd.h>
56#include <bits/ranges_base.h> // input_range, range_reference_t
57#include <bits/ranges_util.h> // subrange
58#include <bits/ranges_algobase.h> // ranges::copy
59#include <bits/stl_iterator.h> // back_insert_iterator
60#include <bits/stl_pair.h> // __is_pair
61#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
62#include <bits/utility.h> // tuple_size_v
63#include <ext/numeric_traits.h> // __int_traits
65#if !__has_builtin(__builtin_toupper)
69#pragma GCC diagnostic push
70#pragma GCC diagnostic ignored "-Wpedantic" // __int128
71#pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
73namespace std _GLIBCXX_VISIBILITY(default)
75_GLIBCXX_BEGIN_NAMESPACE_VERSION
77 // [format.fmt.string], class template basic_format_string
78 template<typename _CharT, typename... _Args> struct basic_format_string;
83 // STATICALLY-WIDEN, see C++20 [time.general]
84 // It doesn't matter for format strings (which can only be char or wchar_t)
85 // but this returns the narrow string for anything that isn't wchar_t. This
86 // is done because const char* can be inserted into any ostream type, and
87 // will be widened at runtime if necessary.
88 template<typename _CharT>
90 _Widen(const char* __narrow, const wchar_t* __wide)
92 if constexpr (is_same_v<_CharT, wchar_t>)
97#define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
98#define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
100 // Size for stack located buffer
101 template<typename _CharT>
102 constexpr size_t __stackbuf_size = 32 * sizeof(void*) / sizeof(_CharT);
104 // Type-erased character sinks.
105 template<typename _CharT> class _Sink;
106 template<typename _CharT> class _Fixedbuf_sink;
107 template<typename _Seq> class _Seq_sink;
109 template<typename _CharT, typename _Alloc = allocator<_CharT>>
111 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
113 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
114 // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
116 // Output iterator that writes to a type-erase character sink.
117 template<typename _CharT>
120 template<typename _CharT>
121 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
123 template<typename _CharT>
124 struct _Runtime_format_string
126 [[__gnu__::__always_inline__]]
127 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
130 _Runtime_format_string(const _Runtime_format_string&) = delete;
131 void operator=(const _Runtime_format_string&) = delete;
134 basic_string_view<_CharT> _M_str;
136 template<typename, typename...> friend struct std::basic_format_string;
138} // namespace __format
141 using format_context = __format::__format_context<char>;
142#ifdef _GLIBCXX_USE_WCHAR_T
143 using wformat_context = __format::__format_context<wchar_t>;
146 // [format.args], class template basic_format_args
147 template<typename _Context> class basic_format_args;
148 using format_args = basic_format_args<format_context>;
149#ifdef _GLIBCXX_USE_WCHAR_T
150 using wformat_args = basic_format_args<wformat_context>;
153 // [format.arguments], arguments
154 // [format.arg], class template basic_format_arg
155 template<typename _Context>
156 class basic_format_arg;
158 /** A compile-time checked format string for the specified argument types.
160 * @since C++23 but available as an extension in C++20.
162 template<typename _CharT, typename... _Args>
163 struct basic_format_string
165 template<typename _Tp>
166 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
168 basic_format_string(const _Tp& __s);
170 [[__gnu__::__always_inline__]]
171 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
175 [[__gnu__::__always_inline__]]
176 constexpr basic_string_view<_CharT>
181 basic_string_view<_CharT> _M_str;
184 template<typename... _Args>
185 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
187#ifdef _GLIBCXX_USE_WCHAR_T
188 template<typename... _Args>
190 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
193#if __cpp_lib_format >= 202311L // >= C++26
194 [[__gnu__::__always_inline__]]
195 inline __format::_Runtime_format_string<char>
196 runtime_format(string_view __fmt) noexcept
199#ifdef _GLIBCXX_USE_WCHAR_T
200 [[__gnu__::__always_inline__]]
201 inline __format::_Runtime_format_string<wchar_t>
202 runtime_format(wstring_view __fmt) noexcept
207 // [format.formatter], formatter
209 /// The primary template of std::formatter is disabled.
210 template<typename _Tp, typename _CharT>
213 formatter() = delete; // No std::formatter specialization for this type.
214 formatter(const formatter&) = delete;
215 formatter& operator=(const formatter&) = delete;
218 // [format.error], class format_error
219 class format_error : public runtime_error
222 explicit format_error(const string& __what) : runtime_error(__what) { }
223 explicit format_error(const char* __what) : runtime_error(__what) { }
226 /// @cond undocumented
229 __throw_format_error(const char* __what)
230 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
234 // XXX use named functions for each constexpr error?
238 __unmatched_left_brace_in_format_string()
239 { __throw_format_error("format error: unmatched '{' in format string"); }
243 __unmatched_right_brace_in_format_string()
244 { __throw_format_error("format error: unmatched '}' in format string"); }
248 __conflicting_indexing_in_format_string()
249 { __throw_format_error("format error: conflicting indexing style in format string"); }
253 __invalid_arg_id_in_format_string()
254 { __throw_format_error("format error: invalid arg-id in format string"); }
258 __failed_to_parse_format_spec()
259 { __throw_format_error("format error: failed to parse format-spec"); }
261 template<typename _CharT> class _Scanner;
263} // namespace __format
266 // [format.parse.ctx], class template basic_format_parse_context
267 template<typename _CharT> class basic_format_parse_context;
268 using format_parse_context = basic_format_parse_context<char>;
269#ifdef _GLIBCXX_USE_WCHAR_T
270 using wformat_parse_context = basic_format_parse_context<wchar_t>;
273 template<typename _CharT>
274 class basic_format_parse_context
277 using char_type = _CharT;
278 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
279 using iterator = const_iterator;
282 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
283 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
286 basic_format_parse_context(const basic_format_parse_context&) = delete;
287 void operator=(const basic_format_parse_context&) = delete;
289 constexpr const_iterator begin() const noexcept { return _M_begin; }
290 constexpr const_iterator end() const noexcept { return _M_end; }
293 advance_to(const_iterator __it) noexcept
299 if (_M_indexing == _Manual)
300 __format::__conflicting_indexing_in_format_string();
303 // _GLIBCXX_RESOLVE_LIB_DEFECTS
304 // 3825. Missing compile-time argument id check in next_arg_id
305 if (std::is_constant_evaluated())
306 if (_M_next_arg_id == _M_num_args)
307 __format::__invalid_arg_id_in_format_string();
308 return _M_next_arg_id++;
312 check_arg_id(size_t __id)
314 if (_M_indexing == _Auto)
315 __format::__conflicting_indexing_in_format_string();
316 _M_indexing = _Manual;
318 if (std::is_constant_evaluated())
319 if (__id >= _M_num_args)
320 __format::__invalid_arg_id_in_format_string();
323#if __cpp_lib_format >= 202305L
324 template<typename... _Ts>
326 check_dynamic_spec(size_t __id) noexcept
328 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
329 "template arguments for check_dynamic_spec<Ts...>(id) "
330 "must be unique and must be one of the allowed types");
332 __check_dynamic_spec<_Ts...>(__id);
337 check_dynamic_spec_integral(size_t __id) noexcept
340 __check_dynamic_spec<int, unsigned, long long,
341 unsigned long long>(__id);
346 check_dynamic_spec_string(size_t __id) noexcept
349 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
354 // True if _Tp occurs exactly once in _Ts.
355 template<typename _Tp, typename... _Ts>
356 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
358 template<typename... _Ts>
360 __valid_types_for_check_dynamic_spec()
362 // _GLIBCXX_RESOLVE_LIB_DEFECTS
363 // 4142. check_dynamic_spec should require at least one type
364 if constexpr (sizeof...(_Ts) == 0)
368 // The types in Ts... are unique. Each type in Ts... is one of
369 // bool, char_type, int, unsigned int, long long int,
370 // unsigned long long int, float, double, long double,
371 // const char_type*, basic_string_view<char_type>, or const void*.
373 = __once<bool, _Ts...>
374 + __once<char_type, _Ts...>
375 + __once<int, _Ts...>
376 + __once<unsigned int, _Ts...>
377 + __once<long long int, _Ts...>
378 + __once<unsigned long long int, _Ts...>
379 + __once<float, _Ts...>
380 + __once<double, _Ts...>
381 + __once<long double, _Ts...>
382 + __once<const char_type*, _Ts...>
383 + __once<basic_string_view<char_type>, _Ts...>
384 + __once<const void*, _Ts...>;
385 return __sum == sizeof...(_Ts);
389 template<typename... _Ts>
391 __check_dynamic_spec(size_t __id) noexcept;
393 // This must not be constexpr.
394 static void __invalid_dynamic_spec(const char*);
396 friend __format::_Scanner<_CharT>;
399 // This constructor should only be used by the implementation.
401 basic_format_parse_context(basic_string_view<_CharT> __fmt,
402 size_t __num_args) noexcept
403 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
409 enum _Indexing { _Unknown, _Manual, _Auto };
410 _Indexing _M_indexing = _Unknown;
411 size_t _M_next_arg_id = 0;
412 size_t _M_num_args = 0;
415/// @cond undocumented
416 template<typename _Tp, template<typename...> class _Class>
417 constexpr bool __is_specialization_of = false;
418 template<template<typename...> class _Class, typename... _Args>
419 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
423 // pre: first != last
424 template<typename _CharT>
425 constexpr pair<unsigned short, const _CharT*>
426 __parse_integer(const _CharT* __first, const _CharT* __last)
428 if (__first == __last)
429 __builtin_unreachable();
431 if constexpr (is_same_v<_CharT, char>)
433 const auto __start = __first;
434 unsigned short __val = 0;
435 // N.B. std::from_chars is not constexpr in C++20.
436 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
437 && __first != __start) [[likely]]
438 return {__val, __first};
442 constexpr int __n = 32;
444 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
445 __buf[__i] = __first[__i];
446 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
447 if (__ptr) [[likely]]
448 return {__v, __first + (__ptr - __buf)};
453 template<typename _CharT>
454 constexpr pair<unsigned short, const _CharT*>
455 __parse_arg_id(const _CharT* __first, const _CharT* __last)
457 if (__first == __last)
458 __builtin_unreachable();
461 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
463 if ('1' <= *__first && *__first <= '9')
465 const unsigned short __id = *__first - '0';
466 const auto __next = __first + 1;
467 // Optimize for most likely case of single digit arg-id.
468 if (__next == __last || !('0' <= *__next && *__next <= '9'))
469 return {__id, __next};
471 return __format::__parse_integer(__first, __last);
477 _Pres_none = 0, // Default type (not valid for integer presentation types).
478 // Presentation types for integral types (including bool and charT).
479 _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
480 // Presentation types for floating-point types.
481 _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
482 _Pres_p = 0, _Pres_P, // For pointers.
483 _Pres_s = 0, // For strings, bool
484 _Pres_seq = 0, _Pres_str, // For ranges
485 _Pres_esc = 0xf, // For strings, charT and ranges
498 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
503 _WP_none, // No width/prec specified.
504 _WP_value, // Fixed width/prec specified.
505 _WP_from_arg // Use a formatting argument for width/prec.
508 template<typename _Context>
510 __int_from_arg(const basic_format_arg<_Context>& __arg);
512 constexpr bool __is_digit(char __c)
513 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
515 constexpr bool __is_xdigit(char __c)
516 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
518 template<typename _CharT>
524 unsigned _M_localized : 1;
525 unsigned _M_zero_fill : 1;
526 _WidthPrec _M_width_kind : 2;
527 _WidthPrec _M_prec_kind : 2;
528 _Pres_type _M_type : 4;
529 unsigned _M_reserved : 1;
530 unsigned _M_reserved2 : 16;
531 unsigned short _M_width;
532 unsigned short _M_prec;
533 char32_t _M_fill = ' ';
535 using iterator = typename basic_string_view<_CharT>::iterator;
537 static constexpr _Align
538 _S_align(_CharT __c) noexcept
542 case '<': return _Align_left;
543 case '>': return _Align_right;
544 case '^': return _Align_centre;
545 default: return _Align_default;
549 // pre: __first != __last
551 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
552 { return _M_parse_fill_and_align(__first, __last, "{"); }
554 // pre: __first != __last
556 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
558 for (char __c : __not_fill)
559 if (*__first == static_cast<_CharT>(__c))
562 using namespace __unicode;
563 if constexpr (__literal_encoding_is_unicode<_CharT>())
565 // Accept any UCS scalar value as fill character.
566 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
569 auto __beg = __uv.begin();
570 char32_t __c = *__beg++;
571 if (__is_scalar_value(__c))
572 if (auto __next = __beg.base(); __next != __last)
573 if (_Align __align = _S_align(*__next))
581 else if (__last - __first >= 2)
582 if (_Align __align = _S_align(__first[1]))
589 if (_Align __align = _S_align(__first[0]))
598 static constexpr _Sign
599 _S_sign(_CharT __c) noexcept
603 case '+': return _Sign_plus;
604 case '-': return _Sign_minus;
605 case ' ': return _Sign_space;
606 default: return _Sign_default;
610 // pre: __first != __last
612 _M_parse_sign(iterator __first, iterator) noexcept
614 if (_Sign __sign = _S_sign(*__first))
622 // pre: *__first is valid
624 _M_parse_alternate_form(iterator __first, iterator) noexcept
634 // pre: __first != __last
636 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
646 // pre: __first != __last
647 static constexpr iterator
648 _S_parse_width_or_precision(iterator __first, iterator __last,
649 unsigned short& __val, bool& __arg_id,
650 basic_format_parse_context<_CharT>& __pc)
652 if (__format::__is_digit(*__first))
654 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
656 __throw_format_error("format error: invalid width or precision "
661 else if (*__first == '{')
665 if (__first == __last)
666 __format::__unmatched_left_brace_in_format_string();
668 __val = __pc.next_arg_id();
671 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
672 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
673 __format::__invalid_arg_id_in_format_string();
675 __pc.check_arg_id(__v);
678#if __cpp_lib_format >= 202305L
679 __pc.check_dynamic_spec_integral(__val);
681 ++__first; // past the '}'
686 // pre: __first != __last
688 _M_parse_width(iterator __first, iterator __last,
689 basic_format_parse_context<_CharT>& __pc)
691 bool __arg_id = false;
693 __throw_format_error("format error: width must be non-zero in "
695 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
697 if (__next != __first)
698 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
702 // pre: __first != __last
704 _M_parse_precision(iterator __first, iterator __last,
705 basic_format_parse_context<_CharT>& __pc)
707 if (__first[0] != '.')
710 iterator __next = ++__first;
711 bool __arg_id = false;
712 if (__next != __last)
713 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
715 if (__next == __first)
716 __throw_format_error("format error: missing precision after '.' in "
718 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
722 // pre: __first != __last
724 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
734 template<typename _Context>
736 _M_get_width(_Context& __ctx) const
739 if (_M_width_kind == _WP_value)
741 else if (_M_width_kind == _WP_from_arg)
742 __width = __format::__int_from_arg(__ctx.arg(_M_width));
746 template<typename _Context>
748 _M_get_precision(_Context& __ctx) const
751 if (_M_prec_kind == _WP_value)
753 else if (_M_prec_kind == _WP_from_arg)
754 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
759 template<typename _Int>
761 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
765 else if (__sign == _Sign_plus)
767 else if (__sign == _Sign_space)
774 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
775 template<typename _Out, typename _CharT>
776 requires output_iterator<_Out, const _CharT&>
778 __write(_Out __out, basic_string_view<_CharT> __str)
780 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
786 for (_CharT __c : __str)
791 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
792 // pre: __align != _Align_default
793 template<typename _Out, typename _CharT>
795 __write_padded(_Out __out, basic_string_view<_CharT> __str,
796 _Align __align, size_t __nfill, char32_t __fill_char)
798 const size_t __buflen = 0x20;
799 _CharT __padding_chars[__buflen];
800 __padding_chars[0] = _CharT();
801 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
803 auto __pad = [&__padding] (size_t __n, _Out& __o) {
806 while (__n > __padding.size())
808 __o = __format::__write(std::move(__o), __padding);
809 __n -= __padding.size();
812 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
815 size_t __l, __r, __max;
816 if (__align == _Align_centre)
819 __r = __l + (__nfill & 1);
822 else if (__align == _Align_right)
835 using namespace __unicode;
836 if constexpr (__literal_encoding_is_unicode<_CharT>())
837 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
839 // Encode fill char as multiple code units of type _CharT.
840 const char32_t __arr[1]{ __fill_char };
841 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
842 basic_string<_CharT> __padstr(__v.begin(), __v.end());
843 __padding = __padstr;
845 __out = __format::__write(std::move(__out), __padding);
846 __out = __format::__write(std::move(__out), __str);
848 __out = __format::__write(std::move(__out), __padding);
852 if (__max < __buflen)
853 __padding.remove_suffix(__buflen - __max);
857 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
859 __out = __format::__write(std::move(__out), __str);
865 // Write STR to OUT, with alignment and padding as determined by SPEC.
866 // pre: __spec._M_align != _Align_default || __align != _Align_default
867 template<typename _CharT, typename _Out>
869 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
870 size_t __estimated_width,
871 basic_format_context<_Out, _CharT>& __fc,
872 const _Spec<_CharT>& __spec,
873 _Align __align = _Align_left)
875 size_t __width = __spec._M_get_width(__fc);
877 if (__width <= __estimated_width)
878 return __format::__write(__fc.out(), __str);
880 const size_t __nfill = __width - __estimated_width;
883 __align = __spec._M_align;
885 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
889 // Values are indices into _Escapes::all.
890 enum class _Term_char : unsigned char {
895 template<typename _CharT>
898 using _Str_view = basic_string_view<_CharT>;
902 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
905 _CharT _S_term(_Term_char __term)
906 { return _S_all()[static_cast<unsigned char>(__term)]; }
910 { return _S_all().substr(0, 3); }
913 _Str_view _S_newline()
914 { return _S_all().substr(3, 3); }
917 _Str_view _S_return()
918 { return _S_all().substr(6, 3); }
921 _Str_view _S_bslash()
922 { return _S_all().substr(9, 3); }
926 { return _S_all().substr(12, 3); }
930 { return _S_all().substr(15, 3); }
934 { return _S_all().substr(18, 2); }
938 { return _S_all().substr(20, 2); }
941 template<typename _CharT>
944 using _Str_view = basic_string_view<_CharT>;
948 { return _GLIBCXX_WIDEN("[]{}(), : "); }
951 _Str_view _S_squares()
952 { return _S_all().substr(0, 2); }
955 _Str_view _S_braces()
956 { return _S_all().substr(2, 2); }
959 _Str_view _S_parens()
960 { return _S_all().substr(4, 2); }
964 { return _S_all().substr(6, 2); }
968 { return _S_all().substr(8, 2); }
971 template<typename _CharT>
972 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
974 using _Esc = _Escapes<_CharT>;
977 case _Esc::_S_tab()[0]:
978 case _Esc::_S_newline()[0]:
979 case _Esc::_S_return()[0]:
980 case _Esc::_S_bslash()[0]:
982 case _Esc::_S_quote()[0]:
983 return __term == _Term_char::_Tc_quote;
984 case _Esc::_S_apos()[0]:
985 return __term == _Term_char::_Tc_apos;
987 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
991 // @pre __c <= 0x10FFFF
992 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
994 if (__unicode::__should_escape_category(__c))
998 return __unicode::__grapheme_cluster_break_property(__c)
999 == __unicode::_Gcb_property::_Gcb_Extend;
1002 using uint_least32_t = __UINT_LEAST32_TYPE__;
1003 template<typename _Out, typename _CharT>
1005 __write_escape_seq(_Out __out, uint_least32_t __val,
1006 basic_string_view<_CharT> __prefix)
1008 using _Str_view = basic_string_view<_CharT>;
1009 constexpr size_t __max = 8;
1011 const string_view __narrow(
1013 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1015 __out = __format::__write(__out, __prefix);
1016 *__out = _Separators<_CharT>::_S_braces()[0];
1018 if constexpr (is_same_v<char, _CharT>)
1019 __out = __format::__write(__out, __narrow);
1020#ifdef _GLIBCXX_USE_WCHAR_T
1023 _CharT __wbuf[__max];
1024 const size_t __n = __narrow.size();
1025 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1026 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1029 *__out = _Separators<_CharT>::_S_braces()[1];
1033 template<typename _Out, typename _CharT>
1035 __write_escaped_char(_Out __out, _CharT __c)
1037 using _UChar = make_unsigned_t<_CharT>;
1038 using _Esc = _Escapes<_CharT>;
1041 case _Esc::_S_tab()[0]:
1042 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1043 case _Esc::_S_newline()[0]:
1044 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1045 case _Esc::_S_return()[0]:
1046 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1047 case _Esc::_S_bslash()[0]:
1048 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1049 case _Esc::_S_quote()[0]:
1050 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1051 case _Esc::_S_apos()[0]:
1052 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1054 return __format::__write_escape_seq(__out,
1055 static_cast<_UChar>(__c),
1060 template<typename _CharT, typename _Out>
1062 __write_escaped_ascii(_Out __out,
1063 basic_string_view<_CharT> __str,
1066 using _Str_view = basic_string_view<_CharT>;
1067 auto __first = __str.begin();
1068 auto const __last = __str.end();
1069 while (__first != __last)
1071 auto __print = __first;
1072 // assume anything outside ASCII is printable
1073 while (__print != __last
1074 && !__format::__should_escape_ascii(*__print, __term))
1077 if (__print != __first)
1078 __out = __format::__write(__out, _Str_view(__first, __print));
1080 if (__print == __last)
1084 __out = __format::__write_escaped_char(__out, *__first);
1090 template<typename _CharT, typename _Out>
1092 __write_escaped_unicode(_Out __out,
1093 basic_string_view<_CharT> __str,
1096 using _Str_view = basic_string_view<_CharT>;
1097 using _UChar = make_unsigned_t<_CharT>;
1098 using _Esc = _Escapes<_CharT>;
1100 static constexpr char32_t __replace = U'\uFFFD';
1101 static constexpr _Str_view __replace_rep = []
1103 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1104 if constexpr (is_same_v<char, _CharT>)
1105 return "\xEF\xBF\xBD";
1110 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1111 auto __first = __v.begin();
1112 auto const __last = __v.end();
1114 bool __prev_esc = true;
1115 while (__first != __last)
1117 bool __esc_ascii = false;
1118 bool __esc_unicode = false;
1119 bool __esc_replace = false;
1120 auto __should_escape = [&](auto const& __it)
1124 = __format::__should_escape_ascii(*__it.base(), __term);
1125 if (__format::__should_escape_unicode(*__it, __prev_esc))
1126 return __esc_unicode = true;
1127 if (*__it == __replace)
1129 _Str_view __units(__it.base(), __it._M_units());
1130 return __esc_replace = (__units != __replace_rep);
1135 auto __print = __first;
1136 while (__print != __last && !__should_escape(__print))
1142 if (__print != __first)
1143 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1145 if (__print == __last)
1150 __out = __format::__write_escaped_char(__out, *__first.base());
1151 else if (__esc_unicode)
1152 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1153 else // __esc_replace
1154 for (_CharT __c : _Str_view(__first.base(), __first._M_units()))
1155 __out = __format::__write_escape_seq(__out,
1156 static_cast<_UChar>(__c),
1165 template<typename _CharT, typename _Out>
1167 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1169 *__out = _Escapes<_CharT>::_S_term(__term);
1172 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1173 __out = __format::__write_escaped_unicode(__out, __str, __term);
1174 else if constexpr (is_same_v<char, _CharT>
1175 && __unicode::__literal_encoding_is_extended_ascii())
1176 __out = __format::__write_escaped_ascii(__out, __str, __term);
1178 // TODO Handle non-ascii extended encoding
1179 __out = __format::__write_escaped_ascii(__out, __str, __term);
1181 *__out = _Escapes<_CharT>::_S_term(__term);
1185 // A lightweight optional<locale>.
1186 struct _Optional_locale
1188 [[__gnu__::__always_inline__]]
1189 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1191 _Optional_locale(const locale& __loc) noexcept
1192 : _M_loc(__loc), _M_hasval(true)
1195 _Optional_locale(const _Optional_locale& __l) noexcept
1196 : _M_dummy(), _M_hasval(__l._M_hasval)
1199 std::construct_at(&_M_loc, __l._M_loc);
1203 operator=(const _Optional_locale& __l) noexcept
1208 _M_loc = __l._M_loc;
1215 else if (__l._M_hasval)
1217 std::construct_at(&_M_loc, __l._M_loc);
1223 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1226 operator=(locale&& __loc) noexcept
1229 _M_loc = std::move(__loc);
1232 std::construct_at(&_M_loc, std::move(__loc));
1243 std::construct_at(&_M_loc);
1249 bool has_value() const noexcept { return _M_hasval; }
1252 char _M_dummy = '\0';
1255 bool _M_hasval = false;
1258 template<__char _CharT>
1259 struct __formatter_str
1261 __formatter_str() = default;
1264 __formatter_str(_Spec<_CharT> __spec) noexcept
1268 constexpr typename basic_format_parse_context<_CharT>::iterator
1269 parse(basic_format_parse_context<_CharT>& __pc)
1271 auto __first = __pc.begin();
1272 const auto __last = __pc.end();
1273 _Spec<_CharT> __spec{};
1275 auto __finalize = [this, &__spec] {
1279 auto __finished = [&] {
1280 if (__first == __last || *__first == '}')
1291 __first = __spec._M_parse_fill_and_align(__first, __last);
1295 __first = __spec._M_parse_width(__first, __last, __pc);
1299 __first = __spec._M_parse_precision(__first, __last, __pc);
1303 if (*__first == 's')
1305#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1306 else if (*__first == '?')
1308 __spec._M_type = _Pres_esc;
1316 __format::__failed_to_parse_format_spec();
1319 template<typename _Out>
1321 format(basic_string_view<_CharT> __s,
1322 basic_format_context<_Out, _CharT>& __fc) const
1324 constexpr auto __term = __format::_Term_char::_Tc_quote;
1325 const auto __write_direct = [&]
1327 if (_M_spec._M_type == _Pres_esc)
1328 return __format::__write_escaped(__fc.out(), __s, __term);
1330 return __format::__write(__fc.out(), __s);
1333 if (_M_spec._M_width_kind == _WP_none
1334 && _M_spec._M_prec_kind == _WP_none)
1335 return __write_direct();
1337 const size_t __prec =
1338 _M_spec._M_prec_kind != _WP_none
1339 ? _M_spec._M_get_precision(__fc)
1340 : basic_string_view<_CharT>::npos;
1342 const size_t __estimated_width = _S_trunc(__s, __prec);
1343 // N.B. Escaping only increases width
1344 if (_M_spec._M_get_width(__fc) <= __estimated_width
1345 && _M_spec._M_prec_kind == _WP_none)
1346 return __write_direct();
1348 if (_M_spec._M_type != _Pres_esc)
1349 return __format::__write_padded_as_spec(__s, __estimated_width,
1352 __format::_Str_sink<_CharT> __sink;
1353 __format::__write_escaped(__sink.out(), __s, __term);
1354 basic_string_view<_CharT> __escaped(__sink.view().data(),
1355 __sink.view().size());
1356 const size_t __escaped_width = _S_trunc(__escaped, __prec);
1357 // N.B. [tab:format.type.string] defines '?' as
1358 // Copies the escaped string ([format.string.escaped]) to the output,
1359 // so precision seem to appy to escaped string.
1360 return __format::__write_padded_as_spec(__escaped, __escaped_width,
1364#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1365 template<ranges::input_range _Rg, typename _Out>
1366 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1367 typename basic_format_context<_Out, _CharT>::iterator
1368 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1370 using _String = basic_string<_CharT>;
1371 using _String_view = basic_string_view<_CharT>;
1372 if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
1374 const size_t __n(ranges::distance(__rg));
1375 if constexpr (ranges::contiguous_range<_Rg>)
1376 return format(_String_view(ranges::data(__rg), __n), __fc);
1377 else if (__n <= __format::__stackbuf_size<_CharT>)
1379 _CharT __buf[__format::__stackbuf_size<_CharT>];
1380 ranges::copy(__rg, __buf);
1381 return format(_String_view(__buf, __n), __fc);
1383 else if constexpr (ranges::sized_range<_Rg>)
1384 return format(_String(from_range, __rg), __fc);
1385 else if constexpr (ranges::random_access_range<_Rg>)
1387 ranges::iterator_t<_Rg> __first = ranges::begin(__rg);
1388 ranges::subrange __sub(__first, __first + __n);
1389 return format(_String(from_range, __sub), __fc);
1393 // N.B. preserve the computed size
1394 ranges::subrange __sub(__rg, __n);
1395 return format(_String(from_range, __sub), __fc);
1399 return format(_String(from_range, __rg), __fc);
1403 set_debug_format() noexcept
1404 { _M_spec._M_type = _Pres_esc; }
1409 _S_trunc(basic_string_view<_CharT>& __s, size_t __prec)
1411 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1413 if (__prec != basic_string_view<_CharT>::npos)
1414 return __unicode::__truncate(__s, __prec);
1416 return __unicode::__field_width(__s);
1420 __s = __s.substr(0, __prec);
1425 _Spec<_CharT> _M_spec{};
1428 template<__char _CharT>
1429 struct __formatter_int
1431 // If no presentation type is specified, meaning of "none" depends
1432 // whether we are formatting an integer or a char or a bool.
1433 static constexpr _Pres_type _AsInteger = _Pres_d;
1434 static constexpr _Pres_type _AsBool = _Pres_s;
1435 static constexpr _Pres_type _AsChar = _Pres_c;
1437 constexpr typename basic_format_parse_context<_CharT>::iterator
1438 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1440 _Spec<_CharT> __spec{};
1441 __spec._M_type = __type;
1443 const auto __last = __pc.end();
1444 auto __first = __pc.begin();
1446 auto __finalize = [this, &__spec] {
1450 auto __finished = [&] {
1451 if (__first == __last || *__first == '}')
1462 __first = __spec._M_parse_fill_and_align(__first, __last);
1466 __first = __spec._M_parse_sign(__first, __last);
1470 __first = __spec._M_parse_alternate_form(__first, __last);
1474 __first = __spec._M_parse_zero_fill(__first, __last);
1478 __first = __spec._M_parse_width(__first, __last, __pc);
1482 __first = __spec._M_parse_locale(__first, __last);
1489 __spec._M_type = _Pres_b;
1493 __spec._M_type = _Pres_B;
1497 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1498 // 3586. format should not print bool with 'c'
1499 if (__type != _AsBool)
1501 __spec._M_type = _Pres_c;
1506 __spec._M_type = _Pres_d;
1510 __spec._M_type = _Pres_o;
1514 __spec._M_type = _Pres_x;
1518 __spec._M_type = _Pres_X;
1522 if (__type == _AsBool)
1524 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1528#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1530 if (__type == _AsChar)
1532 __spec._M_type = _Pres_esc;
1542 __format::__failed_to_parse_format_spec();
1545 template<typename _Tp>
1546 constexpr typename basic_format_parse_context<_CharT>::iterator
1547 _M_parse(basic_format_parse_context<_CharT>& __pc)
1549 if constexpr (is_same_v<_Tp, bool>)
1551 auto __end = _M_do_parse(__pc, _AsBool);
1552 if (_M_spec._M_type == _Pres_s)
1553 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1554 __throw_format_error("format error: format-spec contains "
1555 "invalid formatting options for "
1559 else if constexpr (__char<_Tp>)
1561 auto __end = _M_do_parse(__pc, _AsChar);
1562 if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1563 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1564 /* XXX should be invalid? || _M_spec._M_localized */)
1565 __throw_format_error("format error: format-spec contains "
1566 "invalid formatting options for "
1571 return _M_do_parse(__pc, _AsInteger);
1574 template<typename _Int, typename _Out>
1575 typename basic_format_context<_Out, _CharT>::iterator
1576 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1578 if (_M_spec._M_type == _Pres_c)
1579 return _M_format_character(_S_to_character(__i), __fc);
1581 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1582 to_chars_result __res{};
1584 string_view __base_prefix;
1585 make_unsigned_t<_Int> __u;
1587 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1591 char* __start = __buf + 3;
1592 char* const __end = __buf + sizeof(__buf);
1593 char* const __start_digits = __start;
1595 switch (_M_spec._M_type)
1599 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1600 __res = to_chars(__start, __end, __u, 2);
1604 return _M_format_character(_S_to_character(__i), __fc);
1607 // Should not reach here with _Pres_none for bool or charT, so:
1610 __res = to_chars(__start, __end, __u, 10);
1614 __base_prefix = "0";
1615 __res = to_chars(__start, __end, __u, 8);
1619 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1620 __res = to_chars(__start, __end, __u, 16);
1621 if (_M_spec._M_type == _Pres_X)
1622 for (auto __p = __start; __p != __res.ptr; ++__p)
1623#if __has_builtin(__builtin_toupper)
1624 *__p = __builtin_toupper(*__p);
1626 *__p = std::toupper(*__p);
1630 __builtin_unreachable();
1633 if (_M_spec._M_alt && __base_prefix.size())
1635 __start -= __base_prefix.size();
1636 __builtin_memcpy(__start, __base_prefix.data(),
1637 __base_prefix.size());
1639 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1641 return _M_format_int(string_view(__start, __res.ptr - __start),
1642 __start_digits - __start, __fc);
1645 template<typename _Out>
1646 typename basic_format_context<_Out, _CharT>::iterator
1647 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1649 if (_M_spec._M_type == _Pres_c)
1650 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1651 if (_M_spec._M_type != _Pres_s)
1652 return format(static_cast<unsigned char>(__i), __fc);
1654 basic_string<_CharT> __s;
1656 if (_M_spec._M_localized) [[unlikely]]
1658 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1659 __s = __i ? __np.truename() : __np.falsename();
1660 __est_width = __s.size(); // TODO Unicode-aware estimate
1664 if constexpr (is_same_v<char, _CharT>)
1665 __s = __i ? "true" : "false";
1667 __s = __i ? L"true" : L"false";
1668 __est_width = __s.size();
1671 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1675 [[__gnu__::__always_inline__]]
1677 _S_character_width(_CharT __c)
1679 // N.B. single byte cannot encode charcter of width greater than 1
1680 if constexpr (sizeof(_CharT) > 1u &&
1681 __unicode::__literal_encoding_is_unicode<_CharT>())
1682 return __unicode::__field_width(__c);
1687 template<typename _Out>
1688 typename basic_format_context<_Out, _CharT>::iterator
1689 _M_format_character(_CharT __c,
1690 basic_format_context<_Out, _CharT>& __fc) const
1692 return __format::__write_padded_as_spec({&__c, 1u},
1693 _S_character_width(__c),
1697 template<typename _Out>
1698 typename basic_format_context<_Out, _CharT>::iterator
1699 _M_format_character_escaped(_CharT __c,
1700 basic_format_context<_Out, _CharT>& __fc) const
1702 using _Esc = _Escapes<_CharT>;
1703 constexpr auto __term = __format::_Term_char::_Tc_apos;
1704 const basic_string_view<_CharT> __in(&__c, 1u);
1705 if (_M_spec._M_get_width(__fc) <= 3u)
1706 return __format::__write_escaped(__fc.out(), __in, __term);
1709 __format::_Fixedbuf_sink<_CharT> __sink(__buf);
1710 __format::__write_escaped(__sink.out(), __in, __term);
1712 const basic_string_view<_CharT> __escaped = __sink.view();
1713 size_t __estimated_width;
1714 if (__escaped[1] == _Esc::_S_bslash()[0]) // escape sequence
1715 __estimated_width = __escaped.size();
1717 __estimated_width = 2 + _S_character_width(__c);
1718 return __format::__write_padded_as_spec(__escaped,
1723 template<typename _Int>
1725 _S_to_character(_Int __i)
1727 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1728 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1730 if (_Traits::__min <= __i && __i <= _Traits::__max)
1731 return static_cast<_CharT>(__i);
1733 else if constexpr (is_signed_v<_Int>)
1735 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1736 return static_cast<_CharT>(__i);
1738 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1739 return static_cast<_CharT>(__i);
1740 __throw_format_error("format error: integer not representable as "
1744 template<typename _Out>
1745 typename basic_format_context<_Out, _CharT>::iterator
1746 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1747 basic_format_context<_Out, _CharT>& __fc) const
1749 size_t __width = _M_spec._M_get_width(__fc);
1751 basic_string_view<_CharT> __str;
1752 if constexpr (is_same_v<char, _CharT>)
1753 __str = __narrow_str;
1754#ifdef _GLIBCXX_USE_WCHAR_T
1757 size_t __n = __narrow_str.size();
1758 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1759 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1764 if (_M_spec._M_localized)
1766 const auto& __l = __fc.locale();
1767 if (__l.name() != "C")
1769 auto& __np = use_facet<numpunct<_CharT>>(__l);
1770 string __grp = __np.grouping();
1773 size_t __n = __str.size() - __prefix_len;
1774 auto __p = (_CharT*)__builtin_alloca(2 * __n
1777 auto __s = __str.data();
1778 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1779 __s += __prefix_len;
1780 auto __end = std::__add_grouping(__p + __prefix_len,
1781 __np.thousands_sep(),
1785 __str = {__p, size_t(__end - __p)};
1790 if (__width <= __str.size())
1791 return __format::__write(__fc.out(), __str);
1793 char32_t __fill_char = _M_spec._M_fill;
1794 _Align __align = _M_spec._M_align;
1796 size_t __nfill = __width - __str.size();
1797 auto __out = __fc.out();
1798 if (__align == _Align_default)
1800 __align = _Align_right;
1801 if (_M_spec._M_zero_fill)
1803 __fill_char = _CharT('0');
1804 // Write sign and base prefix before zero filling.
1805 if (__prefix_len != 0)
1807 __out = __format::__write(std::move(__out),
1808 __str.substr(0, __prefix_len));
1809 __str.remove_prefix(__prefix_len);
1813 __fill_char = _CharT(' ');
1815 return __format::__write_padded(std::move(__out), __str,
1816 __align, __nfill, __fill_char);
1819#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1820 template<typename _Tp>
1821 using make_unsigned_t
1822 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1823 std::make_unsigned<_Tp>,
1824 type_identity<unsigned __int128>>::type;
1826 // std::to_chars is not overloaded for int128 in strict mode.
1827 template<typename _Int>
1828 static to_chars_result
1829 to_chars(char* __first, char* __last, _Int __value, int __base)
1830 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1833 _Spec<_CharT> _M_spec{};
1836 // Decide how 128-bit floating-point types should be formatted (or not).
1837 // When supported, the typedef __format::__float128_t is the type that
1838 // format arguments should be converted to for storage in basic_format_arg.
1839 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1840 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1841 // by converting them to long double (or __ieee128 for powerpc64le).
1842 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1843 // support for _Float128, rather than formatting it as another type.
1844#undef _GLIBCXX_FORMAT_F128
1846#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1848 // Format 128-bit floating-point types using __ieee128.
1849 using __float128_t = __ieee128;
1850# define _GLIBCXX_FORMAT_F128 1
1852#ifdef __LONG_DOUBLE_IEEE128__
1853 // These overloads exist in the library, but are not declared.
1854 // Make them available as std::__format::to_chars.
1856 to_chars(char*, char*, __ibm128) noexcept
1857 __asm("_ZSt8to_charsPcS_e");
1860 to_chars(char*, char*, __ibm128, chars_format) noexcept
1861 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1864 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1865 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1866#elif __cplusplus == 202002L
1868 to_chars(char*, char*, __ieee128) noexcept
1869 __asm("_ZSt8to_charsPcS_u9__ieee128");
1872 to_chars(char*, char*, __ieee128, chars_format) noexcept
1873 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1876 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1877 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1880#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1882 // Format 128-bit floating-point types using long double.
1883 using __float128_t = long double;
1884# define _GLIBCXX_FORMAT_F128 1
1886#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1888 // Format 128-bit floating-point types using _Float128.
1889 using __float128_t = _Float128;
1890# define _GLIBCXX_FORMAT_F128 2
1892# if __cplusplus == 202002L
1893 // These overloads exist in the library, but are not declared for C++20.
1894 // Make them available as std::__format::to_chars.
1896 to_chars(char*, char*, _Float128) noexcept
1897# if _GLIBCXX_INLINE_VERSION
1898 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1900 __asm("_ZSt8to_charsPcS_DF128_");
1904 to_chars(char*, char*, _Float128, chars_format) noexcept
1905# if _GLIBCXX_INLINE_VERSION
1906 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1908 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1912 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1913# if _GLIBCXX_INLINE_VERSION
1914 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1916 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1921 using std::to_chars;
1923 // We can format a floating-point type iff it is usable with to_chars.
1924 template<typename _Tp>
1925 concept __formattable_float
1926 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1927 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1929 template<__char _CharT>
1930 struct __formatter_fp
1932 constexpr typename basic_format_parse_context<_CharT>::iterator
1933 parse(basic_format_parse_context<_CharT>& __pc)
1935 _Spec<_CharT> __spec{};
1936 const auto __last = __pc.end();
1937 auto __first = __pc.begin();
1939 auto __finalize = [this, &__spec] {
1943 auto __finished = [&] {
1944 if (__first == __last || *__first == '}')
1955 __first = __spec._M_parse_fill_and_align(__first, __last);
1959 __first = __spec._M_parse_sign(__first, __last);
1963 __first = __spec._M_parse_alternate_form(__first, __last);
1967 __first = __spec._M_parse_zero_fill(__first, __last);
1971 if (__first[0] != '.')
1973 __first = __spec._M_parse_width(__first, __last, __pc);
1978 __first = __spec._M_parse_precision(__first, __last, __pc);
1982 __first = __spec._M_parse_locale(__first, __last);
1989 __spec._M_type = _Pres_a;
1993 __spec._M_type = _Pres_A;
1997 __spec._M_type = _Pres_e;
2001 __spec._M_type = _Pres_E;
2005 __spec._M_type = _Pres_f;
2009 __spec._M_type = _Pres_F;
2013 __spec._M_type = _Pres_g;
2017 __spec._M_type = _Pres_G;
2025 __format::__failed_to_parse_format_spec();
2028 template<typename _Fp, typename _Out>
2029 typename basic_format_context<_Out, _CharT>::iterator
2030 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2032 std::string __dynbuf;
2034 to_chars_result __res{};
2037 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2039 __prec = _M_spec._M_get_precision(__fc);
2041 char* __start = __buf + 1; // reserve space for sign
2042 char* __end = __buf + sizeof(__buf);
2044 chars_format __fmt{};
2045 bool __upper = false;
2046 bool __trailing_zeros = false;
2049 switch (_M_spec._M_type)
2056 if (_M_spec._M_type != _Pres_A)
2058 __fmt = chars_format::hex;
2066 __fmt = chars_format::scientific;
2073 __fmt = chars_format::fixed;
2080 __trailing_zeros = true;
2082 __fmt = chars_format::general;
2086 __fmt = chars_format::general;
2089 __builtin_unreachable();
2092 // Write value into buffer using std::to_chars.
2093 auto __to_chars = [&](char* __b, char* __e) {
2095 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2096 else if (__fmt != chars_format{})
2097 return __format::to_chars(__b, __e, __v, __fmt);
2099 return __format::to_chars(__b, __e, __v);
2102 // First try using stack buffer.
2103 __res = __to_chars(__start, __end);
2105 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2107 // If the buffer is too small it's probably because of a large
2108 // precision, or a very large value in fixed format.
2109 size_t __guess = 8 + __prec;
2110 if (__fmt == chars_format::fixed) // +ddd.prec
2112 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2113 || is_same_v<_Fp, long double>)
2115 // The number of digits to the left of the decimal point
2116 // is floor(log10(max(abs(__v),1)))+1
2118 if constexpr (is_same_v<_Fp, float>)
2119 __builtin_frexpf(__v, &__exp);
2120 else if constexpr (is_same_v<_Fp, double>)
2121 __builtin_frexp(__v, &__exp);
2122 else if constexpr (is_same_v<_Fp, long double>)
2123 __builtin_frexpl(__v, &__exp);
2125 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2128 __guess += numeric_limits<_Fp>::max_exponent10;
2130 if (__guess <= sizeof(__buf)) [[unlikely]]
2131 __guess = sizeof(__buf) * 2;
2132 __dynbuf.reserve(__guess);
2136 // Mangling of this lambda, and thus resize_and_overwrite
2137 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2138 // <format> was new in G++ 13, and is experimental, that
2140 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
2142 __res = __to_chars(__p + 1, __p + __n - 1);
2143 return __res.ec == errc{} ? __res.ptr - __p : 0;
2146 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2148 __start = __dynbuf.data() + 1; // reserve space for sign
2149 __end = __dynbuf.data() + __dynbuf.size();
2151 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2154 // Use uppercase for 'A', 'E', and 'G' formats.
2157 for (char* __p = __start; __p != __res.ptr; ++__p)
2158 *__p = std::toupper(*__p);
2161 bool __have_sign = true;
2162 // Add sign for non-negative values.
2163 if (!__builtin_signbit(__v))
2165 if (_M_spec._M_sign == _Sign_plus)
2167 else if (_M_spec._M_sign == _Sign_space)
2170 __have_sign = false;
2173 string_view __narrow_str(__start, __res.ptr - __start);
2175 // Use alternate form. Ensure decimal point is always present,
2176 // and add trailing zeros (up to precision) for g and G forms.
2177 if (_M_spec._M_alt && __builtin_isfinite(__v))
2179 string_view __s = __narrow_str;
2180 size_t __sigfigs; // Number of significant figures.
2181 size_t __z = 0; // Number of trailing zeros to add.
2182 size_t __p; // Position of the exponent character (if any).
2183 size_t __d = __s.find('.'); // Position of decimal point.
2184 if (__d != __s.npos) // Found decimal point.
2186 __p = __s.find(__expc, __d + 1);
2187 if (__p == __s.npos)
2190 // If presentation type is g or G we might need to add zeros.
2191 if (__trailing_zeros)
2193 // Find number of digits after first significant figure.
2194 if (__s[__have_sign] != '0')
2195 // A string like "D.D" or "-D.DDD"
2196 __sigfigs = __p - __have_sign - 1;
2198 // A string like "0.D" or "-0.0DD".
2199 // Safe to assume there is a non-zero digit, because
2200 // otherwise there would be no decimal point.
2201 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2204 else // No decimal point, we need to insert one.
2206 __p = __s.find(__expc); // Find the exponent, if present.
2207 if (__p == __s.npos)
2209 __d = __p; // Position where '.' should be inserted.
2210 __sigfigs = __d - __have_sign;
2213 if (__trailing_zeros && __prec != 0)
2215 // For g and G presentation types std::to_chars produces
2216 // no more than prec significant figures. Insert this many
2217 // zeros so the result has exactly prec significant figures.
2218 __z = __prec - __sigfigs;
2221 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2223 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2225 // The stack buffer is large enough for the result.
2226 // Move exponent to make space for extra chars.
2227 __builtin_memmove(__start + __p + __extras,
2231 __start[__p++] = '.';
2232 __builtin_memset(__start + __p, '0', __z);
2233 __narrow_str = {__s.data(), __s.size() + __extras};
2235 else // Need to switch to the dynamic buffer.
2237 __dynbuf.reserve(__s.size() + __extras);
2238 if (__dynbuf.empty())
2240 __dynbuf = __s.substr(0, __p);
2244 __dynbuf.append(__z, '0');
2245 __dynbuf.append(__s.substr(__p));
2249 __dynbuf.insert(__p, __extras, '0');
2251 __dynbuf[__p] = '.';
2253 __narrow_str = __dynbuf;
2258 basic_string<_CharT> __wstr;
2259 basic_string_view<_CharT> __str;
2260 if constexpr (is_same_v<_CharT, char>)
2261 __str = __narrow_str;
2262#ifdef _GLIBCXX_USE_WCHAR_T
2265 __wstr = std::__to_wstring_numeric(__narrow_str);
2270 if (_M_spec._M_localized && __builtin_isfinite(__v))
2272 auto __s = _M_localize(__str, __expc, __fc.locale());
2274 __str = __wstr = std::move(__s);
2277 size_t __width = _M_spec._M_get_width(__fc);
2279 if (__width <= __str.size())
2280 return __format::__write(__fc.out(), __str);
2282 char32_t __fill_char = _M_spec._M_fill;
2283 _Align __align = _M_spec._M_align;
2285 size_t __nfill = __width - __str.size();
2286 auto __out = __fc.out();
2287 if (__align == _Align_default)
2289 __align = _Align_right;
2290 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2292 __fill_char = _CharT('0');
2293 // Write sign before zero filling.
2294 if (!__format::__is_xdigit(__narrow_str[0]))
2296 *__out++ = __str[0];
2297 __str.remove_prefix(1);
2301 __fill_char = _CharT(' ');
2303 return __format::__write_padded(std::move(__out), __str,
2304 __align, __nfill, __fill_char);
2307 // Locale-specific format.
2308 basic_string<_CharT>
2309 _M_localize(basic_string_view<_CharT> __str, char __expc,
2310 const locale& __loc) const
2312 basic_string<_CharT> __lstr;
2314 if (__loc == locale::classic())
2315 return __lstr; // Nothing to do.
2317 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2318 const _CharT __point = __np.decimal_point();
2319 const string __grp = __np.grouping();
2321 _CharT __dot, __exp;
2322 if constexpr (is_same_v<_CharT, char>)
2345 __builtin_unreachable();
2349 if (__grp.empty() && __point == __dot)
2350 return __lstr; // Locale uses '.' and no grouping.
2352 size_t __d = __str.find(__dot); // Index of radix character (if any).
2353 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2354 if (__e == __str.npos)
2356 const size_t __r = __str.size() - __e; // Length of remainder.
2357 auto __overwrite = [&](_CharT* __p, size_t) {
2358 // Apply grouping to the digits before the radix or exponent.
2359 auto __end = std::__add_grouping(__p, __np.thousands_sep(),
2360 __grp.data(), __grp.size(),
2361 __str.data(), __str.data() + __e);
2362 if (__r) // If there's a fractional part or exponent
2364 if (__d != __str.npos)
2366 *__end = __point; // Add the locale's radix character.
2370 const size_t __rlen = __str.size() - __e;
2371 // Append fractional digits and/or exponent:
2372 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2375 return (__end - __p);
2377 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2381 _Spec<_CharT> _M_spec{};
2384} // namespace __format
2387 /// Format a character.
2388 template<__format::__char _CharT>
2389 struct formatter<_CharT, _CharT>
2391 formatter() = default;
2393 constexpr typename basic_format_parse_context<_CharT>::iterator
2394 parse(basic_format_parse_context<_CharT>& __pc)
2396 return _M_f.template _M_parse<_CharT>(__pc);
2399 template<typename _Out>
2400 typename basic_format_context<_Out, _CharT>::iterator
2401 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2403 if (_M_f._M_spec._M_type == __format::_Pres_none
2404 || _M_f._M_spec._M_type == __format::_Pres_c)
2405 return _M_f._M_format_character(__u, __fc);
2406 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
2407 return _M_f._M_format_character_escaped(__u, __fc);
2409 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2412#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2414 set_debug_format() noexcept
2415 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2419 __format::__formatter_int<_CharT> _M_f;
2422#ifdef _GLIBCXX_USE_WCHAR_T
2423 /// Format a char value for wide character output.
2425 struct formatter<char, wchar_t>
2427 formatter() = default;
2429 constexpr typename basic_format_parse_context<wchar_t>::iterator
2430 parse(basic_format_parse_context<wchar_t>& __pc)
2432 return _M_f._M_parse<char>(__pc);
2435 template<typename _Out>
2436 typename basic_format_context<_Out, wchar_t>::iterator
2437 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2439 if (_M_f._M_spec._M_type == __format::_Pres_none
2440 || _M_f._M_spec._M_type == __format::_Pres_c)
2441 return _M_f._M_format_character(__u, __fc);
2442 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
2443 return _M_f._M_format_character_escaped(__u, __fc);
2445 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2448#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2450 set_debug_format() noexcept
2451 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2455 __format::__formatter_int<wchar_t> _M_f;
2457#endif // USE_WCHAR_T
2459 /** Format a string.
2462 template<__format::__char _CharT>
2463 struct formatter<_CharT*, _CharT>
2465 formatter() = default;
2467 [[__gnu__::__always_inline__]]
2468 constexpr typename basic_format_parse_context<_CharT>::iterator
2469 parse(basic_format_parse_context<_CharT>& __pc)
2470 { return _M_f.parse(__pc); }
2472 template<typename _Out>
2473 [[__gnu__::__nonnull__]]
2474 typename basic_format_context<_Out, _CharT>::iterator
2475 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2476 { return _M_f.format(__u, __fc); }
2478#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2479 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2483 __format::__formatter_str<_CharT> _M_f;
2486 template<__format::__char _CharT>
2487 struct formatter<const _CharT*, _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 [[__gnu__::__nonnull__]]
2498 typename basic_format_context<_Out, _CharT>::iterator
2499 format(const _CharT* __u,
2500 basic_format_context<_Out, _CharT>& __fc) const
2501 { return _M_f.format(__u, __fc); }
2503#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2504 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2508 __format::__formatter_str<_CharT> _M_f;
2511 template<__format::__char _CharT, size_t _Nm>
2512 struct formatter<_CharT[_Nm], _CharT>
2514 formatter() = default;
2516 [[__gnu__::__always_inline__]]
2517 constexpr typename basic_format_parse_context<_CharT>::iterator
2518 parse(basic_format_parse_context<_CharT>& __pc)
2519 { return _M_f.parse(__pc); }
2521 template<typename _Out>
2522 typename basic_format_context<_Out, _CharT>::iterator
2523 format(const _CharT (&__u)[_Nm],
2524 basic_format_context<_Out, _CharT>& __fc) const
2525 { return _M_f.format({__u, _Nm}, __fc); }
2527#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2528 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2532 __format::__formatter_str<_CharT> _M_f;
2535 template<typename _Traits, typename _Alloc>
2536 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2538 formatter() = default;
2540 [[__gnu__::__always_inline__]]
2541 constexpr typename basic_format_parse_context<char>::iterator
2542 parse(basic_format_parse_context<char>& __pc)
2543 { return _M_f.parse(__pc); }
2545 template<typename _Out>
2546 typename basic_format_context<_Out, char>::iterator
2547 format(const basic_string<char, _Traits, _Alloc>& __u,
2548 basic_format_context<_Out, char>& __fc) const
2549 { return _M_f.format(__u, __fc); }
2551#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2552 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2556 __format::__formatter_str<char> _M_f;
2559#ifdef _GLIBCXX_USE_WCHAR_T
2560 template<typename _Traits, typename _Alloc>
2561 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2563 formatter() = default;
2565 [[__gnu__::__always_inline__]]
2566 constexpr typename basic_format_parse_context<wchar_t>::iterator
2567 parse(basic_format_parse_context<wchar_t>& __pc)
2568 { return _M_f.parse(__pc); }
2570 template<typename _Out>
2571 typename basic_format_context<_Out, wchar_t>::iterator
2572 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2573 basic_format_context<_Out, wchar_t>& __fc) const
2574 { return _M_f.format(__u, __fc); }
2576#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2577 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2581 __format::__formatter_str<wchar_t> _M_f;
2583#endif // USE_WCHAR_T
2585 template<typename _Traits>
2586 struct formatter<basic_string_view<char, _Traits>, char>
2588 formatter() = default;
2590 [[__gnu__::__always_inline__]]
2591 constexpr typename basic_format_parse_context<char>::iterator
2592 parse(basic_format_parse_context<char>& __pc)
2593 { return _M_f.parse(__pc); }
2595 template<typename _Out>
2596 typename basic_format_context<_Out, char>::iterator
2597 format(basic_string_view<char, _Traits> __u,
2598 basic_format_context<_Out, char>& __fc) const
2599 { return _M_f.format(__u, __fc); }
2601#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2602 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2606 __format::__formatter_str<char> _M_f;
2609#ifdef _GLIBCXX_USE_WCHAR_T
2610 template<typename _Traits>
2611 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2613 formatter() = default;
2615 [[__gnu__::__always_inline__]]
2616 constexpr typename basic_format_parse_context<wchar_t>::iterator
2617 parse(basic_format_parse_context<wchar_t>& __pc)
2618 { return _M_f.parse(__pc); }
2620 template<typename _Out>
2621 typename basic_format_context<_Out, wchar_t>::iterator
2622 format(basic_string_view<wchar_t, _Traits> __u,
2623 basic_format_context<_Out, wchar_t>& __fc) const
2624 { return _M_f.format(__u, __fc); }
2626#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2627 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2631 __format::__formatter_str<wchar_t> _M_f;
2633#endif // USE_WCHAR_T
2636/// @cond undocumented
2639 // each cv-unqualified arithmetic type ArithmeticT other than
2640 // char, wchar_t, char8_t, char16_t, or char32_t
2641 template<typename _Tp>
2642 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2644#if defined __SIZEOF_INT128__
2645 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2646 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2650 template<> inline constexpr bool __is_formattable_integer<char> = false;
2651 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2652#ifdef _GLIBCXX_USE_CHAR8_T
2653 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2655 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2656 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2660 /// Format an integer.
2661 template<typename _Tp, __format::__char _CharT>
2662 requires __format::__is_formattable_integer<_Tp>
2663 struct formatter<_Tp, _CharT>
2665 formatter() = default;
2667 [[__gnu__::__always_inline__]]
2668 constexpr typename basic_format_parse_context<_CharT>::iterator
2669 parse(basic_format_parse_context<_CharT>& __pc)
2671 return _M_f.template _M_parse<_Tp>(__pc);
2674 template<typename _Out>
2675 typename basic_format_context<_Out, _CharT>::iterator
2676 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2677 { return _M_f.format(__u, __fc); }
2680 __format::__formatter_int<_CharT> _M_f;
2683#if defined __glibcxx_to_chars
2684 /// Format a floating-point value.
2685 template<__format::__formattable_float _Tp, __format::__char _CharT>
2686 struct formatter<_Tp, _CharT>
2688 formatter() = default;
2690 [[__gnu__::__always_inline__]]
2691 constexpr typename basic_format_parse_context<_CharT>::iterator
2692 parse(basic_format_parse_context<_CharT>& __pc)
2693 { return _M_f.parse(__pc); }
2695 template<typename _Out>
2696 typename basic_format_context<_Out, _CharT>::iterator
2697 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2698 { return _M_f.format(__u, __fc); }
2701 __format::__formatter_fp<_CharT> _M_f;
2704#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2705 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2706 template<__format::__char _CharT>
2707 struct formatter<long double, _CharT>
2709 formatter() = default;
2711 [[__gnu__::__always_inline__]]
2712 constexpr typename basic_format_parse_context<_CharT>::iterator
2713 parse(basic_format_parse_context<_CharT>& __pc)
2714 { return _M_f.parse(__pc); }
2716 template<typename _Out>
2717 typename basic_format_context<_Out, _CharT>::iterator
2718 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2719 { return _M_f.format((double)__u, __fc); }
2722 __format::__formatter_fp<_CharT> _M_f;
2726#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2727 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2728 template<__format::__char _CharT>
2729 struct formatter<_Float16, _CharT>
2731 formatter() = default;
2733 [[__gnu__::__always_inline__]]
2734 constexpr typename basic_format_parse_context<_CharT>::iterator
2735 parse(basic_format_parse_context<_CharT>& __pc)
2736 { return _M_f.parse(__pc); }
2738 template<typename _Out>
2739 typename basic_format_context<_Out, _CharT>::iterator
2740 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2741 { return _M_f.format((float)__u, __fc); }
2744 __format::__formatter_fp<_CharT> _M_f;
2748#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2749 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2750 template<__format::__char _CharT>
2751 struct formatter<_Float32, _CharT>
2753 formatter() = default;
2755 [[__gnu__::__always_inline__]]
2756 constexpr typename basic_format_parse_context<_CharT>::iterator
2757 parse(basic_format_parse_context<_CharT>& __pc)
2758 { return _M_f.parse(__pc); }
2760 template<typename _Out>
2761 typename basic_format_context<_Out, _CharT>::iterator
2762 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2763 { return _M_f.format((float)__u, __fc); }
2766 __format::__formatter_fp<_CharT> _M_f;
2770#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2771 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2772 template<__format::__char _CharT>
2773 struct formatter<_Float64, _CharT>
2775 formatter() = default;
2777 [[__gnu__::__always_inline__]]
2778 constexpr typename basic_format_parse_context<_CharT>::iterator
2779 parse(basic_format_parse_context<_CharT>& __pc)
2780 { return _M_f.parse(__pc); }
2782 template<typename _Out>
2783 typename basic_format_context<_Out, _CharT>::iterator
2784 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2785 { return _M_f.format((double)__u, __fc); }
2788 __format::__formatter_fp<_CharT> _M_f;
2792#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2793 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2794 template<__format::__char _CharT>
2795 struct formatter<_Float128, _CharT>
2797 formatter() = default;
2799 [[__gnu__::__always_inline__]]
2800 constexpr typename basic_format_parse_context<_CharT>::iterator
2801 parse(basic_format_parse_context<_CharT>& __pc)
2802 { return _M_f.parse(__pc); }
2804 template<typename _Out>
2805 typename basic_format_context<_Out, _CharT>::iterator
2806 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2807 { return _M_f.format((__format::__float128_t)__u, __fc); }
2810 __format::__formatter_fp<_CharT> _M_f;
2814#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2815 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2816 template<__format::__char _CharT>
2817 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2819 formatter() = default;
2821 [[__gnu__::__always_inline__]]
2822 constexpr typename basic_format_parse_context<_CharT>::iterator
2823 parse(basic_format_parse_context<_CharT>& __pc)
2824 { return _M_f.parse(__pc); }
2826 template<typename _Out>
2827 typename basic_format_context<_Out, _CharT>::iterator
2828 format(__gnu_cxx::__bfloat16_t __u,
2829 basic_format_context<_Out, _CharT>& __fc) const
2830 { return _M_f.format((float)__u, __fc); }
2833 __format::__formatter_fp<_CharT> _M_f;
2836#endif // __cpp_lib_to_chars
2838 /** Format a pointer.
2841 template<__format::__char _CharT>
2842 struct formatter<const void*, _CharT>
2844 formatter() = default;
2846 constexpr typename basic_format_parse_context<_CharT>::iterator
2847 parse(basic_format_parse_context<_CharT>& __pc)
2849 __format::_Spec<_CharT> __spec{};
2850 const auto __last = __pc.end();
2851 auto __first = __pc.begin();
2853 auto __finalize = [this, &__spec] {
2857 auto __finished = [&] {
2858 if (__first == __last || *__first == '}')
2869 __first = __spec._M_parse_fill_and_align(__first, __last);
2873// _GLIBCXX_RESOLVE_LIB_DEFECTS
2874// P2510R3 Formatting pointers
2875#if __glibcxx_format >= 202304L
2876 __first = __spec._M_parse_zero_fill(__first, __last);
2881 __first = __spec._M_parse_width(__first, __last, __pc);
2883 if (__first != __last)
2885 if (*__first == 'p')
2887#if __glibcxx_format >= 202304L
2888 else if (*__first == 'P')
2890 __spec._M_type = __format::_Pres_P;
2899 __format::__failed_to_parse_format_spec();
2902 template<typename _Out>
2903 typename basic_format_context<_Out, _CharT>::iterator
2904 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2906 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2907 char __buf[2 + sizeof(__v) * 2];
2908 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2910 int __n = __ptr - __buf;
2913#if __glibcxx_format >= 202304L
2914 if (_M_spec._M_type == __format::_Pres_P)
2917 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2918#if __has_builtin(__builtin_toupper)
2919 *__p = __builtin_toupper(*__p);
2921 *__p = std::toupper(*__p);
2926 basic_string_view<_CharT> __str;
2927 if constexpr (is_same_v<_CharT, char>)
2928 __str = string_view(__buf, __n);
2929#ifdef _GLIBCXX_USE_WCHAR_T
2932 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2933 std::__to_wstring_numeric(__buf, __n, __p);
2934 __str = wstring_view(__p, __n);
2938#if __glibcxx_format >= 202304L
2939 if (_M_spec._M_zero_fill)
2941 size_t __width = _M_spec._M_get_width(__fc);
2942 if (__width <= __str.size())
2943 return __format::__write(__fc.out(), __str);
2945 auto __out = __fc.out();
2946 // Write "0x" or "0X" prefix before zero-filling.
2947 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2948 __str.remove_prefix(2);
2949 size_t __nfill = __width - __n;
2950 return __format::__write_padded(std::move(__out), __str,
2951 __format::_Align_right,
2952 __nfill, _CharT('0'));
2956 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2957 __format::_Align_right);
2961 __format::_Spec<_CharT> _M_spec{};
2964 template<__format::__char _CharT>
2965 struct formatter<void*, _CharT>
2967 formatter() = default;
2969 [[__gnu__::__always_inline__]]
2970 constexpr typename basic_format_parse_context<_CharT>::iterator
2971 parse(basic_format_parse_context<_CharT>& __pc)
2972 { return _M_f.parse(__pc); }
2974 template<typename _Out>
2975 typename basic_format_context<_Out, _CharT>::iterator
2976 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2977 { return _M_f.format(__v, __fc); }
2980 formatter<const void*, _CharT> _M_f;
2983 template<__format::__char _CharT>
2984 struct formatter<nullptr_t, _CharT>
2986 formatter() = default;
2988 [[__gnu__::__always_inline__]]
2989 constexpr typename basic_format_parse_context<_CharT>::iterator
2990 parse(basic_format_parse_context<_CharT>& __pc)
2991 { return _M_f.parse(__pc); }
2993 template<typename _Out>
2994 typename basic_format_context<_Out, _CharT>::iterator
2995 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
2996 { return _M_f.format(nullptr, __fc); }
2999 formatter<const void*, _CharT> _M_f;
3003#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3004 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3005 // 3944. Formatters converting sequences of char to sequences of wchar_t
3007 namespace __format { struct __disabled; }
3009 // std::formatter<__disabled, C> uses the primary template, which is disabled.
3011 struct formatter<char*, wchar_t>
3012 : private formatter<__format::__disabled, wchar_t> { };
3014 struct formatter<const char*, wchar_t>
3015 : private formatter<__format::__disabled, wchar_t> { };
3016 template<size_t _Nm>
3017 struct formatter<char[_Nm], wchar_t>
3018 : private formatter<__format::__disabled, wchar_t> { };
3019 template<class _Traits, class _Allocator>
3020 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3021 : private formatter<__format::__disabled, wchar_t> { };
3022 template<class _Traits>
3023 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3024 : private formatter<__format::__disabled, wchar_t> { };
3027/// @cond undocumented
3030 template<typename _Tp, typename _Context,
3032 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
3033 typename _ParseContext
3034 = basic_format_parse_context<typename _Context::char_type>>
3035 concept __parsable_with
3036 = semiregular<_Formatter>
3037 && requires (_Formatter __f, _ParseContext __pc)
3039 { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
3042 template<typename _Tp, typename _Context,
3044 = typename _Context::template formatter_type<remove_const_t<_Tp>>,
3045 typename _ParseContext
3046 = basic_format_parse_context<typename _Context::char_type>>
3047 concept __formattable_with
3048 = semiregular<_Formatter>
3049 && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
3051 { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
3054 // An unspecified output iterator type used in the `formattable` concept.
3055 template<typename _CharT>
3056 using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
3058 template<typename _Tp, typename _CharT,
3059 typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
3060 concept __formattable_impl
3061 = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
3063 template<typename _Formatter>
3064 concept __has_debug_format = requires(_Formatter __f)
3066 __f.set_debug_format();
3069} // namespace __format
3072#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
3073 // [format.formattable], concept formattable
3074 template<typename _Tp, typename _CharT>
3076 = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
3078#endif // format_ranges
3080 /// An iterator after the last character written, and the number of
3081 /// characters that would have been written.
3082 template<typename _Out>
3083 struct format_to_n_result
3086 iter_difference_t<_Out> size;
3089_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3090template<typename, typename> class vector;
3091_GLIBCXX_END_NAMESPACE_CONTAINER
3093/// @cond undocumented
3096 template<typename _CharT>
3099 _Sink<_CharT>* _M_sink = nullptr;
3102 using iterator_category = output_iterator_tag;
3103 using value_type = void;
3104 using difference_type = ptrdiff_t;
3105 using pointer = void;
3106 using reference = void;
3108 _Sink_iter() = default;
3109 _Sink_iter(const _Sink_iter&) = default;
3110 _Sink_iter& operator=(const _Sink_iter&) = default;
3112 [[__gnu__::__always_inline__]]
3114 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3116 [[__gnu__::__always_inline__]]
3117 constexpr _Sink_iter&
3118 operator=(_CharT __c)
3120 _M_sink->_M_write(__c);
3124 [[__gnu__::__always_inline__]]
3125 constexpr _Sink_iter&
3126 operator=(basic_string_view<_CharT> __s)
3128 _M_sink->_M_write(__s);
3132 [[__gnu__::__always_inline__]]
3133 constexpr _Sink_iter&
3134 operator*() { return *this; }
3136 [[__gnu__::__always_inline__]]
3137 constexpr _Sink_iter&
3138 operator++() { return *this; }
3140 [[__gnu__::__always_inline__]]
3141 constexpr _Sink_iter
3142 operator++(int) { return *this; }
3145 _M_reserve(size_t __n) const
3146 { return _M_sink->_M_reserve(__n); }
3149 // Abstract base class for type-erased character sinks.
3150 // All formatting and output is done via this type's iterator,
3151 // to reduce the number of different template instantiations.
3152 template<typename _CharT>
3155 friend class _Sink_iter<_CharT>;
3157 span<_CharT> _M_span;
3158 typename span<_CharT>::iterator _M_next;
3160 // Called when the span is full, to make more space available.
3161 // Precondition: _M_next != _M_span.begin()
3162 // Postcondition: _M_next != _M_span.end()
3163 // TODO: remove the precondition? could make overflow handle it.
3164 virtual void _M_overflow() = 0;
3167 // Precondition: __span.size() != 0
3168 [[__gnu__::__always_inline__]]
3170 _Sink(span<_CharT> __span) noexcept
3171 : _M_span(__span), _M_next(__span.begin())
3174 // The portion of the span that has been written to.
3175 [[__gnu__::__always_inline__]]
3177 _M_used() const noexcept
3178 { return _M_span.first(_M_next - _M_span.begin()); }
3180 // The portion of the span that has not been written to.
3181 [[__gnu__::__always_inline__]]
3182 constexpr span<_CharT>
3183 _M_unused() const noexcept
3184 { return _M_span.subspan(_M_next - _M_span.begin()); }
3186 // Use the start of the span as the next write position.
3187 [[__gnu__::__always_inline__]]
3189 _M_rewind() noexcept
3190 { _M_next = _M_span.begin(); }
3192 // Replace the current output range.
3194 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3197 _M_next = __s.begin() + __pos;
3200 // Called by the iterator for *it++ = c
3202 _M_write(_CharT __c)
3205 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3210 _M_write(basic_string_view<_CharT> __s)
3212 span __to = _M_unused();
3213 while (__to.size() <= __s.size())
3215 __s.copy(__to.data(), __to.size());
3216 _M_next += __to.size();
3217 __s.remove_prefix(__to.size());
3223 __s.copy(__to.data(), __s.size());
3224 _M_next += __s.size();
3228 // A successful _Reservation can be used to directly write
3229 // up to N characters to the sink to avoid unwanted buffering.
3232 // True if the reservation was successful, false otherwise.
3233 explicit operator bool() const noexcept { return _M_sink; }
3234 // A pointer to write directly to the sink.
3235 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3236 // Add n to the _M_next iterator for the sink.
3237 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3241 // Attempt to reserve space to write n characters to the sink.
3242 // If anything is written to the reservation then there must be a call
3243 // to _M_bump(N2) before any call to another member function of *this,
3244 // where N2 is the number of characters written.
3245 virtual _Reservation
3246 _M_reserve(size_t __n)
3248 if (__n <= _M_unused().size())
3251 if (__n <= _M_span.size()) // Cannot meet the request.
3253 _M_overflow(); // Make more space available.
3254 if (__n <= _M_unused().size())
3260 // Update the next output position after writing directly to the sink.
3261 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3267 _Sink(const _Sink&) = delete;
3268 _Sink& operator=(const _Sink&) = delete;
3270 [[__gnu__::__always_inline__]]
3271 constexpr _Sink_iter<_CharT>
3273 { return _Sink_iter<_CharT>(*this); }
3277 template<typename _CharT>
3278 class _Fixedbuf_sink final : public _Sink<_CharT>
3281 _M_overflow() override
3283 __glibcxx_assert(false);
3288 [[__gnu__::__always_inline__]]
3290 _Fixedbuf_sink(span<_CharT> __buf)
3291 : _Sink<_CharT>(__buf)
3294 constexpr basic_string_view<_CharT>
3297 auto __s = this->_M_used();
3298 return basic_string_view<_CharT>(__s.data(), __s.size());
3302 // A sink with an internal buffer. This is used to implement concrete sinks.
3303 template<typename _CharT>
3304 class _Buf_sink : public _Sink<_CharT>
3307 _CharT _M_buf[__stackbuf_size<_CharT>];
3309 [[__gnu__::__always_inline__]]
3311 _Buf_sink() noexcept
3312 : _Sink<_CharT>(_M_buf)
3316 using _GLIBCXX_STD_C::vector;
3318 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3319 // Writes to a buffer then appends that to the sequence when it fills up.
3320 template<typename _Seq>
3321 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
3323 using _CharT = typename _Seq::value_type;
3327 // Transfer buffer contents to the sequence, so buffer can be refilled.
3329 _M_overflow() override
3331 auto __s = this->_M_used();
3332 if (__s.empty()) [[unlikely]]
3333 return; // Nothing in the buffer to transfer to _M_seq.
3335 // If _M_reserve was called then _M_bump must have been called too.
3336 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3338 if constexpr (__is_specialization_of<_Seq, basic_string>)
3339 _M_seq.append(__s.data(), __s.size());
3341 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3343 // Make the whole of _M_buf available for the next write:
3347 typename _Sink<_CharT>::_Reservation
3348 _M_reserve(size_t __n) override
3350 // We might already have n characters available in this->_M_unused(),
3351 // but the whole point of this function is to be an optimization for
3352 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3353 // and then copying that into a basic_string if possible, so this
3354 // function prefers to create space directly in _M_seq rather than
3357 if constexpr (__is_specialization_of<_Seq, basic_string>
3358 || __is_specialization_of<_Seq, vector>)
3360 // Flush the buffer to _M_seq first (should not be needed).
3361 if (this->_M_used().size()) [[unlikely]]
3362 _Seq_sink::_M_overflow();
3364 // Expand _M_seq to make __n new characters available:
3365 const auto __sz = _M_seq.size();
3366 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3367 _M_seq.__resize_and_overwrite(__sz + __n,
3368 [](auto, auto __n2) {
3372 _M_seq.resize(__sz + __n);
3374 // Set _M_used() to be a span over the original part of _M_seq
3375 // and _M_unused() to be the extra capacity we just created:
3376 this->_M_reset(_M_seq, __sz);
3379 else // Try to use the base class' buffer.
3380 return _Sink<_CharT>::_M_reserve(__n);
3384 _M_bump(size_t __n) override
3386 if constexpr (__is_specialization_of<_Seq, basic_string>
3387 || __is_specialization_of<_Seq, vector>)
3389 auto __s = this->_M_used();
3390 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3391 // Truncate the sequence to the part that was actually written to:
3392 _M_seq.resize(__s.size() + __n);
3393 // Switch back to using buffer:
3394 this->_M_reset(this->_M_buf);
3399 // TODO: for SSO string, use SSO buffer as initial span, then switch
3400 // to _M_buf if it overflows? Or even do that for all unused capacity?
3402 [[__gnu__::__always_inline__]]
3403 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3406 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3407 : _M_seq(std::move(__s))
3410 using _Sink<_CharT>::out;
3415 if (this->_M_used().size() != 0)
3416 _Seq_sink::_M_overflow();
3417 return std::move(_M_seq);
3420 // A writable span that views everything written to the sink.
3421 // Will be either a view over _M_seq or the used part of _M_buf.
3425 auto __s = this->_M_used();
3428 if (__s.size() != 0)
3429 _Seq_sink::_M_overflow();
3436 // A sink that writes to an output iterator.
3437 // Writes to a fixed-size buffer and then flushes to the output iterator
3438 // when the buffer fills up.
3439 template<typename _CharT, typename _OutIter>
3440 class _Iter_sink : public _Buf_sink<_CharT>
3443 iter_difference_t<_OutIter> _M_max;
3446 size_t _M_count = 0;
3449 _M_overflow() override
3451 auto __s = this->_M_used();
3452 if (_M_max < 0) // No maximum.
3453 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3454 else if (_M_count < static_cast<size_t>(_M_max))
3456 auto __max = _M_max - _M_count;
3457 span<_CharT> __first;
3458 if (__max < __s.size())
3459 __first = __s.first(static_cast<size_t>(__max));
3462 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3465 _M_count += __s.size();
3469 [[__gnu__::__always_inline__]]
3471 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3472 : _M_out(std::move(__out)), _M_max(__max)
3475 using _Sink<_CharT>::out;
3477 format_to_n_result<_OutIter>
3480 if (this->_M_used().size() != 0)
3481 _Iter_sink::_M_overflow();
3482 iter_difference_t<_OutIter> __count(_M_count);
3483 return { std::move(_M_out), __count };
3487 // Partial specialization for contiguous iterators.
3488 // No buffer is used, characters are written straight to the iterator.
3489 // We do not know the size of the output range, so the span size just grows
3490 // as needed. The end of the span might be an invalid pointer outside the
3491 // valid range, but we never actually call _M_span.end(). This class does
3492 // not introduce any invalid pointer arithmetic or overflows that would not
3493 // have happened anyway.
3494 template<typename _CharT, contiguous_iterator _OutIter>
3495 requires same_as<iter_value_t<_OutIter>, _CharT>
3496 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3499 iter_difference_t<_OutIter> _M_max = -1;
3501 size_t _M_count = 0;
3503 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3507 _M_overflow() override
3509 if (this->_M_unused().size() != 0)
3510 return; // No need to switch to internal buffer yet.
3512 auto __s = this->_M_used();
3516 _M_count += __s.size();
3517 // Span was already sized for the maximum character count,
3518 // if it overflows then any further output must go to the
3519 // internal buffer, to be discarded.
3520 this->_M_reset(this->_M_buf);
3524 // No maximum character count. Just extend the span to allow
3525 // writing more characters to it.
3526 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3530 typename _Sink<_CharT>::_Reservation
3531 _M_reserve(size_t __n) final
3533 auto __avail = this->_M_unused();
3534 if (__n > __avail.size())
3537 return {}; // cannot grow
3539 auto __s = this->_M_used();
3540 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3547 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3548 span<_CharT> __buf) noexcept
3551 return __buf; // Only write to the internal buffer.
3555 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3556 || sizeof(__n) > sizeof(size_t))
3558 // __int128 or __detail::__max_diff_type
3559 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3563 return {__ptr, (size_t)__n};
3566#if __has_builtin(__builtin_dynamic_object_size)
3567 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3568 return {__ptr, __bytes / sizeof(_CharT)};
3570 // Avoid forming a pointer to a different memory page.
3571 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3572 __n = (1024 - __off) / sizeof(_CharT);
3573 if (__n > 0) [[likely]]
3574 return {__ptr, static_cast<size_t>(__n)};
3575 else // Misaligned/packed buffer of wchar_t?
3581 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3582 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3583 _M_first(__out), _M_max(__n)
3586 format_to_n_result<_OutIter>
3589 auto __s = this->_M_used();
3590 if (__s.data() == _M_buf)
3592 // Switched to internal buffer, so must have written _M_max.
3593 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3594 return { _M_first + _M_max, __count };
3596 else // Not using internal buffer yet
3598 iter_difference_t<_OutIter> __count(__s.size());
3599 return { _M_first + __count, __count };
3604 enum _Arg_t : unsigned char {
3605 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3606 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3607 _Arg_i128, _Arg_u128,
3608 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3609#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3611 _Arg_f128 = _Arg_ldbl,
3612 _Arg_ibm128 = _Arg_next_value_,
3619 template<typename _Context>
3622 using _CharT = typename _Context::char_type;
3638 unsigned long long _M_ull;
3641#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3642 long double _M_ldbl;
3644 const _CharT* _M_str;
3645 basic_string_view<_CharT> _M_sv;
3647 _HandleBase _M_handle;
3648#ifdef __SIZEOF_INT128__
3650 unsigned __int128 _M_u128;
3652#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3655#elif _GLIBCXX_FORMAT_F128 == 2
3656 __float128_t _M_f128;
3660 [[__gnu__::__always_inline__]]
3661 _Arg_value() : _M_none() { }
3664 template<typename _Tp>
3665 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3666 { _S_get<_Tp>() = __val; }
3669 template<typename _Tp, typename _Self>
3670 [[__gnu__::__always_inline__]]
3672 _S_get(_Self& __u) noexcept
3674 if constexpr (is_same_v<_Tp, bool>)
3676 else if constexpr (is_same_v<_Tp, _CharT>)
3678 else if constexpr (is_same_v<_Tp, int>)
3680 else if constexpr (is_same_v<_Tp, unsigned>)
3682 else if constexpr (is_same_v<_Tp, long long>)
3684 else if constexpr (is_same_v<_Tp, unsigned long long>)
3686 else if constexpr (is_same_v<_Tp, float>)
3688 else if constexpr (is_same_v<_Tp, double>)
3690#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3691 else if constexpr (is_same_v<_Tp, long double>)
3694 else if constexpr (is_same_v<_Tp, __ieee128>)
3696 else if constexpr (is_same_v<_Tp, __ibm128>)
3697 return __u._M_ibm128;
3699 else if constexpr (is_same_v<_Tp, const _CharT*>)
3701 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3703 else if constexpr (is_same_v<_Tp, const void*>)
3705#ifdef __SIZEOF_INT128__
3706 else if constexpr (is_same_v<_Tp, __int128>)
3708 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3711#if _GLIBCXX_FORMAT_F128 == 2
3712 else if constexpr (is_same_v<_Tp, __float128_t>)
3715 else if constexpr (derived_from<_Tp, _HandleBase>)
3716 return static_cast<_Tp&>(__u._M_handle);
3717 // Otherwise, ill-formed.
3720 template<typename _Tp>
3721 [[__gnu__::__always_inline__]]
3724 { return _S_get<_Tp>(*this); }
3726 template<typename _Tp>
3727 [[__gnu__::__always_inline__]]
3729 _M_get() const noexcept
3730 { return _S_get<_Tp>(*this); }
3732 template<typename _Tp>
3733 [[__gnu__::__always_inline__]]
3735 _M_set(_Tp __v) noexcept
3737 if constexpr (derived_from<_Tp, _HandleBase>)
3738 std::construct_at(&_M_handle, __v);
3740 _S_get<_Tp>(*this) = __v;
3744 // [format.arg.store], class template format-arg-store
3745 template<typename _Context, typename... _Args>
3748 template<typename _Visitor, typename _Ctx>
3749 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
3751 template<typename _Ch, typename _Tp>
3753 __to_arg_t_enum() noexcept;
3754} // namespace __format
3757 template<typename _Context>
3758 class basic_format_arg
3760 using _CharT = typename _Context::char_type;
3762 template<typename _Tp>
3763 static constexpr bool __formattable
3764 = __format::__formattable_with<_Tp, _Context>;
3767 class handle : public __format::_Arg_value<_Context>::_HandleBase
3769 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3771 // Format as const if possible, to reduce instantiations.
3772 template<typename _Tp>
3773 using __maybe_const_t
3774 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3776 template<typename _Tq>
3778 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3779 _Context& __format_ctx, const void* __ptr)
3781 using _Td = remove_const_t<_Tq>;
3782 typename _Context::template formatter_type<_Td> __f;
3783 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3784 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3785 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3788 template<typename _Tp>
3790 handle(_Tp& __val) noexcept
3792 this->_M_ptr = __builtin_addressof(__val);
3793 auto __func = _S_format<__maybe_const_t<_Tp>>;
3794 this->_M_func = reinterpret_cast<void(*)()>(__func);
3797 friend class basic_format_arg<_Context>;
3800 handle(const handle&) = default;
3801 handle& operator=(const handle&) = default;
3803 [[__gnu__::__always_inline__]]
3805 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3807 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3808 _Context&, const void*);
3809 auto __f = reinterpret_cast<_Func>(this->_M_func);
3810 __f(__pc, __fc, this->_M_ptr);
3814 [[__gnu__::__always_inline__]]
3815 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3817 [[nodiscard,__gnu__::__always_inline__]]
3818 explicit operator bool() const noexcept
3819 { return _M_type != __format::_Arg_none; }
3821#if __cpp_lib_format >= 202306L // >= C++26
3822 template<typename _Visitor>
3824 visit(this basic_format_arg __arg, _Visitor&& __vis)
3825 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3827 template<typename _Res, typename _Visitor>
3829 visit(this basic_format_arg __arg, _Visitor&& __vis)
3830 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3834 template<typename _Ctx>
3835 friend class basic_format_args;
3837 template<typename _Ctx, typename... _Args>
3838 friend class __format::_Arg_store;
3840 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3842 __format::_Arg_value<_Context> _M_val;
3843 __format::_Arg_t _M_type;
3845 // Transform incoming argument type to the type stored in _Arg_value.
3846 // e.g. short -> int, std::string -> std::string_view,
3847 // char[3] -> const char*.
3848 template<typename _Tp>
3849 static consteval auto
3852 using _Td = remove_const_t<_Tp>;
3853 if constexpr (is_same_v<_Td, bool>)
3854 return type_identity<bool>();
3855 else if constexpr (is_same_v<_Td, _CharT>)
3856 return type_identity<_CharT>();
3857 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3858 return type_identity<_CharT>();
3859#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3860 else if constexpr (is_same_v<_Td, __int128>)
3861 return type_identity<__int128>();
3862 else if constexpr (is_same_v<_Td, unsigned __int128>)
3863 return type_identity<unsigned __int128>();
3865 else if constexpr (__is_signed_integer<_Td>::value)
3867 if constexpr (sizeof(_Td) <= sizeof(int))
3868 return type_identity<int>();
3869 else if constexpr (sizeof(_Td) <= sizeof(long long))
3870 return type_identity<long long>();
3872 else if constexpr (__is_unsigned_integer<_Td>::value)
3874 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3875 return type_identity<unsigned>();
3876 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3877 return type_identity<unsigned long long>();
3879 else if constexpr (is_same_v<_Td, float>)
3880 return type_identity<float>();
3881 else if constexpr (is_same_v<_Td, double>)
3882 return type_identity<double>();
3883#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3884 else if constexpr (is_same_v<_Td, long double>)
3885 return type_identity<long double>();
3887 else if constexpr (is_same_v<_Td, __ibm128>)
3888 return type_identity<__ibm128>();
3889 else if constexpr (is_same_v<_Td, __ieee128>)
3890 return type_identity<__ieee128>();
3893#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3894 else if constexpr (is_same_v<_Td, _Float16>)
3895 return type_identity<float>();
3898#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3899 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3900 return type_identity<float>();
3903#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3904 else if constexpr (is_same_v<_Td, _Float32>)
3905 return type_identity<float>();
3908#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3909 else if constexpr (is_same_v<_Td, _Float64>)
3910 return type_identity<double>();
3913#if _GLIBCXX_FORMAT_F128
3915 else if constexpr (is_same_v<_Td, _Float128>)
3916 return type_identity<__format::__float128_t>();
3918# if __SIZEOF_FLOAT128__
3919 else if constexpr (is_same_v<_Td, __float128>)
3920 return type_identity<__format::__float128_t>();
3923 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3924 || __is_specialization_of<_Td, basic_string>)
3926 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3927 return type_identity<basic_string_view<_CharT>>();
3929 return type_identity<handle>();
3931 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3932 return type_identity<const _CharT*>();
3933 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3934 return type_identity<const _CharT*>();
3935 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3936 return type_identity<const void*>();
3937 else if constexpr (is_same_v<_Td, nullptr_t>)
3938 return type_identity<const void*>();
3940 return type_identity<handle>();
3943 // Transform a formattable type to the appropriate storage type.
3944 template<typename _Tp>
3945 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3947 // Get the _Arg_t value corresponding to a normalized type.
3948 template<typename _Tp>
3949 static consteval __format::_Arg_t
3952 using namespace __format;
3953 if constexpr (is_same_v<_Tp, bool>)
3955 else if constexpr (is_same_v<_Tp, _CharT>)
3957 else if constexpr (is_same_v<_Tp, int>)
3959 else if constexpr (is_same_v<_Tp, unsigned>)
3961 else if constexpr (is_same_v<_Tp, long long>)
3963 else if constexpr (is_same_v<_Tp, unsigned long long>)
3965 else if constexpr (is_same_v<_Tp, float>)
3967 else if constexpr (is_same_v<_Tp, double>)
3969#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3970 else if constexpr (is_same_v<_Tp, long double>)
3973 // Don't use _Arg_ldbl for this target, it's ambiguous.
3974 else if constexpr (is_same_v<_Tp, __ibm128>)
3976 else if constexpr (is_same_v<_Tp, __ieee128>)
3979 else if constexpr (is_same_v<_Tp, const _CharT*>)
3981 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3983 else if constexpr (is_same_v<_Tp, const void*>)
3985#ifdef __SIZEOF_INT128__
3986 else if constexpr (is_same_v<_Tp, __int128>)
3988 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3992#if _GLIBCXX_FORMAT_F128 == 2
3993 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3996 else if constexpr (is_same_v<_Tp, handle>)
4000 template<typename _Tp>
4002 _M_set(_Tp __v) noexcept
4004 _M_type = _S_to_enum<_Tp>();
4008 template<typename _Tp>
4009 requires __format::__formattable_with<_Tp, _Context>
4011 basic_format_arg(_Tp& __v) noexcept
4013 using _Td = _Normalize<_Tp>;
4014 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4015 _M_set(_Td{__v.data(), __v.size()});
4016 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4017 && is_same_v<_CharT, wchar_t>)
4018 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4020 _M_set(static_cast<_Td>(__v));
4023 template<typename _Ctx, typename... _Argz>
4025 make_format_args(_Argz&...) noexcept;
4027 template<typename _Visitor, typename _Ctx>
4028 friend decltype(auto)
4029 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4031 template<typename _Visitor, typename _Ctx>
4032 friend decltype(auto)
4033 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4035 template<typename _Ch, typename _Tp>
4036 friend consteval __format::_Arg_t
4037 __format::__to_arg_t_enum() noexcept;
4039 template<typename _Visitor>
4041 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4043 using namespace __format;
4047 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4049 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4051 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4053 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4055 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4057 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4059 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4060#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4062 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4064 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4065#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4067 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4070 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
4072 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4076 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4078 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4080 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4083 auto& __h = static_cast<handle&>(_M_val._M_handle);
4084 return std::forward<_Visitor>(__vis)(__h);
4086#ifdef __SIZEOF_INT128__
4088 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4090 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4093#if _GLIBCXX_FORMAT_F128 == 2
4095 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
4100 __builtin_unreachable();
4104 template<typename _Visitor>
4106 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4108 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4110 constexpr bool __user_facing = __is_one_of<_Tp,
4111 monostate, bool, _CharT,
4112 int, unsigned int, long long int, unsigned long long int,
4113 float, double, long double,
4114 const _CharT*, basic_string_view<_CharT>,
4115 const void*, handle>::value;
4116 if constexpr (__user_facing)
4117 return std::forward<_Visitor>(__vis)(__val);
4121 return std::forward<_Visitor>(__vis)(__h);
4127 template<typename _Visitor, typename _Context>
4128 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4129 inline decltype(auto)
4130 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4132 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4135/// @cond undocumented
4138 template<typename _Visitor, typename _Ctx>
4139 inline decltype(auto)
4140 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4142 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4145 struct _WidthPrecVisitor
4147 template<typename _Tp>
4149 operator()(_Tp& __arg) const
4151 if constexpr (is_same_v<_Tp, monostate>)
4152 __format::__invalid_arg_id_in_format_string();
4153 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4154 // 3720. Restrict the valid types of arg-id for width and precision
4155 // 3721. Allow an arg-id with a value of zero for width
4156 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4158 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4159 // 3720. Restrict the valid types of arg-id for width and precision
4160 if constexpr (__is_unsigned_integer<_Tp>::value)
4162 else if constexpr (__is_signed_integer<_Tp>::value)
4166 __throw_format_error("format error: argument used for width or "
4167 "precision must be a non-negative integer");
4171#pragma GCC diagnostic push
4172#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4173 template<typename _Context>
4175 __int_from_arg(const basic_format_arg<_Context>& __arg)
4176 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4178 // Pack _Arg_t enum values into a single 60-bit integer.
4179 template<int _Bits, size_t _Nm>
4181 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4183 __UINT64_TYPE__ __packed_types = 0;
4184 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4185 __packed_types = (__packed_types << _Bits) | *__i;
4186 return __packed_types;
4188} // namespace __format
4191 template<typename _Context>
4192 class basic_format_args
4194 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4195 static constexpr int _S_packed_type_mask = 0b11111;
4196 static constexpr int _S_max_packed_args = 12;
4198 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
4200 template<typename... _Args>
4201 using _Store = __format::_Arg_store<_Context, _Args...>;
4203 template<typename _Ctx, typename... _Args>
4204 friend class __format::_Arg_store;
4206 using uint64_t = __UINT64_TYPE__;
4207 using _Format_arg = basic_format_arg<_Context>;
4208 using _Format_arg_val = __format::_Arg_value<_Context>;
4210 // If args are packed then the number of args is in _M_packed_size and
4211 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4212 // If args are not packed then the number of args is in _M_unpacked_size
4213 // and _M_packed_size is zero.
4214 uint64_t _M_packed_size : 4;
4215 uint64_t _M_unpacked_size : 60;
4218 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4219 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4223 _M_size() const noexcept
4224 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4226 typename __format::_Arg_t
4227 _M_type(size_t __i) const noexcept
4229 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4230 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4233 template<typename _Ctx, typename... _Args>
4235 make_format_args(_Args&...) noexcept;
4237 // An array of _Arg_t enums corresponding to _Args...
4238 template<typename... _Args>
4239 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4241 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4244 template<typename... _Args>
4245 basic_format_args(const _Store<_Args...>& __store) noexcept;
4247 [[nodiscard,__gnu__::__always_inline__]]
4248 basic_format_arg<_Context>
4249 get(size_t __i) const noexcept
4251 basic_format_arg<_Context> __arg;
4252 if (__i < _M_packed_size)
4254 __arg._M_type = _M_type(__i);
4255 __arg._M_val = _M_values[__i];
4257 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4258 __arg = _M_args[__i];
4263 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4264 // 3810. CTAD for std::basic_format_args
4265 template<typename _Context, typename... _Args>
4266 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4267 -> basic_format_args<_Context>;
4269 template<typename _Context, typename... _Args>
4271 make_format_args(_Args&... __fmt_args) noexcept;
4273 // An array of type-erased formatting arguments.
4274 template<typename _Context, typename... _Args>
4275 class __format::_Arg_store
4277 friend std::basic_format_args<_Context>;
4279 template<typename _Ctx, typename... _Argz>
4281#if _GLIBCXX_INLINE_VERSION
4282 __8:: // Needed for PR c++/59256
4284 make_format_args(_Argz&...) noexcept;
4286 // For a sufficiently small number of arguments we only store values.
4287 // basic_format_args can get the types from the _Args pack.
4288 static constexpr bool _S_values_only
4289 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4292 = __conditional_t<_S_values_only,
4293 __format::_Arg_value<_Context>,
4294 basic_format_arg<_Context>>;
4296 _Element_t _M_args[sizeof...(_Args)];
4298 template<typename _Tp>
4300 _S_make_elt(_Tp& __v)
4302 using _Tq = remove_const_t<_Tp>;
4303 using _CharT = typename _Context::char_type;
4304 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4305 "std::formatter must be specialized for the type "
4306 "of each format arg");
4307 using __format::__formattable_with;
4308 if constexpr (is_const_v<_Tp>)
4309 if constexpr (!__formattable_with<_Tp, _Context>)
4310 if constexpr (__formattable_with<_Tq, _Context>)
4311 static_assert(__formattable_with<_Tp, _Context>,
4312 "format arg must be non-const because its "
4313 "std::formatter specialization has a "
4314 "non-const reference parameter");
4315 basic_format_arg<_Context> __arg(__v);
4316 if constexpr (_S_values_only)
4317 return __arg._M_val;
4322 template<typename... _Tp>
4323 requires (sizeof...(_Tp) == sizeof...(_Args))
4324 [[__gnu__::__always_inline__]]
4325 _Arg_store(_Tp&... __a) noexcept
4326 : _M_args{_S_make_elt(__a)...}
4330 template<typename _Context>
4331 class __format::_Arg_store<_Context>
4334 template<typename _Context>
4335 template<typename... _Args>
4337 basic_format_args<_Context>::
4338 basic_format_args(const _Store<_Args...>& __store) noexcept
4340 if constexpr (sizeof...(_Args) == 0)
4343 _M_unpacked_size = 0;
4346 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4348 // The number of packed arguments:
4349 _M_packed_size = sizeof...(_Args);
4350 // The packed type enums:
4352 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4353 // The _Arg_value objects.
4354 _M_values = __store._M_args;
4358 // No packed arguments:
4360 // The number of unpacked arguments:
4361 _M_unpacked_size = sizeof...(_Args);
4362 // The basic_format_arg objects:
4363 _M_args = __store._M_args;
4367 /// Capture formatting arguments for use by `std::vformat`.
4368 template<typename _Context = format_context, typename... _Args>
4369 [[nodiscard,__gnu__::__always_inline__]]
4371 make_format_args(_Args&... __fmt_args) noexcept
4373 using _Fmt_arg = basic_format_arg<_Context>;
4374 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4375 _Normalize<_Args>...>;
4376 return _Store(__fmt_args...);
4379#ifdef _GLIBCXX_USE_WCHAR_T
4380 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4381 template<typename... _Args>
4382 [[nodiscard,__gnu__::__always_inline__]]
4384 make_wformat_args(_Args&... __args) noexcept
4385 { return std::make_format_args<wformat_context>(__args...); }
4388/// @cond undocumented
4391 template<typename _Out, typename _CharT, typename _Context>
4393 __do_vformat_to(_Out, basic_string_view<_CharT>,
4394 const basic_format_args<_Context>&,
4395 const locale* = nullptr);
4397 template<typename _CharT> struct __formatter_chrono;
4399} // namespace __format
4402 /** Context for std::format and similar functions.
4404 * A formatting context contains an output iterator and locale to use
4405 * for the formatting operations. Most programs will never need to use
4406 * this class template explicitly. For typical uses of `std::format` the
4407 * library will use the specializations `std::format_context` (for `char`)
4408 * and `std::wformat_context` (for `wchar_t`).
4410 * You are not allowed to define partial or explicit specializations of
4411 * this class template.
4415 template<typename _Out, typename _CharT>
4416 class basic_format_context
4418 static_assert( output_iterator<_Out, const _CharT&> );
4420 basic_format_args<basic_format_context> _M_args;
4422 __format::_Optional_locale _M_loc;
4424 basic_format_context(basic_format_args<basic_format_context> __args,
4426 : _M_args(__args), _M_out(std::move(__out))
4429 basic_format_context(basic_format_args<basic_format_context> __args,
4430 _Out __out, const std::locale& __loc)
4431 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4434 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4435 // 4061. Should std::basic_format_context be
4436 // default-constructible/copyable/movable?
4437 basic_format_context(const basic_format_context&) = delete;
4438 basic_format_context& operator=(const basic_format_context&) = delete;
4440 template<typename _Out2, typename _CharT2, typename _Context2>
4442 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4443 const basic_format_args<_Context2>&,
4446 friend __format::__formatter_chrono<_CharT>;
4449 ~basic_format_context() = default;
4451 using iterator = _Out;
4452 using char_type = _CharT;
4453 template<typename _Tp>
4454 using formatter_type = formatter<_Tp, _CharT>;
4457 basic_format_arg<basic_format_context>
4458 arg(size_t __id) const noexcept
4459 { return _M_args.get(__id); }
4462 std::locale locale() { return _M_loc.value(); }
4465 iterator out() { return std::move(_M_out); }
4467 void advance_to(iterator __it) { _M_out = std::move(__it); }
4471/// @cond undocumented
4474 // Abstract base class defining an interface for scanning format strings.
4475 // Scan the characters in a format string, dividing it up into strings of
4476 // ordinary characters, escape sequences, and replacement fields.
4477 // Call virtual functions for derived classes to parse format-specifiers
4478 // or write formatted output.
4479 template<typename _CharT>
4482 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4484 struct _Parse_context : basic_format_parse_context<_CharT>
4486 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4487 const _Arg_t* _M_types = nullptr;
4491 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4492 : _M_pc(__str, __nargs)
4495 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4496 constexpr iterator end() const noexcept { return _M_pc.end(); }
4501 basic_string_view<_CharT> __fmt = _M_fmt_str();
4503 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4505 _M_pc.advance_to(begin() + 1);
4506 _M_format_arg(_M_pc.next_arg_id());
4510 size_t __lbr = __fmt.find('{');
4511 size_t __rbr = __fmt.find('}');
4513 while (__fmt.size())
4515 auto __cmp = __lbr <=> __rbr;
4519 _M_pc.advance_to(end());
4524 if (__lbr + 1 == __fmt.size()
4525 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4526 __format::__unmatched_left_brace_in_format_string();
4527 const bool __is_escape = __fmt[__lbr + 1] == '{';
4528 iterator __last = begin() + __lbr + int(__is_escape);
4529 _M_on_chars(__last);
4530 _M_pc.advance_to(__last + 1);
4531 __fmt = _M_fmt_str();
4534 if (__rbr != __fmt.npos)
4536 __lbr = __fmt.find('{');
4540 _M_on_replacement_field();
4541 __fmt = _M_fmt_str();
4542 __lbr = __fmt.find('{');
4543 __rbr = __fmt.find('}');
4548 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4549 __format::__unmatched_right_brace_in_format_string();
4550 iterator __last = begin() + __rbr;
4551 _M_on_chars(__last);
4552 _M_pc.advance_to(__last + 1);
4553 __fmt = _M_fmt_str();
4554 if (__lbr != __fmt.npos)
4556 __rbr = __fmt.find('}');
4561 constexpr basic_string_view<_CharT>
4562 _M_fmt_str() const noexcept
4563 { return {begin(), end()}; }
4565 constexpr virtual void _M_on_chars(iterator) { }
4567 constexpr void _M_on_replacement_field()
4569 auto __next = begin();
4573 __id = _M_pc.next_arg_id();
4574 else if (*__next == ':')
4576 __id = _M_pc.next_arg_id();
4577 _M_pc.advance_to(++__next);
4581 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4582 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4583 __format::__invalid_arg_id_in_format_string();
4584 _M_pc.check_arg_id(__id = __i);
4587 _M_pc.advance_to(++__ptr);
4590 _M_pc.advance_to(__ptr);
4592 _M_format_arg(__id);
4593 if (begin() == end() || *begin() != '}')
4594 __format::__unmatched_left_brace_in_format_string();
4595 _M_pc.advance_to(begin() + 1); // Move past '}'
4598 constexpr virtual void _M_format_arg(size_t __id) = 0;
4601 // Process a format string and format the arguments in the context.
4602 template<typename _Out, typename _CharT>
4603 class _Formatting_scanner : public _Scanner<_CharT>
4606 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4607 basic_string_view<_CharT> __str)
4608 : _Scanner<_CharT>(__str), _M_fc(__fc)
4612 basic_format_context<_Out, _CharT>& _M_fc;
4614 using iterator = typename _Scanner<_CharT>::iterator;
4617 _M_on_chars(iterator __last) override
4619 basic_string_view<_CharT> __str(this->begin(), __last);
4620 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4624 _M_format_arg(size_t __id) override
4626 using _Context = basic_format_context<_Out, _CharT>;
4627 using handle = typename basic_format_arg<_Context>::handle;
4629 __format::__visit_format_arg([this](auto& __arg) {
4630 using _Type = remove_reference_t<decltype(__arg)>;
4631 using _Formatter = typename _Context::template formatter_type<_Type>;
4632 if constexpr (is_same_v<_Type, monostate>)
4633 __format::__invalid_arg_id_in_format_string();
4634 else if constexpr (is_same_v<_Type, handle>)
4635 __arg.format(this->_M_pc, this->_M_fc);
4636 else if constexpr (is_default_constructible_v<_Formatter>)
4639 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4640 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4643 static_assert(__format::__formattable_with<_Type, _Context>);
4644 }, _M_fc.arg(__id));
4648 template<typename _CharT, typename _Tp>
4650 __to_arg_t_enum() noexcept
4652 using _Context = __format::__format_context<_CharT>;
4653 using _Fmt_arg = basic_format_arg<_Context>;
4654 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4655 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4658 // Validate a format string for Args.
4659 template<typename _CharT, typename... _Args>
4660 class _Checking_scanner : public _Scanner<_CharT>
4663 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4664 "std::formatter must be specialized for each type being formatted");
4668 _Checking_scanner(basic_string_view<_CharT> __str)
4669 : _Scanner<_CharT>(__str, sizeof...(_Args))
4671#if __cpp_lib_format >= 202305L
4672 this->_M_pc._M_types = _M_types.data();
4678 _M_format_arg(size_t __id) override
4680 if constexpr (sizeof...(_Args) != 0)
4682 if (__id < sizeof...(_Args))
4684 _M_parse_format_spec<_Args...>(__id);
4688 __builtin_unreachable();
4691 template<typename _Tp, typename... _OtherArgs>
4693 _M_parse_format_spec(size_t __id)
4697 formatter<_Tp, _CharT> __f;
4698 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4700 else if constexpr (sizeof...(_OtherArgs) != 0)
4701 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4703 __builtin_unreachable();
4706#if __cpp_lib_format >= 202305L
4707 array<_Arg_t, sizeof...(_Args)>
4708 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
4712 template<typename _Out, typename _CharT, typename _Context>
4714 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4715 const basic_format_args<_Context>& __args,
4716 const locale* __loc)
4718 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4719 _Sink_iter<_CharT> __sink_out;
4721 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4722 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4724 __sink_out = __sink.out();
4726 if constexpr (is_same_v<_CharT, char>)
4727 // Fast path for "{}" format strings and simple format arg types.
4728 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4730 bool __done = false;
4731 __format::__visit_format_arg([&](auto& __arg) {
4732 using _Tp = remove_cvref_t<decltype(__arg)>;
4733 if constexpr (is_same_v<_Tp, bool>)
4735 size_t __len = 4 + !__arg;
4736 const char* __chars[] = { "false", "true" };
4737 if (auto __res = __sink_out._M_reserve(__len))
4739 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4740 __res._M_bump(__len);
4744 else if constexpr (is_same_v<_Tp, char>)
4746 if (auto __res = __sink_out._M_reserve(1))
4748 *__res.get() = __arg;
4753 else if constexpr (is_integral_v<_Tp>)
4755 make_unsigned_t<_Tp> __uval;
4756 const bool __neg = __arg < 0;
4758 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4761 const auto __n = __detail::__to_chars_len(__uval);
4762 if (auto __res = __sink_out._M_reserve(__n + __neg))
4764 auto __ptr = __res.get();
4766 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4768 __res._M_bump(__n + __neg);
4772 else if constexpr (is_convertible_v<_Tp, string_view>)
4774 string_view __sv = __arg;
4775 if (auto __res = __sink_out._M_reserve(__sv.size()))
4777 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4778 __res._M_bump(__sv.size());
4786 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4789 return std::move(__sink)._M_finish().out;
4793 auto __ctx = __loc == nullptr
4794 ? _Context(__args, __sink_out)
4795 : _Context(__args, __sink_out, *__loc);
4796 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4797 __scanner._M_scan();
4799 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4802 return std::move(__sink)._M_finish().out;
4804#pragma GCC diagnostic pop
4806} // namespace __format
4809#if __cpp_lib_format >= 202305L // >= C++26
4810 /// @cond undocumented
4811 // Common implementation of check_dynamic_spec{,_string,_integral}
4812 template<typename _CharT>
4813 template<typename... _Ts>
4815 basic_format_parse_context<_CharT>::
4816 __check_dynamic_spec(size_t __id) noexcept
4818 if (__id >= _M_num_args)
4819 __format::__invalid_arg_id_in_format_string();
4820 if constexpr (sizeof...(_Ts) != 0)
4822 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
4823 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
4824 __format::_Arg_t __types[] = {
4825 __format::__to_arg_t_enum<_CharT, _Ts>()...
4827 for (auto __t : __types)
4831 __invalid_dynamic_spec("arg(id) type does not match");
4836 template<typename _CharT, typename... _Args>
4837 template<typename _Tp>
4838 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4840 basic_format_string<_CharT, _Args...>::
4841 basic_format_string(const _Tp& __s)
4844 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4846 __scanner._M_scan();
4849 // [format.functions], formatting functions
4851 template<typename _Out> requires output_iterator<_Out, const char&>
4852 [[__gnu__::__always_inline__]]
4854 vformat_to(_Out __out, string_view __fmt, format_args __args)
4855 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4857#ifdef _GLIBCXX_USE_WCHAR_T
4858 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4859 [[__gnu__::__always_inline__]]
4861 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4862 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4865 template<typename _Out> requires output_iterator<_Out, const char&>
4866 [[__gnu__::__always_inline__]]
4868 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4871 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4874#ifdef _GLIBCXX_USE_WCHAR_T
4875 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4876 [[__gnu__::__always_inline__]]
4878 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4879 wformat_args __args)
4881 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4887 vformat(string_view __fmt, format_args __args)
4889 __format::_Str_sink<char> __buf;
4890 std::vformat_to(__buf.out(), __fmt, __args);
4891 return std::move(__buf).get();
4894#ifdef _GLIBCXX_USE_WCHAR_T
4897 vformat(wstring_view __fmt, wformat_args __args)
4899 __format::_Str_sink<wchar_t> __buf;
4900 std::vformat_to(__buf.out(), __fmt, __args);
4901 return std::move(__buf).get();
4907 vformat(const locale& __loc, string_view __fmt, format_args __args)
4909 __format::_Str_sink<char> __buf;
4910 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4911 return std::move(__buf).get();
4914#ifdef _GLIBCXX_USE_WCHAR_T
4917 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4919 __format::_Str_sink<wchar_t> __buf;
4920 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4921 return std::move(__buf).get();
4925 template<typename... _Args>
4928 format(format_string<_Args...> __fmt, _Args&&... __args)
4929 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4931#ifdef _GLIBCXX_USE_WCHAR_T
4932 template<typename... _Args>
4935 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4936 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4939 template<typename... _Args>
4942 format(const locale& __loc, format_string<_Args...> __fmt,
4945 return std::vformat(__loc, __fmt.get(),
4946 std::make_format_args(__args...));
4949#ifdef _GLIBCXX_USE_WCHAR_T
4950 template<typename... _Args>
4953 format(const locale& __loc, wformat_string<_Args...> __fmt,
4956 return std::vformat(__loc, __fmt.get(),
4957 std::make_wformat_args(__args...));
4961 template<typename _Out, typename... _Args>
4962 requires output_iterator<_Out, const char&>
4964 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4966 return std::vformat_to(std::move(__out), __fmt.get(),
4967 std::make_format_args(__args...));
4970#ifdef _GLIBCXX_USE_WCHAR_T
4971 template<typename _Out, typename... _Args>
4972 requires output_iterator<_Out, const wchar_t&>
4974 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4976 return std::vformat_to(std::move(__out), __fmt.get(),
4977 std::make_wformat_args(__args...));
4981 template<typename _Out, typename... _Args>
4982 requires output_iterator<_Out, const char&>
4984 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4987 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4988 std::make_format_args(__args...));
4991#ifdef _GLIBCXX_USE_WCHAR_T
4992 template<typename _Out, typename... _Args>
4993 requires output_iterator<_Out, const wchar_t&>
4995 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4998 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4999 std::make_wformat_args(__args...));
5003 template<typename _Out, typename... _Args>
5004 requires output_iterator<_Out, const char&>
5005 inline format_to_n_result<_Out>
5006 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5007 format_string<_Args...> __fmt, _Args&&... __args)
5009 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5010 std::vformat_to(__sink.out(), __fmt.get(),
5011 std::make_format_args(__args...));
5012 return std::move(__sink)._M_finish();
5015#ifdef _GLIBCXX_USE_WCHAR_T
5016 template<typename _Out, typename... _Args>
5017 requires output_iterator<_Out, const wchar_t&>
5018 inline format_to_n_result<_Out>
5019 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5020 wformat_string<_Args...> __fmt, _Args&&... __args)
5022 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5023 std::vformat_to(__sink.out(), __fmt.get(),
5024 std::make_wformat_args(__args...));
5025 return std::move(__sink)._M_finish();
5029 template<typename _Out, typename... _Args>
5030 requires output_iterator<_Out, const char&>
5031 inline format_to_n_result<_Out>
5032 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5033 format_string<_Args...> __fmt, _Args&&... __args)
5035 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5036 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5037 std::make_format_args(__args...));
5038 return std::move(__sink)._M_finish();
5041#ifdef _GLIBCXX_USE_WCHAR_T
5042 template<typename _Out, typename... _Args>
5043 requires output_iterator<_Out, const wchar_t&>
5044 inline format_to_n_result<_Out>
5045 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5046 wformat_string<_Args...> __fmt, _Args&&... __args)
5048 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5049 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5050 std::make_wformat_args(__args...));
5051 return std::move(__sink)._M_finish();
5055/// @cond undocumented
5059 template<typename _CharT>
5060 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5063 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5065 [[__gnu__::__always_inline__]]
5068 { return this->_M_count + this->_M_used().size(); }
5071 template<typename _CharT>
5072 class _Counting_sink : public _Buf_sink<_CharT>
5074 size_t _M_count = 0;
5077 _M_overflow() override
5079 if (!std::is_constant_evaluated())
5080 _M_count += this->_M_used().size();
5085 _Counting_sink() = default;
5087 [[__gnu__::__always_inline__]]
5091 _Counting_sink::_M_overflow();
5096} // namespace __format
5099 template<typename... _Args>
5102 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5104 __format::_Counting_sink<char> __buf;
5105 std::vformat_to(__buf.out(), __fmt.get(),
5106 std::make_format_args(__args...));
5107 return __buf.count();
5110#ifdef _GLIBCXX_USE_WCHAR_T
5111 template<typename... _Args>
5114 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5116 __format::_Counting_sink<wchar_t> __buf;
5117 std::vformat_to(__buf.out(), __fmt.get(),
5118 std::make_wformat_args(__args...));
5119 return __buf.count();
5123 template<typename... _Args>
5126 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5129 __format::_Counting_sink<char> __buf;
5130 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5131 std::make_format_args(__args...));
5132 return __buf.count();
5135#ifdef _GLIBCXX_USE_WCHAR_T
5136 template<typename... _Args>
5139 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5142 __format::_Counting_sink<wchar_t> __buf;
5143 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5144 std::make_wformat_args(__args...));
5145 return __buf.count();
5149#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5150 // [format.range], formatting of ranges
5151 // [format.range.fmtkind], variable template format_kind
5152 enum class range_format {
5161 /// @cond undocumented
5162 template<typename _Rg>
5163 constexpr auto format_kind =
5164 __primary_template_not_defined(
5165 format_kind<_Rg> // you can specialize this for non-const input ranges
5168 template<typename _Tp>
5169 consteval range_format
5172 using _Ref = ranges::range_reference_t<_Tp>;
5173 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5174 return range_format::disabled;
5175 else if constexpr (requires { typename _Tp::key_type; })
5177 if constexpr (requires { typename _Tp::mapped_type; })
5179 using _Up = remove_cvref_t<_Ref>;
5180 if constexpr (__is_pair<_Up>)
5181 return range_format::map;
5182 else if constexpr (__is_specialization_of<_Up, tuple>)
5183 if constexpr (tuple_size_v<_Up> == 2)
5184 return range_format::map;
5186 return range_format::set;
5189 return range_format::sequence;
5193 /// A constant determining how a range should be formatted.
5194 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5195 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5197/// @cond undocumented
5200 template<typename _CharT, typename _Out, typename _Callback>
5201 typename basic_format_context<_Out, _CharT>::iterator
5202 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5203 const _Spec<_CharT>& __spec,
5206 // This is required to implement formatting with padding,
5207 // as we need to format to temporary buffer, using the same iterator.
5208 static_assert(is_same_v<_Out, __format::_Sink_iter<_CharT>>);
5210 if (__spec._M_get_width(__fc) == 0)
5211 return __call(__fc);
5215 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5216 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5222 _M_ctx->advance_to(_M_out);
5230 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5231 _Sink_iter<_CharT> _M_out;
5234 _Restore_out __restore(__fc);
5235 // TODO Consider double sinking, first buffer of width
5236 // size and then original sink, if first buffer is overun
5237 // we do not need to align
5238 _Str_sink<_CharT> __buf;
5239 __fc.advance_to(__buf.out());
5241 __restore._M_trigger();
5243 basic_string_view<_CharT> __str(__buf.view());
5245 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
5246 __width = __unicode::__field_width(__str);
5248 __width = __str.size();
5250 return __format::__write_padded_as_spec(__str, __width, __fc, __spec);
5253 template<typename _Rg, typename _CharT>
5254 concept __const_formattable_range
5255 = ranges::input_range<const _Rg>
5256 && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
5258 // _Rg& and const _Rg& are both formattable and use same formatter
5259 // specialization for their references.
5260 template<typename _Rg, typename _CharT>
5261 concept __simply_formattable_range
5262 = __const_formattable_range<_Rg, _CharT>
5263 && same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>,
5264 remove_cvref_t<ranges::range_reference_t<const _Rg>>>;
5266 template<typename _Rg, typename _CharT>
5267 using __maybe_const_range
5268 = __conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
5270 template<typename _Tp, typename _CharT>
5272 = __conditional_t<formattable<const _Tp, _CharT>, const _Tp, _Tp>;
5274 template<size_t _Pos, typename _Tp, typename _CharT>
5275 struct __indexed_formatter_storage
5280 basic_format_parse_context<_CharT> __pc({});
5281 if (_M_formatter.parse(__pc) != __pc.end())
5282 __format::__failed_to_parse_format_spec();
5285 template<typename _Out>
5287 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5288 basic_format_context<_Out, _CharT>& __fc,
5289 basic_string_view<_CharT> __sep) const
5291 if constexpr (_Pos != 0)
5292 __fc.advance_to(__format::__write(__fc.out(), __sep));
5293 __fc.advance_to(_M_formatter.format(__elem, __fc));
5296 [[__gnu__::__always_inline__]]
5300 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5301 _M_formatter.set_debug_format();
5305 formatter<_Tp, _CharT> _M_formatter;
5308 template<typename _CharT, typename... _Tps>
5309 class __tuple_formatter
5311 using _String_view = basic_string_view<_CharT>;
5312 using _Seps = __format::_Separators<_CharT>;
5316 set_separator(basic_string_view<_CharT> __sep) noexcept
5320 set_brackets(basic_string_view<_CharT> __open,
5321 basic_string_view<_CharT> __close) noexcept
5327 // We deviate from standard, that declares this as template accepting
5328 // unconstrained ParseContext type, which seems unimplementable.
5329 constexpr typename basic_format_parse_context<_CharT>::iterator
5330 parse(basic_format_parse_context<_CharT>& __pc)
5332 auto __first = __pc.begin();
5333 const auto __last = __pc.end();
5334 __format::_Spec<_CharT> __spec{};
5336 auto __finished = [&]
5338 if (__first != __last && *__first != '}')
5342 _M_felems._M_parse();
5343 _M_felems.set_debug_format();
5350 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5354 __first = __spec._M_parse_width(__first, __last, __pc);
5358 if (*__first == 'n')
5361 _M_open = _M_close = _String_view();
5363 else if (*__first == 'm')
5366 if constexpr (sizeof...(_Tps) == 2)
5368 _M_sep = _Seps::_S_colon();
5369 _M_open = _M_close = _String_view();
5372 __throw_format_error("format error: 'm' specifier requires range"
5373 " of pair or tuple of two elements");
5379 __format::__failed_to_parse_format_spec();
5383 template<typename _Tuple, typename _Out, size_t... _Ids>
5384 typename basic_format_context<_Out, _CharT>::iterator
5385 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5386 basic_format_context<_Out, _CharT>& __fc) const
5387 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5389 template<typename _Out>
5390 typename basic_format_context<_Out, _CharT>::iterator
5391 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5392 basic_format_context<_Out, _CharT>& __fc) const
5394 return __format::__format_padded(
5396 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5398 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5399 _M_felems._M_format(__elems..., __nfc, _M_sep);
5400 return __format::__write(__nfc.out(), _M_close);
5405 template<size_t... _Ids>
5406 struct __formatters_storage
5407 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5409 template<size_t _Id, typename _Up>
5410 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5415 (_Base<_Ids, _Tps>::_M_parse(), ...);
5418 template<typename _Out>
5420 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5421 basic_format_context<_Out, _CharT>& __fc,
5422 _String_view __sep) const
5424 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5430 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5434 template<size_t... _Ids>
5436 _S_create_storage(index_sequence<_Ids...>)
5437 -> __formatters_storage<_Ids...>;
5439 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5441 _Spec<_CharT> _M_spec{};
5442 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5443 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5444 _String_view _M_sep = _Seps::_S_comma();
5445 _Formatters _M_felems;
5448 template<typename _Tp>
5449 concept __is_map_formattable
5450 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5452} // namespace __format
5455 // [format.tuple] Tuple formatter
5456 template<__format::__char _CharT, formattable<_CharT> _Fp,
5457 formattable<_CharT> _Sp>
5458 struct formatter<pair<_Fp, _Sp>, _CharT>
5459 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5460 remove_cvref_t<_Sp>>
5463 using __maybe_const_pair
5464 = __conditional_t<formattable<const _Fp, _CharT>
5465 && formattable<const _Sp, _CharT>,
5466 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5468 // We deviate from standard, that declares this as template accepting
5469 // unconstrained FormatContext type, which seems unimplementable.
5470 template<typename _Out>
5471 typename basic_format_context<_Out, _CharT>::iterator
5472 format(__maybe_const_pair& __p,
5473 basic_format_context<_Out, _CharT>& __fc) const
5474 { return this->_M_format_elems(__p.first, __p.second, __fc); }
5477 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5478 struct formatter<tuple<_Tps...>, _CharT>
5479 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5482 using __maybe_const_tuple
5483 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5484 const tuple<_Tps...>, tuple<_Tps...>>;
5486 // We deviate from standard, that declares this as template accepting
5487 // unconstrained FormatContext type, which seems unimplementable.
5488 template<typename _Out>
5489 typename basic_format_context<_Out, _CharT>::iterator
5490 format(__maybe_const_tuple& __t,
5491 basic_format_context<_Out, _CharT>& __fc) const
5492 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5495 // [format.range.formatter], class template range_formatter
5496 template<typename _Tp, __format::__char _CharT = char>
5497 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
5498 class range_formatter
5500 using _String_view = basic_string_view<_CharT>;
5501 using _Seps = __format::_Separators<_CharT>;
5505 set_separator(basic_string_view<_CharT> __sep) noexcept
5509 set_brackets(basic_string_view<_CharT> __open,
5510 basic_string_view<_CharT> __close) noexcept
5516 constexpr formatter<_Tp, _CharT>&
5517 underlying() noexcept
5520 constexpr const formatter<_Tp, _CharT>&
5521 underlying() const noexcept
5524 // We deviate from standard, that declares this as template accepting
5525 // unconstrained ParseContext type, which seems unimplementable.
5526 constexpr typename basic_format_parse_context<_CharT>::iterator
5527 parse(basic_format_parse_context<_CharT>& __pc)
5529 auto __first = __pc.begin();
5530 const auto __last = __pc.end();
5531 __format::_Spec<_CharT> __spec{};
5532 bool __no_brace = false;
5534 auto __finished = [&]
5535 { return __first == __last || *__first == '}'; };
5537 auto __finalize = [&]
5543 auto __parse_val = [&](_String_view __nfs = _String_view())
5545 basic_format_parse_context<_CharT> __npc(__nfs);
5546 if (_M_fval.parse(__npc) != __npc.end())
5547 __format::__failed_to_parse_format_spec();
5548 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
5549 _M_fval.set_debug_format();
5550 return __finalize();
5554 return __parse_val();
5556 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5558 return __parse_val();
5560 __first = __spec._M_parse_width(__first, __last, __pc);
5562 return __parse_val();
5564 if (*__first == '?')
5567 __spec._M_type = __format::_Pres_esc;
5568 if (__finished() || *__first != 's')
5569 __throw_format_error("format error: '?' is allowed only in"
5570 " combination with 's'");
5573 if (*__first == 's')
5576 if constexpr (same_as<_Tp, _CharT>)
5578 if (__spec._M_type != __format::_Pres_esc)
5579 __spec._M_type = __format::_Pres_str;
5581 return __finalize();
5582 __throw_format_error("format error: element format specifier"
5583 " cannot be provided when 's' specifier is used");
5586 __throw_format_error("format error: 's' specifier requires"
5587 " range of character types");
5591 return __parse_val();
5593 if (*__first == 'n')
5596 _M_open = _M_close = _String_view();
5601 return __parse_val();
5603 if (*__first == 'm')
5605 _String_view __m(__first, 1);
5607 if constexpr (__format::__is_map_formattable<_Tp>)
5609 _M_sep = _Seps::_S_comma();
5612 _M_open = _Seps::_S_braces().substr(0, 1);
5613 _M_close = _Seps::_S_braces().substr(1, 1);
5616 return __parse_val(__m);
5617 __throw_format_error("format error: element format specifier"
5618 " cannot be provided when 'm' specifier is used");
5621 __throw_format_error("format error: 'm' specifier requires"
5622 " range of pairs or tuples of two elements");
5626 return __parse_val();
5628 if (*__first == ':')
5630 __pc.advance_to(++__first);
5631 __first = _M_fval.parse(__pc);
5635 return __finalize();
5637 __format::__failed_to_parse_format_spec();
5640 // We deviate from standard, that declares this as template accepting
5641 // unconstrained FormatContext type, which seems unimplementable.
5642 template<ranges::input_range _Rg, typename _Out>
5643 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
5644 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
5645 typename basic_format_context<_Out, _CharT>::iterator
5646 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
5648 using _Range = remove_reference_t<_Rg>;
5649 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
5650 return _M_format<const _Range>(__rg, __fc);
5652 return _M_format(__rg, __fc);
5656 template<ranges::input_range _Rg, typename _Out>
5657 typename basic_format_context<_Out, _CharT>::iterator
5658 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
5660 if constexpr (same_as<_Tp, _CharT>)
5661 if (_M_spec._M_type == __format::_Pres_str
5662 || _M_spec._M_type == __format::_Pres_esc)
5664 __format::__formatter_str __fstr(_M_spec);
5665 return __fstr._M_format_range(__rg, __fc);
5667 return __format::__format_padded(
5669 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
5670 { return _M_format_elems(__rg, __nfc); });
5674 template<ranges::input_range _Rg, typename _Out>
5675 typename basic_format_context<_Out, _CharT>::iterator
5676 _M_format_elems(_Rg& __rg,
5677 basic_format_context<_Out, _CharT>& __fc) const
5679 auto __out = __format::__write(__fc.out(), _M_open);
5681 auto __first = ranges::begin(__rg);
5682 auto const __last = ranges::end(__rg);
5683 if (__first == __last)
5684 return __format::__write(__out, _M_close);
5686 __fc.advance_to(__out);
5687 __out = _M_fval.format(*__first, __fc);
5688 for (++__first; __first != __last; ++__first)
5690 __out = __format::__write(__out, _M_sep);
5691 __fc.advance_to(__out);
5692 __out = _M_fval.format(*__first, __fc);
5695 return __format::__write(__out, _M_close);
5698 __format::_Spec<_CharT> _M_spec{};
5699 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
5700 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
5701 _String_view _M_sep = _Seps::_S_comma();
5702 formatter<_Tp, _CharT> _M_fval;
5705 // In standard this is shown as inheriting from specialization of
5706 // exposition only specialization for range-default-formatter for
5707 // each range_format. We opt for simpler implementation.
5708 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
5709 // specializations for maps, sets, and strings
5710 template<ranges::input_range _Rg, __format::__char _CharT>
5711 requires (format_kind<_Rg> != range_format::disabled)
5712 && formattable<ranges::range_reference_t<_Rg>, _CharT>
5713 struct formatter<_Rg, _CharT>
5716 static const bool _S_range_format_is_string =
5717 (format_kind<_Rg> == range_format::string)
5718 || (format_kind<_Rg> == range_format::debug_string);
5719 using _Vt = remove_cvref_t<
5720 ranges::range_reference_t<
5721 __format::__maybe_const_range<_Rg, _CharT>>>;
5723 static consteval bool _S_is_correct()
5725 if constexpr (_S_range_format_is_string)
5726 static_assert(same_as<_Vt, _CharT>);
5730 static_assert(_S_is_correct());
5733 constexpr formatter() noexcept
5735 using _Seps = __format::_Separators<_CharT>;
5736 if constexpr (format_kind<_Rg> == range_format::map)
5738 static_assert(__format::__is_map_formattable<_Vt>);
5739 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
5740 _Seps::_S_braces().substr(1, 1));
5741 _M_under.underlying().set_brackets({}, {});
5742 _M_under.underlying().set_separator(_Seps::_S_colon());
5744 else if constexpr (format_kind<_Rg> == range_format::set)
5745 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
5746 _Seps::_S_braces().substr(1, 1));
5750 set_separator(basic_string_view<_CharT> __sep) noexcept
5751 requires (!_S_range_format_is_string)
5752 { _M_under.set_separator(__sep); }
5755 set_brackets(basic_string_view<_CharT> __open,
5756 basic_string_view<_CharT> __close) noexcept
5757 requires (!_S_range_format_is_string)
5758 { _M_under.set_brackets(__open, __close); }
5760 // We deviate from standard, that declares this as template accepting
5761 // unconstrained ParseContext type, which seems unimplementable.
5762 constexpr typename basic_format_parse_context<_CharT>::iterator
5763 parse(basic_format_parse_context<_CharT>& __pc)
5765 auto __res = _M_under.parse(__pc);
5766 if constexpr (format_kind<_Rg> == range_format::debug_string)
5767 _M_under.set_debug_format();
5771 // We deviate from standard, that declares this as template accepting
5772 // unconstrained FormatContext type, which seems unimplementable.
5773 template<typename _Out>
5774 typename basic_format_context<_Out, _CharT>::iterator
5775 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
5776 basic_format_context<_Out, _CharT>& __fc) const
5778 if constexpr (_S_range_format_is_string)
5779 return _M_under._M_format_range(__rg, __fc);
5781 return _M_under.format(__rg, __fc);
5785 using _Formatter_under
5786 = __conditional_t<_S_range_format_is_string,
5787 __format::__formatter_str<_CharT>,
5788 range_formatter<_Vt, _CharT>>;
5789 _Formatter_under _M_under;
5791#endif // C++23 formatting ranges
5792#undef _GLIBCXX_WIDEN
5794_GLIBCXX_END_NAMESPACE_VERSION
5796#endif // __cpp_lib_format
5797#pragma GCC diagnostic pop
5798#endif // _GLIBCXX_FORMAT