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, counted_iterator
60#include <bits/stl_pair.h> // __is_pair
61#include <bits/unicode.h> // __is_scalar_value, _Utf_view, etc.
62#include <bits/utility.h> // tuple_size_v
63#include <ext/numeric_traits.h> // __int_traits
65#if !__has_builtin(__builtin_toupper)
69#pragma GCC diagnostic push
70#pragma GCC diagnostic ignored "-Wpedantic" // __int128
71#pragma GCC diagnostic ignored "-Wc++23-extensions" // bf16
73namespace std _GLIBCXX_VISIBILITY(default)
75_GLIBCXX_BEGIN_NAMESPACE_VERSION
77 // [format.fmt.string], class template basic_format_string
78 template<typename _CharT, typename... _Args> struct basic_format_string;
83 // STATICALLY-WIDEN, see C++20 [time.general]
84 // It doesn't matter for format strings (which can only be char or wchar_t)
85 // but this returns the narrow string for anything that isn't wchar_t. This
86 // is done because const char* can be inserted into any ostream type, and
87 // will be widened at runtime if necessary.
88 template<typename _CharT>
90 _Widen(const char* __narrow, const wchar_t* __wide)
92 if constexpr (is_same_v<_CharT, wchar_t>)
97#define _GLIBCXX_WIDEN_(C, S) ::std::__format::_Widen<C>(S, L##S)
98#define _GLIBCXX_WIDEN(S) _GLIBCXX_WIDEN_(_CharT, S)
100 // Size for stack located buffer
101 template<typename _CharT>
102 constexpr size_t __stackbuf_size = 32 * sizeof(void*) / sizeof(_CharT);
104 // Type-erased character sinks.
105 template<typename _CharT> class _Sink;
106 template<typename _CharT> class _Fixedbuf_sink;
107 template<typename _Out, typename _CharT> class _Padding_sink;
109 // Output iterator that writes to a type-erase character sink.
110 template<typename _CharT>
113 // An unspecified output iterator type used in the `formattable` concept.
114 template<typename _CharT>
116 { using type = back_insert_iterator<basic_string<_CharT>>; };
118 template<typename _CharT>
119 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
121 template<typename _CharT>
122 struct _Runtime_format_string
124 [[__gnu__::__always_inline__]]
125 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
128 _Runtime_format_string(const _Runtime_format_string&) = delete;
129 void operator=(const _Runtime_format_string&) = delete;
132 basic_string_view<_CharT> _M_str;
134 template<typename, typename...> friend struct std::basic_format_string;
137} // namespace __format
140 using format_context = __format::__format_context<char>;
141#ifdef _GLIBCXX_USE_WCHAR_T
142 using wformat_context = __format::__format_context<wchar_t>;
145 // [format.args], class template basic_format_args
146 template<typename _Context> class basic_format_args;
147 using format_args = basic_format_args<format_context>;
148#ifdef _GLIBCXX_USE_WCHAR_T
149 using wformat_args = basic_format_args<wformat_context>;
152 // [format.arguments], arguments
153 // [format.arg], class template basic_format_arg
154 template<typename _Context>
155 class basic_format_arg;
157 /** A compile-time checked format string for the specified argument types.
159 * @since C++23 but available as an extension in C++20.
161 template<typename _CharT, typename... _Args>
162 struct basic_format_string
164 template<typename _Tp>
165 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
167 basic_format_string(const _Tp& __s);
169 [[__gnu__::__always_inline__]]
170 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
174 [[__gnu__::__always_inline__]]
175 constexpr basic_string_view<_CharT>
180 basic_string_view<_CharT> _M_str;
183 template<typename... _Args>
184 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
186#ifdef _GLIBCXX_USE_WCHAR_T
187 template<typename... _Args>
189 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
192#if __cpp_lib_format >= 202311L // >= C++26
193 [[__gnu__::__always_inline__]]
194 inline __format::_Runtime_format_string<char>
195 runtime_format(string_view __fmt) noexcept
198#ifdef _GLIBCXX_USE_WCHAR_T
199 [[__gnu__::__always_inline__]]
200 inline __format::_Runtime_format_string<wchar_t>
201 runtime_format(wstring_view __fmt) noexcept
206 // [format.formatter], formatter
208 /// The primary template of std::formatter is disabled.
209 template<typename _Tp, typename _CharT>
212 formatter() = delete; // No std::formatter specialization for this type.
213 formatter(const formatter&) = delete;
214 formatter& operator=(const formatter&) = delete;
217 // [format.error], class format_error
218 class format_error : public runtime_error
221 explicit format_error(const string& __what) : runtime_error(__what) { }
222 explicit format_error(const char* __what) : runtime_error(__what) { }
225 /// @cond undocumented
228 __throw_format_error(const char* __what)
229 { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
233 // XXX use named functions for each constexpr error?
237 __unmatched_left_brace_in_format_string()
238 { __throw_format_error("format error: unmatched '{' in format string"); }
242 __unmatched_right_brace_in_format_string()
243 { __throw_format_error("format error: unmatched '}' in format string"); }
247 __conflicting_indexing_in_format_string()
248 { __throw_format_error("format error: conflicting indexing style in format string"); }
252 __invalid_arg_id_in_format_string()
253 { __throw_format_error("format error: invalid arg-id in format string"); }
257 __failed_to_parse_format_spec()
258 { __throw_format_error("format error: failed to parse format-spec"); }
260 template<typename _CharT> class _Scanner;
262} // namespace __format
265 // [format.parse.ctx], class template basic_format_parse_context
266 template<typename _CharT> class basic_format_parse_context;
267 using format_parse_context = basic_format_parse_context<char>;
268#ifdef _GLIBCXX_USE_WCHAR_T
269 using wformat_parse_context = basic_format_parse_context<wchar_t>;
272 template<typename _CharT>
273 class basic_format_parse_context
276 using char_type = _CharT;
277 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
278 using iterator = const_iterator;
281 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
282 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
285 basic_format_parse_context(const basic_format_parse_context&) = delete;
286 void operator=(const basic_format_parse_context&) = delete;
288 constexpr const_iterator begin() const noexcept { return _M_begin; }
289 constexpr const_iterator end() const noexcept { return _M_end; }
292 advance_to(const_iterator __it) noexcept
298 if (_M_indexing == _Manual)
299 __format::__conflicting_indexing_in_format_string();
302 // _GLIBCXX_RESOLVE_LIB_DEFECTS
303 // 3825. Missing compile-time argument id check in next_arg_id
304 if (std::is_constant_evaluated())
305 if (_M_next_arg_id == _M_num_args)
306 __format::__invalid_arg_id_in_format_string();
307 return _M_next_arg_id++;
311 check_arg_id(size_t __id)
313 if (_M_indexing == _Auto)
314 __format::__conflicting_indexing_in_format_string();
315 _M_indexing = _Manual;
317 if (std::is_constant_evaluated())
318 if (__id >= _M_num_args)
319 __format::__invalid_arg_id_in_format_string();
322#if __cpp_lib_format >= 202305L
323 template<typename... _Ts>
325 check_dynamic_spec(size_t __id) noexcept
327 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
328 "template arguments for check_dynamic_spec<Ts...>(id) "
329 "must be unique and must be one of the allowed types");
331 __check_dynamic_spec<_Ts...>(__id);
336 check_dynamic_spec_integral(size_t __id) noexcept
339 __check_dynamic_spec<int, unsigned, long long,
340 unsigned long long>(__id);
345 check_dynamic_spec_string(size_t __id) noexcept
348 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
353 // True if _Tp occurs exactly once in _Ts.
354 template<typename _Tp, typename... _Ts>
355 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
357 template<typename... _Ts>
359 __valid_types_for_check_dynamic_spec()
361 // _GLIBCXX_RESOLVE_LIB_DEFECTS
362 // 4142. check_dynamic_spec should require at least one type
363 if constexpr (sizeof...(_Ts) == 0)
367 // The types in Ts... are unique. Each type in Ts... is one of
368 // bool, char_type, int, unsigned int, long long int,
369 // unsigned long long int, float, double, long double,
370 // const char_type*, basic_string_view<char_type>, or const void*.
372 = __once<bool, _Ts...>
373 + __once<char_type, _Ts...>
374 + __once<int, _Ts...>
375 + __once<unsigned int, _Ts...>
376 + __once<long long int, _Ts...>
377 + __once<unsigned long long int, _Ts...>
378 + __once<float, _Ts...>
379 + __once<double, _Ts...>
380 + __once<long double, _Ts...>
381 + __once<const char_type*, _Ts...>
382 + __once<basic_string_view<char_type>, _Ts...>
383 + __once<const void*, _Ts...>;
384 return __sum == sizeof...(_Ts);
388 template<typename... _Ts>
390 __check_dynamic_spec(size_t __id) noexcept;
392 // This must not be constexpr.
393 static void __invalid_dynamic_spec(const char*);
395 friend __format::_Scanner<_CharT>;
398 // This constructor should only be used by the implementation.
400 basic_format_parse_context(basic_string_view<_CharT> __fmt,
401 size_t __num_args) noexcept
402 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
408 enum _Indexing { _Unknown, _Manual, _Auto };
409 _Indexing _M_indexing = _Unknown;
410 size_t _M_next_arg_id = 0;
411 size_t _M_num_args = 0;
414/// @cond undocumented
415 template<typename _Tp, template<typename...> class _Class>
416 constexpr bool __is_specialization_of = false;
417 template<template<typename...> class _Class, typename... _Args>
418 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
422 // pre: first != last
423 template<typename _CharT>
424 constexpr pair<unsigned short, const _CharT*>
425 __parse_integer(const _CharT* __first, const _CharT* __last)
427 if (__first == __last)
428 __builtin_unreachable();
430 if constexpr (is_same_v<_CharT, char>)
432 const auto __start = __first;
433 unsigned short __val = 0;
434 // N.B. std::from_chars is not constexpr in C++20.
435 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
436 && __first != __start) [[likely]]
437 return {__val, __first};
441 constexpr int __n = 32;
443 for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
444 __buf[__i] = __first[__i];
445 auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
446 if (__ptr) [[likely]]
447 return {__v, __first + (__ptr - __buf)};
452 template<typename _CharT>
453 constexpr pair<unsigned short, const _CharT*>
454 __parse_arg_id(const _CharT* __first, const _CharT* __last)
456 if (__first == __last)
457 __builtin_unreachable();
460 return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
462 if ('1' <= *__first && *__first <= '9')
464 const unsigned short __id = *__first - '0';
465 const auto __next = __first + 1;
466 // Optimize for most likely case of single digit arg-id.
467 if (__next == __last || !('0' <= *__next && *__next <= '9'))
468 return {__id, __next};
470 return __format::__parse_integer(__first, __last);
475 enum class _Pres_type : unsigned char {
476 _Pres_none = 0, // Default type (not valid for integer presentation types).
477 _Pres_s = 1, // For strings, bool, ranges
478 // Presentation types for integral types (including bool and charT).
479 _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
480 // Presentation types for floating-point types
481 _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
482 // For pointers, the value are same as hexadecimal presentations for integers
483 _Pres_p = _Pres_x, _Pres_P = _Pres_X,
486 using enum _Pres_type;
488 enum class _Sign : unsigned char {
491 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
496 enum _WidthPrec : unsigned char {
497 _WP_none, // No width/prec specified.
498 _WP_value, // Fixed width/prec specified.
499 _WP_from_arg // Use a formatting argument for width/prec.
501 using enum _WidthPrec;
503 template<typename _Context>
505 __int_from_arg(const basic_format_arg<_Context>& __arg);
507 constexpr bool __is_digit(char __c)
508 { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
510 constexpr bool __is_xdigit(char __c)
511 { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
513 // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
514 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
518 template<typename _CharT>
519 struct _Spec : _SpecBase
521 unsigned short _M_width;
522 unsigned short _M_prec;
523 char32_t _M_fill = ' ';
527 unsigned _M_localized : 1;
528 unsigned _M_zero_fill : 1;
529 _WidthPrec _M_width_kind : 2;
530 _WidthPrec _M_prec_kind : 2;
531 unsigned _M_debug : 1;
532 _Pres_type _M_type : 4;
533 unsigned _M_reserved : 8;
534 // This class has 8 bits of tail padding, that can be used by
537 using iterator = typename basic_string_view<_CharT>::iterator;
539 static constexpr _Align
540 _S_align(_CharT __c) noexcept
544 case '<': return _Align_left;
545 case '>': return _Align_right;
546 case '^': return _Align_centre;
547 default: return _Align_default;
551 // pre: __first != __last
553 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
554 { return _M_parse_fill_and_align(__first, __last, "{"); }
556 // pre: __first != __last
558 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
560 for (char __c : __not_fill)
561 if (*__first == static_cast<_CharT>(__c))
564 using namespace __unicode;
565 if constexpr (__literal_encoding_is_unicode<_CharT>())
567 // Accept any UCS scalar value as fill character.
568 _Utf32_view<ranges::subrange<iterator>> __uv({__first, __last});
571 auto __beg = __uv.begin();
572 char32_t __c = *__beg++;
573 if (__is_scalar_value(__c))
574 if (auto __next = __beg.base(); __next != __last)
575 if (_Align __align = _S_align(*__next); __align != _Align_default)
583 else if (__last - __first >= 2)
584 if (_Align __align = _S_align(__first[1]); __align != _Align_default)
591 if (_Align __align = _S_align(__first[0]); __align != _Align_default)
600 static constexpr _Sign
601 _S_sign(_CharT __c) noexcept
605 case '+': return _Sign_plus;
606 case '-': return _Sign_minus;
607 case ' ': return _Sign_space;
608 default: return _Sign_default;
612 // pre: __first != __last
614 _M_parse_sign(iterator __first, iterator) noexcept
616 if (_Sign __sign = _S_sign(*__first); __sign != _Sign_default)
624 // pre: *__first is valid
626 _M_parse_alternate_form(iterator __first, iterator) noexcept
636 // pre: __first != __last
638 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
648 // pre: __first != __last
649 static constexpr iterator
650 _S_parse_width_or_precision(iterator __first, iterator __last,
651 unsigned short& __val, bool& __arg_id,
652 basic_format_parse_context<_CharT>& __pc)
654 if (__format::__is_digit(*__first))
656 auto [__v, __ptr] = __format::__parse_integer(__first, __last);
658 __throw_format_error("format error: invalid width or precision "
663 else if (*__first == '{')
667 if (__first == __last)
668 __format::__unmatched_left_brace_in_format_string();
670 __val = __pc.next_arg_id();
673 auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
674 if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
675 __format::__invalid_arg_id_in_format_string();
677 __pc.check_arg_id(__v);
680#if __cpp_lib_format >= 202305L
681 __pc.check_dynamic_spec_integral(__val);
683 ++__first; // past the '}'
688 // pre: __first != __last
690 _M_parse_width(iterator __first, iterator __last,
691 basic_format_parse_context<_CharT>& __pc)
693 bool __arg_id = false;
695 __throw_format_error("format error: width must be non-zero in "
697 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
699 if (__next != __first)
700 _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
704 // pre: __first != __last
706 _M_parse_precision(iterator __first, iterator __last,
707 basic_format_parse_context<_CharT>& __pc)
709 if (__first[0] != '.')
712 iterator __next = ++__first;
713 bool __arg_id = false;
714 if (__next != __last)
715 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
717 if (__next == __first)
718 __throw_format_error("format error: missing precision after '.' in "
720 _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
724 // pre: __first != __last
726 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
736 template<typename _Context>
738 _M_get_width(_Context& __ctx) const
741 if (_M_width_kind == _WP_value)
743 else if (_M_width_kind == _WP_from_arg)
744 __width = __format::__int_from_arg(__ctx.arg(_M_width));
748 template<typename _Context>
750 _M_get_precision(_Context& __ctx) const
753 if (_M_prec_kind == _WP_value)
755 else if (_M_prec_kind == _WP_from_arg)
756 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
761 template<typename _Int>
763 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
767 else if (__sign == _Sign_plus)
769 else if (__sign == _Sign_space)
776 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
777 template<typename _Out, typename _CharT>
778 requires output_iterator<_Out, const _CharT&>
780 __write(_Out __out, basic_string_view<_CharT> __str)
782 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
788 for (_CharT __c : __str)
793 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
794 // pre: __align != _Align_default
795 template<typename _Out, typename _CharT>
797 __write_padded(_Out __out, basic_string_view<_CharT> __str,
798 _Align __align, size_t __nfill, char32_t __fill_char)
800 const size_t __buflen = 0x20;
801 _CharT __padding_chars[__buflen];
802 __padding_chars[0] = _CharT();
803 basic_string_view<_CharT> __padding{__padding_chars, __buflen};
805 auto __pad = [&__padding] (size_t __n, _Out& __o) {
808 while (__n > __padding.size())
810 __o = __format::__write(std::move(__o), __padding);
811 __n -= __padding.size();
814 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
817 size_t __l, __r, __max;
818 if (__align == _Align_centre)
821 __r = __l + (__nfill & 1);
824 else if (__align == _Align_right)
837 using namespace __unicode;
838 if constexpr (__literal_encoding_is_unicode<_CharT>())
839 if (!__is_single_code_unit<_CharT>(__fill_char)) [[unlikely]]
841 // Encode fill char as multiple code units of type _CharT.
842 const char32_t __arr[1]{ __fill_char };
843 _Utf_view<_CharT, const char32_t(&)[1]> __v(__arr);
844 basic_string<_CharT> __padstr(__v.begin(), __v.end());
845 __padding = __padstr;
847 __out = __format::__write(std::move(__out), __padding);
848 __out = __format::__write(std::move(__out), __str);
850 __out = __format::__write(std::move(__out), __padding);
854 if (__max < __buflen)
855 __padding.remove_suffix(__buflen - __max);
859 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
861 __out = __format::__write(std::move(__out), __str);
867 // Write STR to OUT, with alignment and padding as determined by SPEC.
868 // pre: __spec._M_align != _Align_default || __align != _Align_default
869 template<typename _CharT, typename _Out>
871 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
872 size_t __estimated_width,
873 basic_format_context<_Out, _CharT>& __fc,
874 const _Spec<_CharT>& __spec,
875 _Align __align = _Align_left)
877 size_t __width = __spec._M_get_width(__fc);
879 if (__width <= __estimated_width)
880 return __format::__write(__fc.out(), __str);
882 const size_t __nfill = __width - __estimated_width;
884 if (__spec._M_align != _Align_default)
885 __align = __spec._M_align;
887 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
891 template<typename _CharT>
893 __truncate(basic_string_view<_CharT>& __s, size_t __prec)
895 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
897 if (__prec != (size_t)-1)
898 return __unicode::__truncate(__s, __prec);
900 return __unicode::__field_width(__s);
904 __s = __s.substr(0, __prec);
909 enum class _Term_char : unsigned char {
914 using enum _Term_char;
916 template<typename _CharT>
919 using _Str_view = basic_string_view<_CharT>;
923 { return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\"'\\'\\u\\x"); }
927 { return _S_all().substr(0, 3); }
930 _Str_view _S_newline()
931 { return _S_all().substr(3, 3); }
934 _Str_view _S_return()
935 { return _S_all().substr(6, 3); }
938 _Str_view _S_bslash()
939 { return _S_all().substr(9, 3); }
943 { return _S_all().substr(12, 3); }
947 { return _S_all().substr(15, 3); }
951 { return _S_all().substr(18, 2); }
955 { return _S_all().substr(20, 2); }
958 _Str_view _S_term(_Term_char __term)
965 return _S_quote().substr(0, 1);
967 return _S_apos().substr(0, 1);
969 __builtin_unreachable();
973 template<typename _CharT>
976 using _Str_view = basic_string_view<_CharT>;
980 { return _GLIBCXX_WIDEN("[]{}(), : "); }
983 _Str_view _S_squares()
984 { return _S_all().substr(0, 2); }
987 _Str_view _S_braces()
988 { return _S_all().substr(2, 2); }
991 _Str_view _S_parens()
992 { return _S_all().substr(4, 2); }
996 { return _S_all().substr(6, 2); }
1000 { return _S_all().substr(8, 2); }
1003 template<typename _CharT>
1004 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1006 using _Esc = _Escapes<_CharT>;
1009 case _Esc::_S_tab()[0]:
1010 case _Esc::_S_newline()[0]:
1011 case _Esc::_S_return()[0]:
1012 case _Esc::_S_bslash()[0]:
1014 case _Esc::_S_quote()[0]:
1015 return __term == _Term_quote;
1016 case _Esc::_S_apos()[0]:
1017 return __term == _Term_apos;
1019 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1023 // @pre __c <= 0x10FFFF
1024 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1026 if (__unicode::__should_escape_category(__c))
1030 return __unicode::__grapheme_cluster_break_property(__c)
1031 == __unicode::_Gcb_property::_Gcb_Extend;
1034 using uint_least32_t = __UINT_LEAST32_TYPE__;
1035 template<typename _Out, typename _CharT>
1037 __write_escape_seq(_Out __out, uint_least32_t __val,
1038 basic_string_view<_CharT> __prefix)
1040 using _Str_view = basic_string_view<_CharT>;
1041 constexpr size_t __max = 8;
1043 const string_view __narrow(
1045 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1047 __out = __format::__write(__out, __prefix);
1048 *__out = _Separators<_CharT>::_S_braces()[0];
1050 if constexpr (is_same_v<char, _CharT>)
1051 __out = __format::__write(__out, __narrow);
1052#ifdef _GLIBCXX_USE_WCHAR_T
1055 _CharT __wbuf[__max];
1056 const size_t __n = __narrow.size();
1057 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1058 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1061 *__out = _Separators<_CharT>::_S_braces()[1];
1065 template<typename _Out, typename _CharT>
1067 __write_escaped_char(_Out __out, _CharT __c)
1069 using _UChar = make_unsigned_t<_CharT>;
1070 using _Esc = _Escapes<_CharT>;
1073 case _Esc::_S_tab()[0]:
1074 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1075 case _Esc::_S_newline()[0]:
1076 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1077 case _Esc::_S_return()[0]:
1078 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1079 case _Esc::_S_bslash()[0]:
1080 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1081 case _Esc::_S_quote()[0]:
1082 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1083 case _Esc::_S_apos()[0]:
1084 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1086 return __format::__write_escape_seq(
1087 __out, static_cast<_UChar>(__c), _Esc::_S_u());
1091 template<typename _CharT, typename _Out>
1093 __write_escaped_ascii(_Out __out,
1094 basic_string_view<_CharT> __str,
1097 using _Str_view = basic_string_view<_CharT>;
1098 auto __first = __str.begin();
1099 auto const __last = __str.end();
1100 while (__first != __last)
1102 auto __print = __first;
1103 // assume anything outside ASCII is printable
1104 while (__print != __last
1105 && !__format::__should_escape_ascii(*__print, __term))
1108 if (__print != __first)
1109 __out = __format::__write(__out, _Str_view(__first, __print));
1111 if (__print == __last)
1115 __out = __format::__write_escaped_char(__out, *__first);
1121 template<typename _CharT, typename _Out>
1123 __write_escaped_unicode(_Out __out,
1124 basic_string_view<_CharT> __str,
1127 using _Str_view = basic_string_view<_CharT>;
1128 using _UChar = make_unsigned_t<_CharT>;
1129 using _Esc = _Escapes<_CharT>;
1131 static constexpr char32_t __replace = U'\uFFFD';
1132 static constexpr _Str_view __replace_rep = []
1134 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1135 if constexpr (is_same_v<char, _CharT>)
1136 return "\xEF\xBF\xBD";
1141 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1142 auto __first = __v.begin();
1143 auto const __last = __v.end();
1145 bool __prev_esc = true;
1146 while (__first != __last)
1148 bool __esc_ascii = false;
1149 bool __esc_unicode = false;
1150 bool __esc_replace = false;
1151 auto __should_escape = [&](auto const& __it)
1155 = __format::__should_escape_ascii(*__it.base(), __term);
1156 if (__format::__should_escape_unicode(*__it, __prev_esc))
1157 return __esc_unicode = true;
1158 if (*__it == __replace)
1160 _Str_view __units(__it.base(), __it._M_units());
1161 return __esc_replace = (__units != __replace_rep);
1166 auto __print = __first;
1167 while (__print != __last && !__should_escape(__print))
1173 if (__print != __first)
1174 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1176 if (__print == __last)
1181 __out = __format::__write_escaped_char(__out, *__first.base());
1182 else if (__esc_unicode)
1183 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1184 else // __esc_replace
1185 for (_CharT __c : _Str_view(__first.base(), __first._M_units()))
1186 __out = __format::__write_escape_seq(__out,
1187 static_cast<_UChar>(__c),
1196 template<typename _CharT, typename _Out>
1198 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1200 __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1202 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1203 __out = __format::__write_escaped_unicode(__out, __str, __term);
1204 else if constexpr (is_same_v<char, _CharT>
1205 && __unicode::__literal_encoding_is_extended_ascii())
1206 __out = __format::__write_escaped_ascii(__out, __str, __term);
1208 // TODO Handle non-ascii extended encoding
1209 __out = __format::__write_escaped_ascii(__out, __str, __term);
1211 return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1214 // A lightweight optional<locale>.
1215 struct _Optional_locale
1217 [[__gnu__::__always_inline__]]
1218 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1220 _Optional_locale(const locale& __loc) noexcept
1221 : _M_loc(__loc), _M_hasval(true)
1224 _Optional_locale(const _Optional_locale& __l) noexcept
1225 : _M_dummy(), _M_hasval(__l._M_hasval)
1228 std::construct_at(&_M_loc, __l._M_loc);
1232 operator=(const _Optional_locale& __l) noexcept
1237 _M_loc = __l._M_loc;
1244 else if (__l._M_hasval)
1246 std::construct_at(&_M_loc, __l._M_loc);
1252 ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
1255 operator=(locale&& __loc) noexcept
1258 _M_loc = std::move(__loc);
1261 std::construct_at(&_M_loc, std::move(__loc));
1272 std::construct_at(&_M_loc);
1278 bool has_value() const noexcept { return _M_hasval; }
1281 char _M_dummy = '\0';
1284 bool _M_hasval = false;
1287 template<__char _CharT>
1288 struct __formatter_str
1290 __formatter_str() = default;
1293 __formatter_str(_Spec<_CharT> __spec) noexcept
1297 constexpr typename basic_format_parse_context<_CharT>::iterator
1298 parse(basic_format_parse_context<_CharT>& __pc)
1300 auto __first = __pc.begin();
1301 const auto __last = __pc.end();
1302 _Spec<_CharT> __spec{};
1304 auto __finalize = [this, &__spec] {
1308 auto __finished = [&] {
1309 if (__first == __last || *__first == '}')
1320 __first = __spec._M_parse_fill_and_align(__first, __last);
1324 __first = __spec._M_parse_width(__first, __last, __pc);
1328 __first = __spec._M_parse_precision(__first, __last, __pc);
1332 if (*__first == 's')
1334 __spec._M_type = _Pres_s;
1337#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1338 else if (*__first == '?')
1340 __spec._M_debug = true;
1348 __format::__failed_to_parse_format_spec();
1351 template<typename _Out>
1353 format(basic_string_view<_CharT> __s,
1354 basic_format_context<_Out, _CharT>& __fc) const
1356 if (_M_spec._M_debug)
1357 return _M_format_escaped(__s, __fc);
1359 if (_M_spec._M_width_kind == _WP_none
1360 && _M_spec._M_prec_kind == _WP_none)
1361 return __format::__write(__fc.out(), __s);
1363 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1364 const size_t __width = __format::__truncate(__s, __maxwidth);
1365 return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1368 template<typename _Out>
1370 _M_format_escaped(basic_string_view<_CharT> __s,
1371 basic_format_context<_Out, _CharT>& __fc) const
1373 const size_t __padwidth = _M_spec._M_get_width(__fc);
1374 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1375 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1377 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1378 const size_t __width = __truncate(__s, __maxwidth);
1379 // N.B. Escaping only increases width
1380 if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1381 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1383 // N.B. [tab:format.type.string] defines '?' as
1384 // Copies the escaped string ([format.string.escaped]) to the output,
1385 // so precision seem to appy to escaped string.
1386 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1387 __format::__write_escaped(__sink.out(), __s, _Term_quote);
1388 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1391#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1392 template<ranges::input_range _Rg, typename _Out>
1393 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1395 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1397 using _Range = remove_reference_t<_Rg>;
1398 using _String = basic_string<_CharT>;
1399 using _String_view = basic_string_view<_CharT>;
1400 if constexpr (!is_lvalue_reference_v<_Rg>)
1401 return _M_format_range<_Range&>(__rg, __fc);
1402 else if constexpr (!is_const_v<_Range>
1403 && __simply_formattable_range<_Range, _CharT>)
1404 return _M_format_range<const _Range&>(__rg, __fc);
1405 else if constexpr (ranges::contiguous_range<_Rg>)
1407 _String_view __str(ranges::data(__rg),
1408 size_t(ranges::distance(__rg)));
1409 return format(__str, __fc);
1411 else if (!_M_spec._M_debug)
1413 const size_t __padwidth = _M_spec._M_get_width(__fc);
1414 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1415 return ranges::copy(__rg, __fc.out()).out;
1417 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth,
1418 _M_spec._M_get_precision(__fc));
1419 ranges::copy(__rg, __sink.out());
1420 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1422 else if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
1424 const size_t __n(ranges::distance(__rg));
1426 if constexpr (!__unicode::__literal_encoding_is_unicode<_CharT>())
1427 if (size_t __max = _M_spec._M_get_precision(__fc); __n > __max)
1430 if (__w <= __format::__stackbuf_size<_CharT>)
1432 _CharT __buf[__format::__stackbuf_size<_CharT>];
1433 ranges::copy_n(ranges::begin(__rg), __w, __buf);
1434 return _M_format_escaped(_String_view(__buf, __n), __fc);
1436 else if constexpr (ranges::random_access_range<_Rg>)
1438 ranges::iterator_t<_Rg> __first = ranges::begin(__rg);
1439 ranges::subrange __sub(__first, __first + __w);
1440 return _M_format_escaped(_String(from_range, __sub), __fc);
1442 else if (__w <= __n)
1444 ranges::subrange __sub(
1445 counted_iterator(ranges::begin(__rg), __w),
1447 return _M_format_escaped(_String(from_range, __sub), __fc);
1449 else if constexpr (ranges::sized_range<_Rg>)
1450 return _M_format_escaped(_String(from_range, __rg), __fc);
1453 // N.B. preserve the computed size
1454 ranges::subrange __sub(__rg, __n);
1455 return _M_format_escaped(_String(from_range, __sub), __fc);
1459 return _M_format_escaped(_String(from_range, __rg), __fc);
1463 set_debug_format() noexcept
1464 { _M_spec._M_debug = true; }
1468 _Spec<_CharT> _M_spec{};
1471 template<__char _CharT>
1472 struct __formatter_int
1474 // If no presentation type is specified, meaning of "none" depends
1475 // whether we are formatting an integer or a char or a bool.
1476 static constexpr _Pres_type _AsInteger = _Pres_d;
1477 static constexpr _Pres_type _AsBool = _Pres_s;
1478 static constexpr _Pres_type _AsChar = _Pres_c;
1480 __formatter_int() = default;
1483 __formatter_int(_Spec<_CharT> __spec) noexcept
1486 if (_M_spec._M_type == _Pres_none)
1487 _M_spec._M_type = _Pres_d;
1490 constexpr typename basic_format_parse_context<_CharT>::iterator
1491 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1493 _Spec<_CharT> __spec{};
1494 __spec._M_type = __type;
1496 const auto __last = __pc.end();
1497 auto __first = __pc.begin();
1499 auto __finalize = [this, &__spec] {
1503 auto __finished = [&] {
1504 if (__first == __last || *__first == '}')
1515 __first = __spec._M_parse_fill_and_align(__first, __last);
1519 __first = __spec._M_parse_sign(__first, __last);
1523 __first = __spec._M_parse_alternate_form(__first, __last);
1527 __first = __spec._M_parse_zero_fill(__first, __last);
1531 __first = __spec._M_parse_width(__first, __last, __pc);
1535 __first = __spec._M_parse_locale(__first, __last);
1542 __spec._M_type = _Pres_b;
1546 __spec._M_type = _Pres_B;
1550 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1551 // 3586. format should not print bool with 'c'
1552 if (__type != _AsBool)
1554 __spec._M_type = _Pres_c;
1559 __spec._M_type = _Pres_d;
1563 __spec._M_type = _Pres_o;
1567 __spec._M_type = _Pres_x;
1571 __spec._M_type = _Pres_X;
1575 if (__type == _AsBool)
1577 __spec._M_type = _Pres_s; // same meaning as "none" for bool
1581#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1583 if (__type == _AsChar)
1585 __spec._M_debug = true;
1595 __format::__failed_to_parse_format_spec();
1598 template<typename _Tp>
1599 constexpr typename basic_format_parse_context<_CharT>::iterator
1600 _M_parse(basic_format_parse_context<_CharT>& __pc)
1602 if constexpr (is_same_v<_Tp, bool>)
1604 auto __end = _M_do_parse(__pc, _AsBool);
1605 if (_M_spec._M_type == _Pres_s)
1606 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1607 || _M_spec._M_zero_fill)
1608 __throw_format_error("format error: format-spec contains "
1609 "invalid formatting options for "
1613 else if constexpr (__char<_Tp>)
1615 auto __end = _M_do_parse(__pc, _AsChar);
1616 if (_M_spec._M_type == _Pres_c)
1617 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1618 || _M_spec._M_zero_fill
1619 /* XXX should be invalid? || _M_spec._M_localized */)
1620 __throw_format_error("format error: format-spec contains "
1621 "invalid formatting options for "
1626 return _M_do_parse(__pc, _AsInteger);
1629 template<typename _Int, typename _Out>
1630 typename basic_format_context<_Out, _CharT>::iterator
1631 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1633 if (_M_spec._M_type == _Pres_c)
1634 return _M_format_character(_S_to_character(__i), __fc);
1636 char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
1637 to_chars_result __res{};
1639 string_view __base_prefix;
1640 make_unsigned_t<_Int> __u;
1642 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1646 char* __start = __buf + 3;
1647 char* const __end = __buf + sizeof(__buf);
1648 char* const __start_digits = __start;
1650 switch (_M_spec._M_type)
1654 __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
1655 __res = to_chars(__start, __end, __u, 2);
1659 return _M_format_character(_S_to_character(__i), __fc);
1662 // Should not reach here with _Pres_none for bool or charT, so:
1665 __res = to_chars(__start, __end, __u, 10);
1669 __base_prefix = "0";
1670 __res = to_chars(__start, __end, __u, 8);
1674 __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
1675 __res = to_chars(__start, __end, __u, 16);
1676 if (_M_spec._M_type == _Pres_X)
1677 for (auto __p = __start; __p != __res.ptr; ++__p)
1678#if __has_builtin(__builtin_toupper)
1679 *__p = __builtin_toupper(*__p);
1681 *__p = std::toupper(*__p);
1685 __builtin_unreachable();
1688 if (_M_spec._M_alt && __base_prefix.size())
1690 __start -= __base_prefix.size();
1691 __builtin_memcpy(__start, __base_prefix.data(),
1692 __base_prefix.size());
1694 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1696 return _M_format_int(string_view(__start, __res.ptr - __start),
1697 __start_digits - __start, __fc);
1700 template<typename _Out>
1701 typename basic_format_context<_Out, _CharT>::iterator
1702 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1704 if (_M_spec._M_type == _Pres_c)
1705 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1706 if (_M_spec._M_type != _Pres_s)
1707 return format(static_cast<unsigned char>(__i), __fc);
1709 basic_string<_CharT> __s;
1711 if (_M_spec._M_localized) [[unlikely]]
1713 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1714 __s = __i ? __np.truename() : __np.falsename();
1715 __est_width = __s.size(); // TODO Unicode-aware estimate
1719 if constexpr (is_same_v<char, _CharT>)
1720 __s = __i ? "true" : "false";
1722 __s = __i ? L"true" : L"false";
1723 __est_width = __s.size();
1726 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1730 template<typename _Out>
1731 typename basic_format_context<_Out, _CharT>::iterator
1732 _M_format_character(_CharT __c,
1733 basic_format_context<_Out, _CharT>& __fc) const
1735 basic_string_view<_CharT> __in(&__c, 1u);
1736 size_t __width = 1u;
1737 // N.B. single byte cannot encode character of width greater than 1
1738 if constexpr (sizeof(_CharT) > 1u &&
1739 __unicode::__literal_encoding_is_unicode<_CharT>())
1740 __width = __unicode::__field_width(__c);
1742 if (!_M_spec._M_debug)
1743 return __format::__write_padded_as_spec(__in, __width,
1747 if (_M_spec._M_get_width(__fc) <= __width)
1748 return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1751 _Fixedbuf_sink<_CharT> __sink(__buf);
1752 __format::__write_escaped(__sink.out(), __in, _Term_apos);
1754 __in = __sink.view();
1755 if (__in[1] == _Escapes<_CharT>::_S_bslash()[0]) // escape sequence
1756 __width = __in.size();
1757 return __format::__write_padded_as_spec(__in, __width,
1761 template<typename _Int>
1763 _S_to_character(_Int __i)
1765 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1766 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1768 if (_Traits::__min <= __i && __i <= _Traits::__max)
1769 return static_cast<_CharT>(__i);
1771 else if constexpr (is_signed_v<_Int>)
1773 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1774 return static_cast<_CharT>(__i);
1776 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1777 return static_cast<_CharT>(__i);
1778 __throw_format_error("format error: integer not representable as "
1782 template<typename _Out>
1783 typename basic_format_context<_Out, _CharT>::iterator
1784 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1785 basic_format_context<_Out, _CharT>& __fc) const
1787 size_t __width = _M_spec._M_get_width(__fc);
1789 basic_string_view<_CharT> __str;
1790 if constexpr (is_same_v<char, _CharT>)
1791 __str = __narrow_str;
1792#ifdef _GLIBCXX_USE_WCHAR_T
1795 size_t __n = __narrow_str.size();
1796 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1797 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1802 if (_M_spec._M_localized)
1804 const auto& __l = __fc.locale();
1805 if (__l.name() != "C")
1807 auto& __np = use_facet<numpunct<_CharT>>(__l);
1808 string __grp = __np.grouping();
1811 size_t __n = __str.size() - __prefix_len;
1812 auto __p = (_CharT*)__builtin_alloca(2 * __n
1815 auto __s = __str.data();
1816 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1817 __s += __prefix_len;
1818 auto __end = std::__add_grouping(__p + __prefix_len,
1819 __np.thousands_sep(),
1823 __str = {__p, size_t(__end - __p)};
1828 if (__width <= __str.size())
1829 return __format::__write(__fc.out(), __str);
1831 char32_t __fill_char = _M_spec._M_fill;
1832 _Align __align = _M_spec._M_align;
1834 size_t __nfill = __width - __str.size();
1835 auto __out = __fc.out();
1836 if (__align == _Align_default)
1838 __align = _Align_right;
1839 if (_M_spec._M_zero_fill)
1841 __fill_char = _CharT('0');
1842 // Write sign and base prefix before zero filling.
1843 if (__prefix_len != 0)
1845 __out = __format::__write(std::move(__out),
1846 __str.substr(0, __prefix_len));
1847 __str.remove_prefix(__prefix_len);
1851 __fill_char = _CharT(' ');
1853 return __format::__write_padded(std::move(__out), __str,
1854 __align, __nfill, __fill_char);
1857 _Spec<_CharT> _M_spec{};
1860#ifdef __BFLT16_DIG__
1861 using __bflt16_t = decltype(0.0bf16);
1864 // Decide how 128-bit floating-point types should be formatted (or not).
1865 // When supported, the typedef __format::__flt128_t is the type that format
1866 // arguments should be converted to before passing them to __formatter_fp.
1867 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1868 // The __float128, _Float128 will be formatted by converting them to:
1869 // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1870 // long double when _GLIBCXX_FORMAT_F128=2,
1871 // _Float128 when _GLIBCXX_FORMAT_F128=3.
1872#undef _GLIBCXX_FORMAT_F128
1874#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1876 // Format 128-bit floating-point types using __ieee128.
1877 using __flt128_t = __ieee128;
1878# define _GLIBCXX_FORMAT_F128 1
1880#ifdef __LONG_DOUBLE_IEEE128__
1881 // These overloads exist in the library, but are not declared.
1882 // Make them available as std::__format::to_chars.
1884 to_chars(char*, char*, __ibm128) noexcept
1885 __asm("_ZSt8to_charsPcS_e");
1888 to_chars(char*, char*, __ibm128, chars_format) noexcept
1889 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1892 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1893 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1894#elif __cplusplus == 202002L
1896 to_chars(char*, char*, __ieee128) noexcept
1897 __asm("_ZSt8to_charsPcS_u9__ieee128");
1900 to_chars(char*, char*, __ieee128, chars_format) noexcept
1901 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1904 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1905 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1908#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1910 // Format 128-bit floating-point types using long double.
1911 using __flt128_t = long double;
1912# define _GLIBCXX_FORMAT_F128 2
1914#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1916 // Format 128-bit floating-point types using _Float128.
1917 using __flt128_t = _Float128;
1918# define _GLIBCXX_FORMAT_F128 3
1920# if __cplusplus == 202002L
1921 // These overloads exist in the library, but are not declared for C++20.
1922 // Make them available as std::__format::to_chars.
1924 to_chars(char*, char*, _Float128) noexcept
1925# if _GLIBCXX_INLINE_VERSION
1926 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1928 __asm("_ZSt8to_charsPcS_DF128_");
1932 to_chars(char*, char*, _Float128, chars_format) noexcept
1933# if _GLIBCXX_INLINE_VERSION
1934 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1936 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1940 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1941# if _GLIBCXX_INLINE_VERSION
1942 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1944 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1949 using std::to_chars;
1951 // We can format a floating-point type iff it is usable with to_chars.
1952 template<typename _Tp>
1953 concept __formattable_float
1954 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1955 { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1957 template<__char _CharT>
1958 struct __formatter_fp
1960 constexpr typename basic_format_parse_context<_CharT>::iterator
1961 parse(basic_format_parse_context<_CharT>& __pc)
1963 _Spec<_CharT> __spec{};
1964 const auto __last = __pc.end();
1965 auto __first = __pc.begin();
1967 auto __finalize = [this, &__spec] {
1971 auto __finished = [&] {
1972 if (__first == __last || *__first == '}')
1983 __first = __spec._M_parse_fill_and_align(__first, __last);
1987 __first = __spec._M_parse_sign(__first, __last);
1991 __first = __spec._M_parse_alternate_form(__first, __last);
1995 __first = __spec._M_parse_zero_fill(__first, __last);
1999 if (__first[0] != '.')
2001 __first = __spec._M_parse_width(__first, __last, __pc);
2006 __first = __spec._M_parse_precision(__first, __last, __pc);
2010 __first = __spec._M_parse_locale(__first, __last);
2017 __spec._M_type = _Pres_a;
2021 __spec._M_type = _Pres_A;
2025 __spec._M_type = _Pres_e;
2029 __spec._M_type = _Pres_E;
2033 __spec._M_type = _Pres_f;
2037 __spec._M_type = _Pres_F;
2041 __spec._M_type = _Pres_g;
2045 __spec._M_type = _Pres_G;
2053 __format::__failed_to_parse_format_spec();
2056 template<typename _Fp, typename _Out>
2057 typename basic_format_context<_Out, _CharT>::iterator
2058 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2060 std::string __dynbuf;
2062 to_chars_result __res{};
2065 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2067 __prec = _M_spec._M_get_precision(__fc);
2069 char* __start = __buf + 1; // reserve space for sign
2070 char* __end = __buf + sizeof(__buf);
2072 chars_format __fmt{};
2073 bool __upper = false;
2074 bool __trailing_zeros = false;
2077 switch (_M_spec._M_type)
2084 if (_M_spec._M_type != _Pres_A)
2086 __fmt = chars_format::hex;
2094 __fmt = chars_format::scientific;
2101 __fmt = chars_format::fixed;
2108 __trailing_zeros = true;
2110 __fmt = chars_format::general;
2114 __fmt = chars_format::general;
2117 __builtin_unreachable();
2120 // Write value into buffer using std::to_chars.
2121 auto __to_chars = [&](char* __b, char* __e) {
2123 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2124 else if (__fmt != chars_format{})
2125 return __format::to_chars(__b, __e, __v, __fmt);
2127 return __format::to_chars(__b, __e, __v);
2130 // First try using stack buffer.
2131 __res = __to_chars(__start, __end);
2133 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2135 // If the buffer is too small it's probably because of a large
2136 // precision, or a very large value in fixed format.
2137 size_t __guess = 8 + __prec;
2138 if (__fmt == chars_format::fixed) // +ddd.prec
2140 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2141 || is_same_v<_Fp, long double>)
2143 // The number of digits to the left of the decimal point
2144 // is floor(log10(max(abs(__v),1)))+1
2146 if constexpr (is_same_v<_Fp, float>)
2147 __builtin_frexpf(__v, &__exp);
2148 else if constexpr (is_same_v<_Fp, double>)
2149 __builtin_frexp(__v, &__exp);
2150 else if constexpr (is_same_v<_Fp, long double>)
2151 __builtin_frexpl(__v, &__exp);
2153 __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
2156 __guess += numeric_limits<_Fp>::max_exponent10;
2158 if (__guess <= sizeof(__buf)) [[unlikely]]
2159 __guess = sizeof(__buf) * 2;
2160 __dynbuf.reserve(__guess);
2164 // Mangling of this lambda, and thus resize_and_overwrite
2165 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2166 // <format> was new in G++ 13, and is experimental, that
2168 auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
2170 __res = __to_chars(__p + 1, __p + __n - 1);
2171 return __res.ec == errc{} ? __res.ptr - __p : 0;
2174 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2176 __start = __dynbuf.data() + 1; // reserve space for sign
2177 __end = __dynbuf.data() + __dynbuf.size();
2179 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2182 // Use uppercase for 'A', 'E', and 'G' formats.
2185 for (char* __p = __start; __p != __res.ptr; ++__p)
2186 *__p = std::toupper(*__p);
2189 bool __have_sign = true;
2190 // Add sign for non-negative values.
2191 if (!__builtin_signbit(__v))
2193 if (_M_spec._M_sign == _Sign_plus)
2195 else if (_M_spec._M_sign == _Sign_space)
2198 __have_sign = false;
2201 string_view __narrow_str(__start, __res.ptr - __start);
2203 // Use alternate form. Ensure decimal point is always present,
2204 // and add trailing zeros (up to precision) for g and G forms.
2205 if (_M_spec._M_alt && __builtin_isfinite(__v))
2207 string_view __s = __narrow_str;
2208 size_t __sigfigs; // Number of significant figures.
2209 size_t __z = 0; // Number of trailing zeros to add.
2210 size_t __p; // Position of the exponent character (if any).
2211 size_t __d = __s.find('.'); // Position of decimal point.
2212 if (__d != __s.npos) // Found decimal point.
2214 __p = __s.find(__expc, __d + 1);
2215 if (__p == __s.npos)
2218 // If presentation type is g or G we might need to add zeros.
2219 if (__trailing_zeros)
2221 // Find number of digits after first significant figure.
2222 if (__s[__have_sign] != '0')
2223 // A string like "D.D" or "-D.DDD"
2224 __sigfigs = __p - __have_sign - 1;
2226 // A string like "0.D" or "-0.0DD".
2227 // Safe to assume there is a non-zero digit, because
2228 // otherwise there would be no decimal point.
2229 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2232 else // No decimal point, we need to insert one.
2234 __p = __s.find(__expc); // Find the exponent, if present.
2235 if (__p == __s.npos)
2237 __d = __p; // Position where '.' should be inserted.
2238 __sigfigs = __d - __have_sign;
2241 if (__trailing_zeros && __prec != 0)
2243 // For g and G presentation types std::to_chars produces
2244 // no more than prec significant figures. Insert this many
2245 // zeros so the result has exactly prec significant figures.
2246 __z = __prec - __sigfigs;
2249 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2251 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2253 // The stack buffer is large enough for the result.
2254 // Move exponent to make space for extra chars.
2255 __builtin_memmove(__start + __p + __extras,
2259 __start[__p++] = '.';
2260 __builtin_memset(__start + __p, '0', __z);
2261 __narrow_str = {__s.data(), __s.size() + __extras};
2263 else // Need to switch to the dynamic buffer.
2265 __dynbuf.reserve(__s.size() + __extras);
2266 if (__dynbuf.empty())
2268 __dynbuf = __s.substr(0, __p);
2272 __dynbuf.append(__z, '0');
2273 __dynbuf.append(__s.substr(__p));
2277 __dynbuf.insert(__p, __extras, '0');
2279 __dynbuf[__p] = '.';
2281 __narrow_str = __dynbuf;
2286 basic_string<_CharT> __wstr;
2287 basic_string_view<_CharT> __str;
2288 if constexpr (is_same_v<_CharT, char>)
2289 __str = __narrow_str;
2290#ifdef _GLIBCXX_USE_WCHAR_T
2293 __wstr = std::__to_wstring_numeric(__narrow_str);
2298 if (_M_spec._M_localized && __builtin_isfinite(__v))
2300 auto __s = _M_localize(__str, __expc, __fc.locale());
2302 __str = __wstr = std::move(__s);
2305 size_t __width = _M_spec._M_get_width(__fc);
2307 if (__width <= __str.size())
2308 return __format::__write(__fc.out(), __str);
2310 char32_t __fill_char = _M_spec._M_fill;
2311 _Align __align = _M_spec._M_align;
2313 size_t __nfill = __width - __str.size();
2314 auto __out = __fc.out();
2315 if (__align == _Align_default)
2317 __align = _Align_right;
2318 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2320 __fill_char = _CharT('0');
2321 // Write sign before zero filling.
2322 if (!__format::__is_xdigit(__narrow_str[0]))
2324 *__out++ = __str[0];
2325 __str.remove_prefix(1);
2329 __fill_char = _CharT(' ');
2331 return __format::__write_padded(std::move(__out), __str,
2332 __align, __nfill, __fill_char);
2335 // Locale-specific format.
2336 basic_string<_CharT>
2337 _M_localize(basic_string_view<_CharT> __str, char __expc,
2338 const locale& __loc) const
2340 basic_string<_CharT> __lstr;
2342 if (__loc == locale::classic())
2343 return __lstr; // Nothing to do.
2345 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2346 const _CharT __point = __np.decimal_point();
2347 const string __grp = __np.grouping();
2349 _CharT __dot, __exp;
2350 if constexpr (is_same_v<_CharT, char>)
2373 __builtin_unreachable();
2377 if (__grp.empty() && __point == __dot)
2378 return __lstr; // Locale uses '.' and no grouping.
2380 size_t __d = __str.find(__dot); // Index of radix character (if any).
2381 size_t __e = min(__d, __str.find(__exp)); // First of radix or exponent
2382 if (__e == __str.npos)
2384 const size_t __r = __str.size() - __e; // Length of remainder.
2385 auto __overwrite = [&](_CharT* __p, size_t) {
2386 // Apply grouping to the digits before the radix or exponent.
2388 if (auto __c = __str.front(); __c == '-' || __c == '+' || __c == ' ')
2393 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
2394 __grp.data(), __grp.size(),
2395 __str.data() + __off,
2396 __str.data() + __e);
2397 if (__r) // If there's a fractional part or exponent
2399 if (__d != __str.npos)
2401 *__end = __point; // Add the locale's radix character.
2405 const size_t __rlen = __str.size() - __e;
2406 // Append fractional digits and/or exponent:
2407 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2410 return (__end - __p);
2412 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2416 _Spec<_CharT> _M_spec{};
2419 template<__format::__char _CharT>
2420 struct __formatter_ptr
2422 __formatter_ptr() = default;
2425 __formatter_ptr(_Spec<_CharT> __spec) noexcept
2427 { _M_set_default(_Pres_p); }
2429 constexpr typename basic_format_parse_context<_CharT>::iterator
2430 parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type = _Pres_p)
2432 __format::_Spec<_CharT> __spec{};
2433 const auto __last = __pc.end();
2434 auto __first = __pc.begin();
2436 auto __finalize = [this, &__spec, __type] {
2438 _M_set_default(__type);
2441 auto __finished = [&] {
2442 if (__first == __last || *__first == '}')
2453 __first = __spec._M_parse_fill_and_align(__first, __last);
2457// _GLIBCXX_RESOLVE_LIB_DEFECTS
2458// P2510R3 Formatting pointers
2459#if __glibcxx_format >= 202304L
2460 __first = __spec._M_parse_zero_fill(__first, __last);
2465 __first = __spec._M_parse_width(__first, __last, __pc);
2469 if (*__first == 'p')
2471 __spec._M_type = _Pres_p;
2472 _M_spec._M_alt = !_M_spec._M_alt;
2475#if __glibcxx_format >= 202304L
2476 else if (*__first == 'P')
2478 __spec._M_type = _Pres_P;
2479 _M_spec._M_alt = !_M_spec._M_alt;
2487 __format::__failed_to_parse_format_spec();
2490 template<typename _Out>
2491 typename basic_format_context<_Out, _CharT>::iterator
2492 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2494 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2495 char __buf[2 + sizeof(__v) * 2];
2496 auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
2498 int __n = __ptr - __buf;
2501#if __glibcxx_format >= 202304L
2502 if (_M_spec._M_type == __format::_Pres_P)
2505 for (auto __p = __buf + 2; __p != __ptr; ++__p)
2506#if __has_builtin(__builtin_toupper)
2507 *__p = __builtin_toupper(*__p);
2509 *__p = std::toupper(*__p);
2514 basic_string_view<_CharT> __str;
2515 if constexpr (is_same_v<_CharT, char>)
2516 __str = string_view(__buf, __n);
2517#ifdef _GLIBCXX_USE_WCHAR_T
2520 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2521 std::__to_wstring_numeric(__buf, __n, __p);
2522 __str = wstring_view(__p, __n);
2526#if __glibcxx_format >= 202304L
2527 if (_M_spec._M_zero_fill)
2529 size_t __width = _M_spec._M_get_width(__fc);
2530 if (__width <= __str.size())
2531 return __format::__write(__fc.out(), __str);
2533 auto __out = __fc.out();
2534 // Write "0x" or "0X" prefix before zero-filling.
2535 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2536 __str.remove_prefix(2);
2537 size_t __nfill = __width - __n;
2538 return __format::__write_padded(std::move(__out), __str,
2539 __format::_Align_right,
2540 __nfill, _CharT('0'));
2544 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2545 __format::_Align_right);
2549 [[__gnu__::__always_inline__]]
2551 _M_set_default(_Pres_type __type)
2553 if (_M_spec._M_type == _Pres_none && __type != _Pres_none)
2555 _M_spec._M_type = __type;
2556 _M_spec._M_alt = !_M_spec._M_alt;
2560 __format::_Spec<_CharT> _M_spec{};
2563} // namespace __format
2566 /// Format a character.
2567 template<__format::__char _CharT>
2568 struct formatter<_CharT, _CharT>
2570 formatter() = default;
2572 constexpr typename basic_format_parse_context<_CharT>::iterator
2573 parse(basic_format_parse_context<_CharT>& __pc)
2575 return _M_f.template _M_parse<_CharT>(__pc);
2578 template<typename _Out>
2579 typename basic_format_context<_Out, _CharT>::iterator
2580 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2582 if (_M_f._M_spec._M_type == __format::_Pres_c)
2583 return _M_f._M_format_character(__u, __fc);
2585 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2588#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2590 set_debug_format() noexcept
2591 { _M_f._M_spec._M_debug = true; }
2595 __format::__formatter_int<_CharT> _M_f;
2598#ifdef _GLIBCXX_USE_WCHAR_T
2599 /// Format a char value for wide character output.
2601 struct formatter<char, wchar_t>
2603 formatter() = default;
2605 constexpr typename basic_format_parse_context<wchar_t>::iterator
2606 parse(basic_format_parse_context<wchar_t>& __pc)
2608 return _M_f._M_parse<char>(__pc);
2611 template<typename _Out>
2612 typename basic_format_context<_Out, wchar_t>::iterator
2613 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2615 if (_M_f._M_spec._M_type == __format::_Pres_c)
2616 return _M_f._M_format_character(__u, __fc);
2618 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2621#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2623 set_debug_format() noexcept
2624 { _M_f._M_spec._M_debug = true; }
2628 __format::__formatter_int<wchar_t> _M_f;
2630#endif // USE_WCHAR_T
2632 /** Format a string.
2635 template<__format::__char _CharT>
2636 struct formatter<_CharT*, _CharT>
2638 formatter() = default;
2640 [[__gnu__::__always_inline__]]
2641 constexpr typename basic_format_parse_context<_CharT>::iterator
2642 parse(basic_format_parse_context<_CharT>& __pc)
2643 { return _M_f.parse(__pc); }
2645 template<typename _Out>
2646 [[__gnu__::__nonnull__]]
2647 typename basic_format_context<_Out, _CharT>::iterator
2648 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2649 { return _M_f.format(__u, __fc); }
2651#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2652 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2656 __format::__formatter_str<_CharT> _M_f;
2659 template<__format::__char _CharT>
2660 struct formatter<const _CharT*, _CharT>
2662 formatter() = default;
2664 [[__gnu__::__always_inline__]]
2665 constexpr typename basic_format_parse_context<_CharT>::iterator
2666 parse(basic_format_parse_context<_CharT>& __pc)
2667 { return _M_f.parse(__pc); }
2669 template<typename _Out>
2670 [[__gnu__::__nonnull__]]
2671 typename basic_format_context<_Out, _CharT>::iterator
2672 format(const _CharT* __u,
2673 basic_format_context<_Out, _CharT>& __fc) const
2674 { return _M_f.format(__u, __fc); }
2676#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2677 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2681 __format::__formatter_str<_CharT> _M_f;
2684 template<__format::__char _CharT, size_t _Nm>
2685 struct formatter<_CharT[_Nm], _CharT>
2687 formatter() = default;
2689 [[__gnu__::__always_inline__]]
2690 constexpr typename basic_format_parse_context<_CharT>::iterator
2691 parse(basic_format_parse_context<_CharT>& __pc)
2692 { return _M_f.parse(__pc); }
2694 template<typename _Out>
2695 typename basic_format_context<_Out, _CharT>::iterator
2696 format(const _CharT (&__u)[_Nm],
2697 basic_format_context<_Out, _CharT>& __fc) const
2698 { return _M_f.format({__u, _Nm}, __fc); }
2700#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2701 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2705 __format::__formatter_str<_CharT> _M_f;
2708 template<typename _Traits, typename _Alloc>
2709 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2711 formatter() = default;
2713 [[__gnu__::__always_inline__]]
2714 constexpr typename basic_format_parse_context<char>::iterator
2715 parse(basic_format_parse_context<char>& __pc)
2716 { return _M_f.parse(__pc); }
2718 template<typename _Out>
2719 typename basic_format_context<_Out, char>::iterator
2720 format(const basic_string<char, _Traits, _Alloc>& __u,
2721 basic_format_context<_Out, char>& __fc) const
2722 { return _M_f.format(__u, __fc); }
2724#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2725 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2729 __format::__formatter_str<char> _M_f;
2732#ifdef _GLIBCXX_USE_WCHAR_T
2733 template<typename _Traits, typename _Alloc>
2734 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2736 formatter() = default;
2738 [[__gnu__::__always_inline__]]
2739 constexpr typename basic_format_parse_context<wchar_t>::iterator
2740 parse(basic_format_parse_context<wchar_t>& __pc)
2741 { return _M_f.parse(__pc); }
2743 template<typename _Out>
2744 typename basic_format_context<_Out, wchar_t>::iterator
2745 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2746 basic_format_context<_Out, wchar_t>& __fc) const
2747 { return _M_f.format(__u, __fc); }
2749#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2750 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2754 __format::__formatter_str<wchar_t> _M_f;
2756#endif // USE_WCHAR_T
2758 template<typename _Traits>
2759 struct formatter<basic_string_view<char, _Traits>, char>
2761 formatter() = default;
2763 [[__gnu__::__always_inline__]]
2764 constexpr typename basic_format_parse_context<char>::iterator
2765 parse(basic_format_parse_context<char>& __pc)
2766 { return _M_f.parse(__pc); }
2768 template<typename _Out>
2769 typename basic_format_context<_Out, char>::iterator
2770 format(basic_string_view<char, _Traits> __u,
2771 basic_format_context<_Out, char>& __fc) const
2772 { return _M_f.format(__u, __fc); }
2774#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2775 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2779 __format::__formatter_str<char> _M_f;
2782#ifdef _GLIBCXX_USE_WCHAR_T
2783 template<typename _Traits>
2784 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2786 formatter() = default;
2788 [[__gnu__::__always_inline__]]
2789 constexpr typename basic_format_parse_context<wchar_t>::iterator
2790 parse(basic_format_parse_context<wchar_t>& __pc)
2791 { return _M_f.parse(__pc); }
2793 template<typename _Out>
2794 typename basic_format_context<_Out, wchar_t>::iterator
2795 format(basic_string_view<wchar_t, _Traits> __u,
2796 basic_format_context<_Out, wchar_t>& __fc) const
2797 { return _M_f.format(__u, __fc); }
2799#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2800 constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
2804 __format::__formatter_str<wchar_t> _M_f;
2806#endif // USE_WCHAR_T
2809/// @cond undocumented
2812 // each cv-unqualified arithmetic type ArithmeticT other than
2813 // char, wchar_t, char8_t, char16_t, or char32_t
2814 template<typename _Tp>
2815 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2817#if defined __SIZEOF_INT128__
2818 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2819 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2823 template<> inline constexpr bool __is_formattable_integer<char> = false;
2824 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2825#ifdef _GLIBCXX_USE_CHAR8_T
2826 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2828 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2829 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2833 /// Format an integer.
2834 template<typename _Tp, __format::__char _CharT>
2835 requires __format::__is_formattable_integer<_Tp>
2836 struct formatter<_Tp, _CharT>
2838 formatter() = default;
2840 [[__gnu__::__always_inline__]]
2841 constexpr typename basic_format_parse_context<_CharT>::iterator
2842 parse(basic_format_parse_context<_CharT>& __pc)
2844 return _M_f.template _M_parse<_Tp>(__pc);
2847 template<typename _Out>
2848 typename basic_format_context<_Out, _CharT>::iterator
2849 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2850 { return _M_f.format(__u, __fc); }
2853 __format::__formatter_int<_CharT> _M_f;
2856#if defined __glibcxx_to_chars
2857 /// Format a floating-point value.
2858 template<__format::__formattable_float _Tp, __format::__char _CharT>
2859 struct formatter<_Tp, _CharT>
2861 formatter() = default;
2863 [[__gnu__::__always_inline__]]
2864 constexpr typename basic_format_parse_context<_CharT>::iterator
2865 parse(basic_format_parse_context<_CharT>& __pc)
2866 { return _M_f.parse(__pc); }
2868 template<typename _Out>
2869 typename basic_format_context<_Out, _CharT>::iterator
2870 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2871 { return _M_f.format(__u, __fc); }
2874 __format::__formatter_fp<_CharT> _M_f;
2877#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2878 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2879 template<__format::__char _CharT>
2880 struct formatter<long double, _CharT>
2882 formatter() = default;
2884 [[__gnu__::__always_inline__]]
2885 constexpr typename basic_format_parse_context<_CharT>::iterator
2886 parse(basic_format_parse_context<_CharT>& __pc)
2887 { return _M_f.parse(__pc); }
2889 template<typename _Out>
2890 typename basic_format_context<_Out, _CharT>::iterator
2891 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2892 { return _M_f.format((double)__u, __fc); }
2895 __format::__formatter_fp<_CharT> _M_f;
2899#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2900 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2901 template<__format::__char _CharT>
2902 struct formatter<_Float16, _CharT>
2904 formatter() = default;
2906 [[__gnu__::__always_inline__]]
2907 constexpr typename basic_format_parse_context<_CharT>::iterator
2908 parse(basic_format_parse_context<_CharT>& __pc)
2909 { return _M_f.parse(__pc); }
2911 template<typename _Out>
2912 typename basic_format_context<_Out, _CharT>::iterator
2913 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2914 { return _M_f.format((float)__u, __fc); }
2917 __format::__formatter_fp<_CharT> _M_f;
2921#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2922 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2923 template<__format::__char _CharT>
2924 struct formatter<_Float32, _CharT>
2926 formatter() = default;
2928 [[__gnu__::__always_inline__]]
2929 constexpr typename basic_format_parse_context<_CharT>::iterator
2930 parse(basic_format_parse_context<_CharT>& __pc)
2931 { return _M_f.parse(__pc); }
2933 template<typename _Out>
2934 typename basic_format_context<_Out, _CharT>::iterator
2935 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2936 { return _M_f.format((float)__u, __fc); }
2939 __format::__formatter_fp<_CharT> _M_f;
2943#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2944 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2945 template<__format::__char _CharT>
2946 struct formatter<_Float64, _CharT>
2948 formatter() = default;
2950 [[__gnu__::__always_inline__]]
2951 constexpr typename basic_format_parse_context<_CharT>::iterator
2952 parse(basic_format_parse_context<_CharT>& __pc)
2953 { return _M_f.parse(__pc); }
2955 template<typename _Out>
2956 typename basic_format_context<_Out, _CharT>::iterator
2957 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2958 { return _M_f.format((double)__u, __fc); }
2961 __format::__formatter_fp<_CharT> _M_f;
2965#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
2966 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
2967 template<__format::__char _CharT>
2968 struct formatter<_Float128, _CharT>
2970 formatter() = default;
2972 [[__gnu__::__always_inline__]]
2973 constexpr typename basic_format_parse_context<_CharT>::iterator
2974 parse(basic_format_parse_context<_CharT>& __pc)
2975 { return _M_f.parse(__pc); }
2977 template<typename _Out>
2978 typename basic_format_context<_Out, _CharT>::iterator
2979 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2980 { return _M_f.format((__format::__flt128_t)__u, __fc); }
2983 __format::__formatter_fp<_CharT> _M_f;
2987#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
2988 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
2989 // when long double is not 128bit IEEE type.
2990 template<__format::__char _CharT>
2991 struct formatter<__float128, _CharT>
2993 formatter() = default;
2995 [[__gnu__::__always_inline__]]
2996 constexpr typename basic_format_parse_context<_CharT>::iterator
2997 parse(basic_format_parse_context<_CharT>& __pc)
2998 { return _M_f.parse(__pc); }
3000 template<typename _Out>
3001 typename basic_format_context<_Out, _CharT>::iterator
3002 format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3003 { return _M_f.format((__format::__flt128_t)__u, __fc); }
3006 __format::__formatter_fp<_CharT> _M_f;
3010#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3011 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3012 template<__format::__char _CharT>
3013 struct formatter<__format::__bflt16_t, _CharT>
3015 formatter() = default;
3017 [[__gnu__::__always_inline__]]
3018 constexpr typename basic_format_parse_context<_CharT>::iterator
3019 parse(basic_format_parse_context<_CharT>& __pc)
3020 { return _M_f.parse(__pc); }
3022 template<typename _Out>
3023 typename basic_format_context<_Out, _CharT>::iterator
3024 format(__gnu_cxx::__bfloat16_t __u,
3025 basic_format_context<_Out, _CharT>& __fc) const
3026 { return _M_f.format((float)__u, __fc); }
3029 __format::__formatter_fp<_CharT> _M_f;
3032#endif // __cpp_lib_to_chars
3034 /** Format a pointer.
3037 template<__format::__char _CharT>
3038 struct formatter<const void*, _CharT>
3040 formatter() = default;
3042 constexpr typename basic_format_parse_context<_CharT>::iterator
3043 parse(basic_format_parse_context<_CharT>& __pc)
3044 { return _M_f.parse(__pc); }
3046 template<typename _Out>
3047 typename basic_format_context<_Out, _CharT>::iterator
3048 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3049 { return _M_f.format(__v, __fc); }
3052 __format::__formatter_ptr<_CharT> _M_f;
3055 template<__format::__char _CharT>
3056 struct formatter<void*, _CharT>
3058 formatter() = default;
3060 [[__gnu__::__always_inline__]]
3061 constexpr typename basic_format_parse_context<_CharT>::iterator
3062 parse(basic_format_parse_context<_CharT>& __pc)
3063 { return _M_f.parse(__pc); }
3065 template<typename _Out>
3066 typename basic_format_context<_Out, _CharT>::iterator
3067 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3068 { return _M_f.format(__v, __fc); }
3071 __format::__formatter_ptr<_CharT> _M_f;
3074 template<__format::__char _CharT>
3075 struct formatter<nullptr_t, _CharT>
3077 formatter() = default;
3079 [[__gnu__::__always_inline__]]
3080 constexpr typename basic_format_parse_context<_CharT>::iterator
3081 parse(basic_format_parse_context<_CharT>& __pc)
3082 { return _M_f.parse(__pc); }
3084 template<typename _Out>
3085 typename basic_format_context<_Out, _CharT>::iterator
3086 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3087 { return _M_f.format(nullptr, __fc); }
3090 __format::__formatter_ptr<_CharT> _M_f;
3094#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3095 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3096 // 3944. Formatters converting sequences of char to sequences of wchar_t
3098 struct __formatter_disabled
3100 __formatter_disabled() = delete; // Cannot format char sequence to wchar_t
3101 __formatter_disabled(const __formatter_disabled&) = delete;
3102 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3106 struct formatter<char*, wchar_t>
3107 : private __formatter_disabled { };
3109 struct formatter<const char*, wchar_t>
3110 : private __formatter_disabled { };
3111 template<size_t _Nm>
3112 struct formatter<char[_Nm], wchar_t>
3113 : private __formatter_disabled { };
3114 template<class _Traits, class _Allocator>
3115 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3116 : private __formatter_disabled { };
3117 template<class _Traits>
3118 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3119 : private __formatter_disabled { };
3122 /// An iterator after the last character written, and the number of
3123 /// characters that would have been written.
3124 template<typename _Out>
3125 struct format_to_n_result
3128 iter_difference_t<_Out> size;
3131_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3132template<typename, typename> class vector;
3133_GLIBCXX_END_NAMESPACE_CONTAINER
3135/// @cond undocumented
3138 template<typename _CharT>
3141 _Sink<_CharT>* _M_sink = nullptr;
3144 using iterator_category = output_iterator_tag;
3145 using value_type = void;
3146 using difference_type = ptrdiff_t;
3147 using pointer = void;
3148 using reference = void;
3150 _Sink_iter() = default;
3151 _Sink_iter(const _Sink_iter&) = default;
3152 _Sink_iter& operator=(const _Sink_iter&) = default;
3154 [[__gnu__::__always_inline__]]
3156 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3158 [[__gnu__::__always_inline__]]
3159 constexpr _Sink_iter&
3160 operator=(_CharT __c)
3162 _M_sink->_M_write(__c);
3166 [[__gnu__::__always_inline__]]
3167 constexpr _Sink_iter&
3168 operator=(basic_string_view<_CharT> __s)
3170 _M_sink->_M_write(__s);
3174 [[__gnu__::__always_inline__]]
3175 constexpr _Sink_iter&
3176 operator*() { return *this; }
3178 [[__gnu__::__always_inline__]]
3179 constexpr _Sink_iter&
3180 operator++() { return *this; }
3182 [[__gnu__::__always_inline__]]
3183 constexpr _Sink_iter
3184 operator++(int) { return *this; }
3187 _M_reserve(size_t __n) const
3188 { return _M_sink->_M_reserve(__n); }
3191 _M_discarding() const
3192 { return _M_sink->_M_discarding(); }
3195 // Abstract base class for type-erased character sinks.
3196 // All formatting and output is done via this type's iterator,
3197 // to reduce the number of different template instantiations.
3198 template<typename _CharT>
3201 friend class _Sink_iter<_CharT>;
3203 span<_CharT> _M_span;
3204 typename span<_CharT>::iterator _M_next;
3206 // Called when the span is full, to make more space available.
3207 // Precondition: _M_next != _M_span.begin()
3208 // Postcondition: _M_next != _M_span.end()
3209 // TODO: remove the precondition? could make overflow handle it.
3210 virtual void _M_overflow() = 0;
3213 // Precondition: __span.size() != 0
3214 [[__gnu__::__always_inline__]]
3216 _Sink(span<_CharT> __span) noexcept
3217 : _M_span(__span), _M_next(__span.begin())
3220 // The portion of the span that has been written to.
3221 [[__gnu__::__always_inline__]]
3223 _M_used() const noexcept
3224 { return _M_span.first(_M_next - _M_span.begin()); }
3226 // The portion of the span that has not been written to.
3227 [[__gnu__::__always_inline__]]
3228 constexpr span<_CharT>
3229 _M_unused() const noexcept
3230 { return _M_span.subspan(_M_next - _M_span.begin()); }
3232 // Use the start of the span as the next write position.
3233 [[__gnu__::__always_inline__]]
3235 _M_rewind() noexcept
3236 { _M_next = _M_span.begin(); }
3238 // Replace the current output range.
3240 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3243 _M_next = __s.begin() + __pos;
3246 // Called by the iterator for *it++ = c
3248 _M_write(_CharT __c)
3251 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
3256 _M_write(basic_string_view<_CharT> __s)
3258 span __to = _M_unused();
3259 while (__to.size() <= __s.size())
3261 __s.copy(__to.data(), __to.size());
3262 _M_next += __to.size();
3263 __s.remove_prefix(__to.size());
3269 __s.copy(__to.data(), __s.size());
3270 _M_next += __s.size();
3274 // A successful _Reservation can be used to directly write
3275 // up to N characters to the sink to avoid unwanted buffering.
3278 // True if the reservation was successful, false otherwise.
3279 explicit operator bool() const noexcept { return _M_sink; }
3280 // A pointer to write directly to the sink.
3281 _CharT* get() const noexcept { return _M_sink->_M_next.operator->(); }
3282 // Add n to the _M_next iterator for the sink.
3283 void _M_bump(size_t __n) { _M_sink->_M_bump(__n); }
3287 // Attempt to reserve space to write n characters to the sink.
3288 // If anything is written to the reservation then there must be a call
3289 // to _M_bump(N2) before any call to another member function of *this,
3290 // where N2 is the number of characters written.
3291 virtual _Reservation
3292 _M_reserve(size_t __n)
3294 if (__n <= _M_unused().size())
3297 if (__n <= _M_span.size()) // Cannot meet the request.
3299 _M_overflow(); // Make more space available.
3300 if (__n <= _M_unused().size())
3306 // Update the next output position after writing directly to the sink.
3307 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3312 // Returns true if the _Sink is discarding incoming characters.
3314 _M_discarding() const
3318 _Sink(const _Sink&) = delete;
3319 _Sink& operator=(const _Sink&) = delete;
3321 [[__gnu__::__always_inline__]]
3322 constexpr _Sink_iter<_CharT>
3324 { return _Sink_iter<_CharT>(*this); }
3328 template<typename _CharT>
3329 class _Fixedbuf_sink final : public _Sink<_CharT>
3332 _M_overflow() override
3334 __glibcxx_assert(false);
3339 [[__gnu__::__always_inline__]]
3341 _Fixedbuf_sink(span<_CharT> __buf)
3342 : _Sink<_CharT>(__buf)
3345 constexpr basic_string_view<_CharT>
3348 auto __s = this->_M_used();
3349 return basic_string_view<_CharT>(__s.data(), __s.size());
3353 // A sink with an internal buffer. This is used to implement concrete sinks.
3354 template<typename _CharT>
3355 class _Buf_sink : public _Sink<_CharT>
3358 _CharT _M_buf[__stackbuf_size<_CharT>];
3360 [[__gnu__::__always_inline__]]
3362 _Buf_sink() noexcept
3363 : _Sink<_CharT>(_M_buf)
3367 using _GLIBCXX_STD_C::vector;
3369 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3370 // Writes to a buffer then appends that to the sequence when it fills up.
3371 template<typename _Seq>
3372 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3374 using _CharT = typename _Seq::value_type;
3378 // Transfer buffer contents to the sequence, so buffer can be refilled.
3380 _M_overflow() override
3382 auto __s = this->_M_used();
3383 if (__s.empty()) [[unlikely]]
3384 return; // Nothing in the buffer to transfer to _M_seq.
3386 // If _M_reserve was called then _M_bump must have been called too.
3387 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3389 if constexpr (__is_specialization_of<_Seq, basic_string>)
3390 _M_seq.append(__s.data(), __s.size());
3392 _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
3394 // Make the whole of _M_buf available for the next write:
3398 typename _Sink<_CharT>::_Reservation
3399 _M_reserve(size_t __n) override
3401 // We might already have n characters available in this->_M_unused(),
3402 // but the whole point of this function is to be an optimization for
3403 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3404 // and then copying that into a basic_string if possible, so this
3405 // function prefers to create space directly in _M_seq rather than
3408 if constexpr (__is_specialization_of<_Seq, basic_string>
3409 || __is_specialization_of<_Seq, vector>)
3411 // Flush the buffer to _M_seq first (should not be needed).
3412 if (this->_M_used().size()) [[unlikely]]
3413 _Seq_sink::_M_overflow();
3415 // Expand _M_seq to make __n new characters available:
3416 const auto __sz = _M_seq.size();
3417 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3418 _M_seq.__resize_and_overwrite(__sz + __n,
3419 [](auto, auto __n2) {
3423 _M_seq.resize(__sz + __n);
3425 // Set _M_used() to be a span over the original part of _M_seq
3426 // and _M_unused() to be the extra capacity we just created:
3427 this->_M_reset(_M_seq, __sz);
3430 else // Try to use the base class' buffer.
3431 return _Sink<_CharT>::_M_reserve(__n);
3435 _M_bump(size_t __n) override
3437 if constexpr (__is_specialization_of<_Seq, basic_string>
3438 || __is_specialization_of<_Seq, vector>)
3440 auto __s = this->_M_used();
3441 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3442 // Truncate the sequence to the part that was actually written to:
3443 _M_seq.resize(__s.size() + __n);
3444 // Switch back to using buffer:
3445 this->_M_reset(this->_M_buf);
3449 void _M_trim(span<const _CharT> __s)
3450 requires __is_specialization_of<_Seq, basic_string>
3452 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3453 || __s.data() == _M_seq.data());
3454 if (__s.data() == _M_seq.data())
3455 _M_seq.resize(__s.size());
3457 this->_M_reset(this->_M_buf, __s.size());
3461 // TODO: for SSO string, use SSO buffer as initial span, then switch
3462 // to _M_buf if it overflows? Or even do that for all unused capacity?
3464 [[__gnu__::__always_inline__]]
3465 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3468 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3469 : _M_seq(std::move(__s))
3472 using _Sink<_CharT>::out;
3477 if (this->_M_used().size() != 0)
3478 _Seq_sink::_M_overflow();
3479 return std::move(_M_seq);
3482 // A writable span that views everything written to the sink.
3483 // Will be either a view over _M_seq or the used part of _M_buf.
3487 auto __s = this->_M_used();
3490 if (__s.size() != 0)
3491 _Seq_sink::_M_overflow();
3497 basic_string_view<_CharT>
3500 auto __span = _M_span();
3501 return basic_string_view<_CharT>(__span.data(), __span.size());
3505 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3507 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3509 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3510 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3511 // Writes to a fixed-size buffer and then flushes to the output iterator
3512 // when the buffer fills up.
3513 template<typename _CharT, typename _OutIter>
3514 class _Iter_sink : public _Buf_sink<_CharT>
3517 iter_difference_t<_OutIter> _M_max;
3520 size_t _M_count = 0;
3523 _M_overflow() override
3525 auto __s = this->_M_used();
3526 if (_M_max < 0) // No maximum.
3527 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3528 else if (_M_count < static_cast<size_t>(_M_max))
3530 auto __max = _M_max - _M_count;
3531 span<_CharT> __first;
3532 if (__max < __s.size())
3533 __first = __s.first(static_cast<size_t>(__max));
3536 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3539 _M_count += __s.size();
3543 _M_discarding() const override
3545 // format_to_n return total number of characters, that would be written,
3546 // see C++20 [format.functions] p20
3551 [[__gnu__::__always_inline__]]
3553 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3554 : _M_out(std::move(__out)), _M_max(__max)
3557 using _Sink<_CharT>::out;
3559 format_to_n_result<_OutIter>
3562 if (this->_M_used().size() != 0)
3563 _Iter_sink::_M_overflow();
3564 iter_difference_t<_OutIter> __count(_M_count);
3565 return { std::move(_M_out), __count };
3569 // Partial specialization for contiguous iterators.
3570 // No buffer is used, characters are written straight to the iterator.
3571 // We do not know the size of the output range, so the span size just grows
3572 // as needed. The end of the span might be an invalid pointer outside the
3573 // valid range, but we never actually call _M_span.end(). This class does
3574 // not introduce any invalid pointer arithmetic or overflows that would not
3575 // have happened anyway.
3576 template<typename _CharT, contiguous_iterator _OutIter>
3577 requires same_as<iter_value_t<_OutIter>, _CharT>
3578 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3581 iter_difference_t<_OutIter> _M_max = -1;
3583 size_t _M_count = 0;
3585 _CharT _M_buf[64]; // Write here after outputting _M_max characters.
3589 _M_overflow() override
3591 if (this->_M_unused().size() != 0)
3592 return; // No need to switch to internal buffer yet.
3594 auto __s = this->_M_used();
3598 _M_count += __s.size();
3599 // Span was already sized for the maximum character count,
3600 // if it overflows then any further output must go to the
3601 // internal buffer, to be discarded.
3602 this->_M_reset(this->_M_buf);
3606 // No maximum character count. Just extend the span to allow
3607 // writing more characters to it.
3608 this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
3613 _M_discarding() const override
3615 // format_to_n return total number of characters, that would be written,
3616 // see C++20 [format.functions] p20
3620 typename _Sink<_CharT>::_Reservation
3621 _M_reserve(size_t __n) final
3623 auto __avail = this->_M_unused();
3624 if (__n > __avail.size())
3627 return {}; // cannot grow
3629 auto __s = this->_M_used();
3630 this->_M_reset({__s.data(), __s.size() + __n}, __s.size());
3637 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3638 span<_CharT> __buf) noexcept
3641 return __buf; // Only write to the internal buffer.
3645 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3646 || sizeof(__n) > sizeof(size_t))
3648 // __int128 or __detail::__max_diff_type
3649 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3653 return {__ptr, (size_t)__n};
3656#if __has_builtin(__builtin_dynamic_object_size)
3657 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3658 return {__ptr, __bytes / sizeof(_CharT)};
3660 // Avoid forming a pointer to a different memory page.
3661 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3662 __n = (1024 - __off) / sizeof(_CharT);
3663 if (__n > 0) [[likely]]
3664 return {__ptr, static_cast<size_t>(__n)};
3665 else // Misaligned/packed buffer of wchar_t?
3671 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3672 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3673 _M_first(__out), _M_max(__n)
3676 format_to_n_result<_OutIter>
3679 auto __s = this->_M_used();
3680 if (__s.data() == _M_buf)
3682 // Switched to internal buffer, so must have written _M_max.
3683 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3684 return { _M_first + _M_max, __count };
3686 else // Not using internal buffer yet
3688 iter_difference_t<_OutIter> __count(__s.size());
3689 return { _M_first + __count, __count };
3694 // A sink for handling the padded outputs (_M_padwidth) or truncated
3695 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3696 // until sufficient number of characters is written. After that if sequence
3697 // is longer than _M_padwidth it's written to _M_out, and further writes are
3699 // * buffered and forwarded to _M_out, if below _M_maxwidth,
3700 // * ignored otherwise
3701 // If field width of written sequence is no greater than _M_padwidth, the
3702 // sequence is written during _M_finish call.
3703 template<typename _Out, typename _CharT>
3704 class _Padding_sink : public _Str_sink<_CharT>
3709 size_t _M_printwidth;
3711 [[__gnu__::__always_inline__]]
3714 { return _M_printwidth >= _M_maxwidth; }
3716 [[__gnu__::__always_inline__]]
3718 _M_buffering() const
3720 if (_M_printwidth < _M_padwidth)
3722 if (_M_maxwidth != (size_t)-1)
3723 return _M_printwidth < _M_maxwidth;
3728 _M_sync_discarding()
3730 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3731 if (_M_out._M_discarding())
3732 _M_maxwidth = _M_printwidth;
3738 span<_CharT> __new = this->_M_used();
3739 basic_string_view<_CharT> __str(__new.data(), __new.size());
3740 _M_out = __format::__write(std::move(_M_out), __str);
3741 _M_sync_discarding();
3748 auto __str = this->view();
3749 // Compute actual field width, possibly truncated.
3750 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3752 this->_M_trim(__str);
3756 // We have more characters than padidng, no padding is needed,
3757 // write direclty to _M_out.
3758 if (_M_printwidth >= _M_padwidth)
3760 _M_out = __format::__write(std::move(_M_out), __str);
3761 _M_sync_discarding();
3763 // We reached _M_maxwidth that is smaller than _M_padwidth.
3764 // Store the prefix sequence in _M_seq, and free _M_buf.
3766 _Str_sink<_CharT>::_M_overflow();
3768 // Use internal buffer for writes to _M_out.
3769 this->_M_reset(this->_M_buf);
3774 _M_update(size_t __new)
3776 _M_printwidth += __new;
3777 // Compute estimated width, to see if is not reduced.
3778 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3779 return _M_force_update();
3784 _M_overflow() override
3786 // Ignore characters in buffer, and override it.
3789 // Write buffer to _M_out, and override it.
3790 else if (!_M_buffering())
3792 // Update written count, and if input still should be buffered,
3793 // flush the to _M_seq.
3794 else if (_M_update(this->_M_used().size()))
3795 _Str_sink<_CharT>::_M_overflow();
3799 _M_discarding() const override
3800 { return _M_ignoring(); }
3802 typename _Sink<_CharT>::_Reservation
3803 _M_reserve(size_t __n) override
3805 // Ignore characters in buffer, if any.
3808 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3809 if (!_M_buffering())
3811 // Write pending characters if any
3812 if (!this->_M_used().empty())
3814 // Try to reserve from _M_out sink.
3815 if (auto __reserved = _M_out._M_reserve(__n))
3818 return _Sink<_CharT>::_M_reserve(__n);
3822 _M_bump(size_t __n) override
3824 // Ignore the written characters.
3827 // If reservation was made directy sink associated _M_out,
3828 // _M_bump will be called on that sink.
3829 _Sink<_CharT>::_M_bump(__n);
3835 [[__gnu__::__always_inline__]]
3837 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
3838 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
3839 _M_out(std::move(__out)), _M_printwidth(0)
3840 { _M_sync_discarding(); }
3842 [[__gnu__::__always_inline__]]
3844 _Padding_sink(_Out __out, size_t __padwidth)
3845 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
3849 _M_finish(_Align __align, char32_t __fill_char)
3851 // Handle any characters in the buffer.
3852 if (auto __rem = this->_M_used().size())
3856 else if (!_M_buffering())
3862 if (!_M_buffering() || !_M_force_update())
3863 // Characters were already written to _M_out.
3864 if (_M_printwidth >= _M_padwidth)
3865 return std::move(_M_out);
3867 const auto __str = this->view();
3868 if (_M_printwidth >= _M_padwidth)
3869 return __format::__write(std::move(_M_out), __str);
3871 const size_t __nfill = _M_padwidth - _M_printwidth;
3872 return __format::__write_padded(std::move(_M_out), __str,
3873 __align, __nfill, __fill_char);
3877 enum class _Arg_t : unsigned char {
3878 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3879 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3880 _Arg_i128, _Arg_u128, _Arg_float128,
3881 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
3884#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3885 _Arg_ibm128 = _Arg_ldbl,
3886 _Arg_ieee128 = _Arg_float128,
3891 template<typename _Context>
3894 using _CharT = typename _Context::char_type;
3910 unsigned long long _M_ull;
3913#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3914 long double _M_ldbl;
3917 __ieee128 _M_ieee128;
3919#ifdef __SIZEOF_FLOAT128__
3920 __float128 _M_float128;
3922 const _CharT* _M_str;
3923 basic_string_view<_CharT> _M_sv;
3925 _HandleBase _M_handle;
3926#ifdef __SIZEOF_INT128__
3928 unsigned __int128 _M_u128;
3930#ifdef __BFLT16_DIG__
3944 [[__gnu__::__always_inline__]]
3945 _Arg_value() : _M_none() { }
3948 template<typename _Tp>
3949 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3950 { _S_get<_Tp>() = __val; }
3953 template<typename _Tp, typename _Self>
3954 [[__gnu__::__always_inline__]]
3956 _S_get(_Self& __u) noexcept
3958 if constexpr (is_same_v<_Tp, bool>)
3960 else if constexpr (is_same_v<_Tp, _CharT>)
3962 else if constexpr (is_same_v<_Tp, int>)
3964 else if constexpr (is_same_v<_Tp, unsigned>)
3966 else if constexpr (is_same_v<_Tp, long long>)
3968 else if constexpr (is_same_v<_Tp, unsigned long long>)
3970 else if constexpr (is_same_v<_Tp, float>)
3972 else if constexpr (is_same_v<_Tp, double>)
3974#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3975 else if constexpr (is_same_v<_Tp, long double>)
3978 else if constexpr (is_same_v<_Tp, __ibm128>)
3979 return __u._M_ibm128;
3980 else if constexpr (is_same_v<_Tp, __ieee128>)
3981 return __u._M_ieee128;
3983#ifdef __SIZEOF_FLOAT128__
3984 else if constexpr (is_same_v<_Tp, __float128>)
3985 return __u._M_float128;
3987 else if constexpr (is_same_v<_Tp, const _CharT*>)
3989 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
3991 else if constexpr (is_same_v<_Tp, const void*>)
3993#ifdef __SIZEOF_INT128__
3994 else if constexpr (is_same_v<_Tp, __int128>)
3996 else if constexpr (is_same_v<_Tp, unsigned __int128>)
3999#ifdef __BFLT16_DIG__
4000 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4004 else if constexpr (is_same_v<_Tp, _Float16>)
4008 else if constexpr (is_same_v<_Tp, _Float32>)
4012 else if constexpr (is_same_v<_Tp, _Float64>)
4015 else if constexpr (derived_from<_Tp, _HandleBase>)
4016 return static_cast<_Tp&>(__u._M_handle);
4017 // Otherwise, ill-formed.
4020 template<typename _Tp>
4021 [[__gnu__::__always_inline__]]
4024 { return _S_get<_Tp>(*this); }
4026 template<typename _Tp>
4027 [[__gnu__::__always_inline__]]
4029 _M_get() const noexcept
4030 { return _S_get<_Tp>(*this); }
4032 template<typename _Tp>
4033 [[__gnu__::__always_inline__]]
4035 _M_set(_Tp __v) noexcept
4037 if constexpr (derived_from<_Tp, _HandleBase>)
4038 std::construct_at(&_M_handle, __v);
4040 _S_get<_Tp>(*this) = __v;
4044 // [format.arg.store], class template format-arg-store
4045 template<typename _Context, typename... _Args>
4048 template<typename _Visitor, typename _Ctx>
4049 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4051 template<typename _Ch, typename _Tp>
4053 __to_arg_t_enum() noexcept;
4054} // namespace __format
4057 template<typename _Context>
4058 class basic_format_arg
4060 using _CharT = typename _Context::char_type;
4062 template<typename _Tp>
4063 static constexpr bool __formattable
4064 = __format::__formattable_with<_Tp, _Context>;
4067 class handle : public __format::_Arg_value<_Context>::_HandleBase
4069 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
4071 // Format as const if possible, to reduce instantiations.
4072 template<typename _Tp>
4073 using __maybe_const_t
4074 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
4076 template<typename _Tq>
4078 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4079 _Context& __format_ctx, const void* __ptr)
4081 using _Td = remove_const_t<_Tq>;
4082 typename _Context::template formatter_type<_Td> __f;
4083 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4084 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4085 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4088 template<typename _Tp>
4090 handle(_Tp& __val) noexcept
4092 this->_M_ptr = __builtin_addressof(__val);
4093 auto __func = _S_format<__maybe_const_t<_Tp>>;
4094 this->_M_func = reinterpret_cast<void(*)()>(__func);
4097 friend class basic_format_arg<_Context>;
4100 handle(const handle&) = default;
4101 handle& operator=(const handle&) = default;
4103 [[__gnu__::__always_inline__]]
4105 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4107 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4108 _Context&, const void*);
4109 auto __f = reinterpret_cast<_Func>(this->_M_func);
4110 __f(__pc, __fc, this->_M_ptr);
4114 [[__gnu__::__always_inline__]]
4115 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4117 [[nodiscard,__gnu__::__always_inline__]]
4118 explicit operator bool() const noexcept
4119 { return _M_type != __format::_Arg_none; }
4121#if __cpp_lib_format >= 202306L // >= C++26
4122 template<typename _Visitor>
4124 visit(this basic_format_arg __arg, _Visitor&& __vis)
4125 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4127 template<typename _Res, typename _Visitor>
4129 visit(this basic_format_arg __arg, _Visitor&& __vis)
4130 { return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4134 template<typename _Ctx>
4135 friend class basic_format_args;
4137 template<typename _Ctx, typename... _Args>
4138 friend class __format::_Arg_store;
4140 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4142 __format::_Arg_value<_Context> _M_val;
4143 __format::_Arg_t _M_type;
4145 // Transform incoming argument type to the type stored in _Arg_value.
4146 // e.g. short -> int, std::string -> std::string_view,
4147 // char[3] -> const char*.
4148 template<typename _Tp>
4149 static consteval auto
4152 using _Td = remove_const_t<_Tp>;
4153 if constexpr (is_same_v<_Td, bool>)
4154 return type_identity<bool>();
4155 else if constexpr (is_same_v<_Td, _CharT>)
4156 return type_identity<_CharT>();
4157 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4158 return type_identity<_CharT>();
4159#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4160 else if constexpr (is_same_v<_Td, __int128>)
4161 return type_identity<__int128>();
4162 else if constexpr (is_same_v<_Td, unsigned __int128>)
4163 return type_identity<unsigned __int128>();
4165 else if constexpr (__is_signed_integer<_Td>::value)
4167 if constexpr (sizeof(_Td) <= sizeof(int))
4168 return type_identity<int>();
4169 else if constexpr (sizeof(_Td) <= sizeof(long long))
4170 return type_identity<long long>();
4172 else if constexpr (__is_unsigned_integer<_Td>::value)
4174 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4175 return type_identity<unsigned>();
4176 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4177 return type_identity<unsigned long long>();
4179 else if constexpr (is_same_v<_Td, float>)
4180 return type_identity<float>();
4181 else if constexpr (is_same_v<_Td, double>)
4182 return type_identity<double>();
4183#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4184 else if constexpr (is_same_v<_Td, long double>)
4185 return type_identity<long double>();
4187 else if constexpr (is_same_v<_Td, __ibm128>)
4188 return type_identity<__ibm128>();
4189 else if constexpr (is_same_v<_Td, __ieee128>)
4190 return type_identity<__ieee128>();
4192#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4193 else if constexpr (is_same_v<_Td, __float128>)
4194 return type_identity<__float128>();
4196#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4197 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4198 return type_identity<__format::__bflt16_t>();
4200#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4201 else if constexpr (is_same_v<_Td, _Float16>)
4202 return type_identity<_Float16>();
4204#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4205 else if constexpr (is_same_v<_Td, _Float32>)
4206 return type_identity<_Float32>();
4208#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4209 else if constexpr (is_same_v<_Td, _Float64>)
4210 return type_identity<_Float64>();
4212 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4213 || __is_specialization_of<_Td, basic_string>)
4215 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4216 return type_identity<basic_string_view<_CharT>>();
4218 return type_identity<handle>();
4220 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4221 return type_identity<const _CharT*>();
4222 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4223 return type_identity<const _CharT*>();
4224 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4225 return type_identity<const void*>();
4226 else if constexpr (is_same_v<_Td, nullptr_t>)
4227 return type_identity<const void*>();
4229 return type_identity<handle>();
4232 // Transform a formattable type to the appropriate storage type.
4233 template<typename _Tp>
4234 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4236 // Get the _Arg_t value corresponding to a normalized type.
4237 template<typename _Tp>
4238 static consteval __format::_Arg_t
4241 using namespace __format;
4242 if constexpr (is_same_v<_Tp, bool>)
4244 else if constexpr (is_same_v<_Tp, _CharT>)
4246 else if constexpr (is_same_v<_Tp, int>)
4248 else if constexpr (is_same_v<_Tp, unsigned>)
4250 else if constexpr (is_same_v<_Tp, long long>)
4252 else if constexpr (is_same_v<_Tp, unsigned long long>)
4254 else if constexpr (is_same_v<_Tp, float>)
4256 else if constexpr (is_same_v<_Tp, double>)
4258#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4259 else if constexpr (is_same_v<_Tp, long double>)
4262 // Don't use _Arg_ldbl for this target, it's ambiguous.
4263 else if constexpr (is_same_v<_Tp, __ibm128>)
4265 else if constexpr (is_same_v<_Tp, __ieee128>)
4266 return _Arg_ieee128;
4268#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4269 else if constexpr (is_same_v<_Tp, __float128>)
4270 return _Arg_float128;
4272#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4273 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4276#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4277 else if constexpr (is_same_v<_Tp, _Float16>)
4280#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4281 else if constexpr (is_same_v<_Tp, _Float32>)
4284#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4285 else if constexpr (is_same_v<_Tp, _Float64>)
4288 else if constexpr (is_same_v<_Tp, const _CharT*>)
4290 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4292 else if constexpr (is_same_v<_Tp, const void*>)
4294#ifdef __SIZEOF_INT128__
4295 else if constexpr (is_same_v<_Tp, __int128>)
4297 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4300 else if constexpr (is_same_v<_Tp, handle>)
4304 template<typename _Tp>
4306 _M_set(_Tp __v) noexcept
4308 _M_type = _S_to_enum<_Tp>();
4312 template<typename _Tp>
4313 requires __format::__formattable_with<_Tp, _Context>
4315 basic_format_arg(_Tp& __v) noexcept
4317 using _Td = _Normalize<_Tp>;
4318 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4319 _M_set(_Td{__v.data(), __v.size()});
4320 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4321 && is_same_v<_CharT, wchar_t>)
4322 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4324 _M_set(static_cast<_Td>(__v));
4327 template<typename _Ctx, typename... _Argz>
4329 make_format_args(_Argz&...) noexcept;
4331 template<typename _Visitor, typename _Ctx>
4332 friend decltype(auto)
4333 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4335 template<typename _Visitor, typename _Ctx>
4336 friend decltype(auto)
4337 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4339 template<typename _Ch, typename _Tp>
4340 friend consteval __format::_Arg_t
4341 __format::__to_arg_t_enum() noexcept;
4343 template<typename _Visitor>
4345 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4347 using namespace __format;
4351 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4353 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4355 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4357 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4359 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4361 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4363 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4364#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4366 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4368 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4369#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4371 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4372#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4374 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4378 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4380 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4382#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4384 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4386#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4388 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4390#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4392 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4394#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4396 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4398#endif // __glibcxx_to_chars
4400 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4402 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4404 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4407 auto& __h = static_cast<handle&>(_M_val._M_handle);
4408 return std::forward<_Visitor>(__vis)(__h);
4410#ifdef __SIZEOF_INT128__
4412 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4414 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4417 __builtin_unreachable();
4421 template<typename _Visitor>
4423 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4425 return _M_visit([&__vis]<typename _Tp>(_Tp& __val) -> decltype(auto)
4427 constexpr bool __user_facing = __is_one_of<_Tp,
4428 monostate, bool, _CharT,
4429 int, unsigned int, long long int, unsigned long long int,
4430 float, double, long double,
4431 const _CharT*, basic_string_view<_CharT>,
4432 const void*, handle>::value;
4433 if constexpr (__user_facing)
4434 return std::forward<_Visitor>(__vis)(__val);
4438 return std::forward<_Visitor>(__vis)(__h);
4444 template<typename _Visitor, typename _Context>
4445 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4446 inline decltype(auto)
4447 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4449 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4452/// @cond undocumented
4455 template<typename _Visitor, typename _Ctx>
4456 inline decltype(auto)
4457 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4459 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4462 struct _WidthPrecVisitor
4464 template<typename _Tp>
4466 operator()(_Tp& __arg) const
4468 if constexpr (is_same_v<_Tp, monostate>)
4469 __format::__invalid_arg_id_in_format_string();
4470 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4471 // 3720. Restrict the valid types of arg-id for width and precision
4472 // 3721. Allow an arg-id with a value of zero for width
4473 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4475 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4476 // 3720. Restrict the valid types of arg-id for width and precision
4477 if constexpr (__is_unsigned_integer<_Tp>::value)
4479 else if constexpr (__is_signed_integer<_Tp>::value)
4483 __throw_format_error("format error: argument used for width or "
4484 "precision must be a non-negative integer");
4488#pragma GCC diagnostic push
4489#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4490 template<typename _Context>
4492 __int_from_arg(const basic_format_arg<_Context>& __arg)
4493 { return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4495 // Pack _Arg_t enum values into a single 60-bit integer.
4496 template<int _Bits, size_t _Nm>
4498 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4500 __UINT64_TYPE__ __packed_types = 0;
4501 for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
4502 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4503 return __packed_types;
4505} // namespace __format
4508 template<typename _Context>
4509 class basic_format_args
4511 static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
4512 static constexpr int _S_packed_type_mask = 0b11111;
4513 static constexpr int _S_max_packed_args = 12;
4515 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4517 template<typename... _Args>
4518 using _Store = __format::_Arg_store<_Context, _Args...>;
4520 template<typename _Ctx, typename... _Args>
4521 friend class __format::_Arg_store;
4523 using uint64_t = __UINT64_TYPE__;
4524 using _Format_arg = basic_format_arg<_Context>;
4525 using _Format_arg_val = __format::_Arg_value<_Context>;
4527 // If args are packed then the number of args is in _M_packed_size and
4528 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4529 // If args are not packed then the number of args is in _M_unpacked_size
4530 // and _M_packed_size is zero.
4531 uint64_t _M_packed_size : 4;
4532 uint64_t _M_unpacked_size : 60;
4535 const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
4536 const _Format_arg* _M_args; // Active when _M_packed_size == 0
4540 _M_size() const noexcept
4541 { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
4543 typename __format::_Arg_t
4544 _M_type(size_t __i) const noexcept
4546 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4547 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4550 template<typename _Ctx, typename... _Args>
4552 make_format_args(_Args&...) noexcept;
4554 // An array of _Arg_t enums corresponding to _Args...
4555 template<typename... _Args>
4556 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4558 { return {_Format_arg::template _S_to_enum<_Args>()...}; }
4561 template<typename... _Args>
4562 basic_format_args(const _Store<_Args...>& __store) noexcept;
4564 [[nodiscard,__gnu__::__always_inline__]]
4565 basic_format_arg<_Context>
4566 get(size_t __i) const noexcept
4568 basic_format_arg<_Context> __arg;
4569 if (__i < _M_packed_size)
4571 __arg._M_type = _M_type(__i);
4572 __arg._M_val = _M_values[__i];
4574 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4575 __arg = _M_args[__i];
4580 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4581 // 3810. CTAD for std::basic_format_args
4582 template<typename _Context, typename... _Args>
4583 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4584 -> basic_format_args<_Context>;
4586 template<typename _Context, typename... _Args>
4588 make_format_args(_Args&... __fmt_args) noexcept;
4590 // An array of type-erased formatting arguments.
4591 template<typename _Context, typename... _Args>
4592 class __format::_Arg_store
4594 friend std::basic_format_args<_Context>;
4596 template<typename _Ctx, typename... _Argz>
4598#if _GLIBCXX_INLINE_VERSION
4599 __8:: // Needed for PR c++/59256
4601 make_format_args(_Argz&...) noexcept;
4603 // For a sufficiently small number of arguments we only store values.
4604 // basic_format_args can get the types from the _Args pack.
4605 static constexpr bool _S_values_only
4606 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4609 = __conditional_t<_S_values_only,
4610 __format::_Arg_value<_Context>,
4611 basic_format_arg<_Context>>;
4613 _Element_t _M_args[sizeof...(_Args)];
4615 template<typename _Tp>
4617 _S_make_elt(_Tp& __v)
4619 using _Tq = remove_const_t<_Tp>;
4620 using _CharT = typename _Context::char_type;
4621 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4622 "std::formatter must be specialized for the type "
4623 "of each format arg");
4624 using __format::__formattable_with;
4625 if constexpr (is_const_v<_Tp>)
4626 if constexpr (!__formattable_with<_Tp, _Context>)
4627 if constexpr (__formattable_with<_Tq, _Context>)
4628 static_assert(__formattable_with<_Tp, _Context>,
4629 "format arg must be non-const because its "
4630 "std::formatter specialization has a "
4631 "non-const reference parameter");
4632 basic_format_arg<_Context> __arg(__v);
4633 if constexpr (_S_values_only)
4634 return __arg._M_val;
4639 template<typename... _Tp>
4640 requires (sizeof...(_Tp) == sizeof...(_Args))
4641 [[__gnu__::__always_inline__]]
4642 _Arg_store(_Tp&... __a) noexcept
4643 : _M_args{_S_make_elt(__a)...}
4647 template<typename _Context>
4648 class __format::_Arg_store<_Context>
4651 template<typename _Context>
4652 template<typename... _Args>
4654 basic_format_args<_Context>::
4655 basic_format_args(const _Store<_Args...>& __store) noexcept
4657 if constexpr (sizeof...(_Args) == 0)
4660 _M_unpacked_size = 0;
4663 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4665 // The number of packed arguments:
4666 _M_packed_size = sizeof...(_Args);
4667 // The packed type enums:
4669 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4670 // The _Arg_value objects.
4671 _M_values = __store._M_args;
4675 // No packed arguments:
4677 // The number of unpacked arguments:
4678 _M_unpacked_size = sizeof...(_Args);
4679 // The basic_format_arg objects:
4680 _M_args = __store._M_args;
4684 /// Capture formatting arguments for use by `std::vformat`.
4685 template<typename _Context = format_context, typename... _Args>
4686 [[nodiscard,__gnu__::__always_inline__]]
4688 make_format_args(_Args&... __fmt_args) noexcept
4690 using _Fmt_arg = basic_format_arg<_Context>;
4691 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4692 _Normalize<_Args>...>;
4693 return _Store(__fmt_args...);
4696#ifdef _GLIBCXX_USE_WCHAR_T
4697 /// Capture formatting arguments for use by `std::vformat` (for wide output).
4698 template<typename... _Args>
4699 [[nodiscard,__gnu__::__always_inline__]]
4701 make_wformat_args(_Args&... __args) noexcept
4702 { return std::make_format_args<wformat_context>(__args...); }
4705/// @cond undocumented
4708 template<typename _Out, typename _CharT, typename _Context>
4710 __do_vformat_to(_Out, basic_string_view<_CharT>,
4711 const basic_format_args<_Context>&,
4712 const locale* = nullptr);
4714 template<typename _CharT> struct __formatter_chrono;
4716} // namespace __format
4719 /** Context for std::format and similar functions.
4721 * A formatting context contains an output iterator and locale to use
4722 * for the formatting operations. Most programs will never need to use
4723 * this class template explicitly. For typical uses of `std::format` the
4724 * library will use the specializations `std::format_context` (for `char`)
4725 * and `std::wformat_context` (for `wchar_t`).
4727 * You are not allowed to define partial or explicit specializations of
4728 * this class template.
4732 template<typename _Out, typename _CharT>
4733 class basic_format_context
4735 static_assert( output_iterator<_Out, const _CharT&> );
4737 basic_format_args<basic_format_context> _M_args;
4739 __format::_Optional_locale _M_loc;
4741 basic_format_context(basic_format_args<basic_format_context> __args,
4743 : _M_args(__args), _M_out(std::move(__out))
4746 basic_format_context(basic_format_args<basic_format_context> __args,
4747 _Out __out, const std::locale& __loc)
4748 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4751 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4752 // 4061. Should std::basic_format_context be
4753 // default-constructible/copyable/movable?
4754 basic_format_context(const basic_format_context&) = delete;
4755 basic_format_context& operator=(const basic_format_context&) = delete;
4757 template<typename _Out2, typename _CharT2, typename _Context2>
4759 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4760 const basic_format_args<_Context2>&,
4763 friend __format::__formatter_chrono<_CharT>;
4766 ~basic_format_context() = default;
4768 using iterator = _Out;
4769 using char_type = _CharT;
4770 template<typename _Tp>
4771 using formatter_type = formatter<_Tp, _CharT>;
4774 basic_format_arg<basic_format_context>
4775 arg(size_t __id) const noexcept
4776 { return _M_args.get(__id); }
4779 std::locale locale() { return _M_loc.value(); }
4782 iterator out() { return std::move(_M_out); }
4784 void advance_to(iterator __it) { _M_out = std::move(__it); }
4788/// @cond undocumented
4791 // Abstract base class defining an interface for scanning format strings.
4792 // Scan the characters in a format string, dividing it up into strings of
4793 // ordinary characters, escape sequences, and replacement fields.
4794 // Call virtual functions for derived classes to parse format-specifiers
4795 // or write formatted output.
4796 template<typename _CharT>
4799 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4801 struct _Parse_context : basic_format_parse_context<_CharT>
4803 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4804 const _Arg_t* _M_types = nullptr;
4808 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4809 : _M_pc(__str, __nargs)
4812 constexpr iterator begin() const noexcept { return _M_pc.begin(); }
4813 constexpr iterator end() const noexcept { return _M_pc.end(); }
4818 basic_string_view<_CharT> __fmt = _M_fmt_str();
4820 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
4822 _M_pc.advance_to(begin() + 1);
4823 _M_format_arg(_M_pc.next_arg_id());
4827 size_t __lbr = __fmt.find('{');
4828 size_t __rbr = __fmt.find('}');
4830 while (__fmt.size())
4832 auto __cmp = __lbr <=> __rbr;
4836 _M_pc.advance_to(end());
4841 if (__lbr + 1 == __fmt.size()
4842 || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
4843 __format::__unmatched_left_brace_in_format_string();
4844 const bool __is_escape = __fmt[__lbr + 1] == '{';
4845 iterator __last = begin() + __lbr + int(__is_escape);
4846 _M_on_chars(__last);
4847 _M_pc.advance_to(__last + 1);
4848 __fmt = _M_fmt_str();
4851 if (__rbr != __fmt.npos)
4853 __lbr = __fmt.find('{');
4857 _M_on_replacement_field();
4858 __fmt = _M_fmt_str();
4859 __lbr = __fmt.find('{');
4860 __rbr = __fmt.find('}');
4865 if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
4866 __format::__unmatched_right_brace_in_format_string();
4867 iterator __last = begin() + __rbr;
4868 _M_on_chars(__last);
4869 _M_pc.advance_to(__last + 1);
4870 __fmt = _M_fmt_str();
4871 if (__lbr != __fmt.npos)
4873 __rbr = __fmt.find('}');
4878 constexpr basic_string_view<_CharT>
4879 _M_fmt_str() const noexcept
4880 { return {begin(), end()}; }
4882 constexpr virtual void _M_on_chars(iterator) { }
4884 constexpr void _M_on_replacement_field()
4886 auto __next = begin();
4890 __id = _M_pc.next_arg_id();
4891 else if (*__next == ':')
4893 __id = _M_pc.next_arg_id();
4894 _M_pc.advance_to(++__next);
4898 auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
4899 if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
4900 __format::__invalid_arg_id_in_format_string();
4901 _M_pc.check_arg_id(__id = __i);
4904 _M_pc.advance_to(++__ptr);
4907 _M_pc.advance_to(__ptr);
4909 _M_format_arg(__id);
4910 if (begin() == end() || *begin() != '}')
4911 __format::__unmatched_left_brace_in_format_string();
4912 _M_pc.advance_to(begin() + 1); // Move past '}'
4915 constexpr virtual void _M_format_arg(size_t __id) = 0;
4918 // Process a format string and format the arguments in the context.
4919 template<typename _Out, typename _CharT>
4920 class _Formatting_scanner : public _Scanner<_CharT>
4923 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4924 basic_string_view<_CharT> __str)
4925 : _Scanner<_CharT>(__str), _M_fc(__fc)
4929 basic_format_context<_Out, _CharT>& _M_fc;
4931 using iterator = typename _Scanner<_CharT>::iterator;
4934 _M_on_chars(iterator __last) override
4936 basic_string_view<_CharT> __str(this->begin(), __last);
4937 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4941 _M_format_arg(size_t __id) override
4943 using _Context = basic_format_context<_Out, _CharT>;
4944 using handle = typename basic_format_arg<_Context>::handle;
4946 __format::__visit_format_arg([this](auto& __arg) {
4947 using _Type = remove_reference_t<decltype(__arg)>;
4948 using _Formatter = typename _Context::template formatter_type<_Type>;
4949 if constexpr (is_same_v<_Type, monostate>)
4950 __format::__invalid_arg_id_in_format_string();
4951 else if constexpr (is_same_v<_Type, handle>)
4952 __arg.format(this->_M_pc, this->_M_fc);
4953 else if constexpr (is_default_constructible_v<_Formatter>)
4956 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4957 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
4960 static_assert(__format::__formattable_with<_Type, _Context>);
4961 }, _M_fc.arg(__id));
4965 template<typename _CharT, typename _Tp>
4967 __to_arg_t_enum() noexcept
4969 using _Context = __format::__format_context<_CharT>;
4970 using _Fmt_arg = basic_format_arg<_Context>;
4971 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
4972 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
4975 // Validate a format string for Args.
4976 template<typename _CharT, typename... _Args>
4977 class _Checking_scanner : public _Scanner<_CharT>
4980 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
4981 "std::formatter must be specialized for each type being formatted");
4985 _Checking_scanner(basic_string_view<_CharT> __str)
4986 : _Scanner<_CharT>(__str, sizeof...(_Args))
4988#if __cpp_lib_format >= 202305L
4989 this->_M_pc._M_types = _M_types.data();
4995 _M_format_arg(size_t __id) override
4997 if constexpr (sizeof...(_Args) != 0)
4999 if (__id < sizeof...(_Args))
5001 _M_parse_format_spec<_Args...>(__id);
5005 __builtin_unreachable();
5008 template<typename _Tp, typename... _OtherArgs>
5010 _M_parse_format_spec(size_t __id)
5014 formatter<_Tp, _CharT> __f;
5015 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5017 else if constexpr (sizeof...(_OtherArgs) != 0)
5018 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5020 __builtin_unreachable();
5023#if __cpp_lib_format >= 202305L
5024 array<_Arg_t, sizeof...(_Args)>
5025 _M_types{ { __format::__to_arg_t_enum<_CharT, _Args>()... } };
5029 template<typename _Out, typename _CharT, typename _Context>
5031 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5032 const basic_format_args<_Context>& __args,
5033 const locale* __loc)
5035 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5036 _Sink_iter<_CharT> __sink_out;
5038 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5039 __sink_out = __out; // Already a sink iterator, safe to use post-move.
5041 __sink_out = __sink.out();
5043 if constexpr (is_same_v<_CharT, char>)
5044 // Fast path for "{}" format strings and simple format arg types.
5045 if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
5047 bool __done = false;
5048 __format::__visit_format_arg([&](auto& __arg) {
5049 using _Tp = remove_cvref_t<decltype(__arg)>;
5050 if constexpr (is_same_v<_Tp, bool>)
5052 size_t __len = 4 + !__arg;
5053 const char* __chars[] = { "false", "true" };
5054 if (auto __res = __sink_out._M_reserve(__len))
5056 __builtin_memcpy(__res.get(), __chars[__arg], __len);
5057 __res._M_bump(__len);
5061 else if constexpr (is_same_v<_Tp, char>)
5063 if (auto __res = __sink_out._M_reserve(1))
5065 *__res.get() = __arg;
5070 else if constexpr (is_integral_v<_Tp>)
5072 make_unsigned_t<_Tp> __uval;
5073 const bool __neg = __arg < 0;
5075 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5078 const auto __n = __detail::__to_chars_len(__uval);
5079 if (auto __res = __sink_out._M_reserve(__n + __neg))
5081 auto __ptr = __res.get();
5083 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5085 __res._M_bump(__n + __neg);
5089 else if constexpr (is_convertible_v<_Tp, string_view>)
5091 string_view __sv = __arg;
5092 if (auto __res = __sink_out._M_reserve(__sv.size()))
5094 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5095 __res._M_bump(__sv.size());
5103 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5106 return std::move(__sink)._M_finish().out;
5110 auto __ctx = __loc == nullptr
5111 ? _Context(__args, __sink_out)
5112 : _Context(__args, __sink_out, *__loc);
5113 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5114 __scanner._M_scan();
5116 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5119 return std::move(__sink)._M_finish().out;
5121#pragma GCC diagnostic pop
5123} // namespace __format
5126#if __cpp_lib_format >= 202305L // >= C++26
5127 /// @cond undocumented
5128 // Common implementation of check_dynamic_spec{,_string,_integral}
5129 template<typename _CharT>
5130 template<typename... _Ts>
5132 basic_format_parse_context<_CharT>::
5133 __check_dynamic_spec(size_t __id) noexcept
5135 if (__id >= _M_num_args)
5136 __format::__invalid_arg_id_in_format_string();
5137 if constexpr (sizeof...(_Ts) != 0)
5139 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5140 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[__id];
5141 __format::_Arg_t __types[] = {
5142 __format::__to_arg_t_enum<_CharT, _Ts>()...
5144 for (auto __t : __types)
5148 __invalid_dynamic_spec("arg(id) type does not match");
5153 template<typename _CharT, typename... _Args>
5154 template<typename _Tp>
5155 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5157 basic_format_string<_CharT, _Args...>::
5158 basic_format_string(const _Tp& __s)
5161 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5163 __scanner._M_scan();
5166 // [format.functions], formatting functions
5168 template<typename _Out> requires output_iterator<_Out, const char&>
5169 [[__gnu__::__always_inline__]]
5171 vformat_to(_Out __out, string_view __fmt, format_args __args)
5172 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5174#ifdef _GLIBCXX_USE_WCHAR_T
5175 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5176 [[__gnu__::__always_inline__]]
5178 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5179 { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5182 template<typename _Out> requires output_iterator<_Out, const char&>
5183 [[__gnu__::__always_inline__]]
5185 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5188 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5191#ifdef _GLIBCXX_USE_WCHAR_T
5192 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5193 [[__gnu__::__always_inline__]]
5195 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5196 wformat_args __args)
5198 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5204 vformat(string_view __fmt, format_args __args)
5206 __format::_Str_sink<char> __buf;
5207 std::vformat_to(__buf.out(), __fmt, __args);
5208 return std::move(__buf).get();
5211#ifdef _GLIBCXX_USE_WCHAR_T
5214 vformat(wstring_view __fmt, wformat_args __args)
5216 __format::_Str_sink<wchar_t> __buf;
5217 std::vformat_to(__buf.out(), __fmt, __args);
5218 return std::move(__buf).get();
5224 vformat(const locale& __loc, string_view __fmt, format_args __args)
5226 __format::_Str_sink<char> __buf;
5227 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5228 return std::move(__buf).get();
5231#ifdef _GLIBCXX_USE_WCHAR_T
5234 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5236 __format::_Str_sink<wchar_t> __buf;
5237 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5238 return std::move(__buf).get();
5242 template<typename... _Args>
5245 format(format_string<_Args...> __fmt, _Args&&... __args)
5246 { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5248#ifdef _GLIBCXX_USE_WCHAR_T
5249 template<typename... _Args>
5252 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5253 { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5256 template<typename... _Args>
5259 format(const locale& __loc, format_string<_Args...> __fmt,
5262 return std::vformat(__loc, __fmt.get(),
5263 std::make_format_args(__args...));
5266#ifdef _GLIBCXX_USE_WCHAR_T
5267 template<typename... _Args>
5270 format(const locale& __loc, wformat_string<_Args...> __fmt,
5273 return std::vformat(__loc, __fmt.get(),
5274 std::make_wformat_args(__args...));
5278 template<typename _Out, typename... _Args>
5279 requires output_iterator<_Out, const char&>
5281 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5283 return std::vformat_to(std::move(__out), __fmt.get(),
5284 std::make_format_args(__args...));
5287#ifdef _GLIBCXX_USE_WCHAR_T
5288 template<typename _Out, typename... _Args>
5289 requires output_iterator<_Out, const wchar_t&>
5291 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5293 return std::vformat_to(std::move(__out), __fmt.get(),
5294 std::make_wformat_args(__args...));
5298 template<typename _Out, typename... _Args>
5299 requires output_iterator<_Out, const char&>
5301 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5304 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5305 std::make_format_args(__args...));
5308#ifdef _GLIBCXX_USE_WCHAR_T
5309 template<typename _Out, typename... _Args>
5310 requires output_iterator<_Out, const wchar_t&>
5312 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5315 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5316 std::make_wformat_args(__args...));
5320 template<typename _Out, typename... _Args>
5321 requires output_iterator<_Out, const char&>
5322 inline format_to_n_result<_Out>
5323 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5324 format_string<_Args...> __fmt, _Args&&... __args)
5326 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5327 std::vformat_to(__sink.out(), __fmt.get(),
5328 std::make_format_args(__args...));
5329 return std::move(__sink)._M_finish();
5332#ifdef _GLIBCXX_USE_WCHAR_T
5333 template<typename _Out, typename... _Args>
5334 requires output_iterator<_Out, const wchar_t&>
5335 inline format_to_n_result<_Out>
5336 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5337 wformat_string<_Args...> __fmt, _Args&&... __args)
5339 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5340 std::vformat_to(__sink.out(), __fmt.get(),
5341 std::make_wformat_args(__args...));
5342 return std::move(__sink)._M_finish();
5346 template<typename _Out, typename... _Args>
5347 requires output_iterator<_Out, const char&>
5348 inline format_to_n_result<_Out>
5349 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5350 format_string<_Args...> __fmt, _Args&&... __args)
5352 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5353 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5354 std::make_format_args(__args...));
5355 return std::move(__sink)._M_finish();
5358#ifdef _GLIBCXX_USE_WCHAR_T
5359 template<typename _Out, typename... _Args>
5360 requires output_iterator<_Out, const wchar_t&>
5361 inline format_to_n_result<_Out>
5362 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5363 wformat_string<_Args...> __fmt, _Args&&... __args)
5365 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5366 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5367 std::make_wformat_args(__args...));
5368 return std::move(__sink)._M_finish();
5372/// @cond undocumented
5376 template<typename _CharT>
5377 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5380 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5382 [[__gnu__::__always_inline__]]
5385 { return this->_M_count + this->_M_used().size(); }
5388 template<typename _CharT>
5389 class _Counting_sink : public _Buf_sink<_CharT>
5391 size_t _M_count = 0;
5394 _M_overflow() override
5396 if (!std::is_constant_evaluated())
5397 _M_count += this->_M_used().size();
5402 _Counting_sink() = default;
5404 [[__gnu__::__always_inline__]]
5408 _Counting_sink::_M_overflow();
5413} // namespace __format
5416 template<typename... _Args>
5419 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5421 __format::_Counting_sink<char> __buf;
5422 std::vformat_to(__buf.out(), __fmt.get(),
5423 std::make_format_args(__args...));
5424 return __buf.count();
5427#ifdef _GLIBCXX_USE_WCHAR_T
5428 template<typename... _Args>
5431 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5433 __format::_Counting_sink<wchar_t> __buf;
5434 std::vformat_to(__buf.out(), __fmt.get(),
5435 std::make_wformat_args(__args...));
5436 return __buf.count();
5440 template<typename... _Args>
5443 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5446 __format::_Counting_sink<char> __buf;
5447 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5448 std::make_format_args(__args...));
5449 return __buf.count();
5452#ifdef _GLIBCXX_USE_WCHAR_T
5453 template<typename... _Args>
5456 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5459 __format::_Counting_sink<wchar_t> __buf;
5460 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5461 std::make_wformat_args(__args...));
5462 return __buf.count();
5466#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5467 /// @cond undocumented
5468 template<typename _Tp>
5469 consteval range_format
5472 using _Ref = ranges::range_reference_t<_Tp>;
5473 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5474 return range_format::disabled;
5475 else if constexpr (requires { typename _Tp::key_type; })
5477 if constexpr (requires { typename _Tp::mapped_type; })
5479 using _Up = remove_cvref_t<_Ref>;
5480 if constexpr (__is_pair<_Up>)
5481 return range_format::map;
5482 else if constexpr (__is_specialization_of<_Up, tuple>)
5483 if constexpr (tuple_size_v<_Up> == 2)
5484 return range_format::map;
5486 return range_format::set;
5489 return range_format::sequence;
5493 /// A constant determining how a range should be formatted.
5494 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5495 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5497/// @cond undocumented
5500 template<typename _CharT, typename _Out, typename _Callback>
5501 typename basic_format_context<_Out, _CharT>::iterator
5502 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5503 const _Spec<_CharT>& __spec,
5506 // This is required to implement formatting with padding,
5507 // as we need to format to temporary buffer, using the same iterator.
5508 static_assert(is_same_v<_Out, __format::_Sink_iter<_CharT>>);
5510 const size_t __padwidth = __spec._M_get_width(__fc);
5511 if (__padwidth == 0)
5512 return __call(__fc);
5516 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5517 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5522 { _M_ctx = nullptr; }
5527 _M_ctx->advance_to(_M_out);
5531 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5532 _Sink_iter<_CharT> _M_out;
5535 _Restore_out __restore(__fc);
5536 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5537 __fc.advance_to(__sink.out());
5539 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5540 __restore._M_disarm();
5544 template<size_t _Pos, typename _Tp, typename _CharT>
5545 struct __indexed_formatter_storage
5550 basic_format_parse_context<_CharT> __pc({});
5551 if (_M_formatter.parse(__pc) != __pc.end())
5552 __format::__failed_to_parse_format_spec();
5555 template<typename _Out>
5557 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5558 basic_format_context<_Out, _CharT>& __fc,
5559 basic_string_view<_CharT> __sep) const
5561 if constexpr (_Pos != 0)
5562 __fc.advance_to(__format::__write(__fc.out(), __sep));
5563 __fc.advance_to(_M_formatter.format(__elem, __fc));
5566 [[__gnu__::__always_inline__]]
5570 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5571 _M_formatter.set_debug_format();
5575 formatter<_Tp, _CharT> _M_formatter;
5578 template<typename _CharT, typename... _Tps>
5579 class __tuple_formatter
5581 using _String_view = basic_string_view<_CharT>;
5582 using _Seps = __format::_Separators<_CharT>;
5586 set_separator(basic_string_view<_CharT> __sep) noexcept
5590 set_brackets(basic_string_view<_CharT> __open,
5591 basic_string_view<_CharT> __close) noexcept
5597 // We deviate from standard, that declares this as template accepting
5598 // unconstrained ParseContext type, which seems unimplementable.
5599 constexpr typename basic_format_parse_context<_CharT>::iterator
5600 parse(basic_format_parse_context<_CharT>& __pc)
5602 auto __first = __pc.begin();
5603 const auto __last = __pc.end();
5604 __format::_Spec<_CharT> __spec{};
5606 auto __finished = [&]
5608 if (__first != __last && *__first != '}')
5612 _M_felems._M_parse();
5613 _M_felems.set_debug_format();
5620 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5624 __first = __spec._M_parse_width(__first, __last, __pc);
5628 if (*__first == 'n')
5631 _M_open = _M_close = _String_view();
5633 else if (*__first == 'm')
5636 if constexpr (sizeof...(_Tps) == 2)
5638 _M_sep = _Seps::_S_colon();
5639 _M_open = _M_close = _String_view();
5642 __throw_format_error("format error: 'm' specifier requires range"
5643 " of pair or tuple of two elements");
5649 __format::__failed_to_parse_format_spec();
5653 template<typename _Tuple, typename _Out, size_t... _Ids>
5654 typename basic_format_context<_Out, _CharT>::iterator
5655 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5656 basic_format_context<_Out, _CharT>& __fc) const
5657 { return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5659 template<typename _Out>
5660 typename basic_format_context<_Out, _CharT>::iterator
5661 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5662 basic_format_context<_Out, _CharT>& __fc) const
5664 return __format::__format_padded(
5666 [this, &__elems...](basic_format_context<_Out, _CharT>& __nfc)
5668 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5669 _M_felems._M_format(__elems..., __nfc, _M_sep);
5670 return __format::__write(__nfc.out(), _M_close);
5675 template<size_t... _Ids>
5676 struct __formatters_storage
5677 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5679 template<size_t _Id, typename _Up>
5680 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5685 (_Base<_Ids, _Tps>::_M_parse(), ...);
5688 template<typename _Out>
5690 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5691 basic_format_context<_Out, _CharT>& __fc,
5692 _String_view __sep) const
5694 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5700 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5704 template<size_t... _Ids>
5706 _S_create_storage(index_sequence<_Ids...>)
5707 -> __formatters_storage<_Ids...>;
5709 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5711 _Spec<_CharT> _M_spec{};
5712 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5713 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5714 _String_view _M_sep = _Seps::_S_comma();
5715 _Formatters _M_felems;
5718 template<typename _Tp>
5719 concept __is_map_formattable
5720 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5722} // namespace __format
5725 // [format.tuple] Tuple formatter
5726 template<__format::__char _CharT, formattable<_CharT> _Fp,
5727 formattable<_CharT> _Sp>
5728 struct formatter<pair<_Fp, _Sp>, _CharT>
5729 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5730 remove_cvref_t<_Sp>>
5733 using __maybe_const_pair
5734 = __conditional_t<formattable<const _Fp, _CharT>
5735 && formattable<const _Sp, _CharT>,
5736 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5738 // We deviate from standard, that declares this as template accepting
5739 // unconstrained FormatContext type, which seems unimplementable.
5740 template<typename _Out>
5741 typename basic_format_context<_Out, _CharT>::iterator
5742 format(__maybe_const_pair& __p,
5743 basic_format_context<_Out, _CharT>& __fc) const
5744 { return this->_M_format_elems(__p.first, __p.second, __fc); }
5747 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5748 struct formatter<tuple<_Tps...>, _CharT>
5749 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5752 using __maybe_const_tuple
5753 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5754 const tuple<_Tps...>, tuple<_Tps...>>;
5756 // We deviate from standard, that declares this as template accepting
5757 // unconstrained FormatContext type, which seems unimplementable.
5758 template<typename _Out>
5759 typename basic_format_context<_Out, _CharT>::iterator
5760 format(__maybe_const_tuple& __t,
5761 basic_format_context<_Out, _CharT>& __fc) const
5762 { return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5765 // [format.range.formatter], class template range_formatter
5766 template<typename _Tp, __format::__char _CharT>
5767 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
5768 class range_formatter
5770 using _String_view = basic_string_view<_CharT>;
5771 using _Seps = __format::_Separators<_CharT>;
5775 set_separator(basic_string_view<_CharT> __sep) noexcept
5779 set_brackets(basic_string_view<_CharT> __open,
5780 basic_string_view<_CharT> __close) noexcept
5786 constexpr formatter<_Tp, _CharT>&
5787 underlying() noexcept
5790 constexpr const formatter<_Tp, _CharT>&
5791 underlying() const noexcept
5794 // We deviate from standard, that declares this as template accepting
5795 // unconstrained ParseContext type, which seems unimplementable.
5796 constexpr typename basic_format_parse_context<_CharT>::iterator
5797 parse(basic_format_parse_context<_CharT>& __pc)
5799 auto __first = __pc.begin();
5800 const auto __last = __pc.end();
5801 __format::_Spec<_CharT> __spec{};
5802 bool __no_brace = false;
5804 auto __finished = [&]
5805 { return __first == __last || *__first == '}'; };
5807 auto __finalize = [&]
5813 auto __parse_val = [&](_String_view __nfs = _String_view())
5815 basic_format_parse_context<_CharT> __npc(__nfs);
5816 if (_M_fval.parse(__npc) != __npc.end())
5817 __format::__failed_to_parse_format_spec();
5818 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
5819 _M_fval.set_debug_format();
5820 return __finalize();
5824 return __parse_val();
5826 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5828 return __parse_val();
5830 __first = __spec._M_parse_width(__first, __last, __pc);
5832 return __parse_val();
5834 if (*__first == '?')
5837 __spec._M_debug = true;
5838 if (__finished() || *__first != 's')
5839 __throw_format_error("format error: '?' is allowed only in"
5840 " combination with 's'");
5843 if (*__first == 's')
5846 if constexpr (same_as<_Tp, _CharT>)
5848 __spec._M_type = __format::_Pres_s;
5850 return __finalize();
5851 __throw_format_error("format error: element format specifier"
5852 " cannot be provided when 's' specifier is used");
5855 __throw_format_error("format error: 's' specifier requires"
5856 " range of character types");
5860 return __parse_val();
5862 if (*__first == 'n')
5865 _M_open = _M_close = _String_view();
5870 return __parse_val();
5872 if (*__first == 'm')
5874 _String_view __m(__first, 1);
5876 if constexpr (__format::__is_map_formattable<_Tp>)
5878 _M_sep = _Seps::_S_comma();
5881 _M_open = _Seps::_S_braces().substr(0, 1);
5882 _M_close = _Seps::_S_braces().substr(1, 1);
5885 return __parse_val(__m);
5886 __throw_format_error("format error: element format specifier"
5887 " cannot be provided when 'm' specifier is used");
5890 __throw_format_error("format error: 'm' specifier requires"
5891 " range of pairs or tuples of two elements");
5895 return __parse_val();
5897 if (*__first == ':')
5899 __pc.advance_to(++__first);
5900 __first = _M_fval.parse(__pc);
5904 return __finalize();
5906 __format::__failed_to_parse_format_spec();
5909 // We deviate from standard, that declares this as template accepting
5910 // unconstrained FormatContext type, which seems unimplementable.
5911 template<ranges::input_range _Rg, typename _Out>
5912 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
5913 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
5914 typename basic_format_context<_Out, _CharT>::iterator
5915 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
5917 using _Range = remove_reference_t<_Rg>;
5918 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
5919 return _M_format<const _Range>(__rg, __fc);
5921 return _M_format(__rg, __fc);
5925 template<ranges::input_range _Rg, typename _Out>
5926 typename basic_format_context<_Out, _CharT>::iterator
5927 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
5929 if constexpr (same_as<_Tp, _CharT>)
5930 if (_M_spec._M_type == __format::_Pres_s)
5932 __format::__formatter_str __fstr(_M_spec);
5933 return __fstr._M_format_range(__rg, __fc);
5935 return __format::__format_padded(
5937 [this, &__rg](basic_format_context<_Out, _CharT>& __nfc)
5938 { return _M_format_elems(__rg, __nfc); });
5942 template<ranges::input_range _Rg, typename _Out>
5943 typename basic_format_context<_Out, _CharT>::iterator
5944 _M_format_elems(_Rg& __rg,
5945 basic_format_context<_Out, _CharT>& __fc) const
5947 auto __out = __format::__write(__fc.out(), _M_open);
5949 auto __first = ranges::begin(__rg);
5950 auto const __last = ranges::end(__rg);
5951 if (__first == __last)
5952 return __format::__write(__out, _M_close);
5954 __fc.advance_to(__out);
5955 __out = _M_fval.format(*__first, __fc);
5956 for (++__first; __first != __last; ++__first)
5958 __out = __format::__write(__out, _M_sep);
5959 __fc.advance_to(__out);
5960 __out = _M_fval.format(*__first, __fc);
5963 return __format::__write(__out, _M_close);
5966 __format::_Spec<_CharT> _M_spec{};
5967 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
5968 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
5969 _String_view _M_sep = _Seps::_S_comma();
5970 formatter<_Tp, _CharT> _M_fval;
5973 // In standard this is shown as inheriting from specialization of
5974 // exposition only specialization for range-default-formatter for
5975 // each range_format. We opt for simpler implementation.
5976 // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
5977 // specializations for maps, sets, and strings
5978 template<ranges::input_range _Rg, __format::__char _CharT>
5979 requires (format_kind<_Rg> != range_format::disabled)
5980 && formattable<ranges::range_reference_t<_Rg>, _CharT>
5981 struct formatter<_Rg, _CharT>
5984 static const bool _S_range_format_is_string =
5985 (format_kind<_Rg> == range_format::string)
5986 || (format_kind<_Rg> == range_format::debug_string);
5987 using _Vt = remove_cvref_t<
5988 ranges::range_reference_t<
5989 __format::__maybe_const_range<_Rg, _CharT>>>;
5991 static consteval bool _S_is_correct()
5993 if constexpr (_S_range_format_is_string)
5994 static_assert(same_as<_Vt, _CharT>);
5998 static_assert(_S_is_correct());
6001 constexpr formatter() noexcept
6003 using _Seps = __format::_Separators<_CharT>;
6004 if constexpr (format_kind<_Rg> == range_format::map)
6006 static_assert(__format::__is_map_formattable<_Vt>);
6007 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6008 _Seps::_S_braces().substr(1, 1));
6009 _M_under.underlying().set_brackets({}, {});
6010 _M_under.underlying().set_separator(_Seps::_S_colon());
6012 else if constexpr (format_kind<_Rg> == range_format::set)
6013 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6014 _Seps::_S_braces().substr(1, 1));
6018 set_separator(basic_string_view<_CharT> __sep) noexcept
6019 requires (format_kind<_Rg> == range_format::sequence)
6020 { _M_under.set_separator(__sep); }
6023 set_brackets(basic_string_view<_CharT> __open,
6024 basic_string_view<_CharT> __close) noexcept
6025 requires (format_kind<_Rg> == range_format::sequence)
6026 { _M_under.set_brackets(__open, __close); }
6028 // We deviate from standard, that declares this as template accepting
6029 // unconstrained ParseContext type, which seems unimplementable.
6030 constexpr typename basic_format_parse_context<_CharT>::iterator
6031 parse(basic_format_parse_context<_CharT>& __pc)
6033 auto __res = _M_under.parse(__pc);
6034 if constexpr (format_kind<_Rg> == range_format::debug_string)
6035 _M_under.set_debug_format();
6039 // We deviate from standard, that declares this as template accepting
6040 // unconstrained FormatContext type, which seems unimplementable.
6041 template<typename _Out>
6042 typename basic_format_context<_Out, _CharT>::iterator
6043 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6044 basic_format_context<_Out, _CharT>& __fc) const
6046 if constexpr (_S_range_format_is_string)
6047 return _M_under._M_format_range(__rg, __fc);
6049 return _M_under.format(__rg, __fc);
6053 using _Formatter_under
6054 = __conditional_t<_S_range_format_is_string,
6055 __format::__formatter_str<_CharT>,
6056 range_formatter<_Vt, _CharT>>;
6057 _Formatter_under _M_under;
6059#endif // C++23 formatting ranges
6060#undef _GLIBCXX_WIDEN
6062_GLIBCXX_END_NAMESPACE_VERSION
6064#endif // __cpp_lib_format
6065#pragma GCC diagnostic pop
6066#endif // _GLIBCXX_FORMAT