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 // An unspecified output iterator type used in the `formattable` concept.
121 template<typename _CharT>
123 { using type = back_insert_iterator<basic_string<_CharT>>; };
125 template<typename _CharT>
126 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
128 template<typename _CharT>
129 struct _Runtime_format_string
131 [[__gnu__::__always_inline__]]
132 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
135 _Runtime_format_string(const _Runtime_format_string&) = delete;
136 void operator=(const _Runtime_format_string&) = delete;
139 basic_string_view<_CharT> _M_str;
141 template<typename, typename...> friend struct std::basic_format_string;
144} // namespace __format
147 using format_context = __format::__format_context<char>;
148#ifdef _GLIBCXX_USE_WCHAR_T
149 using wformat_context = __format::__format_context<wchar_t>;
152 // [format.args], class template basic_format_args
153 template<typename _Context> class basic_format_args;
154 using format_args = basic_format_args<format_context>;
155#ifdef _GLIBCXX_USE_WCHAR_T
156 using wformat_args = basic_format_args<wformat_context>;
159 // [format.arguments], arguments
160 // [format.arg], class template basic_format_arg
161 template<typename _Context>
162 class basic_format_arg;
164 /** A compile-time checked format string for the specified argument types.
166 * @since C++23 but available as an extension in C++20.
168 template<typename _CharT, typename... _Args>
169 struct basic_format_string
171 template<typename _Tp>
172 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
174 basic_format_string(const _Tp& __s);
176 [[__gnu__::__always_inline__]]
177 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
181 [[__gnu__::__always_inline__]]
182 constexpr basic_string_view<_CharT>
187 basic_string_view<_CharT> _M_str;
190 template<typename... _Args>
191 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
193#ifdef _GLIBCXX_USE_WCHAR_T
194 template<typename... _Args>
196 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
199#if __cpp_lib_format >= 202311L // >= C++26
200 [[__gnu__::__always_inline__]]
201 inline __format::_Runtime_format_string<char>
202 runtime_format(string_view __fmt) noexcept
205#ifdef _GLIBCXX_USE_WCHAR_T
206 [[__gnu__::__always_inline__]]
207 inline __format::_Runtime_format_string<wchar_t>
208 runtime_format(wstring_view __fmt) noexcept
213 // [format.formatter], formatter
215 /// The primary template of std::formatter is disabled.
216 template<typename _Tp, typename _CharT>
219 formatter() = delete; // No std::formatter specialization for this type.
220 formatter(const formatter&) = delete;
221 formatter& operator=(const formatter&) = delete;
224 // [format.error], class format_error
225 class format_error : public runtime_error
228 explicit format_error(const string& __what) : runtime_error(__what) { }
229 explicit format_error(const char* __what) : runtime_error(__what) { }
232 /// @cond undocumented
235 __throw_format_error(const char* __what)
236 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
240 // XXX use named functions for each constexpr error?
244 __unmatched_left_brace_in_format_string()
245 { __throw_format_error("format error: unmatched '{' in format string"); }
249 __unmatched_right_brace_in_format_string()
250 { __throw_format_error("format error: unmatched '}' in format string"); }
254 __conflicting_indexing_in_format_string()
255 { __throw_format_error("format error: conflicting indexing style in format string"); }
259 __invalid_arg_id_in_format_string()
260 { __throw_format_error("format error: invalid arg-id in format string"); }
264 __failed_to_parse_format_spec()
265 { __throw_format_error("format error: failed to parse format-spec"); }
267 template<typename _CharT> class _Scanner;
269} // namespace __format
272 // [format.parse.ctx], class template basic_format_parse_context
273 template<typename _CharT> class basic_format_parse_context;
274 using format_parse_context = basic_format_parse_context<char>;
275#ifdef _GLIBCXX_USE_WCHAR_T
276 using wformat_parse_context = basic_format_parse_context<wchar_t>;
279 template<typename _CharT>
280 class basic_format_parse_context
283 using char_type = _CharT;
284 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
285 using iterator = const_iterator;
288 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
289 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
292 basic_format_parse_context(const basic_format_parse_context&) = delete;
293 void operator=(const basic_format_parse_context&) = delete;
295 constexpr const_iterator begin() const noexcept { return _M_begin; }
296 constexpr const_iterator end() const noexcept { return _M_end; }
299 advance_to(const_iterator __it) noexcept
305 if (_M_indexing == _Manual)
306 __format::__conflicting_indexing_in_format_string();
309 // _GLIBCXX_RESOLVE_LIB_DEFECTS
310 // 3825. Missing compile-time argument id check in next_arg_id
311 if (std::is_constant_evaluated())
312 if (_M_next_arg_id == _M_num_args)
313 __format::__invalid_arg_id_in_format_string();
314 return _M_next_arg_id++;
318 check_arg_id(size_t __id)
320 if (_M_indexing == _Auto)
321 __format::__conflicting_indexing_in_format_string();
322 _M_indexing = _Manual;
324 if (std::is_constant_evaluated())
325 if (__id >= _M_num_args)
326 __format::__invalid_arg_id_in_format_string();
329#if __cpp_lib_format >= 202305L
330 template<typename... _Ts>
332 check_dynamic_spec(size_t __id) noexcept
334 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
335 "template arguments for check_dynamic_spec<Ts...>(id) "
336 "must be unique and must be one of the allowed types");
338 __check_dynamic_spec<_Ts...>(__id);
343 check_dynamic_spec_integral(size_t __id) noexcept
346 __check_dynamic_spec<int, unsigned, long long,
347 unsigned long long>(__id);
352 check_dynamic_spec_string(size_t __id) noexcept
355 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
360 // True if _Tp occurs exactly once in _Ts.
361 template<typename _Tp, typename... _Ts>
362 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
364 template<typename... _Ts>
366 __valid_types_for_check_dynamic_spec()
368 // _GLIBCXX_RESOLVE_LIB_DEFECTS
369 // 4142. check_dynamic_spec should require at least one type
370 if constexpr (sizeof...(_Ts) == 0)
374 // The types in Ts... are unique. Each type in Ts... is one of
375 // bool, char_type, int, unsigned int, long long int,
376 // unsigned long long int, float, double, long double,
377 // const char_type*, basic_string_view<char_type>, or const void*.
379 = __once<bool, _Ts...>
380 + __once<char_type, _Ts...>
381 + __once<int, _Ts...>
382 + __once<unsigned int, _Ts...>
383 + __once<long long int, _Ts...>
384 + __once<unsigned long long int, _Ts...>
385 + __once<float, _Ts...>
386 + __once<double, _Ts...>
387 + __once<long double, _Ts...>
388 + __once<const char_type*, _Ts...>
389 + __once<basic_string_view<char_type>, _Ts...>
390 + __once<const void*, _Ts...>;
391 return __sum == sizeof...(_Ts);
395 template<typename... _Ts>
397 __check_dynamic_spec(size_t __id) noexcept;
399 // This must not be constexpr.
400 static void __invalid_dynamic_spec(const char*);
402 friend __format::_Scanner<_CharT>;
405 // This constructor should only be used by the implementation.
407 basic_format_parse_context(basic_string_view<_CharT> __fmt,
408 size_t __num_args) noexcept
409 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
415 enum _Indexing { _Unknown, _Manual, _Auto };
416 _Indexing _M_indexing = _Unknown;
417 size_t _M_next_arg_id = 0;
418 size_t _M_num_args = 0;
421/// @cond undocumented
422 template<typename _Tp, template<typename...> class _Class>
423 constexpr bool __is_specialization_of = false;
424 template<template<typename...> class _Class, typename... _Args>
425 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
429 // pre: first != last
430 template<typename _CharT>
431 constexpr pair<unsigned short, const _CharT*>
432 __parse_integer(const _CharT* __first, const _CharT* __last)
434 if (__first == __last)
435 __builtin_unreachable();
437 if constexpr (is_same_v<_CharT, char>)
439 const auto __start = __first;
440 unsigned short __val = 0;
441 // N.B. std::from_chars is not constexpr in C++20.
442 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
443 && __first != __start) [[likely]]
444 return {__val, __first};
448 constexpr int __n = 32;
450 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
451 __buf[__i] = __first[__i];
452 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
453 if (__ptr) [[likely]]
454 return {__v, __first + (__ptr - __buf)};
459 template<typename _CharT>
460 constexpr pair<unsigned short, const _CharT*>
461 __parse_arg_id(const _CharT* __first, const _CharT* __last)
463 if (__first == __last)
464 __builtin_unreachable();
467 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
469 if ('1' <= *__first && *__first <= '9')
471 const unsigned short __id = *__first - '0';
472 const auto __next = __first + 1;
473 // Optimize for most likely case of single digit arg-id.
474 if (__next == __last || !('0' <= *__next && *__next <= '9'))
475 return {__id, __next};
477 return __format::__parse_integer(__first, __last);
483 _Pres_none = 0, // Default type (not valid for integer presentation types).
484 // Presentation types for integral types (including bool and charT).
485 _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
486 // Presentation types for floating-point types.
487 _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
488 _Pres_p = 0, _Pres_P, // For pointers.
489 _Pres_s = 0, // For strings, bool
490 _Pres_seq = 0, _Pres_str, // For ranges
491 _Pres_esc = 0xf, // For strings, charT and ranges
504 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
509 _WP_none, // No width/prec specified.
510 _WP_value, // Fixed width/prec specified.
511 _WP_from_arg // Use a formatting argument for width/prec.
514 template<typename _Context>
516 __int_from_arg(const basic_format_arg<_Context>& __arg);
518 constexpr bool __is_digit(char __c)
519 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
521 constexpr bool __is_xdigit(char __c)
522 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
524 template<typename _CharT>
530 unsigned _M_localized : 1;
531 unsigned _M_zero_fill : 1;
532 _WidthPrec _M_width_kind : 2;
533 _WidthPrec _M_prec_kind : 2;
534 _Pres_type _M_type : 4;
535 unsigned _M_reserved : 1;
536 unsigned _M_reserved2 : 16;
537 unsigned short _M_width;
538 unsigned short _M_prec;
539 char32_t _M_fill = ' ';
541 using iterator = typename basic_string_view<_CharT>::iterator;
543 static constexpr _Align
544 _S_align(_CharT __c) noexcept
548 case '<': return _Align_left;
549 case '>': return _Align_right;
550 case '^': return _Align_centre;
551 default: return _Align_default;
555 // pre: __first != __last
557 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
558 { return _M_parse_fill_and_align(__first, __last, "{"); }
560 // pre: __first != __last
562 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
564 for (char __c : __not_fill)
565 if (*__first == static_cast<_CharT>(__c))
568 using namespace __unicode;
569 if constexpr (__literal_encoding_is_unicode<_CharT>())
571 // Accept any UCS scalar value as fill character.
572 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
575 auto __beg = __uv.begin();
576 char32_t __c = *__beg++;
577 if (__is_scalar_value(__c))
578 if (auto __next = __beg.base(); __next != __last)
579 if (_Align __align = _S_align(*__next))
587 else if (__last - __first >= 2)
588 if (_Align __align = _S_align(__first[1]))
595 if (_Align __align = _S_align(__first[0]))
604 static constexpr _Sign
605 _S_sign(_CharT __c) noexcept
609 case '+': return _Sign_plus;
610 case '-': return _Sign_minus;
611 case ' ': return _Sign_space;
612 default: return _Sign_default;
616 // pre: __first != __last
618 _M_parse_sign(iterator __first, iterator) noexcept
620 if (_Sign __sign = _S_sign(*__first))
628 // pre: *__first is valid
630 _M_parse_alternate_form(iterator __first, iterator) noexcept
640 // pre: __first != __last
642 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
652 // pre: __first != __last
653 static constexpr iterator
654 _S_parse_width_or_precision(iterator __first, iterator __last,
655 unsigned short& __val, bool& __arg_id,
656 basic_format_parse_context<_CharT>& __pc)
658 if (__format::__is_digit(*__first))
660 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
662 __throw_format_error("format error: invalid width or precision "
667 else if (*__first == '{')
671 if (__first == __last)
672 __format::__unmatched_left_brace_in_format_string();
674 __val = __pc.next_arg_id();
677 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
678 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
679 __format::__invalid_arg_id_in_format_string();
681 __pc.check_arg_id(__v);
684#if __cpp_lib_format >= 202305L
685 __pc.check_dynamic_spec_integral(__val);
687 ++__first; // past the '}'
692 // pre: __first != __last
694 _M_parse_width(iterator __first, iterator __last,
695 basic_format_parse_context<_CharT>& __pc)
697 bool __arg_id = false;
699 __throw_format_error("format error: width must be non-zero in "
701 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
703 if (__next != __first)
704 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
708 // pre: __first != __last
710 _M_parse_precision(iterator __first, iterator __last,
711 basic_format_parse_context<_CharT>& __pc)
713 if (__first[0] != '.')
716 iterator __next = ++__first;
717 bool __arg_id = false;
718 if (__next != __last)
719 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
721 if (__next == __first)
722 __throw_format_error("format error: missing precision after '.' in "
724 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
728 // pre: __first != __last
730 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
740 template<typename _Context>
742 _M_get_width(_Context& __ctx) const
745 if (_M_width_kind == _WP_value)
747 else if (_M_width_kind == _WP_from_arg)
748 __width = __format::__int_from_arg(__ctx.arg(_M_width));
752 template<typename _Context>
754 _M_get_precision(_Context& __ctx) const
757 if (_M_prec_kind == _WP_value)
759 else if (_M_prec_kind == _WP_from_arg)
760 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
765 template<typename _Int>
767 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
771 else if (__sign == _Sign_plus)
773 else if (__sign == _Sign_space)
780 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
781 template<typename _Out, typename _CharT>
782 requires output_iterator<_Out, const _CharT&>
784 __write(_Out __out, basic_string_view<_CharT> __str)
786 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
792 for (_CharT __c : __str)
797 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
798 // pre: __align != _Align_default
799 template<typename _Out, typename _CharT>
801 __write_padded(_Out __out, basic_string_view<_CharT> __str,
802 _Align __align, size_t __nfill, char32_t __fill_char)
804 const size_t __buflen = 0x20;
805 _CharT __padding_chars[__buflen];
806 __padding_chars[0] = _CharT();
807 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
809 auto __pad = [&__padding] (size_t __n, _Out& __o) {
812 while (__n > __padding.size())
814 __o = __format::__write(std::move(__o), __padding);
815 __n -= __padding.size();
818 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
821 size_t __l, __r, __max;
822 if (__align == _Align_centre)
825 __r = __l + (__nfill & 1);
828 else if (__align == _Align_right)
841 using namespace __unicode;
842 if constexpr (__literal_encoding_is_unicode<_CharT>())
843 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
845 // Encode fill char as multiple code units of type _CharT.
846 const char32_t __arr[1]{ __fill_char };
847 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
848 basic_string<_CharT> __padstr(__v.begin(), __v.end());
849 __padding = __padstr;
851 __out = __format::__write(std::move(__out), __padding);
852 __out = __format::__write(std::move(__out), __str);
854 __out = __format::__write(std::move(__out), __padding);
858 if (__max < __buflen)
859 __padding.remove_suffix(__buflen - __max);
863 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
865 __out = __format::__write(std::move(__out), __str);
871 // Write STR to OUT, with alignment and padding as determined by SPEC.
872 // pre: __spec._M_align != _Align_default || __align != _Align_default
873 template<typename _CharT, typename _Out>
875 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
876 size_t __estimated_width,
877 basic_format_context<_Out, _CharT>& __fc,
878 const _Spec<_CharT>& __spec,
879 _Align __align = _Align_left)
881 size_t __width = __spec._M_get_width(__fc);
883 if (__width <= __estimated_width)
884 return __format::__write(__fc.out(), __str);
886 const size_t __nfill = __width - __estimated_width;
889 __align = __spec._M_align;
891 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
895 // Values are indices into _Escapes::all.
896 enum class _Term_char : unsigned char {
901 template<typename _CharT>
904 using _Str_view = basic_string_view<_CharT>;
908 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
911 _CharT _S_term(_Term_char __term)
912 { return _S_all()[static_cast<unsigned char>(__term)]; }
916 { return _S_all().substr(0, 3); }
919 _Str_view _S_newline()
920 { return _S_all().substr(3, 3); }
923 _Str_view _S_return()
924 { return _S_all().substr(6, 3); }
927 _Str_view _S_bslash()
928 { return _S_all().substr(9, 3); }
932 { return _S_all().substr(12, 3); }
936 { return _S_all().substr(15, 3); }
940 { return _S_all().substr(18, 2); }
944 { return _S_all().substr(20, 2); }
947 template<typename _CharT>
950 using _Str_view = basic_string_view<_CharT>;
954 { return _GLIBCXX_WIDEN("[]{}(), : "); }
957 _Str_view _S_squares()
958 { return _S_all().substr(0, 2); }
961 _Str_view _S_braces()
962 { return _S_all().substr(2, 2); }
965 _Str_view _S_parens()
966 { return _S_all().substr(4, 2); }
970 { return _S_all().substr(6, 2); }
974 { return _S_all().substr(8, 2); }
977 template<typename _CharT>
978 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
980 using _Esc = _Escapes<_CharT>;
983 case _Esc::_S_tab()[0]:
984 case _Esc::_S_newline()[0]:
985 case _Esc::_S_return()[0]:
986 case _Esc::_S_bslash()[0]:
988 case _Esc::_S_quote()[0]:
989 return __term == _Term_char::_Tc_quote;
990 case _Esc::_S_apos()[0]:
991 return __term == _Term_char::_Tc_apos;
993 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
997 // @pre __c <= 0x10FFFF
998 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1000 if (__unicode::__should_escape_category(__c))
1004 return __unicode::__grapheme_cluster_break_property(__c)
1005 == __unicode::_Gcb_property::_Gcb_Extend;
1008 using uint_least32_t = __UINT_LEAST32_TYPE__;
1009 template<typename _Out, typename _CharT>
1011 __write_escape_seq(_Out __out, uint_least32_t __val,
1012 basic_string_view<_CharT> __prefix)
1014 using _Str_view = basic_string_view<_CharT>;
1015 constexpr size_t __max = 8;
1017 const string_view __narrow(
1019 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1021 __out = __format::__write(__out, __prefix);
1022 *__out = _Separators<_CharT>::_S_braces()[0];
1024 if constexpr (is_same_v<char, _CharT>)
1025 __out = __format::__write(__out, __narrow);
1026#ifdef _GLIBCXX_USE_WCHAR_T
1029 _CharT __wbuf[__max];
1030 const size_t __n = __narrow.size();
1031 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1032 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1035 *__out = _Separators<_CharT>::_S_braces()[1];
1039 template<typename _Out, typename _CharT>
1041 __write_escaped_char(_Out __out, _CharT __c)
1043 using _UChar = make_unsigned_t<_CharT>;
1044 using _Esc = _Escapes<_CharT>;
1047 case _Esc::_S_tab()[0]:
1048 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1049 case _Esc::_S_newline()[0]:
1050 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1051 case _Esc::_S_return()[0]:
1052 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1053 case _Esc::_S_bslash()[0]:
1054 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1055 case _Esc::_S_quote()[0]:
1056 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1057 case _Esc::_S_apos()[0]:
1058 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1060 return __format::__write_escape_seq(__out,
1061 static_cast<_UChar>(__c),
1066 template<typename _CharT, typename _Out>
1068 __write_escaped_ascii(_Out __out,
1069 basic_string_view<_CharT> __str,
1072 using _Str_view = basic_string_view<_CharT>;
1073 auto __first = __str.begin();
1074 auto const __last = __str.end();
1075 while (__first != __last)
1077 auto __print = __first;
1078 // assume anything outside ASCII is printable
1079 while (__print != __last
1080 && !__format::__should_escape_ascii(*__print, __term))
1083 if (__print != __first)
1084 __out = __format::__write(__out, _Str_view(__first, __print));
1086 if (__print == __last)
1090 __out = __format::__write_escaped_char(__out, *__first);
1096 template<typename _CharT, typename _Out>
1098 __write_escaped_unicode(_Out __out,
1099 basic_string_view<_CharT> __str,
1102 using _Str_view = basic_string_view<_CharT>;
1103 using _UChar = make_unsigned_t<_CharT>;
1104 using _Esc = _Escapes<_CharT>;
1106 static constexpr char32_t __replace = U'\uFFFD';
1107 static constexpr _Str_view __replace_rep = []
1109 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1110 if constexpr (is_same_v<char, _CharT>)
1111 return "\xEF\xBF\xBD";
1116 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1117 auto __first = __v.begin();
1118 auto const __last = __v.end();
1120 bool __prev_esc = true;
1121 while (__first != __last)
1123 bool __esc_ascii = false;
1124 bool __esc_unicode = false;
1125 bool __esc_replace = false;
1126 auto __should_escape = [&](auto const& __it)
1130 = __format::__should_escape_ascii(*__it.base(), __term);
1131 if (__format::__should_escape_unicode(*__it, __prev_esc))
1132 return __esc_unicode = true;
1133 if (*__it == __replace)
1135 _Str_view __units(__it.base(), __it._M_units());
1136 return __esc_replace = (__units != __replace_rep);
1141 auto __print = __first;
1142 while (__print != __last && !__should_escape(__print))
1148 if (__print != __first)
1149 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1151 if (__print == __last)
1156 __out = __format::__write_escaped_char(__out, *__first.base());
1157 else if (__esc_unicode)
1158 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1159 else // __esc_replace
1160 for (_CharT __c : _Str_view(__first.base(), __first._M_units()))
1161 __out = __format::__write_escape_seq(__out,
1162 static_cast<_UChar>(__c),
1171 template<typename _CharT, typename _Out>
1173 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1175 *__out = _Escapes<_CharT>::_S_term(__term);
1178 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1179 __out = __format::__write_escaped_unicode(__out, __str, __term);
1180 else if constexpr (is_same_v<char, _CharT>
1181 && __unicode::__literal_encoding_is_extended_ascii())
1182 __out = __format::__write_escaped_ascii(__out, __str, __term);
1184 // TODO Handle non-ascii extended encoding
1185 __out = __format::__write_escaped_ascii(__out, __str, __term);
1187 *__out = _Escapes<_CharT>::_S_term(__term);
1191 // A lightweight optional<locale>.
1192 struct _Optional_locale
1194 [[__gnu__::__always_inline__]]
1195 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1197 _Optional_locale(const locale& __loc) noexcept
1198 : _M_loc(__loc), _M_hasval(true)
1201 _Optional_locale(const _Optional_locale& __l) noexcept
1202 : _M_dummy(), _M_hasval(__l._M_hasval)
1205 std::construct_at(&_M_loc, __l._M_loc);
1209 operator=(const _Optional_locale& __l) noexcept
1214 _M_loc = __l._M_loc;
1221 else if (__l._M_hasval)
1223 std::construct_at(&_M_loc, __l._M_loc);
1229 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1232 operator=(locale&& __loc) noexcept
1235 _M_loc = std::move(__loc);
1238 std::construct_at(&_M_loc, std::move(__loc));
1249 std::construct_at(&_M_loc);
1255 bool has_value() const noexcept { return _M_hasval; }
1258 char _M_dummy = '\0';
1261 bool _M_hasval = false;
1264 template<__char _CharT>
1265 struct __formatter_str
1267 __formatter_str() = default;
1270 __formatter_str(_Spec<_CharT> __spec) noexcept
1274 constexpr typename basic_format_parse_context<_CharT>::iterator
1275 parse(basic_format_parse_context<_CharT>& __pc)
1277 auto __first = __pc.begin();
1278 const auto __last = __pc.end();
1279 _Spec<_CharT> __spec{};
1281 auto __finalize = [this, &__spec] {
1285 auto __finished = [&] {
1286 if (__first == __last || *__first == '}')
1297 __first = __spec._M_parse_fill_and_align(__first, __last);
1301 __first = __spec._M_parse_width(__first, __last, __pc);
1305 __first = __spec._M_parse_precision(__first, __last, __pc);
1309 if (*__first == 's')
1311#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1312 else if (*__first == '?')
1314 __spec._M_type = _Pres_esc;
1322 __format::__failed_to_parse_format_spec();
1325 template<typename _Out>
1327 format(basic_string_view<_CharT> __s,
1328 basic_format_context<_Out, _CharT>& __fc) const
1330 constexpr auto __term = __format::_Term_char::_Tc_quote;
1331 const auto __write_direct = [&]
1333 if (_M_spec._M_type == _Pres_esc)
1334 return __format::__write_escaped(__fc.out(), __s, __term);
1336 return __format::__write(__fc.out(), __s);
1339 if (_M_spec._M_width_kind == _WP_none
1340 && _M_spec._M_prec_kind == _WP_none)
1341 return __write_direct();
1343 const size_t __prec =
1344 _M_spec._M_prec_kind != _WP_none
1345 ? _M_spec._M_get_precision(__fc)
1346 : basic_string_view<_CharT>::npos;
1348 const size_t __estimated_width = _S_trunc(__s, __prec);
1349 // N.B. Escaping only increases width
1350 if (_M_spec._M_get_width(__fc) <= __estimated_width
1351 && _M_spec._M_prec_kind == _WP_none)
1352 return __write_direct();
1354 if (_M_spec._M_type != _Pres_esc)
1355 return __format::__write_padded_as_spec(__s, __estimated_width,
1358 __format::_Str_sink<_CharT> __sink;
1359 __format::__write_escaped(__sink.out(), __s, __term);
1360 basic_string_view<_CharT> __escaped(__sink.view().data(),
1361 __sink.view().size());
1362 const size_t __escaped_width = _S_trunc(__escaped, __prec);
1363 // N.B. [tab:format.type.string] defines '?' as
1364 // Copies the escaped string ([format.string.escaped]) to the output,
1365 // so precision seem to appy to escaped string.
1366 return __format::__write_padded_as_spec(__escaped, __escaped_width,
1370#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1371 template<ranges::input_range _Rg, typename _Out>
1372 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1373 typename basic_format_context<_Out, _CharT>::iterator
1374 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1376 using _String = basic_string<_CharT>;
1377 using _String_view = basic_string_view<_CharT>;
1378 if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
1380 const size_t __n(ranges::distance(__rg));
1381 if constexpr (ranges::contiguous_range<_Rg>)
1382 return format(_String_view(ranges::data(__rg), __n), __fc);
1383 else if (__n <= __format::__stackbuf_size<_CharT>)
1385 _CharT __buf[__format::__stackbuf_size<_CharT>];
1386 ranges::copy(__rg, __buf);
1387 return format(_String_view(__buf, __n), __fc);
1389 else if constexpr (ranges::sized_range<_Rg>)
1390 return format(_String(from_range, __rg), __fc);
1391 else if constexpr (ranges::random_access_range<_Rg>)
1393 ranges::iterator_t<_Rg> __first = ranges::begin(__rg);
1394 ranges::subrange __sub(__first, __first + __n);
1395 return format(_String(from_range, __sub), __fc);
1399 // N.B. preserve the computed size
1400 ranges::subrange __sub(__rg, __n);
1401 return format(_String(from_range, __sub), __fc);
1405 return format(_String(from_range, __rg), __fc);
1409 set_debug_format() noexcept
1410 { _M_spec._M_type = _Pres_esc; }
1415 _S_trunc(basic_string_view<_CharT>& __s, size_t __prec)
1417 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1419 if (__prec != basic_string_view<_CharT>::npos)
1420 return __unicode::__truncate(__s, __prec);
1422 return __unicode::__field_width(__s);
1426 __s = __s.substr(0, __prec);
1431 _Spec<_CharT> _M_spec{};
1434 template<__char _CharT>
1435 struct __formatter_int
1437 // If no presentation type is specified, meaning of "none" depends
1438 // whether we are formatting an integer or a char or a bool.
1439 static constexpr _Pres_type _AsInteger = _Pres_d;
1440 static constexpr _Pres_type _AsBool = _Pres_s;
1441 static constexpr _Pres_type _AsChar = _Pres_c;
1443 constexpr typename basic_format_parse_context<_CharT>::iterator
1444 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1446 _Spec<_CharT> __spec{};
1447 __spec._M_type = __type;
1449 const auto __last = __pc.end();
1450 auto __first = __pc.begin();
1452 auto __finalize = [this, &__spec] {
1456 auto __finished = [&] {
1457 if (__first == __last || *__first == '}')
1468 __first = __spec._M_parse_fill_and_align(__first, __last);
1472 __first = __spec._M_parse_sign(__first, __last);
1476 __first = __spec._M_parse_alternate_form(__first, __last);
1480 __first = __spec._M_parse_zero_fill(__first, __last);
1484 __first = __spec._M_parse_width(__first, __last, __pc);
1488 __first = __spec._M_parse_locale(__first, __last);
1495 __spec._M_type = _Pres_b;
1499 __spec._M_type = _Pres_B;
1503 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1504 // 3586. format should not print bool with 'c'
1505 if (__type != _AsBool)
1507 __spec._M_type = _Pres_c;
1512 __spec._M_type = _Pres_d;
1516 __spec._M_type = _Pres_o;
1520 __spec._M_type = _Pres_x;
1524 __spec._M_type = _Pres_X;
1528 if (__type == _AsBool)
1530 __spec._M_type = _Pres_s; // same value (and meaning) as "none"
1534#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1536 if (__type == _AsChar)
1538 __spec._M_type = _Pres_esc;
1548 __format::__failed_to_parse_format_spec();
1551 template<typename _Tp>
1552 constexpr typename basic_format_parse_context<_CharT>::iterator
1553 _M_parse(basic_format_parse_context<_CharT>& __pc)
1555 if constexpr (is_same_v<_Tp, bool>)
1557 auto __end = _M_do_parse(__pc, _AsBool);
1558 if (_M_spec._M_type == _Pres_s)
1559 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
1560 __throw_format_error("format error: format-spec contains "
1561 "invalid formatting options for "
1565 else if constexpr (__char<_Tp>)
1567 auto __end = _M_do_parse(__pc, _AsChar);
1568 if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
1569 if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
1570 /* XXX should be invalid? || _M_spec._M_localized */)
1571 __throw_format_error("format error: format-spec contains "
1572 "invalid formatting options for "
1577 return _M_do_parse(__pc, _AsInteger);
1580 template<typename _Int, typename _Out>
1581 typename basic_format_context<_Out, _CharT>::iterator
1582 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1584 if (_M_spec._M_type == _Pres_c)
1585 return _M_format_character(_S_to_character(__i), __fc);
1587 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1588 to_chars_result __res{};
1590 string_view __base_prefix;
1591 make_unsigned_t<_Int> __u;
1593 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1597 char* __start = __buf + 3;
1598 char* const __end = __buf + sizeof(__buf);
1599 char* const __start_digits = __start;
1601 switch (_M_spec._M_type)
1605 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1606 __res = to_chars(__start, __end, __u, 2);
1610 return _M_format_character(_S_to_character(__i), __fc);
1613 // Should not reach here with _Pres_none for bool or charT, so:
1616 __res = to_chars(__start, __end, __u, 10);
1620 __base_prefix = "0";
1621 __res = to_chars(__start, __end, __u, 8);
1625 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1626 __res = to_chars(__start, __end, __u, 16);
1627 if (_M_spec._M_type == _Pres_X)
1628 for (auto __p = __start; __p != __res.ptr; ++__p)
1629#if __has_builtin(__builtin_toupper)
1630 *__p = __builtin_toupper(*__p);
1632 *__p = std::toupper(*__p);
1636 __builtin_unreachable();
1639 if (_M_spec._M_alt && __base_prefix.size())
1641 __start -= __base_prefix.size();
1642 __builtin_memcpy(__start, __base_prefix.data(),
1643 __base_prefix.size());
1645 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1647 return _M_format_int(string_view(__start, __res.ptr - __start),
1648 __start_digits - __start, __fc);
1651 template<typename _Out>
1652 typename basic_format_context<_Out, _CharT>::iterator
1653 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1655 if (_M_spec._M_type == _Pres_c)
1656 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1657 if (_M_spec._M_type != _Pres_s)
1658 return format(static_cast<unsigned char>(__i), __fc);
1660 basic_string<_CharT> __s;
1662 if (_M_spec._M_localized) [[unlikely]]
1664 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1665 __s = __i ? __np.truename() : __np.falsename();
1666 __est_width = __s.size(); // TODO Unicode-aware estimate
1670 if constexpr (is_same_v<char, _CharT>)
1671 __s = __i ? "true" : "false";
1673 __s = __i ? L"true" : L"false";
1674 __est_width = __s.size();
1677 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1681 [[__gnu__::__always_inline__]]
1683 _S_character_width(_CharT __c)
1685 // N.B. single byte cannot encode charcter of width greater than 1
1686 if constexpr (sizeof(_CharT) > 1u &&
1687 __unicode::__literal_encoding_is_unicode<_CharT>())
1688 return __unicode::__field_width(__c);
1693 template<typename _Out>
1694 typename basic_format_context<_Out, _CharT>::iterator
1695 _M_format_character(_CharT __c,
1696 basic_format_context<_Out, _CharT>& __fc) const
1698 return __format::__write_padded_as_spec({&__c, 1u},
1699 _S_character_width(__c),
1703 template<typename _Out>
1704 typename basic_format_context<_Out, _CharT>::iterator
1705 _M_format_character_escaped(_CharT __c,
1706 basic_format_context<_Out, _CharT>& __fc) const
1708 using _Esc = _Escapes<_CharT>;
1709 constexpr auto __term = __format::_Term_char::_Tc_apos;
1710 const basic_string_view<_CharT> __in(&__c, 1u);
1711 if (_M_spec._M_get_width(__fc) <= 3u)
1712 return __format::__write_escaped(__fc.out(), __in, __term);
1715 __format::_Fixedbuf_sink<_CharT> __sink(__buf);
1716 __format::__write_escaped(__sink.out(), __in, __term);
1718 const basic_string_view<_CharT> __escaped = __sink.view();
1719 size_t __estimated_width;
1720 if (__escaped[1] == _Esc::_S_bslash()[0]) // escape sequence
1721 __estimated_width = __escaped.size();
1723 __estimated_width = 2 + _S_character_width(__c);
1724 return __format::__write_padded_as_spec(__escaped,
1729 template<typename _Int>
1731 _S_to_character(_Int __i)
1733 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1734 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1736 if (_Traits::__min <= __i && __i <= _Traits::__max)
1737 return static_cast<_CharT>(__i);
1739 else if constexpr (is_signed_v<_Int>)
1741 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1742 return static_cast<_CharT>(__i);
1744 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1745 return static_cast<_CharT>(__i);
1746 __throw_format_error("format error: integer not representable as "
1750 template<typename _Out>
1751 typename basic_format_context<_Out, _CharT>::iterator
1752 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1753 basic_format_context<_Out, _CharT>& __fc) const
1755 size_t __width = _M_spec._M_get_width(__fc);
1757 basic_string_view<_CharT> __str;
1758 if constexpr (is_same_v<char, _CharT>)
1759 __str = __narrow_str;
1760#ifdef _GLIBCXX_USE_WCHAR_T
1763 size_t __n = __narrow_str.size();
1764 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1765 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1770 if (_M_spec._M_localized)
1772 const auto& __l = __fc.locale();
1773 if (__l.name() != "C")
1775 auto& __np = use_facet<numpunct<_CharT>>(__l);
1776 string __grp = __np.grouping();
1779 size_t __n = __str.size() - __prefix_len;
1780 auto __p = (_CharT*)__builtin_alloca(2 * __n
1783 auto __s = __str.data();
1784 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1785 __s += __prefix_len;
1786 auto __end = std::__add_grouping(__p + __prefix_len,
1787 __np.thousands_sep(),
1791 __str = {__p, size_t(__end - __p)};
1796 if (__width <= __str.size())
1797 return __format::__write(__fc.out(), __str);
1799 char32_t __fill_char = _M_spec._M_fill;
1800 _Align __align = _M_spec._M_align;
1802 size_t __nfill = __width - __str.size();
1803 auto __out = __fc.out();
1804 if (__align == _Align_default)
1806 __align = _Align_right;
1807 if (_M_spec._M_zero_fill)
1809 __fill_char = _CharT('0');
1810 // Write sign and base prefix before zero filling.
1811 if (__prefix_len != 0)
1813 __out = __format::__write(std::move(__out),
1814 __str.substr(0, __prefix_len));
1815 __str.remove_prefix(__prefix_len);
1819 __fill_char = _CharT(' ');
1821 return __format::__write_padded(std::move(__out), __str,
1822 __align, __nfill, __fill_char);
1825#if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
1826 template<typename _Tp>
1827 using make_unsigned_t
1828 = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
1829 std::make_unsigned<_Tp>,
1830 type_identity<unsigned __int128>>::type;
1832 // std::to_chars is not overloaded for int128 in strict mode.
1833 template<typename _Int>
1834 static to_chars_result
1835 to_chars(char* __first, char* __last, _Int __value, int __base)
1836 { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
1839 _Spec<_CharT> _M_spec{};
1842 // Decide how 128-bit floating-point types should be formatted (or not).
1843 // When supported, the typedef __format::__float128_t is the type that
1844 // format arguments should be converted to for storage in basic_format_arg.
1845 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1846 // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
1847 // by converting them to long double (or __ieee128 for powerpc64le).
1848 // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
1849 // support for _Float128, rather than formatting it as another type.
1850#undef _GLIBCXX_FORMAT_F128
1852#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1854 // Format 128-bit floating-point types using __ieee128.
1855 using __float128_t = __ieee128;
1856# define _GLIBCXX_FORMAT_F128 1
1858#ifdef __LONG_DOUBLE_IEEE128__
1859 // These overloads exist in the library, but are not declared.
1860 // Make them available as std::__format::to_chars.
1862 to_chars(char*, char*, __ibm128) noexcept
1863 __asm("_ZSt8to_charsPcS_e");
1866 to_chars(char*, char*, __ibm128, chars_format) noexcept
1867 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1870 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1871 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1872#elif __cplusplus == 202002L
1874 to_chars(char*, char*, __ieee128) noexcept
1875 __asm("_ZSt8to_charsPcS_u9__ieee128");
1878 to_chars(char*, char*, __ieee128, chars_format) noexcept
1879 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1882 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1883 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1886#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1888 // Format 128-bit floating-point types using long double.
1889 using __float128_t = long double;
1890# define _GLIBCXX_FORMAT_F128 1
1892#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1894 // Format 128-bit floating-point types using _Float128.
1895 using __float128_t = _Float128;
1896# define _GLIBCXX_FORMAT_F128 2
1898# if __cplusplus == 202002L
1899 // These overloads exist in the library, but are not declared for C++20.
1900 // Make them available as std::__format::to_chars.
1902 to_chars(char*, char*, _Float128) noexcept
1903# if _GLIBCXX_INLINE_VERSION
1904 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1906 __asm("_ZSt8to_charsPcS_DF128_");
1910 to_chars(char*, char*, _Float128, chars_format) noexcept
1911# if _GLIBCXX_INLINE_VERSION
1912 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1914 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1918 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1919# if _GLIBCXX_INLINE_VERSION
1920 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1922 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1927 using std::to_chars;
1929 // We can format a floating-point type iff it is usable with to_chars.
1930 template<typename _Tp>
1931 concept __formattable_float
1932 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1933 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1935 template<__char _CharT>
1936 struct __formatter_fp
1938 constexpr typename basic_format_parse_context<_CharT>::iterator
1939 parse(basic_format_parse_context<_CharT>& __pc)
1941 _Spec<_CharT> __spec{};
1942 const auto __last = __pc.end();
1943 auto __first = __pc.begin();
1945 auto __finalize = [this, &__spec] {
1949 auto __finished = [&] {
1950 if (__first == __last || *__first == '}')
1961 __first = __spec._M_parse_fill_and_align(__first, __last);
1965 __first = __spec._M_parse_sign(__first, __last);
1969 __first = __spec._M_parse_alternate_form(__first, __last);
1973 __first = __spec._M_parse_zero_fill(__first, __last);
1977 if (__first[0] != '.')
1979 __first = __spec._M_parse_width(__first, __last, __pc);
1984 __first = __spec._M_parse_precision(__first, __last, __pc);
1988 __first = __spec._M_parse_locale(__first, __last);
1995 __spec._M_type = _Pres_a;
1999 __spec._M_type = _Pres_A;
2003 __spec._M_type = _Pres_e;
2007 __spec._M_type = _Pres_E;
2011 __spec._M_type = _Pres_f;
2015 __spec._M_type = _Pres_F;
2019 __spec._M_type = _Pres_g;
2023 __spec._M_type = _Pres_G;
2031 __format::__failed_to_parse_format_spec();
2034 template<typename _Fp, typename _Out>
2035 typename basic_format_context<_Out, _CharT>::iterator
2036 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2038 std::string __dynbuf;
2040 to_chars_result __res{};
2043 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2045 __prec = _M_spec._M_get_precision(__fc);
2047 char* __start = __buf + 1; // reserve space for sign
2048 char* __end = __buf + sizeof(__buf);
2050 chars_format __fmt{};
2051 bool __upper = false;
2052 bool __trailing_zeros = false;
2055 switch (_M_spec._M_type)
2062 if (_M_spec._M_type != _Pres_A)
2064 __fmt = chars_format::hex;
2072 __fmt = chars_format::scientific;
2079 __fmt = chars_format::fixed;
2086 __trailing_zeros = true;
2088 __fmt = chars_format::general;
2092 __fmt = chars_format::general;
2095 __builtin_unreachable();
2098 // Write value into buffer using std::to_chars.
2099 auto __to_chars = [&](char* __b, char* __e) {
2101 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2102 else if (__fmt != chars_format{})
2103 return __format::to_chars(__b, __e, __v, __fmt);
2105 return __format::to_chars(__b, __e, __v);
2108 // First try using stack buffer.
2109 __res = __to_chars(__start, __end);
2111 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2113 // If the buffer is too small it's probably because of a large
2114 // precision, or a very large value in fixed format.
2115 size_t __guess = 8 + __prec;
2116 if (__fmt == chars_format::fixed) // +ddd.prec
2118 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2119 || is_same_v<_Fp, long double>)
2121 // The number of digits to the left of the decimal point
2122 // is floor(log10(max(abs(__v),1)))+1
2124 if constexpr (is_same_v<_Fp, float>)
2125 __builtin_frexpf(__v, &__exp);
2126 else if constexpr (is_same_v<_Fp, double>)
2127 __builtin_frexp(__v, &__exp);
2128 else if constexpr (is_same_v<_Fp, long double>)
2129 __builtin_frexpl(__v, &__exp);
2131 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2134 __guess += numeric_limits<_Fp>::max_exponent10;
2136 if (__guess <= sizeof(__buf)) [[unlikely]]
2137 __guess = sizeof(__buf) * 2;
2138 __dynbuf.reserve(__guess);
2142 // Mangling of this lambda, and thus resize_and_overwrite
2143 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2144 // <format> was new in G++ 13, and is experimental, that
2146 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
2148 __res = __to_chars(__p + 1, __p + __n - 1);
2149 return __res.ec == errc{} ? __res.ptr - __p : 0;
2152 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2154 __start = __dynbuf.data() + 1; // reserve space for sign
2155 __end = __dynbuf.data() + __dynbuf.size();
2157 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2160 // Use uppercase for 'A', 'E', and 'G' formats.
2163 for (char* __p = __start; __p != __res.ptr; ++__p)
2164 *__p = std::toupper(*__p);
2167 bool __have_sign = true;
2168 // Add sign for non-negative values.
2169 if (!__builtin_signbit(__v))
2171 if (_M_spec._M_sign == _Sign_plus)
2173 else if (_M_spec._M_sign == _Sign_space)
2176 __have_sign = false;
2179 string_view __narrow_str(__start, __res.ptr - __start);
2181 // Use alternate form. Ensure decimal point is always present,
2182 // and add trailing zeros (up to precision) for g and G forms.
2183 if (_M_spec._M_alt && __builtin_isfinite(__v))
2185 string_view __s = __narrow_str;
2186 size_t __sigfigs; // Number of significant figures.
2187 size_t __z = 0; // Number of trailing zeros to add.
2188 size_t __p; // Position of the exponent character (if any).
2189 size_t __d = __s.find('.'); // Position of decimal point.
2190 if (__d != __s.npos) // Found decimal point.
2192 __p = __s.find(__expc, __d + 1);
2193 if (__p == __s.npos)
2196 // If presentation type is g or G we might need to add zeros.
2197 if (__trailing_zeros)
2199 // Find number of digits after first significant figure.
2200 if (__s[__have_sign] != '0')
2201 // A string like "D.D" or "-D.DDD"
2202 __sigfigs = __p - __have_sign - 1;
2204 // A string like "0.D" or "-0.0DD".
2205 // Safe to assume there is a non-zero digit, because
2206 // otherwise there would be no decimal point.
2207 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2210 else // No decimal point, we need to insert one.
2212 __p = __s.find(__expc); // Find the exponent, if present.
2213 if (__p == __s.npos)
2215 __d = __p; // Position where '.' should be inserted.
2216 __sigfigs = __d - __have_sign;
2219 if (__trailing_zeros && __prec != 0)
2221 // For g and G presentation types std::to_chars produces
2222 // no more than prec significant figures. Insert this many
2223 // zeros so the result has exactly prec significant figures.
2224 __z = __prec - __sigfigs;
2227 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2229 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2231 // The stack buffer is large enough for the result.
2232 // Move exponent to make space for extra chars.
2233 __builtin_memmove(__start + __p + __extras,
2237 __start[__p++] = '.';
2238 __builtin_memset(__start + __p, '0', __z);
2239 __narrow_str = {__s.data(), __s.size() + __extras};
2241 else // Need to switch to the dynamic buffer.
2243 __dynbuf.reserve(__s.size() + __extras);
2244 if (__dynbuf.empty())
2246 __dynbuf = __s.substr(0, __p);
2250 __dynbuf.append(__z, '0');
2251 __dynbuf.append(__s.substr(__p));
2255 __dynbuf.insert(__p, __extras, '0');
2257 __dynbuf[__p] = '.';
2259 __narrow_str = __dynbuf;
2264 basic_string<_CharT> __wstr;
2265 basic_string_view<_CharT> __str;
2266 if constexpr (is_same_v<_CharT, char>)
2267 __str = __narrow_str;
2268#ifdef _GLIBCXX_USE_WCHAR_T
2271 __wstr = std::__to_wstring_numeric(__narrow_str);
2276 if (_M_spec._M_localized && __builtin_isfinite(__v))
2278 auto __s = _M_localize(__str, __expc, __fc.locale());
2280 __str = __wstr = std::move(__s);
2283 size_t __width = _M_spec._M_get_width(__fc);
2285 if (__width <= __str.size())
2286 return __format::__write(__fc.out(), __str);
2288 char32_t __fill_char = _M_spec._M_fill;
2289 _Align __align = _M_spec._M_align;
2291 size_t __nfill = __width - __str.size();
2292 auto __out = __fc.out();
2293 if (__align == _Align_default)
2295 __align = _Align_right;
2296 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2298 __fill_char = _CharT('0');
2299 // Write sign before zero filling.
2300 if (!__format::__is_xdigit(__narrow_str[0]))
2302 *__out++ = __str[0];
2303 __str.remove_prefix(1);
2307 __fill_char = _CharT(' ');
2309 return __format::__write_padded(std::move(__out), __str,
2310 __align, __nfill, __fill_char);
2313 // Locale-specific format.
2314 basic_string<_CharT>
2315 _M_localize(basic_string_view<_CharT> __str, char __expc,
2316 const locale& __loc) const
2318 basic_string<_CharT> __lstr;
2320 if (__loc == locale::classic())
2321 return __lstr; // Nothing to do.
2323 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2324 const _CharT __point = __np.decimal_point();
2325 const string __grp = __np.grouping();
2327 _CharT __dot, __exp;
2328 if constexpr (is_same_v<_CharT, char>)
2351 __builtin_unreachable();
2355 if (__grp.empty() && __point == __dot)
2356 return __lstr; // Locale uses '.' and no grouping.
2358 size_t __d = __str.find(__dot); // Index of radix character (if any).
2359 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2360 if (__e == __str.npos)
2362 const size_t __r = __str.size() - __e; // Length of remainder.
2363 auto __overwrite = [&](_CharT* __p, size_t) {
2364 // Apply grouping to the digits before the radix or exponent.
2366 if (auto __c = __str.front(); __c == '-' || __c == '+' || __c == ' ')
2371 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
2372 __grp.data(), __grp.size(),
2373 __str.data() + __off,
2374 __str.data() + __e);
2375 if (__r) // If there's a fractional part or exponent
2377 if (__d != __str.npos)
2379 *__end = __point; // Add the locale's radix character.
2383 const size_t __rlen = __str.size() - __e;
2384 // Append fractional digits and/or exponent:
2385 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2388 return (__end - __p);
2390 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2394 _Spec<_CharT> _M_spec{};
2397} // namespace __format
2400 /// Format a character.
2401 template<__format::__char _CharT>
2402 struct formatter<_CharT, _CharT>
2404 formatter() = default;
2406 constexpr typename basic_format_parse_context<_CharT>::iterator
2407 parse(basic_format_parse_context<_CharT>& __pc)
2409 return _M_f.template _M_parse<_CharT>(__pc);
2412 template<typename _Out>
2413 typename basic_format_context<_Out, _CharT>::iterator
2414 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2416 if (_M_f._M_spec._M_type == __format::_Pres_none
2417 || _M_f._M_spec._M_type == __format::_Pres_c)
2418 return _M_f._M_format_character(__u, __fc);
2419 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
2420 return _M_f._M_format_character_escaped(__u, __fc);
2422 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2425#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2427 set_debug_format() noexcept
2428 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2432 __format::__formatter_int<_CharT> _M_f;
2435#ifdef _GLIBCXX_USE_WCHAR_T
2436 /// Format a char value for wide character output.
2438 struct formatter<char, wchar_t>
2440 formatter() = default;
2442 constexpr typename basic_format_parse_context<wchar_t>::iterator
2443 parse(basic_format_parse_context<wchar_t>& __pc)
2445 return _M_f._M_parse<char>(__pc);
2448 template<typename _Out>
2449 typename basic_format_context<_Out, wchar_t>::iterator
2450 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2452 if (_M_f._M_spec._M_type == __format::_Pres_none
2453 || _M_f._M_spec._M_type == __format::_Pres_c)
2454 return _M_f._M_format_character(__u, __fc);
2455 else if (_M_f._M_spec._M_type == __format::_Pres_esc)
2456 return _M_f._M_format_character_escaped(__u, __fc);
2458 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2461#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2463 set_debug_format() noexcept
2464 { _M_f._M_spec._M_type = __format::_Pres_esc; }
2468 __format::__formatter_int<wchar_t> _M_f;
2470#endif // USE_WCHAR_T
2472 /** Format a string.
2475 template<__format::__char _CharT>
2476 struct formatter<_CharT*, _CharT>
2478 formatter() = default;
2480 [[__gnu__::__always_inline__]]
2481 constexpr typename basic_format_parse_context<_CharT>::iterator
2482 parse(basic_format_parse_context<_CharT>& __pc)
2483 { return _M_f.parse(__pc); }
2485 template<typename _Out>
2486 [[__gnu__::__nonnull__]]
2487 typename basic_format_context<_Out, _CharT>::iterator
2488 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2489 { return _M_f.format(__u, __fc); }
2491#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2492 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2496 __format::__formatter_str<_CharT> _M_f;
2499 template<__format::__char _CharT>
2500 struct formatter<const _CharT*, _CharT>
2502 formatter() = default;
2504 [[__gnu__::__always_inline__]]
2505 constexpr typename basic_format_parse_context<_CharT>::iterator
2506 parse(basic_format_parse_context<_CharT>& __pc)
2507 { return _M_f.parse(__pc); }
2509 template<typename _Out>
2510 [[__gnu__::__nonnull__]]
2511 typename basic_format_context<_Out, _CharT>::iterator
2512 format(const _CharT* __u,
2513 basic_format_context<_Out, _CharT>& __fc) const
2514 { return _M_f.format(__u, __fc); }
2516#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2517 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2521 __format::__formatter_str<_CharT> _M_f;
2524 template<__format::__char _CharT, size_t _Nm>
2525 struct formatter<_CharT[_Nm], _CharT>
2527 formatter() = default;
2529 [[__gnu__::__always_inline__]]
2530 constexpr typename basic_format_parse_context<_CharT>::iterator
2531 parse(basic_format_parse_context<_CharT>& __pc)
2532 { return _M_f.parse(__pc); }
2534 template<typename _Out>
2535 typename basic_format_context<_Out, _CharT>::iterator
2536 format(const _CharT (&__u)[_Nm],
2537 basic_format_context<_Out, _CharT>& __fc) const
2538 { return _M_f.format({__u, _Nm}, __fc); }
2540#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2541 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2545 __format::__formatter_str<_CharT> _M_f;
2548 template<typename _Traits, typename _Alloc>
2549 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2551 formatter() = default;
2553 [[__gnu__::__always_inline__]]
2554 constexpr typename basic_format_parse_context<char>::iterator
2555 parse(basic_format_parse_context<char>& __pc)
2556 { return _M_f.parse(__pc); }
2558 template<typename _Out>
2559 typename basic_format_context<_Out, char>::iterator
2560 format(const basic_string<char, _Traits, _Alloc>& __u,
2561 basic_format_context<_Out, char>& __fc) const
2562 { return _M_f.format(__u, __fc); }
2564#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2565 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2569 __format::__formatter_str<char> _M_f;
2572#ifdef _GLIBCXX_USE_WCHAR_T
2573 template<typename _Traits, typename _Alloc>
2574 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2576 formatter() = default;
2578 [[__gnu__::__always_inline__]]
2579 constexpr typename basic_format_parse_context<wchar_t>::iterator
2580 parse(basic_format_parse_context<wchar_t>& __pc)
2581 { return _M_f.parse(__pc); }
2583 template<typename _Out>
2584 typename basic_format_context<_Out, wchar_t>::iterator
2585 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2586 basic_format_context<_Out, wchar_t>& __fc) const
2587 { return _M_f.format(__u, __fc); }
2589#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2590 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2594 __format::__formatter_str<wchar_t> _M_f;
2596#endif // USE_WCHAR_T
2598 template<typename _Traits>
2599 struct formatter<basic_string_view<char, _Traits>, char>
2601 formatter() = default;
2603 [[__gnu__::__always_inline__]]
2604 constexpr typename basic_format_parse_context<char>::iterator
2605 parse(basic_format_parse_context<char>& __pc)
2606 { return _M_f.parse(__pc); }
2608 template<typename _Out>
2609 typename basic_format_context<_Out, char>::iterator
2610 format(basic_string_view<char, _Traits> __u,
2611 basic_format_context<_Out, char>& __fc) const
2612 { return _M_f.format(__u, __fc); }
2614#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2615 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2619 __format::__formatter_str<char> _M_f;
2622#ifdef _GLIBCXX_USE_WCHAR_T
2623 template<typename _Traits>
2624 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2626 formatter() = default;
2628 [[__gnu__::__always_inline__]]
2629 constexpr typename basic_format_parse_context<wchar_t>::iterator
2630 parse(basic_format_parse_context<wchar_t>& __pc)
2631 { return _M_f.parse(__pc); }
2633 template<typename _Out>
2634 typename basic_format_context<_Out, wchar_t>::iterator
2635 format(basic_string_view<wchar_t, _Traits> __u,
2636 basic_format_context<_Out, wchar_t>& __fc) const
2637 { return _M_f.format(__u, __fc); }
2639#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2640 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2644 __format::__formatter_str<wchar_t> _M_f;
2646#endif // USE_WCHAR_T
2649/// @cond undocumented
2652 // each cv-unqualified arithmetic type ArithmeticT other than
2653 // char, wchar_t, char8_t, char16_t, or char32_t
2654 template<typename _Tp>
2655 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2657#if defined __SIZEOF_INT128__
2658 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2659 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2663 template<> inline constexpr bool __is_formattable_integer<char> = false;
2664 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2665#ifdef _GLIBCXX_USE_CHAR8_T
2666 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2668 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2669 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2673 /// Format an integer.
2674 template<typename _Tp, __format::__char _CharT>
2675 requires __format::__is_formattable_integer<_Tp>
2676 struct formatter<_Tp, _CharT>
2678 formatter() = default;
2680 [[__gnu__::__always_inline__]]
2681 constexpr typename basic_format_parse_context<_CharT>::iterator
2682 parse(basic_format_parse_context<_CharT>& __pc)
2684 return _M_f.template _M_parse<_Tp>(__pc);
2687 template<typename _Out>
2688 typename basic_format_context<_Out, _CharT>::iterator
2689 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2690 { return _M_f.format(__u, __fc); }
2693 __format::__formatter_int<_CharT> _M_f;
2696#if defined __glibcxx_to_chars
2697 /// Format a floating-point value.
2698 template<__format::__formattable_float _Tp, __format::__char _CharT>
2699 struct formatter<_Tp, _CharT>
2701 formatter() = default;
2703 [[__gnu__::__always_inline__]]
2704 constexpr typename basic_format_parse_context<_CharT>::iterator
2705 parse(basic_format_parse_context<_CharT>& __pc)
2706 { return _M_f.parse(__pc); }
2708 template<typename _Out>
2709 typename basic_format_context<_Out, _CharT>::iterator
2710 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2711 { return _M_f.format(__u, __fc); }
2714 __format::__formatter_fp<_CharT> _M_f;
2717#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2718 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2719 template<__format::__char _CharT>
2720 struct formatter<long double, _CharT>
2722 formatter() = default;
2724 [[__gnu__::__always_inline__]]
2725 constexpr typename basic_format_parse_context<_CharT>::iterator
2726 parse(basic_format_parse_context<_CharT>& __pc)
2727 { return _M_f.parse(__pc); }
2729 template<typename _Out>
2730 typename basic_format_context<_Out, _CharT>::iterator
2731 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2732 { return _M_f.format((double)__u, __fc); }
2735 __format::__formatter_fp<_CharT> _M_f;
2739#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2740 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2741 template<__format::__char _CharT>
2742 struct formatter<_Float16, _CharT>
2744 formatter() = default;
2746 [[__gnu__::__always_inline__]]
2747 constexpr typename basic_format_parse_context<_CharT>::iterator
2748 parse(basic_format_parse_context<_CharT>& __pc)
2749 { return _M_f.parse(__pc); }
2751 template<typename _Out>
2752 typename basic_format_context<_Out, _CharT>::iterator
2753 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2754 { return _M_f.format((float)__u, __fc); }
2757 __format::__formatter_fp<_CharT> _M_f;
2761#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2762 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2763 template<__format::__char _CharT>
2764 struct formatter<_Float32, _CharT>
2766 formatter() = default;
2768 [[__gnu__::__always_inline__]]
2769 constexpr typename basic_format_parse_context<_CharT>::iterator
2770 parse(basic_format_parse_context<_CharT>& __pc)
2771 { return _M_f.parse(__pc); }
2773 template<typename _Out>
2774 typename basic_format_context<_Out, _CharT>::iterator
2775 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2776 { return _M_f.format((float)__u, __fc); }
2779 __format::__formatter_fp<_CharT> _M_f;
2783#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2784 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2785 template<__format::__char _CharT>
2786 struct formatter<_Float64, _CharT>
2788 formatter() = default;
2790 [[__gnu__::__always_inline__]]
2791 constexpr typename basic_format_parse_context<_CharT>::iterator
2792 parse(basic_format_parse_context<_CharT>& __pc)
2793 { return _M_f.parse(__pc); }
2795 template<typename _Out>
2796 typename basic_format_context<_Out, _CharT>::iterator
2797 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2798 { return _M_f.format((double)__u, __fc); }
2801 __format::__formatter_fp<_CharT> _M_f;
2805#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128 == 1
2806 // Reuse __formatter_fp<C>::format<__float128_t, Out> for _Float128.
2807 template<__format::__char _CharT>
2808 struct formatter<_Float128, _CharT>
2810 formatter() = default;
2812 [[__gnu__::__always_inline__]]
2813 constexpr typename basic_format_parse_context<_CharT>::iterator
2814 parse(basic_format_parse_context<_CharT>& __pc)
2815 { return _M_f.parse(__pc); }
2817 template<typename _Out>
2818 typename basic_format_context<_Out, _CharT>::iterator
2819 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2820 { return _M_f.format((__format::__float128_t)__u, __fc); }
2823 __format::__formatter_fp<_CharT> _M_f;
2827#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2828 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
2829 template<__format::__char _CharT>
2830 struct formatter<__gnu_cxx::__bfloat16_t, _CharT>
2832 formatter() = default;
2834 [[__gnu__::__always_inline__]]
2835 constexpr typename basic_format_parse_context<_CharT>::iterator
2836 parse(basic_format_parse_context<_CharT>& __pc)
2837 { return _M_f.parse(__pc); }
2839 template<typename _Out>
2840 typename basic_format_context<_Out, _CharT>::iterator
2841 format(__gnu_cxx::__bfloat16_t __u,
2842 basic_format_context<_Out, _CharT>& __fc) const
2843 { return _M_f.format((float)__u, __fc); }
2846 __format::__formatter_fp<_CharT> _M_f;
2849#endif // __cpp_lib_to_chars
2851 /** Format a pointer.
2854 template<__format::__char _CharT>
2855 struct formatter<const void*, _CharT>
2857 formatter() = default;
2859 constexpr typename basic_format_parse_context<_CharT>::iterator
2860 parse(basic_format_parse_context<_CharT>& __pc)
2862 __format::_Spec<_CharT> __spec{};
2863 const auto __last = __pc.end();
2864 auto __first = __pc.begin();
2866 auto __finalize = [this, &__spec] {
2870 auto __finished = [&] {
2871 if (__first == __last || *__first == '}')
2882 __first = __spec._M_parse_fill_and_align(__first, __last);
2886// _GLIBCXX_RESOLVE_LIB_DEFECTS
2887// P2510R3 Formatting pointers
2888#if __glibcxx_format >= 202304L
2889 __first = __spec._M_parse_zero_fill(__first, __last);
2894 __first = __spec._M_parse_width(__first, __last, __pc);
2896 if (__first != __last)
2898 if (*__first == 'p')
2900#if __glibcxx_format >= 202304L
2901 else if (*__first == 'P')
2903 __spec._M_type = __format::_Pres_P;
2912 __format::__failed_to_parse_format_spec();
2915 template<typename _Out>
2916 typename basic_format_context<_Out, _CharT>::iterator
2917 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2919 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2920 char __buf[2 + sizeof(__v) * 2];
2921 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2923 int __n = __ptr - __buf;
2926#if __glibcxx_format >= 202304L
2927 if (_M_spec._M_type == __format::_Pres_P)
2930 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2931#if __has_builtin(__builtin_toupper)
2932 *__p = __builtin_toupper(*__p);
2934 *__p = std::toupper(*__p);
2939 basic_string_view<_CharT> __str;
2940 if constexpr (is_same_v<_CharT, char>)
2941 __str = string_view(__buf, __n);
2942#ifdef _GLIBCXX_USE_WCHAR_T
2945 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2946 std::__to_wstring_numeric(__buf, __n, __p);
2947 __str = wstring_view(__p, __n);
2951#if __glibcxx_format >= 202304L
2952 if (_M_spec._M_zero_fill)
2954 size_t __width = _M_spec._M_get_width(__fc);
2955 if (__width <= __str.size())
2956 return __format::__write(__fc.out(), __str);
2958 auto __out = __fc.out();
2959 // Write "0x" or "0X" prefix before zero-filling.
2960 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2961 __str.remove_prefix(2);
2962 size_t __nfill = __width - __n;
2963 return __format::__write_padded(std::move(__out), __str,
2964 __format::_Align_right,
2965 __nfill, _CharT('0'));
2969 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2970 __format::_Align_right);
2974 __format::_Spec<_CharT> _M_spec{};
2977 template<__format::__char _CharT>
2978 struct formatter<void*, _CharT>
2980 formatter() = default;
2982 [[__gnu__::__always_inline__]]
2983 constexpr typename basic_format_parse_context<_CharT>::iterator
2984 parse(basic_format_parse_context<_CharT>& __pc)
2985 { return _M_f.parse(__pc); }
2987 template<typename _Out>
2988 typename basic_format_context<_Out, _CharT>::iterator
2989 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
2990 { return _M_f.format(__v, __fc); }
2993 formatter<const void*, _CharT> _M_f;
2996 template<__format::__char _CharT>
2997 struct formatter<nullptr_t, _CharT>
2999 formatter() = default;
3001 [[__gnu__::__always_inline__]]
3002 constexpr typename basic_format_parse_context<_CharT>::iterator
3003 parse(basic_format_parse_context<_CharT>& __pc)
3004 { return _M_f.parse(__pc); }
3006 template<typename _Out>
3007 typename basic_format_context<_Out, _CharT>::iterator
3008 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3009 { return _M_f.format(nullptr, __fc); }
3012 formatter<const void*, _CharT> _M_f;
3016#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3017 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3018 // 3944. Formatters converting sequences of char to sequences of wchar_t
3020 struct __formatter_disabled
3022 __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3023 __formatter_disabled(const __formatter_disabled&) = delete;
3024 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3028 struct formatter<char*, wchar_t>
3029 : private __formatter_disabled { };
3031 struct formatter<const char*, wchar_t>
3032 : private __formatter_disabled { };
3033 template<size_t _Nm>
3034 struct formatter<char[_Nm], wchar_t>
3035 : private __formatter_disabled { };
3036 template<class _Traits, class _Allocator>
3037 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3038 : private __formatter_disabled { };
3039 template<class _Traits>
3040 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3041 : private __formatter_disabled { };
3044 /// An iterator after the last character written, and the number of
3045 /// characters that would have been written.
3046 template<typename _Out>
3047 struct format_to_n_result
3050 iter_difference_t<_Out> size;
3053_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3054template<typename, typename> class vector;
3055_GLIBCXX_END_NAMESPACE_CONTAINER
3057/// @cond undocumented
3060 template<typename _CharT>
3063 _Sink<_CharT>* _M_sink = nullptr;
3066 using iterator_category = output_iterator_tag;
3067 using value_type = void;
3068 using difference_type = ptrdiff_t;
3069 using pointer = void;
3070 using reference = void;
3072 _Sink_iter() = default;
3073 _Sink_iter(const _Sink_iter&) = default;
3074 _Sink_iter& operator=(const _Sink_iter&) = default;
3076 [[__gnu__::__always_inline__]]
3078 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3080 [[__gnu__::__always_inline__]]
3081 constexpr _Sink_iter&
3082 operator=(_CharT __c)
3084 _M_sink->_M_write(__c);
3088 [[__gnu__::__always_inline__]]
3089 constexpr _Sink_iter&
3090 operator=(basic_string_view<_CharT> __s)
3092 _M_sink->_M_write(__s);
3096 [[__gnu__::__always_inline__]]
3097 constexpr _Sink_iter&
3098 operator*() { return *this; }
3100 [[__gnu__::__always_inline__]]
3101 constexpr _Sink_iter&
3102 operator++() { return *this; }
3104 [[__gnu__::__always_inline__]]
3105 constexpr _Sink_iter
3106 operator++(int) { return *this; }
3109 _M_reserve(size_t __n) const
3110 { return _M_sink->_M_reserve(__n); }
3113 // Abstract base class for type-erased character sinks.
3114 // All formatting and output is done via this type's iterator,
3115 // to reduce the number of different template instantiations.
3116 template<typename _CharT>
3119 friend class _Sink_iter<_CharT>;
3121 span<_CharT> _M_span;
3122 typename span<_CharT>::iterator _M_next;
3124 // Called when the span is full, to make more space available.
3125 // Precondition: _M_next != _M_span.begin()
3126 // Postcondition: _M_next != _M_span.end()
3127 // TODO: remove the precondition? could make overflow handle it.
3128 virtual void _M_overflow() = 0;
3131 // Precondition: __span.size() != 0
3132 [[__gnu__::__always_inline__]]
3134 _Sink(span<_CharT> __span) noexcept
3135 : _M_span(__span), _M_next(__span.begin())
3138 // The portion of the span that has been written to.
3139 [[__gnu__::__always_inline__]]
3141 _M_used() const noexcept
3142 { return _M_span.first(_M_next - _M_span.begin()); }
3144 // The portion of the span that has not been written to.
3145 [[__gnu__::__always_inline__]]
3146 constexpr span<_CharT>
3147 _M_unused() const noexcept
3148 { return _M_span.subspan(_M_next - _M_span.begin()); }
3150 // Use the start of the span as the next write position.
3151 [[__gnu__::__always_inline__]]
3153 _M_rewind() noexcept
3154 { _M_next = _M_span.begin(); }
3156 // Replace the current output range.
3158 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3161 _M_next = __s.begin() + __pos;
3164 // Called by the iterator for *it++ = c
3166 _M_write(_CharT __c)
3169 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3174 _M_write(basic_string_view<_CharT> __s)
3176 span __to = _M_unused();
3177 while (__to.size() <= __s.size())
3179 __s.copy(__to.data(), __to.size());
3180 _M_next += __to.size();
3181 __s.remove_prefix(__to.size());
3187 __s.copy(__to.data(), __s.size());
3188 _M_next += __s.size();
3192 // A successful _Reservation can be used to directly write
3193 // up to N characters to the sink to avoid unwanted buffering.
3196 // True if the reservation was successful, false otherwise.
3197 explicit operator bool() const noexcept { return _M_sink; }
3198 // A pointer to write directly to the sink.
3199 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3200 // Add n to the _M_next iterator for the sink.
3201 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3205 // Attempt to reserve space to write n characters to the sink.
3206 // If anything is written to the reservation then there must be a call
3207 // to _M_bump(N2) before any call to another member function of *this,
3208 // where N2 is the number of characters written.
3209 virtual _Reservation
3210 _M_reserve(size_t __n)
3212 if (__n <= _M_unused().size())
3215 if (__n <= _M_span.size()) // Cannot meet the request.
3217 _M_overflow(); // Make more space available.
3218 if (__n <= _M_unused().size())
3224 // Update the next output position after writing directly to the sink.
3225 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3231 _Sink(const _Sink&) = delete;
3232 _Sink& operator=(const _Sink&) = delete;
3234 [[__gnu__::__always_inline__]]
3235 constexpr _Sink_iter<_CharT>
3237 { return _Sink_iter<_CharT>(*this); }
3241 template<typename _CharT>
3242 class _Fixedbuf_sink final : public _Sink<_CharT>
3245 _M_overflow() override
3247 __glibcxx_assert(false);
3252 [[__gnu__::__always_inline__]]
3254 _Fixedbuf_sink(span<_CharT> __buf)
3255 : _Sink<_CharT>(__buf)
3258 constexpr basic_string_view<_CharT>
3261 auto __s = this->_M_used();
3262 return basic_string_view<_CharT>(__s.data(), __s.size());
3266 // A sink with an internal buffer. This is used to implement concrete sinks.
3267 template<typename _CharT>
3268 class _Buf_sink : public _Sink<_CharT>
3271 _CharT _M_buf[__stackbuf_size<_CharT>];
3273 [[__gnu__::__always_inline__]]
3275 _Buf_sink() noexcept
3276 : _Sink<_CharT>(_M_buf)
3280 using _GLIBCXX_STD_C::vector;
3282 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3283 // Writes to a buffer then appends that to the sequence when it fills up.
3284 template<typename _Seq>
3285 class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
3287 using _CharT = typename _Seq::value_type;
3291 // Transfer buffer contents to the sequence, so buffer can be refilled.
3293 _M_overflow() override
3295 auto __s = this->_M_used();
3296 if (__s.empty()) [[unlikely]]
3297 return; // Nothing in the buffer to transfer to _M_seq.
3299 // If _M_reserve was called then _M_bump must have been called too.
3300 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3302 if constexpr (__is_specialization_of<_Seq, basic_string>)
3303 _M_seq.append(__s.data(), __s.size());
3305 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3307 // Make the whole of _M_buf available for the next write:
3311 typename _Sink<_CharT>::_Reservation
3312 _M_reserve(size_t __n) override
3314 // We might already have n characters available in this->_M_unused(),
3315 // but the whole point of this function is to be an optimization for
3316 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3317 // and then copying that into a basic_string if possible, so this
3318 // function prefers to create space directly in _M_seq rather than
3321 if constexpr (__is_specialization_of<_Seq, basic_string>
3322 || __is_specialization_of<_Seq, vector>)
3324 // Flush the buffer to _M_seq first (should not be needed).
3325 if (this->_M_used().size()) [[unlikely]]
3326 _Seq_sink::_M_overflow();
3328 // Expand _M_seq to make __n new characters available:
3329 const auto __sz = _M_seq.size();
3330 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3331 _M_seq.__resize_and_overwrite(__sz + __n,
3332 [](auto, auto __n2) {
3336 _M_seq.resize(__sz + __n);
3338 // Set _M_used() to be a span over the original part of _M_seq
3339 // and _M_unused() to be the extra capacity we just created:
3340 this->_M_reset(_M_seq, __sz);
3343 else // Try to use the base class' buffer.
3344 return _Sink<_CharT>::_M_reserve(__n);
3348 _M_bump(size_t __n) override
3350 if constexpr (__is_specialization_of<_Seq, basic_string>
3351 || __is_specialization_of<_Seq, vector>)
3353 auto __s = this->_M_used();
3354 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3355 // Truncate the sequence to the part that was actually written to:
3356 _M_seq.resize(__s.size() + __n);
3357 // Switch back to using buffer:
3358 this->_M_reset(this->_M_buf);
3363 // TODO: for SSO string, use SSO buffer as initial span, then switch
3364 // to _M_buf if it overflows? Or even do that for all unused capacity?
3366 [[__gnu__::__always_inline__]]
3367 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3370 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3371 : _M_seq(std::move(__s))
3374 using _Sink<_CharT>::out;
3379 if (this->_M_used().size() != 0)
3380 _Seq_sink::_M_overflow();
3381 return std::move(_M_seq);
3384 // A writable span that views everything written to the sink.
3385 // Will be either a view over _M_seq or the used part of _M_buf.
3389 auto __s = this->_M_used();
3392 if (__s.size() != 0)
3393 _Seq_sink::_M_overflow();
3400 // A sink that writes to an output iterator.
3401 // Writes to a fixed-size buffer and then flushes to the output iterator
3402 // when the buffer fills up.
3403 template<typename _CharT, typename _OutIter>
3404 class _Iter_sink : public _Buf_sink<_CharT>
3407 iter_difference_t<_OutIter> _M_max;
3410 size_t _M_count = 0;
3413 _M_overflow() override
3415 auto __s = this->_M_used();
3416 if (_M_max < 0) // No maximum.
3417 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3418 else if (_M_count < static_cast<size_t>(_M_max))
3420 auto __max = _M_max - _M_count;
3421 span<_CharT> __first;
3422 if (__max < __s.size())
3423 __first = __s.first(static_cast<size_t>(__max));
3426 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3429 _M_count += __s.size();
3433 [[__gnu__::__always_inline__]]
3435 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3436 : _M_out(std::move(__out)), _M_max(__max)
3439 using _Sink<_CharT>::out;
3441 format_to_n_result<_OutIter>
3444 if (this->_M_used().size() != 0)
3445 _Iter_sink::_M_overflow();
3446 iter_difference_t<_OutIter> __count(_M_count);
3447 return { std::move(_M_out), __count };
3451 // Partial specialization for contiguous iterators.
3452 // No buffer is used, characters are written straight to the iterator.
3453 // We do not know the size of the output range, so the span size just grows
3454 // as needed. The end of the span might be an invalid pointer outside the
3455 // valid range, but we never actually call _M_span.end(). This class does
3456 // not introduce any invalid pointer arithmetic or overflows that would not
3457 // have happened anyway.
3458 template<typename _CharT, contiguous_iterator _OutIter>
3459 requires same_as<iter_value_t<_OutIter>, _CharT>
3460 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3463 iter_difference_t<_OutIter> _M_max = -1;
3465 size_t _M_count = 0;
3467 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3471 _M_overflow() override
3473 if (this->_M_unused().size() != 0)
3474 return; // No need to switch to internal buffer yet.
3476 auto __s = this->_M_used();
3480 _M_count += __s.size();
3481 // Span was already sized for the maximum character count,
3482 // if it overflows then any further output must go to the
3483 // internal buffer, to be discarded.
3484 this->_M_reset(this->_M_buf);
3488 // No maximum character count. Just extend the span to allow
3489 // writing more characters to it.
3490 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3494 typename _Sink<_CharT>::_Reservation
3495 _M_reserve(size_t __n) final
3497 auto __avail = this->_M_unused();
3498 if (__n > __avail.size())
3501 return {}; // cannot grow
3503 auto __s = this->_M_used();
3504 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3511 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3512 span<_CharT> __buf) noexcept
3515 return __buf; // Only write to the internal buffer.
3519 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3520 || sizeof(__n) > sizeof(size_t))
3522 // __int128 or __detail::__max_diff_type
3523 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3527 return {__ptr, (size_t)__n};
3530#if __has_builtin(__builtin_dynamic_object_size)
3531 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3532 return {__ptr, __bytes / sizeof(_CharT)};
3534 // Avoid forming a pointer to a different memory page.
3535 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3536 __n = (1024 - __off) / sizeof(_CharT);
3537 if (__n > 0) [[likely]]
3538 return {__ptr, static_cast<size_t>(__n)};
3539 else // Misaligned/packed buffer of wchar_t?
3545 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3546 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3547 _M_first(__out), _M_max(__n)
3550 format_to_n_result<_OutIter>
3553 auto __s = this->_M_used();
3554 if (__s.data() == _M_buf)
3556 // Switched to internal buffer, so must have written _M_max.
3557 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3558 return { _M_first + _M_max, __count };
3560 else // Not using internal buffer yet
3562 iter_difference_t<_OutIter> __count(__s.size());
3563 return { _M_first + __count, __count };
3568 enum _Arg_t : unsigned char {
3569 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3570 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3571 _Arg_i128, _Arg_u128,
3572 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
3573#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3575 _Arg_f128 = _Arg_ldbl,
3576 _Arg_ibm128 = _Arg_next_value_,
3583 template<typename _Context>
3586 using _CharT = typename _Context::char_type;
3602 unsigned long long _M_ull;
3605#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3606 long double _M_ldbl;
3608 const _CharT* _M_str;
3609 basic_string_view<_CharT> _M_sv;
3611 _HandleBase _M_handle;
3612#ifdef __SIZEOF_INT128__
3614 unsigned __int128 _M_u128;
3616#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3619#elif _GLIBCXX_FORMAT_F128 == 2
3620 __float128_t _M_f128;
3624 [[__gnu__::__always_inline__]]
3625 _Arg_value() : _M_none() { }
3628 template<typename _Tp>
3629 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3630 { _S_get<_Tp>() = __val; }
3633 template<typename _Tp, typename _Self>
3634 [[__gnu__::__always_inline__]]
3636 _S_get(_Self& __u) noexcept
3638 if constexpr (is_same_v<_Tp, bool>)
3640 else if constexpr (is_same_v<_Tp, _CharT>)
3642 else if constexpr (is_same_v<_Tp, int>)
3644 else if constexpr (is_same_v<_Tp, unsigned>)
3646 else if constexpr (is_same_v<_Tp, long long>)
3648 else if constexpr (is_same_v<_Tp, unsigned long long>)
3650 else if constexpr (is_same_v<_Tp, float>)
3652 else if constexpr (is_same_v<_Tp, double>)
3654#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3655 else if constexpr (is_same_v<_Tp, long double>)
3658 else if constexpr (is_same_v<_Tp, __ieee128>)
3660 else if constexpr (is_same_v<_Tp, __ibm128>)
3661 return __u._M_ibm128;
3663 else if constexpr (is_same_v<_Tp, const _CharT*>)
3665 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3667 else if constexpr (is_same_v<_Tp, const void*>)
3669#ifdef __SIZEOF_INT128__
3670 else if constexpr (is_same_v<_Tp, __int128>)
3672 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3675#if _GLIBCXX_FORMAT_F128 == 2
3676 else if constexpr (is_same_v<_Tp, __float128_t>)
3679 else if constexpr (derived_from<_Tp, _HandleBase>)
3680 return static_cast<_Tp&>(__u._M_handle);
3681 // Otherwise, ill-formed.
3684 template<typename _Tp>
3685 [[__gnu__::__always_inline__]]
3688 { return _S_get<_Tp>(*this); }
3690 template<typename _Tp>
3691 [[__gnu__::__always_inline__]]
3693 _M_get() const noexcept
3694 { return _S_get<_Tp>(*this); }
3696 template<typename _Tp>
3697 [[__gnu__::__always_inline__]]
3699 _M_set(_Tp __v) noexcept
3701 if constexpr (derived_from<_Tp, _HandleBase>)
3702 std::construct_at(&_M_handle, __v);
3704 _S_get<_Tp>(*this) = __v;
3708 // [format.arg.store], class template format-arg-store
3709 template<typename _Context, typename... _Args>
3712 template<typename _Visitor, typename _Ctx>
3713 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
3715 template<typename _Ch, typename _Tp>
3717 __to_arg_t_enum() noexcept;
3718} // namespace __format
3721 template<typename _Context>
3722 class basic_format_arg
3724 using _CharT = typename _Context::char_type;
3726 template<typename _Tp>
3727 static constexpr bool __formattable
3728 = __format::__formattable_with<_Tp, _Context>;
3731 class handle : public __format::_Arg_value<_Context>::_HandleBase
3733 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
3735 // Format as const if possible, to reduce instantiations.
3736 template<typename _Tp>
3737 using __maybe_const_t
3738 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
3740 template<typename _Tq>
3742 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
3743 _Context& __format_ctx, const void* __ptr)
3745 using _Td = remove_const_t<_Tq>;
3746 typename _Context::template formatter_type<_Td> __f;
3747 __parse_ctx.advance_to(__f.parse(__parse_ctx));
3748 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
3749 __format_ctx.advance_to(__f.format(__val, __format_ctx));
3752 template<typename _Tp>
3754 handle(_Tp& __val) noexcept
3756 this->_M_ptr = __builtin_addressof(__val);
3757 auto __func = _S_format<__maybe_const_t<_Tp>>;
3758 this->_M_func = reinterpret_cast<void(*)()>(__func);
3761 friend class basic_format_arg<_Context>;
3764 handle(const handle&) = default;
3765 handle& operator=(const handle&) = default;
3767 [[__gnu__::__always_inline__]]
3769 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
3771 using _Func = void(*)(basic_format_parse_context<_CharT>&,
3772 _Context&, const void*);
3773 auto __f = reinterpret_cast<_Func>(this->_M_func);
3774 __f(__pc, __fc, this->_M_ptr);
3778 [[__gnu__::__always_inline__]]
3779 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
3781 [[nodiscard,__gnu__::__always_inline__]]
3782 explicit operator bool() const noexcept
3783 { return _M_type != __format::_Arg_none; }
3785#if __cpp_lib_format >= 202306L // >= C++26
3786 template<typename _Visitor>
3788 visit(this basic_format_arg __arg, _Visitor&& __vis)
3789 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3791 template<typename _Res, typename _Visitor>
3793 visit(this basic_format_arg __arg, _Visitor&& __vis)
3794 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
3798 template<typename _Ctx>
3799 friend class basic_format_args;
3801 template<typename _Ctx, typename... _Args>
3802 friend class __format::_Arg_store;
3804 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
3806 __format::_Arg_value<_Context> _M_val;
3807 __format::_Arg_t _M_type;
3809 // Transform incoming argument type to the type stored in _Arg_value.
3810 // e.g. short -> int, std::string -> std::string_view,
3811 // char[3] -> const char*.
3812 template<typename _Tp>
3813 static consteval auto
3816 using _Td = remove_const_t<_Tp>;
3817 if constexpr (is_same_v<_Td, bool>)
3818 return type_identity<bool>();
3819 else if constexpr (is_same_v<_Td, _CharT>)
3820 return type_identity<_CharT>();
3821 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
3822 return type_identity<_CharT>();
3823#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
3824 else if constexpr (is_same_v<_Td, __int128>)
3825 return type_identity<__int128>();
3826 else if constexpr (is_same_v<_Td, unsigned __int128>)
3827 return type_identity<unsigned __int128>();
3829 else if constexpr (__is_signed_integer<_Td>::value)
3831 if constexpr (sizeof(_Td) <= sizeof(int))
3832 return type_identity<int>();
3833 else if constexpr (sizeof(_Td) <= sizeof(long long))
3834 return type_identity<long long>();
3836 else if constexpr (__is_unsigned_integer<_Td>::value)
3838 if constexpr (sizeof(_Td) <= sizeof(unsigned))
3839 return type_identity<unsigned>();
3840 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
3841 return type_identity<unsigned long long>();
3843 else if constexpr (is_same_v<_Td, float>)
3844 return type_identity<float>();
3845 else if constexpr (is_same_v<_Td, double>)
3846 return type_identity<double>();
3847#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3848 else if constexpr (is_same_v<_Td, long double>)
3849 return type_identity<long double>();
3851 else if constexpr (is_same_v<_Td, __ibm128>)
3852 return type_identity<__ibm128>();
3853 else if constexpr (is_same_v<_Td, __ieee128>)
3854 return type_identity<__ieee128>();
3857#if defined(__FLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3858 else if constexpr (is_same_v<_Td, _Float16>)
3859 return type_identity<float>();
3862#if defined(__BFLT16_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3863 else if constexpr (is_same_v<_Td, decltype(0.0bf16)>)
3864 return type_identity<float>();
3867#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3868 else if constexpr (is_same_v<_Td, _Float32>)
3869 return type_identity<float>();
3872#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
3873 else if constexpr (is_same_v<_Td, _Float64>)
3874 return type_identity<double>();
3877#if _GLIBCXX_FORMAT_F128
3879 else if constexpr (is_same_v<_Td, _Float128>)
3880 return type_identity<__format::__float128_t>();
3882# if __SIZEOF_FLOAT128__
3883 else if constexpr (is_same_v<_Td, __float128>)
3884 return type_identity<__format::__float128_t>();
3887 else if constexpr (__is_specialization_of<_Td, basic_string_view>
3888 || __is_specialization_of<_Td, basic_string>)
3890 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
3891 return type_identity<basic_string_view<_CharT>>();
3893 return type_identity<handle>();
3895 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
3896 return type_identity<const _CharT*>();
3897 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
3898 return type_identity<const _CharT*>();
3899 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
3900 return type_identity<const void*>();
3901 else if constexpr (is_same_v<_Td, nullptr_t>)
3902 return type_identity<const void*>();
3904 return type_identity<handle>();
3907 // Transform a formattable type to the appropriate storage type.
3908 template<typename _Tp>
3909 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
3911 // Get the _Arg_t value corresponding to a normalized type.
3912 template<typename _Tp>
3913 static consteval __format::_Arg_t
3916 using namespace __format;
3917 if constexpr (is_same_v<_Tp, bool>)
3919 else if constexpr (is_same_v<_Tp, _CharT>)
3921 else if constexpr (is_same_v<_Tp, int>)
3923 else if constexpr (is_same_v<_Tp, unsigned>)
3925 else if constexpr (is_same_v<_Tp, long long>)
3927 else if constexpr (is_same_v<_Tp, unsigned long long>)
3929 else if constexpr (is_same_v<_Tp, float>)
3931 else if constexpr (is_same_v<_Tp, double>)
3933#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3934 else if constexpr (is_same_v<_Tp, long double>)
3937 // Don't use _Arg_ldbl for this target, it's ambiguous.
3938 else if constexpr (is_same_v<_Tp, __ibm128>)
3940 else if constexpr (is_same_v<_Tp, __ieee128>)
3943 else if constexpr (is_same_v<_Tp, const _CharT*>)
3945 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3947 else if constexpr (is_same_v<_Tp, const void*>)
3949#ifdef __SIZEOF_INT128__
3950 else if constexpr (is_same_v<_Tp, __int128>)
3952 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3956#if _GLIBCXX_FORMAT_F128 == 2
3957 else if constexpr (is_same_v<_Tp, __format::__float128_t>)
3960 else if constexpr (is_same_v<_Tp, handle>)
3964 template<typename _Tp>
3966 _M_set(_Tp __v) noexcept
3968 _M_type = _S_to_enum<_Tp>();
3972 template<typename _Tp>
3973 requires __format::__formattable_with<_Tp, _Context>
3975 basic_format_arg(_Tp& __v) noexcept
3977 using _Td = _Normalize<_Tp>;
3978 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
3979 _M_set(_Td{__v.data(), __v.size()});
3980 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
3981 && is_same_v<_CharT, wchar_t>)
3982 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
3984 _M_set(static_cast<_Td>(__v));
3987 template<typename _Ctx, typename... _Argz>
3989 make_format_args(_Argz&...) noexcept;
3991 template<typename _Visitor, typename _Ctx>
3992 friend decltype(auto)
3993 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
3995 template<typename _Visitor, typename _Ctx>
3996 friend decltype(auto)
3997 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
3999 template<typename _Ch, typename _Tp>
4000 friend consteval __format::_Arg_t
4001 __format::__to_arg_t_enum() noexcept;
4003 template<typename _Visitor>
4005 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4007 using namespace __format;
4011 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4013 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4015 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4017 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4019 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4021 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4023 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4024#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4026 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4028 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4029#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4031 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4034 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
4036 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4040 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4042 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4044 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4047 auto& __h = static_cast<handle&>(_M_val._M_handle);
4048 return std::forward<_Visitor>(__vis)(__h);
4050#ifdef __SIZEOF_INT128__
4052 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4054 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4057#if _GLIBCXX_FORMAT_F128 == 2
4059 return std::forward<_Visitor>(__vis)(_M_val._M_f128);
4064 __builtin_unreachable();
4068 template<typename _Visitor>
4070 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4072 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4074 constexpr bool __user_facing = __is_one_of<_Tp,
4075 monostate, bool, _CharT,
4076 int, unsigned int, long long int, unsigned long long int,
4077 float, double, long double,
4078 const _CharT*, basic_string_view<_CharT>,
4079 const void*, handle>::value;
4080 if constexpr (__user_facing)
4081 return std::forward<_Visitor>(__vis)(__val);
4085 return std::forward<_Visitor>(__vis)(__h);
4091 template<typename _Visitor, typename _Context>
4092 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4093 inline decltype(auto)
4094 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4096 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4099/// @cond undocumented
4102 template<typename _Visitor, typename _Ctx>
4103 inline decltype(auto)
4104 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4106 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4109 struct _WidthPrecVisitor
4111 template<typename _Tp>
4113 operator()(_Tp& __arg) const
4115 if constexpr (is_same_v<_Tp, monostate>)
4116 __format::__invalid_arg_id_in_format_string();
4117 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4118 // 3720. Restrict the valid types of arg-id for width and precision
4119 // 3721. Allow an arg-id with a value of zero for width
4120 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4122 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4123 // 3720. Restrict the valid types of arg-id for width and precision
4124 if constexpr (__is_unsigned_integer<_Tp>::value)
4126 else if constexpr (__is_signed_integer<_Tp>::value)
4130 __throw_format_error("format error: argument used for width or "
4131 "precision must be a non-negative integer");
4135#pragma GCC diagnostic push
4136#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4137 template<typename _Context>
4139 __int_from_arg(const basic_format_arg<_Context>& __arg)
4140 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4142 // Pack _Arg_t enum values into a single 60-bit integer.
4143 template<int _Bits, size_t _Nm>
4145 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4147 __UINT64_TYPE__ __packed_types = 0;
4148 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4149 __packed_types = (__packed_types << _Bits) | *__i;
4150 return __packed_types;
4152} // namespace __format
4155 template<typename _Context>
4156 class basic_format_args
4158 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4159 static constexpr int _S_packed_type_mask = 0b11111;
4160 static constexpr int _S_max_packed_args = 12;
4162 static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
4164 template<typename... _Args>
4165 using _Store = __format::_Arg_store<_Context, _Args...>;
4167 template<typename _Ctx, typename... _Args>
4168 friend class __format::_Arg_store;
4170 using uint64_t = __UINT64_TYPE__;
4171 using _Format_arg = basic_format_arg<_Context>;
4172 using _Format_arg_val = __format::_Arg_value<_Context>;
4174 // If args are packed then the number of args is in _M_packed_size and
4175 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4176 // If args are not packed then the number of args is in _M_unpacked_size
4177 // and _M_packed_size is zero.
4178 uint64_t _M_packed_size : 4;
4179 uint64_t _M_unpacked_size : 60;
4182 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4183 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4187 _M_size() const noexcept
4188 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4190 typename __format::_Arg_t
4191 _M_type(size_t __i) const noexcept
4193 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4194 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4197 template<typename _Ctx, typename... _Args>
4199 make_format_args(_Args&...) noexcept;
4201 // An array of _Arg_t enums corresponding to _Args...
4202 template<typename... _Args>
4203 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4205 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4208 template<typename... _Args>
4209 basic_format_args(const _Store<_Args...>& __store) noexcept;
4211 [[nodiscard,__gnu__::__always_inline__]]
4212 basic_format_arg<_Context>
4213 get(size_t __i) const noexcept
4215 basic_format_arg<_Context> __arg;
4216 if (__i < _M_packed_size)
4218 __arg._M_type = _M_type(__i);
4219 __arg._M_val = _M_values[__i];
4221 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4222 __arg = _M_args[__i];
4227 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4228 // 3810. CTAD for std::basic_format_args
4229 template<typename _Context, typename... _Args>
4230 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4231 -> basic_format_args<_Context>;
4233 template<typename _Context, typename... _Args>
4235 make_format_args(_Args&... __fmt_args) noexcept;
4237 // An array of type-erased formatting arguments.
4238 template<typename _Context, typename... _Args>
4239 class __format::_Arg_store
4241 friend std::basic_format_args<_Context>;
4243 template<typename _Ctx, typename... _Argz>
4245#if _GLIBCXX_INLINE_VERSION
4246 __8:: // Needed for PR c++/59256
4248 make_format_args(_Argz&...) noexcept;
4250 // For a sufficiently small number of arguments we only store values.
4251 // basic_format_args can get the types from the _Args pack.
4252 static constexpr bool _S_values_only
4253 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4256 = __conditional_t<_S_values_only,
4257 __format::_Arg_value<_Context>,
4258 basic_format_arg<_Context>>;
4260 _Element_t _M_args[sizeof...(_Args)];
4262 template<typename _Tp>
4264 _S_make_elt(_Tp& __v)
4266 using _Tq = remove_const_t<_Tp>;
4267 using _CharT = typename _Context::char_type;
4268 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4269 "std::formatter must be specialized for the type "
4270 "of each format arg");
4271 using __format::__formattable_with;
4272 if constexpr (is_const_v<_Tp>)
4273 if constexpr (!__formattable_with<_Tp, _Context>)
4274 if constexpr (__formattable_with<_Tq, _Context>)
4275 static_assert(__formattable_with<_Tp, _Context>,
4276 "format arg must be non-const because its "
4277 "std::formatter specialization has a "
4278 "non-const reference parameter");
4279 basic_format_arg<_Context> __arg(__v);
4280 if constexpr (_S_values_only)
4281 return __arg._M_val;
4286 template<typename... _Tp>
4287 requires (sizeof...(_Tp) == sizeof...(_Args))
4288 [[__gnu__::__always_inline__]]
4289 _Arg_store(_Tp&... __a) noexcept
4290 : _M_args{_S_make_elt(__a)...}
4294 template<typename _Context>
4295 class __format::_Arg_store<_Context>
4298 template<typename _Context>
4299 template<typename... _Args>
4301 basic_format_args<_Context>::
4302 basic_format_args(const _Store<_Args...>& __store) noexcept
4304 if constexpr (sizeof...(_Args) == 0)
4307 _M_unpacked_size = 0;
4310 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4312 // The number of packed arguments:
4313 _M_packed_size = sizeof...(_Args);
4314 // The packed type enums:
4316 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4317 // The _Arg_value objects.
4318 _M_values = __store._M_args;
4322 // No packed arguments:
4324 // The number of unpacked arguments:
4325 _M_unpacked_size = sizeof...(_Args);
4326 // The basic_format_arg objects:
4327 _M_args = __store._M_args;
4331 /// Capture formatting arguments for use by `std::vformat`.
4332 template<typename _Context = format_context, typename... _Args>
4333 [[nodiscard,__gnu__::__always_inline__]]
4335 make_format_args(_Args&... __fmt_args) noexcept
4337 using _Fmt_arg = basic_format_arg<_Context>;
4338 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4339 _Normalize<_Args>...>;
4340 return _Store(__fmt_args...);
4343#ifdef _GLIBCXX_USE_WCHAR_T
4344 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4345 template<typename... _Args>
4346 [[nodiscard,__gnu__::__always_inline__]]
4348 make_wformat_args(_Args&... __args) noexcept
4349 { return std::make_format_args<wformat_context>(__args...); }
4352/// @cond undocumented
4355 template<typename _Out, typename _CharT, typename _Context>
4357 __do_vformat_to(_Out, basic_string_view<_CharT>,
4358 const basic_format_args<_Context>&,
4359 const locale* = nullptr);
4361 template<typename _CharT> struct __formatter_chrono;
4363} // namespace __format
4366 /** Context for std::format and similar functions.
4368 * A formatting context contains an output iterator and locale to use
4369 * for the formatting operations. Most programs will never need to use
4370 * this class template explicitly. For typical uses of `std::format` the
4371 * library will use the specializations `std::format_context` (for `char`)
4372 * and `std::wformat_context` (for `wchar_t`).
4374 * You are not allowed to define partial or explicit specializations of
4375 * this class template.
4379 template<typename _Out, typename _CharT>
4380 class basic_format_context
4382 static_assert( output_iterator<_Out, const _CharT&> );
4384 basic_format_args<basic_format_context> _M_args;
4386 __format::_Optional_locale _M_loc;
4388 basic_format_context(basic_format_args<basic_format_context> __args,
4390 : _M_args(__args), _M_out(std::move(__out))
4393 basic_format_context(basic_format_args<basic_format_context> __args,
4394 _Out __out, const std::locale& __loc)
4395 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4398 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4399 // 4061. Should std::basic_format_context be
4400 // default-constructible/copyable/movable?
4401 basic_format_context(const basic_format_context&) = delete;
4402 basic_format_context& operator=(const basic_format_context&) = delete;
4404 template<typename _Out2, typename _CharT2, typename _Context2>
4406 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4407 const basic_format_args<_Context2>&,
4410 friend __format::__formatter_chrono<_CharT>;
4413 ~basic_format_context() = default;
4415 using iterator = _Out;
4416 using char_type = _CharT;
4417 template<typename _Tp>
4418 using formatter_type = formatter<_Tp, _CharT>;
4421 basic_format_arg<basic_format_context>
4422 arg(size_t __id) const noexcept
4423 { return _M_args.get(__id); }
4426 std::locale locale() { return _M_loc.value(); }
4429 iterator out() { return std::move(_M_out); }
4431 void advance_to(iterator __it) { _M_out = std::move(__it); }
4435/// @cond undocumented
4438 // Abstract base class defining an interface for scanning format strings.
4439 // Scan the characters in a format string, dividing it up into strings of
4440 // ordinary characters, escape sequences, and replacement fields.
4441 // Call virtual functions for derived classes to parse format-specifiers
4442 // or write formatted output.
4443 template<typename _CharT>
4446 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4448 struct _Parse_context : basic_format_parse_context<_CharT>
4450 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4451 const _Arg_t* _M_types = nullptr;
4455 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4456 : _M_pc(__str, __nargs)
4459 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4460 constexpr iterator end() const noexcept { return _M_pc.end(); }
4465 basic_string_view<_CharT> __fmt = _M_fmt_str();
4467 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4469 _M_pc.advance_to(begin() + 1);
4470 _M_format_arg(_M_pc.next_arg_id());
4474 size_t __lbr = __fmt.find('{');
4475 size_t __rbr = __fmt.find('}');
4477 while (__fmt.size())
4479 auto __cmp = __lbr <=> __rbr;
4483 _M_pc.advance_to(end());
4488 if (__lbr + 1 == __fmt.size()
4489 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4490 __format::__unmatched_left_brace_in_format_string();
4491 const bool __is_escape = __fmt[__lbr + 1] == '{';
4492 iterator __last = begin() + __lbr + int(__is_escape);
4493 _M_on_chars(__last);
4494 _M_pc.advance_to(__last + 1);
4495 __fmt = _M_fmt_str();
4498 if (__rbr != __fmt.npos)
4500 __lbr = __fmt.find('{');
4504 _M_on_replacement_field();
4505 __fmt = _M_fmt_str();
4506 __lbr = __fmt.find('{');
4507 __rbr = __fmt.find('}');
4512 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4513 __format::__unmatched_right_brace_in_format_string();
4514 iterator __last = begin() + __rbr;
4515 _M_on_chars(__last);
4516 _M_pc.advance_to(__last + 1);
4517 __fmt = _M_fmt_str();
4518 if (__lbr != __fmt.npos)
4520 __rbr = __fmt.find('}');
4525 constexpr basic_string_view<_CharT>
4526 _M_fmt_str() const noexcept
4527 { return {begin(), end()}; }
4529 constexpr virtual void _M_on_chars(iterator) { }
4531 constexpr void _M_on_replacement_field()
4533 auto __next = begin();
4537 __id = _M_pc.next_arg_id();
4538 else if (*__next == ':')
4540 __id = _M_pc.next_arg_id();
4541 _M_pc.advance_to(++__next);
4545 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4546 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4547 __format::__invalid_arg_id_in_format_string();
4548 _M_pc.check_arg_id(__id = __i);
4551 _M_pc.advance_to(++__ptr);
4554 _M_pc.advance_to(__ptr);
4556 _M_format_arg(__id);
4557 if (begin() == end() || *begin() != '}')
4558 __format::__unmatched_left_brace_in_format_string();
4559 _M_pc.advance_to(begin() + 1); // Move past '}'
4562 constexpr virtual void _M_format_arg(size_t __id) = 0;
4565 // Process a format string and format the arguments in the context.
4566 template<typename _Out, typename _CharT>
4567 class _Formatting_scanner : public _Scanner<_CharT>
4570 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4571 basic_string_view<_CharT> __str)
4572 : _Scanner<_CharT>(__str), _M_fc(__fc)
4576 basic_format_context<_Out, _CharT>& _M_fc;
4578 using iterator = typename _Scanner<_CharT>::iterator;
4581 _M_on_chars(iterator __last) override
4583 basic_string_view<_CharT> __str(this->begin(), __last);
4584 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4588 _M_format_arg(size_t __id) override
4590 using _Context = basic_format_context<_Out, _CharT>;
4591 using handle = typename basic_format_arg<_Context>::handle;
4593 __format::__visit_format_arg([this](auto& __arg) {
4594 using _Type = remove_reference_t<decltype(__arg)>;
4595 using _Formatter = typename _Context::template formatter_type<_Type>;
4596 if constexpr (is_same_v<_Type, monostate>)
4597 __format::__invalid_arg_id_in_format_string();
4598 else if constexpr (is_same_v<_Type, handle>)
4599 __arg.format(this->_M_pc, this->_M_fc);
4600 else if constexpr (is_default_constructible_v<_Formatter>)
4603 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4604 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4607 static_assert(__format::__formattable_with<_Type, _Context>);
4608 }, _M_fc.arg(__id));
4612 template<typename _CharT, typename _Tp>
4614 __to_arg_t_enum() noexcept
4616 using _Context = __format::__format_context<_CharT>;
4617 using _Fmt_arg = basic_format_arg<_Context>;
4618 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4619 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4622 // Validate a format string for Args.
4623 template<typename _CharT, typename... _Args>
4624 class _Checking_scanner : public _Scanner<_CharT>
4627 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4628 "std::formatter must be specialized for each type being formatted");
4632 _Checking_scanner(basic_string_view<_CharT> __str)
4633 : _Scanner<_CharT>(__str, sizeof...(_Args))
4635#if __cpp_lib_format >= 202305L
4636 this->_M_pc._M_types = _M_types.data();
4642 _M_format_arg(size_t __id) override
4644 if constexpr (sizeof...(_Args) != 0)
4646 if (__id < sizeof...(_Args))
4648 _M_parse_format_spec<_Args...>(__id);
4652 __builtin_unreachable();
4655 template<typename _Tp, typename... _OtherArgs>
4657 _M_parse_format_spec(size_t __id)
4661 formatter<_Tp, _CharT> __f;
4662 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4664 else if constexpr (sizeof...(_OtherArgs) != 0)
4665 _M_parse_format_spec<_OtherArgs...>(__id - 1);
4667 __builtin_unreachable();
4670#if __cpp_lib_format >= 202305L
4671 array<_Arg_t, sizeof...(_Args)>
4672 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
4676 template<typename _Out, typename _CharT, typename _Context>
4678 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
4679 const basic_format_args<_Context>& __args,
4680 const locale* __loc)
4682 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
4683 _Sink_iter<_CharT> __sink_out;
4685 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4686 __sink_out = __out; // Already a sink iterator, safe to use post-move.
4688 __sink_out = __sink.out();
4690 if constexpr (is_same_v<_CharT, char>)
4691 // Fast path for "{}" format strings and simple format arg types.
4692 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4694 bool __done = false;
4695 __format::__visit_format_arg([&](auto& __arg) {
4696 using _Tp = remove_cvref_t<decltype(__arg)>;
4697 if constexpr (is_same_v<_Tp, bool>)
4699 size_t __len = 4 + !__arg;
4700 const char* __chars[] = { "false", "true" };
4701 if (auto __res = __sink_out._M_reserve(__len))
4703 __builtin_memcpy(__res.get(), __chars[__arg], __len);
4704 __res._M_bump(__len);
4708 else if constexpr (is_same_v<_Tp, char>)
4710 if (auto __res = __sink_out._M_reserve(1))
4712 *__res.get() = __arg;
4717 else if constexpr (is_integral_v<_Tp>)
4719 make_unsigned_t<_Tp> __uval;
4720 const bool __neg = __arg < 0;
4722 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
4725 const auto __n = __detail::__to_chars_len(__uval);
4726 if (auto __res = __sink_out._M_reserve(__n + __neg))
4728 auto __ptr = __res.get();
4730 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
4732 __res._M_bump(__n + __neg);
4736 else if constexpr (is_convertible_v<_Tp, string_view>)
4738 string_view __sv = __arg;
4739 if (auto __res = __sink_out._M_reserve(__sv.size()))
4741 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
4742 __res._M_bump(__sv.size());
4750 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4753 return std::move(__sink)._M_finish().out;
4757 auto __ctx = __loc == nullptr
4758 ? _Context(__args, __sink_out)
4759 : _Context(__args, __sink_out, *__loc);
4760 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
4761 __scanner._M_scan();
4763 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
4766 return std::move(__sink)._M_finish().out;
4768#pragma GCC diagnostic pop
4770} // namespace __format
4773#if __cpp_lib_format >= 202305L // >= C++26
4774 /// @cond undocumented
4775 // Common implementation of check_dynamic_spec{,_string,_integral}
4776 template<typename _CharT>
4777 template<typename... _Ts>
4779 basic_format_parse_context<_CharT>::
4780 __check_dynamic_spec(size_t __id) noexcept
4782 if (__id >= _M_num_args)
4783 __format::__invalid_arg_id_in_format_string();
4784 if constexpr (sizeof...(_Ts) != 0)
4786 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
4787 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
4788 __format::_Arg_t __types[] = {
4789 __format::__to_arg_t_enum<_CharT, _Ts>()...
4791 for (auto __t : __types)
4795 __invalid_dynamic_spec("arg(id) type does not match");
4800 template<typename _CharT, typename... _Args>
4801 template<typename _Tp>
4802 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
4804 basic_format_string<_CharT, _Args...>::
4805 basic_format_string(const _Tp& __s)
4808 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
4810 __scanner._M_scan();
4813 // [format.functions], formatting functions
4815 template<typename _Out> requires output_iterator<_Out, const char&>
4816 [[__gnu__::__always_inline__]]
4818 vformat_to(_Out __out, string_view __fmt, format_args __args)
4819 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4821#ifdef _GLIBCXX_USE_WCHAR_T
4822 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4823 [[__gnu__::__always_inline__]]
4825 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
4826 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
4829 template<typename _Out> requires output_iterator<_Out, const char&>
4830 [[__gnu__::__always_inline__]]
4832 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
4835 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4838#ifdef _GLIBCXX_USE_WCHAR_T
4839 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
4840 [[__gnu__::__always_inline__]]
4842 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
4843 wformat_args __args)
4845 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
4851 vformat(string_view __fmt, format_args __args)
4853 __format::_Str_sink<char> __buf;
4854 std::vformat_to(__buf.out(), __fmt, __args);
4855 return std::move(__buf).get();
4858#ifdef _GLIBCXX_USE_WCHAR_T
4861 vformat(wstring_view __fmt, wformat_args __args)
4863 __format::_Str_sink<wchar_t> __buf;
4864 std::vformat_to(__buf.out(), __fmt, __args);
4865 return std::move(__buf).get();
4871 vformat(const locale& __loc, string_view __fmt, format_args __args)
4873 __format::_Str_sink<char> __buf;
4874 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4875 return std::move(__buf).get();
4878#ifdef _GLIBCXX_USE_WCHAR_T
4881 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
4883 __format::_Str_sink<wchar_t> __buf;
4884 std::vformat_to(__buf.out(), __loc, __fmt, __args);
4885 return std::move(__buf).get();
4889 template<typename... _Args>
4892 format(format_string<_Args...> __fmt, _Args&&... __args)
4893 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
4895#ifdef _GLIBCXX_USE_WCHAR_T
4896 template<typename... _Args>
4899 format(wformat_string<_Args...> __fmt, _Args&&... __args)
4900 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
4903 template<typename... _Args>
4906 format(const locale& __loc, format_string<_Args...> __fmt,
4909 return std::vformat(__loc, __fmt.get(),
4910 std::make_format_args(__args...));
4913#ifdef _GLIBCXX_USE_WCHAR_T
4914 template<typename... _Args>
4917 format(const locale& __loc, wformat_string<_Args...> __fmt,
4920 return std::vformat(__loc, __fmt.get(),
4921 std::make_wformat_args(__args...));
4925 template<typename _Out, typename... _Args>
4926 requires output_iterator<_Out, const char&>
4928 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
4930 return std::vformat_to(std::move(__out), __fmt.get(),
4931 std::make_format_args(__args...));
4934#ifdef _GLIBCXX_USE_WCHAR_T
4935 template<typename _Out, typename... _Args>
4936 requires output_iterator<_Out, const wchar_t&>
4938 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
4940 return std::vformat_to(std::move(__out), __fmt.get(),
4941 std::make_wformat_args(__args...));
4945 template<typename _Out, typename... _Args>
4946 requires output_iterator<_Out, const char&>
4948 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
4951 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4952 std::make_format_args(__args...));
4955#ifdef _GLIBCXX_USE_WCHAR_T
4956 template<typename _Out, typename... _Args>
4957 requires output_iterator<_Out, const wchar_t&>
4959 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
4962 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
4963 std::make_wformat_args(__args...));
4967 template<typename _Out, typename... _Args>
4968 requires output_iterator<_Out, const char&>
4969 inline format_to_n_result<_Out>
4970 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4971 format_string<_Args...> __fmt, _Args&&... __args)
4973 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
4974 std::vformat_to(__sink.out(), __fmt.get(),
4975 std::make_format_args(__args...));
4976 return std::move(__sink)._M_finish();
4979#ifdef _GLIBCXX_USE_WCHAR_T
4980 template<typename _Out, typename... _Args>
4981 requires output_iterator<_Out, const wchar_t&>
4982 inline format_to_n_result<_Out>
4983 format_to_n(_Out __out, iter_difference_t<_Out> __n,
4984 wformat_string<_Args...> __fmt, _Args&&... __args)
4986 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
4987 std::vformat_to(__sink.out(), __fmt.get(),
4988 std::make_wformat_args(__args...));
4989 return std::move(__sink)._M_finish();
4993 template<typename _Out, typename... _Args>
4994 requires output_iterator<_Out, const char&>
4995 inline format_to_n_result<_Out>
4996 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
4997 format_string<_Args...> __fmt, _Args&&... __args)
4999 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5000 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5001 std::make_format_args(__args...));
5002 return std::move(__sink)._M_finish();
5005#ifdef _GLIBCXX_USE_WCHAR_T
5006 template<typename _Out, typename... _Args>
5007 requires output_iterator<_Out, const wchar_t&>
5008 inline format_to_n_result<_Out>
5009 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5010 wformat_string<_Args...> __fmt, _Args&&... __args)
5012 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5013 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5014 std::make_wformat_args(__args...));
5015 return std::move(__sink)._M_finish();
5019/// @cond undocumented
5023 template<typename _CharT>
5024 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5027 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5029 [[__gnu__::__always_inline__]]
5032 { return this->_M_count + this->_M_used().size(); }
5035 template<typename _CharT>
5036 class _Counting_sink : public _Buf_sink<_CharT>
5038 size_t _M_count = 0;
5041 _M_overflow() override
5043 if (!std::is_constant_evaluated())
5044 _M_count += this->_M_used().size();
5049 _Counting_sink() = default;
5051 [[__gnu__::__always_inline__]]
5055 _Counting_sink::_M_overflow();
5060} // namespace __format
5063 template<typename... _Args>
5066 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5068 __format::_Counting_sink<char> __buf;
5069 std::vformat_to(__buf.out(), __fmt.get(),
5070 std::make_format_args(__args...));
5071 return __buf.count();
5074#ifdef _GLIBCXX_USE_WCHAR_T
5075 template<typename... _Args>
5078 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5080 __format::_Counting_sink<wchar_t> __buf;
5081 std::vformat_to(__buf.out(), __fmt.get(),
5082 std::make_wformat_args(__args...));
5083 return __buf.count();
5087 template<typename... _Args>
5090 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5093 __format::_Counting_sink<char> __buf;
5094 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5095 std::make_format_args(__args...));
5096 return __buf.count();
5099#ifdef _GLIBCXX_USE_WCHAR_T
5100 template<typename... _Args>
5103 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5106 __format::_Counting_sink<wchar_t> __buf;
5107 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5108 std::make_wformat_args(__args...));
5109 return __buf.count();
5113#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5114 // [format.range], formatting of ranges
5115 // [format.range.fmtkind], variable template format_kind
5116 enum class range_format {
5125 /** @brief A constant determining how a range should be formatted.
5127 * The primary template of `std::format_kind` cannot be instantiated.
5128 * There is a partial specialization for input ranges and you can
5129 * specialize the variable template for your own cv-unqualified types
5130 * that satisfy the `ranges::input_range` concept.
5134 template<typename _Rg>
5135 constexpr auto format_kind = []{
5136 static_assert(false, "cannot use primary template of 'std::format_kind'");
5137 return type_identity<_Rg>{};
5140 /// @cond undocumented
5141 template<typename _Tp>
5142 consteval range_format
5145 using _Ref = ranges::range_reference_t<_Tp>;
5146 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5147 return range_format::disabled;
5148 else if constexpr (requires { typename _Tp::key_type; })
5150 if constexpr (requires { typename _Tp::mapped_type; })
5152 using _Up = remove_cvref_t<_Ref>;
5153 if constexpr (__is_pair<_Up>)
5154 return range_format::map;
5155 else if constexpr (__is_specialization_of<_Up, tuple>)
5156 if constexpr (tuple_size_v<_Up> == 2)
5157 return range_format::map;
5159 return range_format::set;
5162 return range_format::sequence;
5166 /// A constant determining how a range should be formatted.
5167 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5168 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5170/// @cond undocumented
5173 template<typename _CharT, typename _Out, typename _Callback>
5174 typename basic_format_context<_Out, _CharT>::iterator
5175 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5176 const _Spec<_CharT>& __spec,
5179 // This is required to implement formatting with padding,
5180 // as we need to format to temporary buffer, using the same iterator.
5181 static_assert(is_same_v<_Out, __format::_Sink_iter<_CharT>>);
5183 if (__spec._M_get_width(__fc) == 0)
5184 return __call(__fc);
5188 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5189 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5195 _M_ctx->advance_to(_M_out);
5203 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5204 _Sink_iter<_CharT> _M_out;
5207 _Restore_out __restore(__fc);
5208 // TODO Consider double sinking, first buffer of width
5209 // size and then original sink, if first buffer is overun
5210 // we do not need to align
5211 _Str_sink<_CharT> __buf;
5212 __fc.advance_to(__buf.out());
5214 __restore._M_trigger();
5216 basic_string_view<_CharT> __str(__buf.view());
5218 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
5219 __width = __unicode::__field_width(__str);
5221 __width = __str.size();
5223 return __format::__write_padded_as_spec(__str, __width, __fc, __spec);
5226 // _Rg& and const _Rg& are both formattable and use same formatter
5227 // specialization for their references.
5228 template<typename _Rg, typename _CharT>
5229 concept __simply_formattable_range
5230 = __const_formattable_range<_Rg, _CharT>
5231 && same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>,
5232 remove_cvref_t<ranges::range_reference_t<const _Rg>>>;
5234 template<size_t _Pos, typename _Tp, typename _CharT>
5235 struct __indexed_formatter_storage
5240 basic_format_parse_context<_CharT> __pc({});
5241 if (_M_formatter.parse(__pc) != __pc.end())
5242 __format::__failed_to_parse_format_spec();
5245 template<typename _Out>
5247 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5248 basic_format_context<_Out, _CharT>& __fc,
5249 basic_string_view<_CharT> __sep) const
5251 if constexpr (_Pos != 0)
5252 __fc.advance_to(__format::__write(__fc.out(), __sep));
5253 __fc.advance_to(_M_formatter.format(__elem, __fc));
5256 [[__gnu__::__always_inline__]]
5260 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5261 _M_formatter.set_debug_format();
5265 formatter<_Tp, _CharT> _M_formatter;
5268 template<typename _CharT, typename... _Tps>
5269 class __tuple_formatter
5271 using _String_view = basic_string_view<_CharT>;
5272 using _Seps = __format::_Separators<_CharT>;
5276 set_separator(basic_string_view<_CharT> __sep) noexcept
5280 set_brackets(basic_string_view<_CharT> __open,
5281 basic_string_view<_CharT> __close) noexcept
5287 // We deviate from standard, that declares this as template accepting
5288 // unconstrained ParseContext type, which seems unimplementable.
5289 constexpr typename basic_format_parse_context<_CharT>::iterator
5290 parse(basic_format_parse_context<_CharT>& __pc)
5292 auto __first = __pc.begin();
5293 const auto __last = __pc.end();
5294 __format::_Spec<_CharT> __spec{};
5296 auto __finished = [&]
5298 if (__first != __last && *__first != '}')
5302 _M_felems._M_parse();
5303 _M_felems.set_debug_format();
5310 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5314 __first = __spec._M_parse_width(__first, __last, __pc);
5318 if (*__first == 'n')
5321 _M_open = _M_close = _String_view();
5323 else if (*__first == 'm')
5326 if constexpr (sizeof...(_Tps) == 2)
5328 _M_sep = _Seps::_S_colon();
5329 _M_open = _M_close = _String_view();
5332 __throw_format_error("format error: 'm' specifier requires range"
5333 " of pair or tuple of two elements");
5339 __format::__failed_to_parse_format_spec();
5343 template<typename _Tuple, typename _Out, size_t... _Ids>
5344 typename basic_format_context<_Out, _CharT>::iterator
5345 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5346 basic_format_context<_Out, _CharT>& __fc) const
5347 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5349 template<typename _Out>
5350 typename basic_format_context<_Out, _CharT>::iterator
5351 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5352 basic_format_context<_Out, _CharT>& __fc) const
5354 return __format::__format_padded(
5356 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5358 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5359 _M_felems._M_format(__elems..., __nfc, _M_sep);
5360 return __format::__write(__nfc.out(), _M_close);
5365 template<size_t... _Ids>
5366 struct __formatters_storage
5367 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5369 template<size_t _Id, typename _Up>
5370 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5375 (_Base<_Ids, _Tps>::_M_parse(), ...);
5378 template<typename _Out>
5380 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5381 basic_format_context<_Out, _CharT>& __fc,
5382 _String_view __sep) const
5384 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5390 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5394 template<size_t... _Ids>
5396 _S_create_storage(index_sequence<_Ids...>)
5397 -> __formatters_storage<_Ids...>;
5399 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5401 _Spec<_CharT> _M_spec{};
5402 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5403 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5404 _String_view _M_sep = _Seps::_S_comma();
5405 _Formatters _M_felems;
5408 template<typename _Tp>
5409 concept __is_map_formattable
5410 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5412} // namespace __format
5415 // [format.tuple] Tuple formatter
5416 template<__format::__char _CharT, formattable<_CharT> _Fp,
5417 formattable<_CharT> _Sp>
5418 struct formatter<pair<_Fp, _Sp>, _CharT>
5419 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5420 remove_cvref_t<_Sp>>
5423 using __maybe_const_pair
5424 = __conditional_t<formattable<const _Fp, _CharT>
5425 && formattable<const _Sp, _CharT>,
5426 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5428 // We deviate from standard, that declares this as template accepting
5429 // unconstrained FormatContext type, which seems unimplementable.
5430 template<typename _Out>
5431 typename basic_format_context<_Out, _CharT>::iterator
5432 format(__maybe_const_pair& __p,
5433 basic_format_context<_Out, _CharT>& __fc) const
5434 { return this->_M_format_elems(__p.first, __p.second, __fc); }
5437 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5438 struct formatter<tuple<_Tps...>, _CharT>
5439 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5442 using __maybe_const_tuple
5443 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5444 const tuple<_Tps...>, tuple<_Tps...>>;
5446 // We deviate from standard, that declares this as template accepting
5447 // unconstrained FormatContext type, which seems unimplementable.
5448 template<typename _Out>
5449 typename basic_format_context<_Out, _CharT>::iterator
5450 format(__maybe_const_tuple& __t,
5451 basic_format_context<_Out, _CharT>& __fc) const
5452 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5455 // [format.range.formatter], class template range_formatter
5456 template<typename _Tp, __format::__char _CharT>
5457 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
5458 class range_formatter
5460 using _String_view = basic_string_view<_CharT>;
5461 using _Seps = __format::_Separators<_CharT>;
5465 set_separator(basic_string_view<_CharT> __sep) noexcept
5469 set_brackets(basic_string_view<_CharT> __open,
5470 basic_string_view<_CharT> __close) noexcept
5476 constexpr formatter<_Tp, _CharT>&
5477 underlying() noexcept
5480 constexpr const formatter<_Tp, _CharT>&
5481 underlying() const noexcept
5484 // We deviate from standard, that declares this as template accepting
5485 // unconstrained ParseContext type, which seems unimplementable.
5486 constexpr typename basic_format_parse_context<_CharT>::iterator
5487 parse(basic_format_parse_context<_CharT>& __pc)
5489 auto __first = __pc.begin();
5490 const auto __last = __pc.end();
5491 __format::_Spec<_CharT> __spec{};
5492 bool __no_brace = false;
5494 auto __finished = [&]
5495 { return __first == __last || *__first == '}'; };
5497 auto __finalize = [&]
5503 auto __parse_val = [&](_String_view __nfs = _String_view())
5505 basic_format_parse_context<_CharT> __npc(__nfs);
5506 if (_M_fval.parse(__npc) != __npc.end())
5507 __format::__failed_to_parse_format_spec();
5508 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
5509 _M_fval.set_debug_format();
5510 return __finalize();
5514 return __parse_val();
5516 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5518 return __parse_val();
5520 __first = __spec._M_parse_width(__first, __last, __pc);
5522 return __parse_val();
5524 if (*__first == '?')
5527 __spec._M_type = __format::_Pres_esc;
5528 if (__finished() || *__first != 's')
5529 __throw_format_error("format error: '?' is allowed only in"
5530 " combination with 's'");
5533 if (*__first == 's')
5536 if constexpr (same_as<_Tp, _CharT>)
5538 if (__spec._M_type != __format::_Pres_esc)
5539 __spec._M_type = __format::_Pres_str;
5541 return __finalize();
5542 __throw_format_error("format error: element format specifier"
5543 " cannot be provided when 's' specifier is used");
5546 __throw_format_error("format error: 's' specifier requires"
5547 " range of character types");
5551 return __parse_val();
5553 if (*__first == 'n')
5556 _M_open = _M_close = _String_view();
5561 return __parse_val();
5563 if (*__first == 'm')
5565 _String_view __m(__first, 1);
5567 if constexpr (__format::__is_map_formattable<_Tp>)
5569 _M_sep = _Seps::_S_comma();
5572 _M_open = _Seps::_S_braces().substr(0, 1);
5573 _M_close = _Seps::_S_braces().substr(1, 1);
5576 return __parse_val(__m);
5577 __throw_format_error("format error: element format specifier"
5578 " cannot be provided when 'm' specifier is used");
5581 __throw_format_error("format error: 'm' specifier requires"
5582 " range of pairs or tuples of two elements");
5586 return __parse_val();
5588 if (*__first == ':')
5590 __pc.advance_to(++__first);
5591 __first = _M_fval.parse(__pc);
5595 return __finalize();
5597 __format::__failed_to_parse_format_spec();
5600 // We deviate from standard, that declares this as template accepting
5601 // unconstrained FormatContext type, which seems unimplementable.
5602 template<ranges::input_range _Rg, typename _Out>
5603 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
5604 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
5605 typename basic_format_context<_Out, _CharT>::iterator
5606 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
5608 using _Range = remove_reference_t<_Rg>;
5609 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
5610 return _M_format<const _Range>(__rg, __fc);
5612 return _M_format(__rg, __fc);
5616 template<ranges::input_range _Rg, typename _Out>
5617 typename basic_format_context<_Out, _CharT>::iterator
5618 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
5620 if constexpr (same_as<_Tp, _CharT>)
5621 if (_M_spec._M_type == __format::_Pres_str
5622 || _M_spec._M_type == __format::_Pres_esc)
5624 __format::__formatter_str __fstr(_M_spec);
5625 return __fstr._M_format_range(__rg, __fc);
5627 return __format::__format_padded(
5629 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
5630 { return _M_format_elems(__rg, __nfc); });
5634 template<ranges::input_range _Rg, typename _Out>
5635 typename basic_format_context<_Out, _CharT>::iterator
5636 _M_format_elems(_Rg& __rg,
5637 basic_format_context<_Out, _CharT>& __fc) const
5639 auto __out = __format::__write(__fc.out(), _M_open);
5641 auto __first = ranges::begin(__rg);
5642 auto const __last = ranges::end(__rg);
5643 if (__first == __last)
5644 return __format::__write(__out, _M_close);
5646 __fc.advance_to(__out);
5647 __out = _M_fval.format(*__first, __fc);
5648 for (++__first; __first != __last; ++__first)
5650 __out = __format::__write(__out, _M_sep);
5651 __fc.advance_to(__out);
5652 __out = _M_fval.format(*__first, __fc);
5655 return __format::__write(__out, _M_close);
5658 __format::_Spec<_CharT> _M_spec{};
5659 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
5660 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
5661 _String_view _M_sep = _Seps::_S_comma();
5662 formatter<_Tp, _CharT> _M_fval;
5665 // In standard this is shown as inheriting from specialization of
5666 // exposition only specialization for range-default-formatter for
5667 // each range_format. We opt for simpler implementation.
5668 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
5669 // specializations for maps, sets, and strings
5670 template<ranges::input_range _Rg, __format::__char _CharT>
5671 requires (format_kind<_Rg> != range_format::disabled)
5672 && formattable<ranges::range_reference_t<_Rg>, _CharT>
5673 struct formatter<_Rg, _CharT>
5676 static const bool _S_range_format_is_string =
5677 (format_kind<_Rg> == range_format::string)
5678 || (format_kind<_Rg> == range_format::debug_string);
5679 using _Vt = remove_cvref_t<
5680 ranges::range_reference_t<
5681 __format::__maybe_const_range<_Rg, _CharT>>>;
5683 static consteval bool _S_is_correct()
5685 if constexpr (_S_range_format_is_string)
5686 static_assert(same_as<_Vt, _CharT>);
5690 static_assert(_S_is_correct());
5693 constexpr formatter() noexcept
5695 using _Seps = __format::_Separators<_CharT>;
5696 if constexpr (format_kind<_Rg> == range_format::map)
5698 static_assert(__format::__is_map_formattable<_Vt>);
5699 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
5700 _Seps::_S_braces().substr(1, 1));
5701 _M_under.underlying().set_brackets({}, {});
5702 _M_under.underlying().set_separator(_Seps::_S_colon());
5704 else if constexpr (format_kind<_Rg> == range_format::set)
5705 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
5706 _Seps::_S_braces().substr(1, 1));
5710 set_separator(basic_string_view<_CharT> __sep) noexcept
5711 requires (!_S_range_format_is_string)
5712 { _M_under.set_separator(__sep); }
5715 set_brackets(basic_string_view<_CharT> __open,
5716 basic_string_view<_CharT> __close) noexcept
5717 requires (!_S_range_format_is_string)
5718 { _M_under.set_brackets(__open, __close); }
5720 // We deviate from standard, that declares this as template accepting
5721 // unconstrained ParseContext type, which seems unimplementable.
5722 constexpr typename basic_format_parse_context<_CharT>::iterator
5723 parse(basic_format_parse_context<_CharT>& __pc)
5725 auto __res = _M_under.parse(__pc);
5726 if constexpr (format_kind<_Rg> == range_format::debug_string)
5727 _M_under.set_debug_format();
5731 // We deviate from standard, that declares this as template accepting
5732 // unconstrained FormatContext type, which seems unimplementable.
5733 template<typename _Out>
5734 typename basic_format_context<_Out, _CharT>::iterator
5735 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
5736 basic_format_context<_Out, _CharT>& __fc) const
5738 if constexpr (_S_range_format_is_string)
5739 return _M_under._M_format_range(__rg, __fc);
5741 return _M_under.format(__rg, __fc);
5745 using _Formatter_under
5746 = __conditional_t<_S_range_format_is_string,
5747 __format::__formatter_str<_CharT>,
5748 range_formatter<_Vt, _CharT>>;
5749 _Formatter_under _M_under;
5751#endif // C++23 formatting ranges
5752#undef _GLIBCXX_WIDEN
5754_GLIBCXX_END_NAMESPACE_VERSION
5756#endif // __cpp_lib_format
5757#pragma GCC diagnostic pop
5758#endif // _GLIBCXX_FORMAT