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> // 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 // Output iterator that ignores the characters
114 template<typename _CharT>
117 // An unspecified output iterator type used in the `
formattable`
concept.
118 template<typename _CharT>
120 {
using type = _Drop_iter<_CharT>; };
122 template<typename _CharT>
123 using __format_context = basic_format_context<_Sink_iter<_CharT>, _CharT>;
125 template<typename _CharT>
126 struct _Runtime_format_string
128 [[
__gnu__::__always_inline__]]
129 _Runtime_format_string(basic_string_view<_CharT> __s) noexcept
132 _Runtime_format_string(const _Runtime_format_string&) = delete;
133 void operator=(const _Runtime_format_string&) = delete;
136 basic_string_view<_CharT> _M_str;
138 template<typename, typename...> friend struct std::basic_format_string;
141}
// namespace __format
144 using format_context = __format::__format_context<char>;
145#ifdef _GLIBCXX_USE_WCHAR_T
146 using wformat_context = __format::__format_context<wchar_t>;
149 // [
format.args]
, class template basic_format_args
150 template<typename _Context> class basic_format_args;
151 using format_args = basic_format_args<format_context>;
152#ifdef _GLIBCXX_USE_WCHAR_T
153 using wformat_args = basic_format_args<wformat_context>;
156 // [
format.arguments]
, arguments
157 // [
format.arg]
, class template basic_format_arg
158 template<typename _Context>
159 class basic_format_arg;
161 /** A compile-time checked format string for the specified argument types.
163 * @
since C++23 but available as an extension in C++20.
165 template<typename _CharT, typename... _Args>
166 struct basic_format_string
168 template<typename _Tp>
169 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
171 basic_format_string(const _Tp& __s);
173 [[
__gnu__::__always_inline__]]
174 basic_format_string(__format::_Runtime_format_string<_CharT> __s) noexcept
178 [[
__gnu__::__always_inline__]]
179 constexpr basic_string_view<_CharT>
184 basic_string_view<_CharT> _M_str;
187 template<typename... _Args>
188 using format_string = basic_format_string<char, type_identity_t<_Args>...>;
190#ifdef _GLIBCXX_USE_WCHAR_T
191 template<typename... _Args>
193 = basic_format_string<wchar_t, type_identity_t<_Args>...>;
196#if __cpp_lib_format >= 202311L // >= C++26
197 [[
__gnu__::__always_inline__]]
198 inline __format::_Runtime_format_string<char>
199 runtime_format(string_view __fmt) noexcept
202#ifdef _GLIBCXX_USE_WCHAR_T
203 [[
__gnu__::__always_inline__]]
204 inline __format::_Runtime_format_string<wchar_t>
205 runtime_format(wstring_view __fmt) noexcept
210 // [
format.formatter]
, formatter
212 /// The primary template of std::formatter is disabled.
213 template<typename _Tp, typename _CharT>
216 formatter() = delete;
// No std::formatter specialization for this type.
217 formatter(const formatter&) = delete;
218 formatter& operator=(const formatter&) = delete;
221 // [
format.error]
, class format_error
222 class format_error : public runtime_error
225 explicit format_error(const string& __what) : runtime_error(__what) { }
226 explicit format_error(const char* __what) : runtime_error(__what) { }
229 /// @
cond undocumented
232 __throw_format_error(const char* __what)
233 {
_GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
237 // XXX use named functions for each constexpr error?
241 __unmatched_left_brace_in_format_string()
242 {
__throw_format_error("format error: unmatched '{' in format string"); }
246 __unmatched_right_brace_in_format_string()
247 {
__throw_format_error("format error: unmatched '}' in format string"); }
251 __conflicting_indexing_in_format_string()
252 {
__throw_format_error("format error: conflicting indexing style in format string"); }
256 __invalid_arg_id_in_format_string()
257 {
__throw_format_error("format error: invalid arg-id in format string"); }
261 __failed_to_parse_format_spec()
262 {
__throw_format_error("format error: failed to parse format-spec"); }
264 template<typename _CharT> class _Scanner;
266}
// namespace __format
269 // [
format.parse.ctx]
, class template basic_format_parse_context
270 template<typename _CharT> class basic_format_parse_context;
271 using format_parse_context = basic_format_parse_context<char>;
272#ifdef _GLIBCXX_USE_WCHAR_T
273 using wformat_parse_context = basic_format_parse_context<wchar_t>;
276 template<typename _CharT>
277 class basic_format_parse_context
280 using char_type = _CharT;
281 using const_iterator = typename basic_string_view<_CharT>::const_iterator;
282 using iterator = const_iterator;
285 basic_format_parse_context(basic_string_view<_CharT> __fmt) noexcept
286 : _M_begin(__fmt.begin()), _M_end(__fmt.end())
289 basic_format_parse_context(const basic_format_parse_context&) = delete;
290 void operator=(const basic_format_parse_context&) = delete;
292 constexpr const_iterator begin() const noexcept {
return _M_begin; }
293 constexpr const_iterator end() const noexcept {
return _M_end; }
296 advance_to(const_iterator __it) noexcept
302 if (_M_indexing == _Manual)
303 __format::__conflicting_indexing_in_format_string();
306 // _GLIBCXX_RESOLVE_LIB_DEFECTS
307 // 3825.
Missing compile-time argument id check in next_arg_id
308 if (std::is_constant_evaluated())
309 if (_M_next_arg_id == _M_num_args)
310 __format::__invalid_arg_id_in_format_string();
311 return _M_next_arg_id++;
315 check_arg_id(size_t __id)
317 if (_M_indexing == _Auto)
318 __format::__conflicting_indexing_in_format_string();
319 _M_indexing = _Manual;
321 if (std::is_constant_evaluated())
322 if (__id >= _M_num_args)
323 __format::__invalid_arg_id_in_format_string();
326#if __cpp_lib_format >= 202305L
327 template<typename... _Ts>
329 check_dynamic_spec(size_t __id) noexcept
331 static_assert(__valid_types_for_check_dynamic_spec<_Ts...>(),
332 "template arguments for check_dynamic_spec<Ts...>(id) "
333 "must be unique and must be one of the allowed types");
335 __check_dynamic_spec<_Ts...>(__id);
340 check_dynamic_spec_integral(size_t __id) noexcept
343 __check_dynamic_spec<int, unsigned, long long,
344 unsigned long long>(__id);
349 check_dynamic_spec_string(size_t __id) noexcept
352 __check_dynamic_spec<const _CharT*, basic_string_view<_CharT>>(__id);
357 // True if _Tp occurs exactly once in _Ts.
358 template<typename _Tp, typename... _Ts>
359 static constexpr bool __once = (is_same_v<_Tp, _Ts> + ...) == 1;
361 template<typename... _Ts>
363 __valid_types_for_check_dynamic_spec()
365 // _GLIBCXX_RESOLVE_LIB_DEFECTS
366 // 4142.
check_dynamic_spec should require at least one type
367 if constexpr (sizeof...(_Ts) == 0)
371 // The types in Ts... are unique. Each type in Ts... is one of
372 // bool, char_type, int, unsigned int, long long int,
373 // unsigned long long int, float, double, long double,
374 // const char_type*, basic_string_view<char_type>, or const void*.
376 = __once<bool, _Ts...>
377 + __once<char_type, _Ts...>
378 + __once<int, _Ts...>
379 + __once<unsigned int, _Ts...>
380 + __once<long long int, _Ts...>
381 + __once<unsigned long long int, _Ts...>
382 + __once<float, _Ts...>
383 + __once<double, _Ts...>
384 + __once<long double, _Ts...>
385 + __once<const char_type*, _Ts...>
386 + __once<basic_string_view<char_type>, _Ts...>
387 + __once<const void*, _Ts...>;
388 return __sum == sizeof...(_Ts);
392 template<typename... _Ts>
394 __check_dynamic_spec(size_t __id) noexcept;
396 // This must not be constexpr.
397 static void __invalid_dynamic_spec(const char*);
399 friend __format::_Scanner<_CharT>;
402 // This constructor should only be used by the implementation.
404 basic_format_parse_context(basic_string_view<_CharT> __fmt,
405 size_t __num_args) noexcept
406 : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
412 enum _Indexing {
_Unknown, _Manual, _Auto };
413 _Indexing _M_indexing = _Unknown;
414 size_t _M_next_arg_id = 0;
415 size_t _M_num_args = 0;
418/// @
cond undocumented
419 template<typename _Tp, template<typename...> class _Class>
420 constexpr bool __is_specialization_of = false;
421 template<template<typename...> class _Class, typename... _Args>
422 constexpr bool __is_specialization_of<_Class<_Args...>, _Class> = true;
426 // pre: first != last
427 template<typename _CharT>
428 constexpr pair<unsigned short, const _CharT*>
429 __parse_integer(const _CharT* __first, const _CharT* __last)
431 if (__first == __last)
432 __builtin_unreachable();
434 if constexpr (is_same_v<_CharT, char>)
436 const auto __start = __first;
437 unsigned short __val = 0;
438 // N.B. std::from_chars is not constexpr in C++20.
439 if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
440 && __first != __start) [[
likely]]
441 return {
__val, __first};
445 constexpr int __n = 32;
447 for (int __i = 0;
__i < __n && (__first + __i) != __last;
++__i)
448 __buf[
__i]
= __first[
__i];
449 auto [
__v, __ptr]
= __format::__parse_integer(__buf, __buf + __n);
450 if (__ptr) [[
likely]]
451 return {
__v, __first + (__ptr - __buf)};
456 template<typename _CharT>
457 constexpr pair<unsigned short, const _CharT*>
458 __parse_arg_id(const _CharT* __first, const _CharT* __last)
460 if (__first == __last)
461 __builtin_unreachable();
464 return {
0, __first + 1};
// No leading zeros allowed, so '0...
' == 0
466 if ('1' <= *__first && *__first <= '9')
468 const unsigned short __id = *__first - '0';
469 const auto __next = __first + 1;
470 // Optimize for most likely case of single digit arg-id.
471 if (__next == __last || !('0' <= *__next && *__next <= '9'))
472 return {
__id, __next};
474 return __format::__parse_integer(__first, __last);
479 enum class _Pres_type : unsigned char {
480 _Pres_none = 0, // Default type (not valid for integer presentation types).
481 _Pres_s = 1, // For strings, bool, ranges
482 // Presentation types for integral types (including bool and charT).
483 _Pres_c = 2, _Pres_x, _Pres_X, _Pres_d, _Pres_o, _Pres_b, _Pres_B,
484 // Presentation types for floating-point types
485 _Pres_g = 1, _Pres_G, _Pres_a, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F,
486 // For pointers, the value are same as hexadecimal presentations for integers
487 _Pres_p = _Pres_x, _Pres_P = _Pres_X,
490 using enum _Pres_type;
492 enum class _Sign : unsigned char {
495 _Sign_minus, // XXX does this need to be distinct from _Sign_default?
500 enum _WidthPrec : unsigned char {
501 _WP_none, // No width/prec specified.
502 _WP_value, // Fixed width/prec specified.
503 _WP_from_arg // Use a formatting argument for width/prec.
505 using enum _WidthPrec;
507 template<typename _Context>
509 __int_from_arg(const basic_format_arg<_Context>& __arg);
511 constexpr bool __is_digit(char __c)
512 {
return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
514 constexpr bool __is_xdigit(char __c)
515 {
return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
517 // Used to make _Spec a non-C++98 POD, so the tail-padding is used.
518 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#pod
522 template<typename _CharT>
523 struct _Spec : _SpecBase
525 unsigned short _M_width;
526 unsigned short _M_prec;
527 char32_t _M_fill = ' ';
531 unsigned _M_localized : 1;
532 unsigned _M_zero_fill : 1;
533 _WidthPrec _M_width_kind : 2;
534 _WidthPrec _M_prec_kind : 2;
535 unsigned _M_debug : 1;
536 _Pres_type _M_type : 4;
537 unsigned _M_reserved : 8;
538 // This class has 8 bits of tail padding, that can be used by
541 using iterator = typename basic_string_view<_CharT>::iterator;
543 static constexpr _Align
544 _S_align(_CharT __c) noexcept
548 case '<': return _Align_left;
549 case '>': return _Align_right;
550 case '^': return _Align_centre;
551 default: return _Align_default;
555 // pre: __first != __last
557 _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
558 {
return _M_parse_fill_and_align(__first, __last, "{"); }
560 // pre: __first != __last
562 _M_parse_fill_and_align(iterator __first, iterator __last, string_view __not_fill) noexcept
564 for (char __c : __not_fill)
565 if (*__first == static_cast<_CharT>(__c))
568 using namespace __unicode;
569 if constexpr (__literal_encoding_is_unicode<_CharT>())
571 // Accept any UCS scalar value as fill character.
572 _Utf32_view<ranges::subrange<iterator>> __uv({
__first, __last}
);
575 auto __beg = __uv.begin();
576 char32_t __c = *__beg++;
577 if (__is_scalar_value(__c))
578 if (auto __next = __beg.base();
__next != __last)
579 if (_Align __align = _S_align(*__next);
__align != _Align_default)
587 else if (__last - __first >= 2)
588 if (_Align __align = _S_align(__first[
1]
);
__align != _Align_default)
595 if (_Align __align = _S_align(__first[
0]
);
__align != _Align_default)
604 static constexpr _Sign
605 _S_sign(_CharT __c) noexcept
609 case '+': return _Sign_plus;
610 case '-': return _Sign_minus;
611 case ' ': return _Sign_space;
612 default: return _Sign_default;
616 // pre: __first != __last
618 _M_parse_sign(iterator __first, iterator) noexcept
620 if (_Sign __sign = _S_sign(*__first);
__sign != _Sign_default)
628 // pre: *__first is valid
630 _M_parse_alternate_form(iterator __first, iterator) noexcept
640 // pre: __first != __last
642 _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
652 // pre: __first != __last
653 static constexpr iterator
654 _S_parse_width_or_precision(iterator __first, iterator __last,
655 unsigned short& __val, bool& __arg_id,
656 basic_format_parse_context<_CharT>& __pc)
658 if (__format::__is_digit(*__first))
660 auto [
__v, __ptr]
= __format::__parse_integer(__first, __last);
662 __throw_format_error("format error: invalid width or precision "
667 else if (*__first == '{
')
671 if (__first == __last)
672 __format::__unmatched_left_brace_in_format_string();
674 __val = __pc.next_arg_id();
677 auto [
__v, __ptr]
= __format::__parse_arg_id(__first, __last);
678 if (__ptr == nullptr || __ptr == __last || *__ptr != '}
')
679 __format::__invalid_arg_id_in_format_string();
681 __pc.check_arg_id(__v);
684#if __cpp_lib_format >= 202305L
685 __pc.check_dynamic_spec_integral(__val);
687 ++__first;
// past the '}
'
692 // pre: __first != __last
694 _M_parse_width(iterator __first, iterator __last,
695 basic_format_parse_context<_CharT>& __pc)
697 bool __arg_id = false;
699 __throw_format_error("format error: width must be non-zero in "
701 auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
703 if (__next != __first)
704 _M_width_kind = __arg_id ?
_WP_from_arg : _WP_value;
708 // pre: __first != __last
710 _M_parse_precision(iterator __first, iterator __last,
711 basic_format_parse_context<_CharT>& __pc)
713 if (__first[
0]
!= '.')
716 iterator __next = ++__first;
717 bool __arg_id = false;
718 if (__next != __last)
719 __next = _S_parse_width_or_precision(__first, __last, _M_prec,
721 if (__next == __first)
722 __throw_format_error("format error: missing precision after '.' in "
724 _M_prec_kind = __arg_id ?
_WP_from_arg : _WP_value;
728 // pre: __first != __last
730 _M_parse_locale(iterator __first, iterator /* __last */) noexcept
740 template<typename _Context>
742 _M_get_width(_Context& __ctx) const
745 if (_M_width_kind == _WP_value)
747 else if (_M_width_kind == _WP_from_arg)
748 __width = __format::__int_from_arg(__ctx.arg(_M_width));
752 template<typename _Context>
754 _M_get_precision(_Context& __ctx) const
757 if (_M_prec_kind == _WP_value)
759 else if (_M_prec_kind == _WP_from_arg)
760 __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
765 template<typename _Int>
767 __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
771 else if (__sign == _Sign_plus)
773 else if (__sign == _Sign_space)
780 // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
781 template<typename _Out, typename _CharT>
782 requires output_iterator<_Out, const _CharT&>
784 __write(_Out __out, basic_string_view<_CharT> __str)
786 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
792 for (_CharT __c : __str)
797 // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
798 // pre: __align != _Align_default
799 template<typename _Out, typename _CharT>
801 __write_padded(_Out __out, basic_string_view<_CharT> __str,
802 _Align __align, size_t __nfill, char32_t __fill_char)
804 const size_t __buflen = 0x20;
805 _CharT __padding_chars[
__buflen];
806 __padding_chars[
0]
= _CharT();
807 basic_string_view<_CharT> __padding{
__padding_chars, __buflen};
809 auto __pad = [
&__padding]
(size_t __n, _Out& __o) {
812 while (__n > __padding.size())
814 __o = __format::__write(std::move(__o), __padding);
815 __n -= __padding.size();
818 __o = __format::__write(std::move(__o), __padding.substr(0, __n));
821 size_t __l, __r, __max;
822 if (__align == _Align_centre)
825 __r = __l + (__nfill & 1);
828 else if (__align == _Align_right)
841 using namespace __unicode;
842 if constexpr (__literal_encoding_is_unicode<_CharT>())
843 if (!__is_single_code_unit<_CharT>(__fill_char)) [[
unlikely]]
845 // Encode fill char as multiple code units of type _CharT.
846 const char32_t __arr[
1]{
__fill_char };
847 _Utf_view<_CharT, const char32_t(&)[
1]
> __v(__arr);
848 basic_string<_CharT> __padstr(__v.begin(), __v.end());
849 __padding = __padstr;
851 __out = __format::__write(std::move(__out), __padding);
852 __out = __format::__write(std::move(__out), __str);
854 __out = __format::__write(std::move(__out), __padding);
858 if (__max < __buflen)
859 __padding.remove_suffix(__buflen - __max);
863 char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
865 __out = __format::__write(std::move(__out), __str);
871 // Write STR to OUT, with alignment and padding as determined by SPEC.
872 // pre: __spec._M_align != _Align_default || __align != _Align_default
873 template<typename _CharT, typename _Out>
875 __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
876 size_t __estimated_width,
877 basic_format_context<_Out, _CharT>& __fc,
878 const _Spec<_CharT>& __spec,
879 _Align __align = _Align_left)
881 size_t __width = __spec._M_get_width(__fc);
883 if (__width <= __estimated_width)
884 return __format::__write(__fc.out(), __str);
886 const size_t __nfill = __width - __estimated_width;
888 if (__spec._M_align != _Align_default)
889 __align = __spec._M_align;
891 return __format::__write_padded(__fc.out(), __str, __align, __nfill,
895 template<typename _CharT>
897 __truncate(basic_string_view<_CharT>& __s, size_t __prec)
899 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
901 if (__prec != (size_t)-1)
902 return __unicode::__truncate(__s, __prec);
904 return __unicode::__field_width(__s);
908 __s = __s.substr(0, __prec);
913 enum class _Term_char : unsigned char {
918 using enum _Term_char;
920 template<typename _CharT>
923 using _Str_view = basic_string_view<_CharT>;
927 {
return _GLIBCXX_WIDEN("\t\\t\n\\n\r\\r\\\\\\\"\\\
"'\\'\\u\\x"); }
931 {
return _S_all().substr(0, 3); }
934 _Str_view _S_newline()
935 {
return _S_all().substr(3, 3); }
938 _Str_view _S_return()
939 {
return _S_all().substr(6, 3); }
942 _Str_view _S_bslash()
943 {
return _S_all().substr(9, 3); }
947 {
return _S_all().substr(12, 3); }
951 {
return _S_all().substr(15, 3); }
955 {
return _S_all().substr(18, 2); }
959 {
return _S_all().substr(20, 2); }
962 _Str_view _S_term(_Term_char __term)
969 return _S_quote().substr(0, 1);
971 return _S_apos().substr(0, 1);
973 __builtin_unreachable();
977 template<typename _CharT>
980 using _Str_view = basic_string_view<_CharT>;
984 {
return _GLIBCXX_WIDEN("[]{}(), : "); }
987 _Str_view _S_squares()
988 {
return _S_all().substr(0, 2); }
991 _Str_view _S_braces()
992 {
return _S_all().substr(2, 2); }
995 _Str_view _S_parens()
996 {
return _S_all().substr(4, 2); }
1000 {
return _S_all().substr(6, 2); }
1003 _Str_view _S_colon()
1004 {
return _S_all().substr(8, 2); }
1007 template<typename _CharT>
1008 constexpr bool __should_escape_ascii(_CharT __c, _Term_char __term)
1010 using _Esc = _Escapes<_CharT>;
1013 case _Esc::_S_tab()[
0]
:
1014 case _Esc::_S_newline()[
0]
:
1015 case _Esc::_S_return()[
0]
:
1016 case _Esc::_S_bslash()[
0]
:
1018 case _Esc::_S_quote()[
0]
:
1019 return __term == _Term_quote;
1020 case _Esc::_S_apos()[
0]
:
1021 return __term == _Term_apos;
1023 return (__c >= 0 && __c < 0x20) || __c == 0x7f;
1027 // @
pre __c <= 0x10FFFF
1028 constexpr bool __should_escape_unicode(char32_t __c, bool __prev_esc)
1030 if (__unicode::__should_escape_category(__c))
1034 return __unicode::__grapheme_cluster_break_property(__c)
1035 == __unicode::_Gcb_property::_Gcb_Extend;
1038 using uint_least32_t = __UINT_LEAST32_TYPE__;
1039 template<typename _Out, typename _CharT>
1041 __write_escape_seq(_Out __out, uint_least32_t __val,
1042 basic_string_view<_CharT> __prefix)
1044 using _Str_view = basic_string_view<_CharT>;
1045 constexpr size_t __max = 8;
1047 const string_view __narrow(
1049 std::__to_chars_i<uint_least32_t>(__buf, __buf + __max, __val, 16).ptr);
1051 __out = __format::__write(__out, __prefix);
1052 *__out = _Separators<_CharT>::_S_braces()[
0];
1054 if constexpr (is_same_v<char, _CharT>)
1055 __out = __format::__write(__out, __narrow);
1056#ifdef _GLIBCXX_USE_WCHAR_T
1059 _CharT __wbuf[
__max];
1060 const size_t __n = __narrow.size();
1061 std::__to_wstring_numeric(__narrow.data(), __n, __wbuf);
1062 __out = __format::__write(__out, _Str_view(__wbuf, __n));
1065 *__out = _Separators<_CharT>::_S_braces()[
1];
1069 template<typename _Out, typename _CharT>
1071 __write_escaped_char(_Out __out, _CharT __c)
1073 using _UChar = make_unsigned_t<_CharT>;
1074 using _Esc = _Escapes<_CharT>;
1077 case _Esc::_S_tab()[
0]
:
1078 return __format::__write(__out, _Esc::_S_tab().substr(1, 2));
1079 case _Esc::_S_newline()[
0]
:
1080 return __format::__write(__out, _Esc::_S_newline().substr(1, 2));
1081 case _Esc::_S_return()[
0]
:
1082 return __format::__write(__out, _Esc::_S_return().substr(1, 2));
1083 case _Esc::_S_bslash()[
0]
:
1084 return __format::__write(__out, _Esc::_S_bslash().substr(1, 2));
1085 case _Esc::_S_quote()[
0]
:
1086 return __format::__write(__out, _Esc::_S_quote().substr(1, 2));
1087 case _Esc::_S_apos()[
0]
:
1088 return __format::__write(__out, _Esc::_S_apos().substr(1, 2));
1090 return __format::__write_escape_seq(
1091 __out, static_cast<_UChar>(__c), _Esc::_S_u());
1095 template<typename _CharT, typename _Out>
1097 __write_escaped_ascii(_Out __out,
1098 basic_string_view<_CharT> __str,
1101 using _Str_view = basic_string_view<_CharT>;
1102 auto __first = __str.begin();
1103 auto const __last = __str.end();
1104 while (__first != __last)
1106 auto __print = __first;
1107 // assume anything outside ASCII is printable
1108 while (__print != __last
1109 && !__format::__should_escape_ascii(*__print, __term))
1112 if (__print != __first)
1113 __out = __format::__write(__out, _Str_view(__first, __print));
1115 if (__print == __last)
1119 __out = __format::__write_escaped_char(__out, *__first);
1125 template<typename _CharT, typename _Out>
1127 __write_escaped_unicode(_Out __out,
1128 basic_string_view<_CharT> __str,
1131 using _Str_view = basic_string_view<_CharT>;
1132 using _UChar = make_unsigned_t<_CharT>;
1133 using _Esc = _Escapes<_CharT>;
1135 static constexpr char32_t __replace = U'\
uFFFD';
1136 static constexpr _Str_view __replace_rep = []
1138 // N.B. "\uFFFD" is ill-formed if encoding is not unicode.
1139 if constexpr (is_same_v<char, _CharT>)
1140 return "\xEF\xBF\xBD";
1145 __unicode::_Utf_view<char32_t, _Str_view> __v(std::move(__str));
1146 auto __first = __v.begin();
1147 auto const __last = __v.end();
1149 bool __prev_esc = true;
1150 while (__first != __last)
1152 bool __esc_ascii = false;
1153 bool __esc_unicode = false;
1154 bool __esc_replace = false;
1155 auto __should_escape = [
&]
(auto const& __it)
1159 = __format::__should_escape_ascii(*__it.base(), __term);
1160 if (__format::__should_escape_unicode(*__it, __prev_esc))
1161 return __esc_unicode = true;
1162 if (*__it == __replace)
1164 _Str_view __units(__it.base(), __it._M_units());
1165 return __esc_replace = (__units != __replace_rep);
1170 auto __print = __first;
1171 while (__print != __last && !__should_escape(__print))
1177 if (__print != __first)
1178 __out = __format::__write(__out, _Str_view(__first.base(), __print.base()));
1180 if (__print == __last)
1185 __out = __format::__write_escaped_char(__out, *__first.base());
1186 else if (__esc_unicode)
1187 __out = __format::__write_escape_seq(__out, *__first, _Esc::_S_u());
1188 else // __esc_replace
1189 for (_CharT __c : _Str_view(__first.base(), __first._M_units()))
1190 __out = __format::__write_escape_seq(__out,
1191 static_cast<_UChar>(__c),
1200 template<typename _CharT, typename _Out>
1202 __write_escaped(_Out __out, basic_string_view<_CharT> __str, _Term_char __term)
1204 __out = __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1206 if constexpr (__unicode::__literal_encoding_is_unicode<_CharT>())
1207 __out = __format::__write_escaped_unicode(__out, __str, __term);
1208 else if constexpr (is_same_v<char, _CharT>
1209 && __unicode::__literal_encoding_is_extended_ascii())
1210 __out = __format::__write_escaped_ascii(__out, __str, __term);
1212 // TODO Handle non-ascii extended encoding
1213 __out = __format::__write_escaped_ascii(__out, __str, __term);
1215 return __format::__write(__out, _Escapes<_CharT>::_S_term(__term));
1218 // A lightweight optional<locale>.
1219 struct _Optional_locale
1221 [[
__gnu__::__always_inline__]]
1222 _Optional_locale() : _M_dummy(), _M_hasval(false) { }
1224 _Optional_locale(const locale& __loc) noexcept
1225 : _M_loc(__loc), _M_hasval(true)
1228 _Optional_locale(const _Optional_locale& __l) noexcept
1229 : _M_dummy(), _M_hasval(__l._M_hasval)
1232 std::construct_at(&_M_loc, __l._M_loc);
1236 operator=(const _Optional_locale& __l) noexcept
1241 _M_loc = __l._M_loc;
1248 else if (__l._M_hasval)
1250 std::construct_at(&_M_loc, __l._M_loc);
1256 ~_Optional_locale() {
if (_M_hasval) _M_loc.~locale(); }
1259 operator=(locale&& __loc) noexcept
1262 _M_loc = std::move(__loc);
1265 std::construct_at(&_M_loc, std::move(__loc));
1276 std::construct_at(&_M_loc);
1282 bool has_value() const noexcept {
return _M_hasval; }
1285 char _M_dummy = '\
0';
1288 bool _M_hasval = false;
1291 template<__char _CharT>
1292 struct __formatter_str
1294 __formatter_str() = default;
1297 __formatter_str(_Spec<_CharT> __spec) noexcept
1301 constexpr typename basic_format_parse_context<_CharT>::iterator
1302 parse(basic_format_parse_context<_CharT>& __pc)
1304 auto __first = __pc.begin();
1305 const auto __last = __pc.end();
1306 _Spec<_CharT> __spec{};
1308 auto __finalize = [
this, &__spec] {
1312 auto __finished = [
&] {
1313 if (__first == __last || *__first == '}
')
1324 __first = __spec._M_parse_fill_and_align(__first, __last);
1328 __first = __spec._M_parse_width(__first, __last, __pc);
1332 __first = __spec._M_parse_precision(__first, __last, __pc);
1336 if (*__first == 's')
1338 __spec._M_type = _Pres_s;
1341#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1342 else if (*__first == '?
')
1344 __spec._M_debug = true;
1352 __format::__failed_to_parse_format_spec();
1355 template<typename _Out>
1357 format(basic_string_view<_CharT> __s,
1358 basic_format_context<_Out, _CharT>& __fc) const
1360 if (_M_spec._M_debug)
1361 return _M_format_escaped(__s, __fc);
1363 if (_M_spec._M_width_kind == _WP_none
1364 && _M_spec._M_prec_kind == _WP_none)
1365 return __format::__write(__fc.out(), __s);
1367 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1368 const size_t __width = __format::__truncate(__s, __maxwidth);
1369 return __format::__write_padded_as_spec(__s, __width, __fc, _M_spec);
1372 template<typename _Out>
1374 _M_format_escaped(basic_string_view<_CharT> __s,
1375 basic_format_context<_Out, _CharT>& __fc) const
1377 const size_t __padwidth = _M_spec._M_get_width(__fc);
1378 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1379 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1381 const size_t __maxwidth = _M_spec._M_get_precision(__fc);
1382 const size_t __width = __truncate(__s, __maxwidth);
1383 // N.B. Escaping only increases width
1384 if (__padwidth <= __width && _M_spec._M_prec_kind == _WP_none)
1385 return __format::__write_escaped(__fc.out(), __s, _Term_quote);
1387 // N.B. [
tab:format.type.string]
defines '?
' as
1388 // Copies the escaped string ([
format.string.escaped]
) to the output,
1389 // so precision seem to appy to escaped string.
1390 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth, __maxwidth);
1391 __format::__write_escaped(__sink.out(), __s, _Term_quote);
1392 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1395#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1396 template<ranges::input_range _Rg, typename _Out>
1397 requires same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _CharT>
1399 _M_format_range(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
1401 using _Range = remove_reference_t<_Rg>;
1402 using _String = basic_string<_CharT>;
1403 using _String_view = basic_string_view<_CharT>;
1404 if constexpr (!is_lvalue_reference_v<_Rg>)
1405 return _M_format_range<_Range&>(__rg, __fc);
1406 else if constexpr (!is_const_v<_Range>
1407 && __simply_formattable_range<_Range, _CharT>)
1408 return _M_format_range<const _Range&>(__rg, __fc);
1409 else if constexpr (ranges::contiguous_range<_Rg>)
1411 _String_view __str(ranges::data(__rg),
1412 size_t(ranges::distance(__rg)));
1413 return format(__str, __fc);
1415 else if (!_M_spec._M_debug)
1417 const size_t __padwidth = _M_spec._M_get_width(__fc);
1418 if (__padwidth == 0 && _M_spec._M_prec_kind == _WP_none)
1419 return ranges::copy(__rg, __fc.out()).out;
1421 _Padding_sink<_Out, _CharT> __sink(__fc.out(), __padwidth,
1422 _M_spec._M_get_precision(__fc));
1423 ranges::copy(__rg, __sink.out());
1424 return __sink._M_finish(_M_spec._M_align, _M_spec._M_fill);
1426 else if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
1428 const size_t __n(ranges::distance(__rg));
1430 if constexpr (!__unicode::__literal_encoding_is_unicode<_CharT>())
1431 if (size_t __max = _M_spec._M_get_precision(__fc);
__n > __max)
1434 if (__w <= __format::__stackbuf_size<_CharT>)
1436 _CharT __buf[
__format::__stackbuf_size<_CharT>];
1437 ranges::copy_n(ranges::begin(__rg), __w, __buf);
1438 return _M_format_escaped(_String_view(__buf, __n), __fc);
1440 else if constexpr (ranges::random_access_range<_Rg>)
1442 ranges::iterator_t<_Rg> __first = ranges::begin(__rg);
1443 ranges::subrange __sub(__first, ranges::next(__first, __w));
1444 return _M_format_escaped(_String(from_range, __sub), __fc);
1446 else if (__w <= __n)
1448 ranges::subrange __sub(
1449 counted_iterator(ranges::begin(__rg), __w),
1451 return _M_format_escaped(_String(from_range, __sub), __fc);
1453 else if constexpr (ranges::sized_range<_Rg>)
1454 return _M_format_escaped(_String(from_range, __rg), __fc);
1457 // N.B. preserve the computed size
1458 ranges::subrange __sub(__rg, __n);
1459 return _M_format_escaped(_String(from_range, __sub), __fc);
1463 return _M_format_escaped(_String(from_range, __rg), __fc);
1467 set_debug_format() noexcept
1468 {
_M_spec._M_debug = true; }
1472 _Spec<_CharT> _M_spec{};
1475 template<__char _CharT>
1476 struct __formatter_int
1478 // If no presentation type is specified, meaning of "none" depends
1479 // whether we are formatting an integer or a char or a bool.
1480 static constexpr _Pres_type _AsInteger = _Pres_d;
1481 static constexpr _Pres_type _AsBool = _Pres_s;
1482 static constexpr _Pres_type _AsChar = _Pres_c;
1484 __formatter_int() = default;
1487 __formatter_int(_Spec<_CharT> __spec) noexcept
1490 if (_M_spec._M_type == _Pres_none)
1491 _M_spec._M_type = _Pres_d;
1494 constexpr typename basic_format_parse_context<_CharT>::iterator
1495 _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
1497 _Spec<_CharT> __spec{};
1498 __spec._M_type = __type;
1500 const auto __last = __pc.end();
1501 auto __first = __pc.begin();
1503 auto __finalize = [
this, &__spec] {
1507 auto __finished = [
&] {
1508 if (__first == __last || *__first == '}
')
1519 __first = __spec._M_parse_fill_and_align(__first, __last);
1523 __first = __spec._M_parse_sign(__first, __last);
1527 __first = __spec._M_parse_alternate_form(__first, __last);
1531 __first = __spec._M_parse_zero_fill(__first, __last);
1535 __first = __spec._M_parse_width(__first, __last, __pc);
1539 __first = __spec._M_parse_locale(__first, __last);
1546 __spec._M_type = _Pres_b;
1550 __spec._M_type = _Pres_B;
1554 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1555 // 3586.
format should not print bool with 'c'
1556 if (__type != _AsBool)
1558 __spec._M_type = _Pres_c;
1563 __spec._M_type = _Pres_d;
1567 __spec._M_type = _Pres_o;
1571 __spec._M_type = _Pres_x;
1575 __spec._M_type = _Pres_X;
1579 if (__type == _AsBool)
1581 __spec._M_type = _Pres_s;
// same meaning as "none" for bool
1585#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
1587 if (__type == _AsChar)
1589 __spec._M_debug = true;
1599 __format::__failed_to_parse_format_spec();
1602 template<typename _Tp>
1603 constexpr typename basic_format_parse_context<_CharT>::iterator
1604 _M_parse(basic_format_parse_context<_CharT>& __pc)
1606 if constexpr (is_same_v<_Tp, bool>)
1608 auto __end = _M_do_parse(__pc, _AsBool);
1609 if (_M_spec._M_type == _Pres_s)
1610 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1611 || _M_spec._M_zero_fill)
1612 __throw_format_error("format error: format-spec contains "
1613 "invalid formatting options for "
1617 else if constexpr (__char<_Tp>)
1619 auto __end = _M_do_parse(__pc, _AsChar);
1620 if (_M_spec._M_type == _Pres_c)
1621 if (_M_spec._M_sign != _Sign_default || _M_spec._M_alt
1622 || _M_spec._M_zero_fill
1623 /* XXX should be invalid?
|| _M_spec._M_localized */)
1624 __throw_format_error("format error: format-spec contains "
1625 "invalid formatting options for "
1630 return _M_do_parse(__pc, _AsInteger);
1633 template<typename _Int, typename _Out>
1634 typename basic_format_context<_Out, _CharT>::iterator
1635 format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
1637 if (_M_spec._M_type == _Pres_c)
1638 return _M_format_character(_S_to_character(__i), __fc);
1640 char __buf[
sizeof(_Int) * __CHAR_BIT__ + 3];
1641 to_chars_result __res{};
1643 string_view __base_prefix;
1644 make_unsigned_t<_Int> __u;
1646 __u = -static_cast<make_unsigned_t<_Int>>(__i);
1650 char* __start = __buf + 3;
1651 char* const __end = __buf + sizeof(__buf);
1652 char* const __start_digits = __start;
1654 switch (_M_spec._M_type)
1658 __base_prefix = _M_spec._M_type == _Pres_b ?
"0b" : "0B";
1659 __res = to_chars(__start, __end, __u, 2);
1663 return _M_format_character(_S_to_character(__i), __fc);
1666 // Should not reach here with _Pres_none for bool or charT, so:
1669 __res = to_chars(__start, __end, __u, 10);
1673 __base_prefix = "0";
1674 __res = to_chars(__start, __end, __u, 8);
1678 __base_prefix = _M_spec._M_type == _Pres_x ?
"0x" : "0X";
1679 __res = to_chars(__start, __end, __u, 16);
1680 if (_M_spec._M_type == _Pres_X)
1681 for (auto __p = __start;
__p != __res.ptr;
++__p)
1682#if __has_builtin(__builtin_toupper)
1683 *__p = __builtin_toupper(*__p);
1685 *__p = std::toupper(*__p);
1689 __builtin_unreachable();
1692 if (_M_spec._M_alt && __base_prefix.size())
1694 __start -= __base_prefix.size();
1695 __builtin_memcpy(__start, __base_prefix.data(),
1696 __base_prefix.size());
1698 __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
1700 return _M_format_int(string_view(__start, __res.ptr - __start),
1701 __start_digits - __start, __fc);
1704 template<typename _Out>
1705 typename basic_format_context<_Out, _CharT>::iterator
1706 format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
1708 if (_M_spec._M_type == _Pres_c)
1709 return _M_format_character(static_cast<unsigned char>(__i), __fc);
1710 if (_M_spec._M_type != _Pres_s)
1711 return format(static_cast<unsigned char>(__i), __fc);
1713 basic_string<_CharT> __s;
1715 if (_M_spec._M_localized) [[
unlikely]]
1717 auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
1718 __s = __i ?
__np.truename() : __np.falsename();
1719 __est_width = __s.size();
// TODO Unicode-aware estimate
1723 if constexpr (is_same_v<char, _CharT>)
1724 __s = __i ?
"true" : "false";
1726 __s = __i ?
L"true" : L"false";
1727 __est_width = __s.size();
1730 return __format::__write_padded_as_spec(__s, __est_width, __fc,
1734 template<typename _Out>
1735 typename basic_format_context<_Out, _CharT>::iterator
1736 _M_format_character(_CharT __c,
1737 basic_format_context<_Out, _CharT>& __fc) const
1739 basic_string_view<_CharT> __in(&__c, 1u);
1740 size_t __width = 1u;
1741 // N.B. single byte cannot encode character of width greater than 1
1742 if constexpr (sizeof(_CharT) > 1u &&
1743 __unicode::__literal_encoding_is_unicode<_CharT>())
1744 __width = __unicode::__field_width(__c);
1746 if (!_M_spec._M_debug)
1747 return __format::__write_padded_as_spec(__in, __width,
1751 if (_M_spec._M_get_width(__fc) <= __width)
1752 return __format::__write_escaped(__fc.out(), __in, _Term_apos);
1755 _Fixedbuf_sink<_CharT> __sink(__buf);
1756 __format::__write_escaped(__sink.out(), __in, _Term_apos);
1758 __in = __sink.view();
1759 if (__in[
1]
== _Escapes<_CharT>::_S_bslash()[
0]
) // escape sequence
1760 __width = __in.size();
1761 return __format::__write_padded_as_spec(__in, __width,
1765 template<typename _Int>
1767 _S_to_character(_Int __i)
1769 using _Traits = __gnu_cxx::__int_traits<_CharT>;
1770 if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
1772 if (_Traits::__min <= __i && __i <= _Traits::__max)
1773 return static_cast<_CharT>(__i);
1775 else if constexpr (is_signed_v<_Int>)
1777 if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
1778 return static_cast<_CharT>(__i);
1780 else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
1781 return static_cast<_CharT>(__i);
1782 __throw_format_error("format error: integer not representable as "
1786 template<typename _Out>
1787 typename basic_format_context<_Out, _CharT>::iterator
1788 _M_format_int(string_view __narrow_str, size_t __prefix_len,
1789 basic_format_context<_Out, _CharT>& __fc) const
1791 size_t __width = _M_spec._M_get_width(__fc);
1793 basic_string_view<_CharT> __str;
1794 if constexpr (is_same_v<char, _CharT>)
1795 __str = __narrow_str;
1796#ifdef _GLIBCXX_USE_WCHAR_T
1799 size_t __n = __narrow_str.size();
1800 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
1801 std::__to_wstring_numeric(__narrow_str.data(), __n, __p);
1806 if (_M_spec._M_localized)
1808 const auto& __l = __fc.locale();
1809 if (__l.name() != "C")
1811 auto& __np = use_facet<numpunct<_CharT>>(__l);
1812 string __grp = __np.grouping();
1815 size_t __n = __str.size() - __prefix_len;
1816 auto __p = (_CharT*)__builtin_alloca(2 * __n
1819 auto __s = __str.data();
1820 char_traits<_CharT>::copy(__p, __s, __prefix_len);
1821 __s += __prefix_len;
1822 auto __end = std::__add_grouping(__p + __prefix_len,
1823 __np.thousands_sep(),
1827 __str = {
__p, size_t(__end - __p)};
1832 if (__width <= __str.size())
1833 return __format::__write(__fc.out(), __str);
1835 char32_t __fill_char = _M_spec._M_fill;
1836 _Align __align = _M_spec._M_align;
1838 size_t __nfill = __width - __str.size();
1839 auto __out = __fc.out();
1840 if (__align == _Align_default)
1842 __align = _Align_right;
1843 if (_M_spec._M_zero_fill)
1845 __fill_char = _CharT('0');
1846 // Write sign and base prefix before zero filling.
1847 if (__prefix_len != 0)
1849 __out = __format::__write(std::move(__out),
1850 __str.substr(0, __prefix_len));
1851 __str.remove_prefix(__prefix_len);
1855 __fill_char = _CharT(' ');
1857 return __format::__write_padded(std::move(__out), __str,
1858 __align, __nfill, __fill_char);
1861 _Spec<_CharT> _M_spec{};
1864#ifdef __BFLT16_DIG__
1865 using __bflt16_t = decltype(0.
0bf16);
1868 // Decide how 128-bit floating-point types should be formatted (or not).
1869 // When supported, the typedef __format::__flt128_t is the type that format
1870 // arguments should be converted to before passing them to __formatter_fp.
1871 // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
1872 // The __float128, _Float128 will be formatted by converting them to:
1873 // __ieee128 (same as __float128) when _GLIBCXX_FORMAT_F128=1,
1874 // long double when _GLIBCXX_FORMAT_F128=2,
1875 // _Float128 when _GLIBCXX_FORMAT_F128=3.
1876#undef _GLIBCXX_FORMAT_F128
1878#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
1880 // Format 128-bit floating-point types using __ieee128.
1881 using __flt128_t = __ieee128;
1882# define _GLIBCXX_FORMAT_F128 1
1884#ifdef __LONG_DOUBLE_IEEE128__
1885 // These overloads exist in the library, but are not declared.
1886 // Make them available as std::__format::to_chars.
1888 to_chars(char*, char*, __ibm128) noexcept
1889 __asm("_ZSt8to_charsPcS_e");
1892 to_chars(char*, char*, __ibm128, chars_format) noexcept
1893 __asm("_ZSt8to_charsPcS_eSt12chars_format");
1896 to_chars(char*, char*, __ibm128, chars_format, int) noexcept
1897 __asm("_ZSt8to_charsPcS_eSt12chars_formati");
1898#elif __cplusplus == 202002L
1900 to_chars(char*, char*, __ieee128) noexcept
1901 __asm("_ZSt8to_charsPcS_u9__ieee128");
1904 to_chars(char*, char*, __ieee128, chars_format) noexcept
1905 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
1908 to_chars(char*, char*, __ieee128, chars_format, int) noexcept
1909 __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
1912#elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
1914 // Format 128-bit floating-point types using long double.
1915 using __flt128_t = long double;
1916# define _GLIBCXX_FORMAT_F128 2
1918#elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
1920 // Format 128-bit floating-point types using _Float128.
1921 using __flt128_t = _Float128;
1922# define _GLIBCXX_FORMAT_F128 3
1924# if __cplusplus == 202002L
1925 // These overloads exist in the library, but are not declared for C++20.
1926 // Make them available as std::__format::to_chars.
1928 to_chars(char*, char*, _Float128) noexcept
1929# if _GLIBCXX_INLINE_VERSION
1930 __asm("_ZNSt3__88to_charsEPcS0_DF128_");
1932 __asm("_ZSt8to_charsPcS_DF128_");
1936 to_chars(char*, char*, _Float128, chars_format) noexcept
1937# if _GLIBCXX_INLINE_VERSION
1938 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
1940 __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
1944 to_chars(char*, char*, _Float128, chars_format, int) noexcept
1945# if _GLIBCXX_INLINE_VERSION
1946 __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
1948 __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
1953 using std::to_chars;
1955 // We can format a floating-point type iff it is usable with to_chars.
1956 template<typename _Tp>
1957 concept __formattable_float
1958 = is_same_v<remove_cv_t<_Tp>, _Tp> && requires (_Tp __t, char* __p)
1959 {
__format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
1961 template<__char _CharT>
1962 struct __formatter_fp
1964 constexpr typename basic_format_parse_context<_CharT>::iterator
1965 parse(basic_format_parse_context<_CharT>& __pc)
1967 _Spec<_CharT> __spec{};
1968 const auto __last = __pc.end();
1969 auto __first = __pc.begin();
1971 auto __finalize = [
this, &__spec] {
1975 auto __finished = [
&] {
1976 if (__first == __last || *__first == '}
')
1987 __first = __spec._M_parse_fill_and_align(__first, __last);
1991 __first = __spec._M_parse_sign(__first, __last);
1995 __first = __spec._M_parse_alternate_form(__first, __last);
1999 __first = __spec._M_parse_zero_fill(__first, __last);
2003 if (__first[
0]
!= '.')
2005 __first = __spec._M_parse_width(__first, __last, __pc);
2010 __first = __spec._M_parse_precision(__first, __last, __pc);
2014 __first = __spec._M_parse_locale(__first, __last);
2021 __spec._M_type = _Pres_a;
2025 __spec._M_type = _Pres_A;
2029 __spec._M_type = _Pres_e;
2033 __spec._M_type = _Pres_E;
2037 __spec._M_type = _Pres_f;
2041 __spec._M_type = _Pres_F;
2045 __spec._M_type = _Pres_g;
2049 __spec._M_type = _Pres_G;
2057 __format::__failed_to_parse_format_spec();
2060 template<typename _Fp, typename _Out>
2061 typename basic_format_context<_Out, _CharT>::iterator
2062 format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
2064 std::string __dynbuf;
2066 to_chars_result __res{};
2069 bool __use_prec = _M_spec._M_prec_kind != _WP_none;
2071 __prec = _M_spec._M_get_precision(__fc);
2073 char* __start = __buf + 1;
// reserve space for sign
2074 char* __end = __buf + sizeof(__buf);
2076 chars_format __fmt{};
2077 bool __upper = false;
2078 bool __trailing_zeros = false;
2081 switch (_M_spec._M_type)
2088 if (_M_spec._M_type != _Pres_A)
2090 __fmt = chars_format::hex;
2098 __fmt = chars_format::scientific;
2105 __fmt = chars_format::fixed;
2112 __trailing_zeros = true;
2114 __fmt = chars_format::general;
2118 __fmt = chars_format::general;
2121 __builtin_unreachable();
2124 // Write value into buffer using std::to_chars.
2125 auto __to_chars = [
&]
(char* __b, char* __e) {
2127 return __format::to_chars(__b, __e, __v, __fmt, __prec);
2128 else if (__fmt != chars_format{}
)
2129 return __format::to_chars(__b, __e, __v, __fmt);
2131 return __format::to_chars(__b, __e, __v);
2134 // First try using stack buffer.
2135 __res = __to_chars(__start, __end);
2137 if (__builtin_expect(__res.ec == errc::value_too_large, 0))
2139 // If the buffer is too small it's probably because of a large
2140 // precision, or a very large value in fixed format.
2141 size_t __guess = 8 + __prec;
2142 if (__fmt == chars_format::fixed) // +ddd.prec
2144 if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
2145 || is_same_v<_Fp, long double>)
2147 // The number of digits to the left of the decimal point
2148 // is floor(log10(max(abs(__v),1)))+1
2150 if constexpr (is_same_v<_Fp, float>)
2151 __builtin_frexpf(__v, &__exp);
2152 else if constexpr (is_same_v<_Fp, double>)
2153 __builtin_frexp(__v, &__exp);
2154 else if constexpr (is_same_v<_Fp, long double>)
2155 __builtin_frexpl(__v, &__exp);
2157 __guess += 1U + __exp * 4004U / 13301U;
// log10(2) approx.
2160 __guess += numeric_limits<_Fp>::max_exponent10;
2162 if (__guess <= sizeof(__buf)) [[
unlikely]]
2163 __guess = sizeof(__buf) * 2;
2164 __dynbuf.reserve(__guess);
2168 // Mangling of this lambda, and thus resize_and_overwrite
2169 // instantiated with it, was fixed in ABI 18 (G++ 13). Since
2170 // <format> was new in G++ 13, and is experimental, that
2172 auto __overwrite = [
&__to_chars, &__res]
(char* __p, size_t __n)
2174 __res = __to_chars(__p + 1, __p + __n - 1);
2175 return __res.ec == errc{} ?
__res.ptr - __p : 0;
2178 __dynbuf.__resize_and_overwrite(__dynbuf.capacity() * 2,
2180 __start = __dynbuf.data() + 1;
// reserve space for sign
2181 __end = __dynbuf.data() + __dynbuf.size();
2183 while (__builtin_expect(__res.ec == errc::value_too_large, 0));
2186 // Use uppercase for 'A', 'E', and 'G' formats.
2189 for (char* __p = __start;
__p != __res.ptr;
++__p)
2190 *__p = std::toupper(*__p);
2193 bool __have_sign = true;
2194 // Add sign for non-negative values.
2195 if (!__builtin_signbit(__v))
2197 if (_M_spec._M_sign == _Sign_plus)
2199 else if (_M_spec._M_sign == _Sign_space)
2202 __have_sign = false;
2205 string_view __narrow_str(__start, __res.ptr - __start);
2207 // Use alternate form. Ensure decimal point is always present,
2208 // and add trailing zeros (up to precision) for g and G forms.
2209 if (_M_spec._M_alt && __builtin_isfinite(__v))
2211 string_view __s = __narrow_str;
2212 size_t __sigfigs;
// Number of significant figures.
2213 size_t __z = 0;
// Number of trailing zeros to add.
2214 size_t __p;
// Position of the exponent character (if any).
2215 size_t __d = __s.find('.');
// Position of decimal point.
2216 if (__d != __s.npos) // Found decimal point.
2218 __p = __s.find(__expc, __d + 1);
2219 if (__p == __s.npos)
2222 // If presentation type is g or G we might need to add zeros.
2223 if (__trailing_zeros)
2225 // Find number of digits after first significant figure.
2226 if (__s[
__have_sign]
!= '0')
2227 // A string like "D.D" or "-D.DDD"
2228 __sigfigs = __p - __have_sign - 1;
2230 // A string like "0.D" or "-0.0DD".
2231 // Safe to assume there is a non-zero digit, because
2232 // otherwise there would be no decimal point.
2233 __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
2236 else // No decimal point, we need to insert one.
2238 __p = __s.find(__expc);
// Find the exponent, if present.
2239 if (__p == __s.npos)
2241 __d = __p;
// Position where '.' should be inserted.
2242 __sigfigs = __d - __have_sign;
2245 if (__trailing_zeros && __prec != 0)
2247 // For g and G presentation types std::to_chars produces
2248 // no more than prec significant figures. Insert this many
2249 // zeros so the result has exactly prec significant figures.
2250 __z = __prec - __sigfigs;
2253 if (size_t __extras = int(__d == __p) + __z) // How many to add.
2255 if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
2257 // The stack buffer is large enough for the result.
2258 // Move exponent to make space for extra chars.
2259 __builtin_memmove(__start + __p + __extras,
2263 __start[
__p++]
= '.';
2264 __builtin_memset(__start + __p, '0', __z);
2265 __narrow_str = {
__s.data(), __s.size() + __extras};
2267 else // Need to switch to the dynamic buffer.
2269 __dynbuf.reserve(__s.size() + __extras);
2270 if (__dynbuf.empty())
2272 __dynbuf = __s.substr(0, __p);
2276 __dynbuf.append(__z, '0');
2277 __dynbuf.append(__s.substr(__p));
2281 __dynbuf.insert(__p, __extras, '0');
2283 __dynbuf[
__p]
= '.';
2285 __narrow_str = __dynbuf;
2290 basic_string<_CharT> __wstr;
2291 basic_string_view<_CharT> __str;
2292 if constexpr (is_same_v<_CharT, char>)
2293 __str = __narrow_str;
2294#ifdef _GLIBCXX_USE_WCHAR_T
2297 __wstr = std::__to_wstring_numeric(__narrow_str);
2302 if (_M_spec._M_localized && __builtin_isfinite(__v))
2304 auto __s = _M_localize(__str, __expc, __fc.locale());
2306 __str = __wstr = std::move(__s);
2309 size_t __width = _M_spec._M_get_width(__fc);
2311 if (__width <= __str.size())
2312 return __format::__write(__fc.out(), __str);
2314 char32_t __fill_char = _M_spec._M_fill;
2315 _Align __align = _M_spec._M_align;
2317 size_t __nfill = __width - __str.size();
2318 auto __out = __fc.out();
2319 if (__align == _Align_default)
2321 __align = _Align_right;
2322 if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
2324 __fill_char = _CharT('0');
2325 // Write sign before zero filling.
2326 if (!__format::__is_xdigit(__narrow_str[
0]
))
2328 *__out++ = __str[
0];
2329 __str.remove_prefix(1);
2333 __fill_char = _CharT(' ');
2335 return __format::__write_padded(std::move(__out), __str,
2336 __align, __nfill, __fill_char);
2339 // Locale-specific format.
2340 basic_string<_CharT>
2341 _M_localize(basic_string_view<_CharT> __str, char __expc,
2342 const locale& __loc) const
2344 basic_string<_CharT> __lstr;
2346 if (__loc == locale::classic())
2347 return __lstr;
// Nothing to do.
2349 const auto& __np = use_facet<numpunct<_CharT>>(__loc);
2350 const _CharT __point = __np.decimal_point();
2351 const string __grp = __np.grouping();
2353 _CharT __dot, __exp;
2354 if constexpr (is_same_v<_CharT, char>)
2377 __builtin_unreachable();
2381 if (__grp.empty() && __point == __dot)
2382 return __lstr;
// Locale uses '.' and no grouping.
2384 size_t __d = __str.find(__dot);
// Index of radix character (if any).
2385 size_t __e = min(__d, __str.find(__exp));
// First of radix or exponent
2386 if (__e == __str.npos)
2388 const size_t __r = __str.size() - __e;
// Length of remainder.
2389 auto __overwrite = [
&]
(_CharT* __p, size_t) {
2390 // Apply grouping to the digits before the radix or exponent.
2392 if (auto __c = __str.front();
__c == '-' || __c == '+' || __c == ' ')
2397 auto __end = std::__add_grouping(__p + __off, __np.thousands_sep(),
2398 __grp.data(), __grp.size(),
2399 __str.data() + __off,
2400 __str.data() + __e);
2401 if (__r) // If there's a fractional part or exponent
2403 if (__d != __str.npos)
2405 *__end = __point;
// Add the locale's radix character.
2409 const size_t __rlen = __str.size() - __e;
2410 // Append fractional digits and/or exponent:
2411 char_traits<_CharT>::copy(__end, __str.data() + __e, __rlen);
2414 return (__end - __p);
2416 __lstr.__resize_and_overwrite(__e * 2 + __r, __overwrite);
2420 _Spec<_CharT> _M_spec{};
2423 template<__format::__char _CharT>
2424 struct __formatter_ptr
2426 __formatter_ptr() = default;
2429 __formatter_ptr(_Spec<_CharT> __spec) noexcept
2431 {
_M_set_default(_Pres_p); }
2433 constexpr typename basic_format_parse_context<_CharT>::iterator
2434 parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type = _Pres_p)
2436 __format::_Spec<_CharT> __spec{};
2437 const auto __last = __pc.end();
2438 auto __first = __pc.begin();
2440 auto __finalize = [
this, &__spec, __type] {
2442 _M_set_default(__type);
2445 auto __finished = [
&] {
2446 if (__first == __last || *__first == '}
')
2457 __first = __spec._M_parse_fill_and_align(__first, __last);
2461// _GLIBCXX_RESOLVE_LIB_DEFECTS
2462// P2510R3 Formatting pointers
2463#if __glibcxx_format >= 202304L
2464 __first = __spec._M_parse_zero_fill(__first, __last);
2469 __first = __spec._M_parse_width(__first, __last, __pc);
2473 if (*__first == 'p')
2475 __spec._M_type = _Pres_p;
2476 _M_spec._M_alt = !_M_spec._M_alt;
2479#if __glibcxx_format >= 202304L
2480 else if (*__first == 'P')
2482 __spec._M_type = _Pres_P;
2483 _M_spec._M_alt = !_M_spec._M_alt;
2491 __format::__failed_to_parse_format_spec();
2494 template<typename _Out>
2495 typename basic_format_context<_Out, _CharT>::iterator
2496 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
2498 auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
2499 char __buf[
2 + sizeof(__v) * 2];
2500 auto [
__ptr, __ec]
= std::to_chars(__buf + 2, std::end(__buf),
2502 int __n = __ptr - __buf;
2505#if __glibcxx_format >= 202304L
2506 if (_M_spec._M_type == __format::_Pres_P)
2509 for (auto __p = __buf + 2;
__p != __ptr;
++__p)
2510#if __has_builtin(__builtin_toupper)
2511 *__p = __builtin_toupper(*__p);
2513 *__p = std::toupper(*__p);
2518 basic_string_view<_CharT> __str;
2519 if constexpr (is_same_v<_CharT, char>)
2520 __str = string_view(__buf, __n);
2521#ifdef _GLIBCXX_USE_WCHAR_T
2524 auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
2525 std::__to_wstring_numeric(__buf, __n, __p);
2526 __str = wstring_view(__p, __n);
2530#if __glibcxx_format >= 202304L
2531 if (_M_spec._M_zero_fill)
2533 size_t __width = _M_spec._M_get_width(__fc);
2534 if (__width <= __str.size())
2535 return __format::__write(__fc.out(), __str);
2537 auto __out = __fc.out();
2538 // Write "0x" or "0X" prefix before zero-filling.
2539 __out = __format::__write(std::move(__out), __str.substr(0, 2));
2540 __str.remove_prefix(2);
2541 size_t __nfill = __width - __n;
2542 return __format::__write_padded(std::move(__out), __str,
2543 __format::_Align_right,
2544 __nfill, _CharT('0'));
2548 return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
2549 __format::_Align_right);
2553 [[
__gnu__::__always_inline__]]
2555 _M_set_default(_Pres_type __type)
2557 if (_M_spec._M_type == _Pres_none && __type != _Pres_none)
2559 _M_spec._M_type = __type;
2560 _M_spec._M_alt = !_M_spec._M_alt;
2564 __format::_Spec<_CharT> _M_spec{};
2567}
// namespace __format
2570 /// Format a character.
2571 template<__format::__char _CharT>
2572 struct formatter<_CharT, _CharT>
2574 formatter() = default;
2576 constexpr typename basic_format_parse_context<_CharT>::iterator
2577 parse(basic_format_parse_context<_CharT>& __pc)
2579 return _M_f.template _M_parse<_CharT>(__pc);
2582 template<typename _Out>
2583 typename basic_format_context<_Out, _CharT>::iterator
2584 format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
2586 if (_M_f._M_spec._M_type == __format::_Pres_c)
2587 return _M_f._M_format_character(__u, __fc);
2589 return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
2592#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2594 set_debug_format() noexcept
2595 {
_M_f._M_spec._M_debug = true; }
2599 __format::__formatter_int<_CharT> _M_f;
2602#ifdef _GLIBCXX_USE_WCHAR_T
2603 /// Format a char value for wide character output.
2605 struct formatter<char, wchar_t>
2607 formatter() = default;
2609 constexpr typename basic_format_parse_context<wchar_t>::iterator
2610 parse(basic_format_parse_context<wchar_t>& __pc)
2612 return _M_f._M_parse<char>(__pc);
2615 template<typename _Out>
2616 typename basic_format_context<_Out, wchar_t>::iterator
2617 format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
2619 if (_M_f._M_spec._M_type == __format::_Pres_c)
2620 return _M_f._M_format_character(__u, __fc);
2622 return _M_f.format(static_cast<unsigned char>(__u), __fc);
2625#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2627 set_debug_format() noexcept
2628 {
_M_f._M_spec._M_debug = true; }
2632 __format::__formatter_int<wchar_t> _M_f;
2634#endif // USE_WCHAR_T
2636 /** Format a string.
2639 template<__format::__char _CharT>
2640 struct formatter<_CharT*, _CharT>
2642 formatter() = default;
2644 [[
__gnu__::__always_inline__]]
2645 constexpr typename basic_format_parse_context<_CharT>::iterator
2646 parse(basic_format_parse_context<_CharT>& __pc)
2647 {
return _M_f.parse(__pc); }
2649 template<typename _Out>
2650 [[
__gnu__::__nonnull__]]
2651 typename basic_format_context<_Out, _CharT>::iterator
2652 format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
2653 {
return _M_f.format(__u, __fc); }
2655#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2656 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2660 __format::__formatter_str<_CharT> _M_f;
2663 template<__format::__char _CharT>
2664 struct formatter<const _CharT*, _CharT>
2666 formatter() = default;
2668 [[
__gnu__::__always_inline__]]
2669 constexpr typename basic_format_parse_context<_CharT>::iterator
2670 parse(basic_format_parse_context<_CharT>& __pc)
2671 {
return _M_f.parse(__pc); }
2673 template<typename _Out>
2674 [[
__gnu__::__nonnull__]]
2675 typename basic_format_context<_Out, _CharT>::iterator
2676 format(const _CharT* __u,
2677 basic_format_context<_Out, _CharT>& __fc) const
2678 {
return _M_f.format(__u, __fc); }
2680#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2681 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2685 __format::__formatter_str<_CharT> _M_f;
2688 template<__format::__char _CharT, size_t _Nm>
2689 struct formatter<_CharT[
_Nm]
, _CharT>
2691 formatter() = default;
2693 [[
__gnu__::__always_inline__]]
2694 constexpr typename basic_format_parse_context<_CharT>::iterator
2695 parse(basic_format_parse_context<_CharT>& __pc)
2696 {
return _M_f.parse(__pc); }
2698 template<typename _Out>
2699 typename basic_format_context<_Out, _CharT>::iterator
2700 format(const _CharT (&__u)[
_Nm]
,
2701 basic_format_context<_Out, _CharT>& __fc) const
2702 {
return _M_f.format({
__u, _Nm}
, __fc); }
2704#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2705 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2709 __format::__formatter_str<_CharT> _M_f;
2712 template<typename _Traits, typename _Alloc>
2713 struct formatter<basic_string<char, _Traits, _Alloc>, char>
2715 formatter() = default;
2717 [[
__gnu__::__always_inline__]]
2718 constexpr typename basic_format_parse_context<char>::iterator
2719 parse(basic_format_parse_context<char>& __pc)
2720 {
return _M_f.parse(__pc); }
2722 template<typename _Out>
2723 typename basic_format_context<_Out, char>::iterator
2724 format(const basic_string<char, _Traits, _Alloc>& __u,
2725 basic_format_context<_Out, char>& __fc) const
2726 {
return _M_f.format(__u, __fc); }
2728#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2729 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2733 __format::__formatter_str<char> _M_f;
2736#ifdef _GLIBCXX_USE_WCHAR_T
2737 template<typename _Traits, typename _Alloc>
2738 struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
2740 formatter() = default;
2742 [[
__gnu__::__always_inline__]]
2743 constexpr typename basic_format_parse_context<wchar_t>::iterator
2744 parse(basic_format_parse_context<wchar_t>& __pc)
2745 {
return _M_f.parse(__pc); }
2747 template<typename _Out>
2748 typename basic_format_context<_Out, wchar_t>::iterator
2749 format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
2750 basic_format_context<_Out, wchar_t>& __fc) const
2751 {
return _M_f.format(__u, __fc); }
2753#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2754 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2758 __format::__formatter_str<wchar_t> _M_f;
2760#endif // USE_WCHAR_T
2762 template<typename _Traits>
2763 struct formatter<basic_string_view<char, _Traits>, char>
2765 formatter() = default;
2767 [[
__gnu__::__always_inline__]]
2768 constexpr typename basic_format_parse_context<char>::iterator
2769 parse(basic_format_parse_context<char>& __pc)
2770 {
return _M_f.parse(__pc); }
2772 template<typename _Out>
2773 typename basic_format_context<_Out, char>::iterator
2774 format(basic_string_view<char, _Traits> __u,
2775 basic_format_context<_Out, char>& __fc) const
2776 {
return _M_f.format(__u, __fc); }
2778#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2779 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2783 __format::__formatter_str<char> _M_f;
2786#ifdef _GLIBCXX_USE_WCHAR_T
2787 template<typename _Traits>
2788 struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
2790 formatter() = default;
2792 [[
__gnu__::__always_inline__]]
2793 constexpr typename basic_format_parse_context<wchar_t>::iterator
2794 parse(basic_format_parse_context<wchar_t>& __pc)
2795 {
return _M_f.parse(__pc); }
2797 template<typename _Out>
2798 typename basic_format_context<_Out, wchar_t>::iterator
2799 format(basic_string_view<wchar_t, _Traits> __u,
2800 basic_format_context<_Out, wchar_t>& __fc) const
2801 {
return _M_f.format(__u, __fc); }
2803#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
2804 constexpr void set_debug_format() noexcept {
_M_f.set_debug_format(); }
2808 __format::__formatter_str<wchar_t> _M_f;
2810#endif // USE_WCHAR_T
2813/// @
cond undocumented
2816 // each cv-unqualified arithmetic type ArithmeticT other than
2817 // char, wchar_t, char8_t, char16_t, or char32_t
2818 template<typename _Tp>
2819 constexpr bool __is_formattable_integer = __is_integer<_Tp>::__value;
2821#if defined __SIZEOF_INT128__
2822 template<> inline constexpr bool __is_formattable_integer<__int128> = true;
2823 template<> inline constexpr bool __is_formattable_integer<unsigned __int128>
2827 template<> inline constexpr bool __is_formattable_integer<char> = false;
2828 template<> inline constexpr bool __is_formattable_integer<wchar_t> = false;
2829#ifdef _GLIBCXX_USE_CHAR8_T
2830 template<> inline constexpr bool __is_formattable_integer<char8_t> = false;
2832 template<> inline constexpr bool __is_formattable_integer<char16_t> = false;
2833 template<> inline constexpr bool __is_formattable_integer<char32_t> = false;
2837 /// Format an integer.
2838 template<typename _Tp, __format::__char _CharT>
2839 requires __format::__is_formattable_integer<_Tp>
2840 struct formatter<_Tp, _CharT>
2842 formatter() = default;
2844 [[
__gnu__::__always_inline__]]
2845 constexpr typename basic_format_parse_context<_CharT>::iterator
2846 parse(basic_format_parse_context<_CharT>& __pc)
2848 return _M_f.template _M_parse<_Tp>(__pc);
2851 template<typename _Out>
2852 typename basic_format_context<_Out, _CharT>::iterator
2853 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2854 {
return _M_f.format(__u, __fc); }
2857 __format::__formatter_int<_CharT> _M_f;
2860#if defined __glibcxx_to_chars
2861 /// Format a floating-point value.
2862 template<__format::__formattable_float _Tp, __format::__char _CharT>
2863 struct formatter<_Tp, _CharT>
2865 formatter() = default;
2867 [[
__gnu__::__always_inline__]]
2868 constexpr typename basic_format_parse_context<_CharT>::iterator
2869 parse(basic_format_parse_context<_CharT>& __pc)
2870 {
return _M_f.parse(__pc); }
2872 template<typename _Out>
2873 typename basic_format_context<_Out, _CharT>::iterator
2874 format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
2875 {
return _M_f.format(__u, __fc); }
2878 __format::__formatter_fp<_CharT> _M_f;
2881#if __LDBL_MANT_DIG__ == __DBL_MANT_DIG__
2882 // Reuse __formatter_fp<C>::format<double, Out> for long double.
2883 template<__format::__char _CharT>
2884 struct formatter<long double, _CharT>
2886 formatter() = default;
2888 [[
__gnu__::__always_inline__]]
2889 constexpr typename basic_format_parse_context<_CharT>::iterator
2890 parse(basic_format_parse_context<_CharT>& __pc)
2891 {
return _M_f.parse(__pc); }
2893 template<typename _Out>
2894 typename basic_format_context<_Out, _CharT>::iterator
2895 format(long double __u, basic_format_context<_Out, _CharT>& __fc) const
2896 {
return _M_f.format((double)__u, __fc); }
2899 __format::__formatter_fp<_CharT> _M_f;
2903#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2904 // Reuse __formatter_fp<C>::format<float, Out> for _Float16.
2905 template<__format::__char _CharT>
2906 struct formatter<_Float16, _CharT>
2908 formatter() = default;
2910 [[
__gnu__::__always_inline__]]
2911 constexpr typename basic_format_parse_context<_CharT>::iterator
2912 parse(basic_format_parse_context<_CharT>& __pc)
2913 {
return _M_f.parse(__pc); }
2915 template<typename _Out>
2916 typename basic_format_context<_Out, _CharT>::iterator
2917 format(_Float16 __u, basic_format_context<_Out, _CharT>& __fc) const
2918 {
return _M_f.format((float)__u, __fc); }
2921 __format::__formatter_fp<_CharT> _M_f;
2925#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
2926 // Reuse __formatter_fp<C>::format<float, Out> for _Float32.
2927 template<__format::__char _CharT>
2928 struct formatter<_Float32, _CharT>
2930 formatter() = default;
2932 [[
__gnu__::__always_inline__]]
2933 constexpr typename basic_format_parse_context<_CharT>::iterator
2934 parse(basic_format_parse_context<_CharT>& __pc)
2935 {
return _M_f.parse(__pc); }
2937 template<typename _Out>
2938 typename basic_format_context<_Out, _CharT>::iterator
2939 format(_Float32 __u, basic_format_context<_Out, _CharT>& __fc) const
2940 {
return _M_f.format((float)__u, __fc); }
2943 __format::__formatter_fp<_CharT> _M_f;
2947#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
2948 // Reuse __formatter_fp<C>::format<double, Out> for _Float64.
2949 template<__format::__char _CharT>
2950 struct formatter<_Float64, _CharT>
2952 formatter() = default;
2954 [[
__gnu__::__always_inline__]]
2955 constexpr typename basic_format_parse_context<_CharT>::iterator
2956 parse(basic_format_parse_context<_CharT>& __pc)
2957 {
return _M_f.parse(__pc); }
2959 template<typename _Out>
2960 typename basic_format_context<_Out, _CharT>::iterator
2961 format(_Float64 __u, basic_format_context<_Out, _CharT>& __fc) const
2962 {
return _M_f.format((double)__u, __fc); }
2965 __format::__formatter_fp<_CharT> _M_f;
2969#if defined(__FLT128_DIG__) && _GLIBCXX_FORMAT_F128
2970 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for _Float128.
2971 template<__format::__char _CharT>
2972 struct formatter<_Float128, _CharT>
2974 formatter() = default;
2976 [[
__gnu__::__always_inline__]]
2977 constexpr typename basic_format_parse_context<_CharT>::iterator
2978 parse(basic_format_parse_context<_CharT>& __pc)
2979 {
return _M_f.parse(__pc); }
2981 template<typename _Out>
2982 typename basic_format_context<_Out, _CharT>::iterator
2983 format(_Float128 __u, basic_format_context<_Out, _CharT>& __fc) const
2984 {
return _M_f.format((__format::__flt128_t)__u, __fc); }
2987 __format::__formatter_fp<_CharT> _M_f;
2991#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128 == 2
2992 // Use __formatter_fp<C>::format<__format::__flt128_t, Out> for __float128,
2993 // when long double is not 128bit IEEE type.
2994 template<__format::__char _CharT>
2995 struct formatter<__float128, _CharT>
2997 formatter() = default;
2999 [[
__gnu__::__always_inline__]]
3000 constexpr typename basic_format_parse_context<_CharT>::iterator
3001 parse(basic_format_parse_context<_CharT>& __pc)
3002 {
return _M_f.parse(__pc); }
3004 template<typename _Out>
3005 typename basic_format_context<_Out, _CharT>::iterator
3006 format(__float128 __u, basic_format_context<_Out, _CharT>& __fc) const
3007 {
return _M_f.format((__format::__flt128_t)__u, __fc); }
3010 __format::__formatter_fp<_CharT> _M_f;
3014#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
3015 // Reuse __formatter_fp<C>::format<float, Out> for bfloat16_t.
3016 template<__format::__char _CharT>
3017 struct formatter<__format::__bflt16_t, _CharT>
3019 formatter() = default;
3021 [[
__gnu__::__always_inline__]]
3022 constexpr typename basic_format_parse_context<_CharT>::iterator
3023 parse(basic_format_parse_context<_CharT>& __pc)
3024 {
return _M_f.parse(__pc); }
3026 template<typename _Out>
3027 typename basic_format_context<_Out, _CharT>::iterator
3028 format(__gnu_cxx::__bfloat16_t __u,
3029 basic_format_context<_Out, _CharT>& __fc) const
3030 {
return _M_f.format((float)__u, __fc); }
3033 __format::__formatter_fp<_CharT> _M_f;
3036#endif // __cpp_lib_to_chars
3038 /** Format a pointer.
3041 template<__format::__char _CharT>
3042 struct formatter<const void*, _CharT>
3044 formatter() = default;
3046 constexpr typename basic_format_parse_context<_CharT>::iterator
3047 parse(basic_format_parse_context<_CharT>& __pc)
3048 {
return _M_f.parse(__pc); }
3050 template<typename _Out>
3051 typename basic_format_context<_Out, _CharT>::iterator
3052 format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
3053 {
return _M_f.format(__v, __fc); }
3056 __format::__formatter_ptr<_CharT> _M_f;
3059 template<__format::__char _CharT>
3060 struct formatter<void*, _CharT>
3062 formatter() = default;
3064 [[
__gnu__::__always_inline__]]
3065 constexpr typename basic_format_parse_context<_CharT>::iterator
3066 parse(basic_format_parse_context<_CharT>& __pc)
3067 {
return _M_f.parse(__pc); }
3069 template<typename _Out>
3070 typename basic_format_context<_Out, _CharT>::iterator
3071 format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
3072 {
return _M_f.format(__v, __fc); }
3075 __format::__formatter_ptr<_CharT> _M_f;
3078 template<__format::__char _CharT>
3079 struct formatter<nullptr_t, _CharT>
3081 formatter() = default;
3083 [[
__gnu__::__always_inline__]]
3084 constexpr typename basic_format_parse_context<_CharT>::iterator
3085 parse(basic_format_parse_context<_CharT>& __pc)
3086 {
return _M_f.parse(__pc); }
3088 template<typename _Out>
3089 typename basic_format_context<_Out, _CharT>::iterator
3090 format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
3091 {
return _M_f.format(nullptr, __fc); }
3094 __format::__formatter_ptr<_CharT> _M_f;
3098#if defined _GLIBCXX_USE_WCHAR_T && __glibcxx_format_ranges
3099 // _GLIBCXX_RESOLVE_LIB_DEFECTS
3100 // 3944.
Formatters converting sequences of char to sequences of wchar_t
3102 struct __formatter_disabled
3104 __formatter_disabled() = delete;
// Cannot format char sequence to wchar_t
3105 __formatter_disabled(const __formatter_disabled&) = delete;
3106 __formatter_disabled& operator=(const __formatter_disabled&) = delete;
3110 struct formatter<char*, wchar_t>
3111 : private __formatter_disabled { };
3113 struct formatter<const char*, wchar_t>
3114 : private __formatter_disabled { };
3115 template<size_t _Nm>
3116 struct formatter<char[
_Nm]
, wchar_t>
3117 : private __formatter_disabled { };
3118 template<class _Traits, class _Allocator>
3119 struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
3120 : private __formatter_disabled { };
3121 template<class _Traits>
3122 struct formatter<basic_string_view<char, _Traits>, wchar_t>
3123 : private __formatter_disabled { };
3126 /// An iterator after the last character written, and the number of
3127 /// characters that would have been written.
3128 template<typename _Out>
3129 struct format_to_n_result
3132 iter_difference_t<_Out> size;
3135_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
3136template<typename, typename> class vector;
3137_GLIBCXX_END_NAMESPACE_CONTAINER
3139/// @
cond undocumented
3142 template<typename _CharT>
3146 using iterator_category = output_iterator_tag;
3147 using value_type = void;
3148 using difference_type = ptrdiff_t;
3149 using pointer = void;
3150 using reference = void;
3152 _Drop_iter() = default;
3153 _Drop_iter(const _Drop_iter&) = default;
3154 _Drop_iter& operator=(const _Drop_iter&) = default;
3156 [[
__gnu__::__always_inline__]]
3157 constexpr _Drop_iter&
3158 operator=(_CharT __c)
3161 [[
__gnu__::__always_inline__]]
3162 constexpr _Drop_iter&
3163 operator=(basic_string_view<_CharT> __s)
3166 [[
__gnu__::__always_inline__]]
3167 constexpr _Drop_iter&
3168 operator*() {
return *this; }
3170 [[
__gnu__::__always_inline__]]
3171 constexpr _Drop_iter&
3172 operator++() {
return *this; }
3174 [[
__gnu__::__always_inline__]]
3175 constexpr _Drop_iter
3176 operator++(int) {
return *this; }
3179 template<typename _CharT>
3182 _Sink<_CharT>* _M_sink = nullptr;
3185 using iterator_category = output_iterator_tag;
3186 using value_type = void;
3187 using difference_type = ptrdiff_t;
3188 using pointer = void;
3189 using reference = void;
3191 _Sink_iter() = default;
3192 _Sink_iter(const _Sink_iter&) = default;
3193 _Sink_iter& operator=(const _Sink_iter&) = default;
3195 [[
__gnu__::__always_inline__]]
3197 _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
3199 [[
__gnu__::__always_inline__]]
3200 constexpr _Sink_iter&
3201 operator=(_CharT __c)
3203 _M_sink->_M_write(__c);
3207 [[
__gnu__::__always_inline__]]
3208 constexpr _Sink_iter&
3209 operator=(basic_string_view<_CharT> __s)
3211 _M_sink->_M_write(__s);
3215 [[
__gnu__::__always_inline__]]
3216 constexpr _Sink_iter&
3217 operator*() {
return *this; }
3219 [[
__gnu__::__always_inline__]]
3220 constexpr _Sink_iter&
3221 operator++() {
return *this; }
3223 [[
__gnu__::__always_inline__]]
3224 constexpr _Sink_iter
3225 operator++(int) {
return *this; }
3228 _M_reserve(size_t __n) const
3229 {
return _M_sink->_M_reserve(__n); }
3232 _M_discarding() const
3233 {
return _M_sink->_M_discarding(); }
3236 // Abstract base class for type-erased character sinks.
3237 // All formatting and output is done via this type's iterator,
3238 // to reduce the number of different template instantiations.
3239 template<typename _CharT>
3242 friend class _Sink_iter<_CharT>;
3244 span<_CharT> _M_span;
3245 typename span<_CharT>::iterator _M_next;
3247 // Called when the span is full, to make more space available.
3248 // Precondition: _M_next != _M_span.begin()
3249 // Postcondition: _M_next != _M_span.end()
3250 // TODO: remove the precondition?
could make overflow handle it.
3251 virtual void _M_overflow() = 0;
3254 // Precondition: __span.size() != 0
3255 [[
__gnu__::__always_inline__]]
3257 _Sink(span<_CharT> __span) noexcept
3258 : _M_span(__span), _M_next(__span.begin())
3261 // The portion of the span that has been written to.
3262 [[
__gnu__::__always_inline__]]
3264 _M_used() const noexcept
3265 {
return _M_span.first(_M_next - _M_span.begin()); }
3267 // The portion of the span that has not been written to.
3268 [[
__gnu__::__always_inline__]]
3269 constexpr span<_CharT>
3270 _M_unused() const noexcept
3271 {
return _M_span.subspan(_M_next - _M_span.begin()); }
3273 // Use the start of the span as the next write position.
3274 [[
__gnu__::__always_inline__]]
3276 _M_rewind() noexcept
3277 {
_M_next = _M_span.begin(); }
3279 // Replace the current output range.
3281 _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
3284 _M_next = __s.begin() + __pos;
3287 // Called by the iterator for *it++ = c
3289 _M_write(_CharT __c)
3292 if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[
unlikely]]
3297 _M_write(basic_string_view<_CharT> __s)
3299 span __to = _M_unused();
3300 while (__to.size() <= __s.size())
3302 __s.copy(__to.data(), __to.size());
3303 _M_next += __to.size();
3304 __s.remove_prefix(__to.size());
3310 __s.copy(__to.data(), __s.size());
3311 _M_next += __s.size();
3315 // A successful _Reservation can be used to directly write
3316 // up to N characters to the sink to avoid unwanted buffering.
3319 // True if the reservation was successful, false otherwise.
3320 explicit operator bool() const noexcept {
return _M_sink; }
3321 // A pointer to write directly to the sink.
3322 _CharT* get() const noexcept {
return _M_sink->_M_next.operator->(); }
3323 // Add n to the _M_next iterator for the sink.
3324 void _M_bump(size_t __n) {
_M_sink->_M_bump(__n); }
3328 // Attempt to reserve space to write n characters to the sink.
3329 // If anything is written to the reservation then there must be a call
3330 // to _M_bump(N2) before any call to another member function of *this,
3331 // where N2 is the number of characters written.
3332 virtual _Reservation
3333 _M_reserve(size_t __n)
3335 if (__n <= _M_unused().size())
3338 if (__n <= _M_span.size()) // Cannot meet the request.
3340 _M_overflow();
// Make more space available.
3341 if (__n <= _M_unused().size())
3347 // Update the next output position after writing directly to the sink.
3348 // pre: no calls to _M_write or _M_overflow since _M_reserve.
3353 // Returns true if the _Sink is discarding incoming characters.
3355 _M_discarding() const
3359 _Sink(const _Sink&) = delete;
3360 _Sink& operator=(const _Sink&) = delete;
3362 [[
__gnu__::__always_inline__]]
3363 constexpr _Sink_iter<_CharT>
3365 {
return _Sink_iter<_CharT>(*this); }
3369 template<typename _CharT>
3370 class _Fixedbuf_sink final : public _Sink<_CharT>
3373 _M_overflow() override
3375 __glibcxx_assert(false);
3380 [[
__gnu__::__always_inline__]]
3382 _Fixedbuf_sink(span<_CharT> __buf)
3383 : _Sink<_CharT>(__buf)
3386 constexpr basic_string_view<_CharT>
3389 auto __s = this->_M_used();
3390 return basic_string_view<_CharT>(__s.data(), __s.size());
3394 // A sink with an internal buffer. This is used to implement concrete sinks.
3395 template<typename _CharT>
3396 class _Buf_sink : public _Sink<_CharT>
3399 _CharT _M_buf[
__stackbuf_size<_CharT>];
3401 [[
__gnu__::__always_inline__]]
3403 _Buf_sink() noexcept
3404 : _Sink<_CharT>(_M_buf)
3408 using _GLIBCXX_STD_C::vector;
3410 // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
3411 // Writes to a buffer then appends that to the sequence when it fills up.
3412 template<typename _Seq>
3413 class _Seq_sink : public _Buf_sink<typename _Seq::value_type>
3415 using _CharT = typename _Seq::value_type;
3419 // Transfer buffer contents to the sequence, so buffer can be refilled.
3421 _M_overflow() override
3423 auto __s = this->_M_used();
3424 if (__s.empty()) [[
unlikely]]
3425 return;
// Nothing in the buffer to transfer to _M_seq.
3427 // If _M_reserve was called then _M_bump must have been called too.
3428 _GLIBCXX_DEBUG_ASSERT(__s.data() != _M_seq.data());
3430 if constexpr (__is_specialization_of<_Seq, basic_string>)
3431 _M_seq.append(__s.data(), __s.size());
3433 _M_seq.insert(_M_seq.end(), __s.
begin(), __s.
end());
3435 // Make the whole of _M_buf available for the next write:
3439 typename _Sink<_CharT>::_Reservation
3440 _M_reserve(size_t __n) override
3442 // We might already have n characters available in this->_M_unused(),
3443 // but the whole point of this function is to be an optimization for
3444 // the std::format("{}", x) case. We want to avoid writing to _M_buf
3445 // and then copying that into a basic_string if possible, so this
3446 // function prefers to create space directly in _M_seq rather than
3449 if constexpr (__is_specialization_of<_Seq, basic_string>
3450 || __is_specialization_of<_Seq, vector>)
3452 // Flush the buffer to _M_seq first (should not be needed).
3453 if (this->_M_used().size()) [[
unlikely]]
3454 _Seq_sink::_M_overflow();
3456 // Expand _M_seq to make __n new characters available:
3457 const auto __sz = _M_seq.size();
3458 if constexpr (is_same_v<string, _Seq> || is_same_v<wstring, _Seq>)
3459 _M_seq.__resize_and_overwrite(__sz + __n,
3460 []
(auto, auto __n2) {
3464 _M_seq.resize(__sz + __n);
3466 // Set _M_used() to be a span over the original part of _M_seq
3467 // and _M_unused() to be the extra capacity we just created:
3468 this->_M_reset(_M_seq, __sz);
3471 else // Try to use the base class' buffer.
3472 return _Sink<_CharT>::_M_reserve(__n);
3476 _M_bump(size_t __n) override
3478 if constexpr (__is_specialization_of<_Seq, basic_string>
3479 || __is_specialization_of<_Seq, vector>)
3481 auto __s = this->_M_used();
3482 _GLIBCXX_DEBUG_ASSERT(__s.data() == _M_seq.data());
3483 // Truncate the sequence to the part that was actually written to:
3484 _M_seq.resize(__s.size() + __n);
3485 // Switch back to using buffer:
3486 this->_M_reset(this->_M_buf);
3490 void _M_trim(span<const _CharT> __s)
3491 requires __is_specialization_of<_Seq, basic_string>
3493 _GLIBCXX_DEBUG_ASSERT(__s.data() == this->_M_buf
3494 || __s.data() == _M_seq.data());
3495 if (__s.data() == _M_seq.data())
3496 _M_seq.resize(__s.size());
3498 this->_M_reset(this->_M_buf, __s.size());
3502 // TODO: for SSO string, use SSO buffer as initial span, then switch
3503 // to _M_buf if it overflows?
Or even do that for all unused capacity?
3505 [[
__gnu__::__always_inline__]]
3506 _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
3509 _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
3510 : _M_seq(std::move(__s))
3513 using _Sink<_CharT>::out;
3518 if (this->_M_used().size() != 0)
3519 _Seq_sink::_M_overflow();
3520 return std::move(_M_seq);
3523 // A writable span that views everything written to the sink.
3524 // Will be either a view over _M_seq or the used part of _M_buf.
3528 auto __s = this->_M_used();
3531 if (__s.size() != 0)
3532 _Seq_sink::_M_overflow();
3538 basic_string_view<_CharT>
3541 auto __span = _M_span();
3542 return basic_string_view<_CharT>(__span.data(), __span.size());
3546 template<typename _CharT, typename _Alloc = allocator<_CharT>>
3548 = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
3550 // template<typename _CharT, typename _Alloc = allocator<_CharT>>
3551 // using _Vec_sink = _Seq_sink<vector<_CharTthis-> sink that writes to an output iterator.
3552 // Writes to a fixed-size buffer and then flushes to the output iterator
3553 // when the buffer fills up.
3554 template<typename _CharT, typename _OutIter>
3555 class _Iter_sink : public _Buf_sink<_CharT>
3558 iter_difference_t<_OutIter> _M_max;
3561 size_t _M_count = 0;
3564 _M_overflow() override
3566 auto __s = this->_M_used();
3567 if (_M_max < 0) // No maximum.
3568 _M_out = ranges::copy(__s, std::move(_M_out)).out;
3569 else if (_M_count < static_cast<size_t>(_M_max))
3571 auto __max = _M_max - _M_count;
3572 span<_CharT> __first;
3573 if (__max < __s.size())
3574 __first = __s.first(static_cast<size_t>(__max));
3577 _M_out = ranges::copy(__first, std::move(_M_out)).out;
3580 _M_count += __s.size();
3584 _M_discarding() const override
3586 // format_to_n return total number of characters, that would be written,
3587 // see C++20 [
format.functions]
p20
3592 [[
__gnu__::__always_inline__]]
3594 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
3595 : _M_out(std::move(__out)), _M_max(__max)
3598 using _Sink<_CharT>::out;
3600 format_to_n_result<_OutIter>
3603 if (this->_M_used().size() != 0)
3604 _Iter_sink::_M_overflow();
3605 iter_difference_t<_OutIter> __count(_M_count);
3606 return {
std::move(_M_out), __count };
3610 // Partial specialization for contiguous iterators.
3611 // No buffer is used, characters are written straight to the iterator.
3612 // We do not know the size of the output range, so the span size just grows
3613 // as needed. The end of the span might be an invalid pointer outside the
3614 // valid range, but we never actually call _M_span.end(). This class does
3615 // not introduce any invalid pointer arithmetic or overflows that would not
3616 // have happened anyway.
3617 template<typename _CharT, contiguous_iterator _OutIter>
3618 requires same_as<iter_value_t<_OutIter>, _CharT>
3619 class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
3622 iter_difference_t<_OutIter> _M_max = -1;
3624 size_t _M_count = 0;
3626 _CharT _M_buf[
64];
// Write here after outputting _M_max characters.
3630 _M_overflow() override
3632 if (this->_M_unused().size() != 0)
3633 return;
// No need to switch to internal buffer yet.
3635 auto __s = this->_M_used();
3639 _M_count += __s.size();
3640 // Span was already sized for the maximum character count,
3641 // if it overflows then any further output must go to the
3642 // internal buffer, to be discarded.
3643 this->_M_reset(this->_M_buf);
3647 // No maximum character count. Just extend the span to allow
3648 // writing more characters to it.
3649 this->_M_reset({
__s.data(), __s.size() + 1024}
, __s.size());
3654 _M_discarding() const override
3656 // format_to_n return total number of characters, that would be written,
3657 // see C++20 [
format.functions]
p20
3661 typename _Sink<_CharT>::_Reservation
3662 _M_reserve(size_t __n) final
3664 auto __avail = this->_M_unused();
3665 if (__n > __avail.size())
3668 return {};
// cannot grow
3670 auto __s = this->_M_used();
3671 this->_M_reset({
__s.data(), __s.size() + __n}
, __s.size());
3678 _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
3679 span<_CharT> __buf) noexcept
3682 return __buf;
// Only write to the internal buffer.
3686 if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
3687 || sizeof(__n) > sizeof(size_t))
3689 // __int128 or __detail::__max_diff_type
3690 auto __m = iter_difference_t<_OutIter>((size_t)-1);
3694 return {
__ptr, (size_t)__n};
3697#if __has_builtin(__builtin_dynamic_object_size)
3698 if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
3699 return {
__ptr, __bytes / sizeof(_CharT)};
3701 // Avoid forming a pointer to a different memory page.
3702 const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
3703 __n = (1024 - __off) / sizeof(_CharT);
3704 if (__n > 0) [[
likely]]
3705 return {
__ptr, static_cast<size_t>(__n)};
3706 else // Misaligned/packed buffer of wchar_t?
3712 _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
3713 : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
3714 _M_first(__out), _M_max(__n)
3717 format_to_n_result<_OutIter>
3720 auto __s = this->_M_used();
3721 if (__s.data() == _M_buf)
3723 // Switched to internal buffer, so must have written _M_max.
3724 iter_difference_t<_OutIter> __count(_M_count + __s.size());
3725 return {
_M_first + _M_max, __count };
3727 else // Not using internal buffer yet
3729 iter_difference_t<_OutIter> __count(__s.size());
3730 return {
_M_first + __count, __count };
3735 // A sink for handling the padded outputs (_M_padwidth) or truncated
3736 // (_M_maxwidth). The handling is done by writting to buffer (_Str_strink)
3737 // until sufficient number of characters is written. After that if sequence
3738 // is longer than _M_padwidth it's written to _M_out, and further writes are
3740 // * buffered and forwarded to _M_out, if below _M_maxwidth,
3741 // * ignored otherwise
3742 // If field width of written sequence is no greater than _M_padwidth, the
3743 // sequence is written during _M_finish call.
3744 template<typename _Out, typename _CharT>
3745 class _Padding_sink : public _Str_sink<_CharT>
3750 size_t _M_printwidth;
3752 [[
__gnu__::__always_inline__]]
3755 {
return _M_printwidth >= _M_maxwidth; }
3757 [[
__gnu__::__always_inline__]]
3759 _M_buffering() const
3761 if (_M_printwidth < _M_padwidth)
3763 if (_M_maxwidth != (size_t)-1)
3764 return _M_printwidth < _M_maxwidth;
3769 _M_sync_discarding()
3771 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3772 if (_M_out._M_discarding())
3773 _M_maxwidth = _M_printwidth;
3779 span<_CharT> __new = this->_M_used();
3780 basic_string_view<_CharT> __str(__new.data(), __new.size());
3781 _M_out = __format::__write(std::move(_M_out), __str);
3782 _M_sync_discarding();
3789 auto __str = this->view();
3790 // Compute actual field width, possibly truncated.
3791 _M_printwidth = __format::__truncate(__str, _M_maxwidth);
3793 this->_M_trim(__str);
3797 // We have more characters than padidng, no padding is needed,
3798 // write direclty to _M_out.
3799 if (_M_printwidth >= _M_padwidth)
3801 _M_out = __format::__write(std::move(_M_out), __str);
3802 _M_sync_discarding();
3804 // We reached _M_maxwidth that is smaller than _M_padwidth.
3805 // Store the prefix sequence in _M_seq, and free _M_buf.
3807 _Str_sink<_CharT>::_M_overflow();
3809 // Use internal buffer for writes to _M_out.
3810 this->_M_reset(this->_M_buf);
3815 _M_update(size_t __new)
3817 _M_printwidth += __new;
3818 // Compute estimated width, to see if is not reduced.
3819 if (_M_printwidth >= _M_padwidth || _M_printwidth >= _M_maxwidth)
3820 return _M_force_update();
3825 _M_overflow() override
3827 // Ignore characters in buffer, and override it.
3830 // Write buffer to _M_out, and override it.
3831 else if (!_M_buffering())
3833 // Update written count, and if input still should be buffered,
3834 // flush the to _M_seq.
3835 else if (_M_update(this->_M_used().size()))
3836 _Str_sink<_CharT>::_M_overflow();
3840 _M_discarding() const override
3841 {
return _M_ignoring(); }
3843 typename _Sink<_CharT>::_Reservation
3844 _M_reserve(size_t __n) override
3846 // Ignore characters in buffer, if any.
3849 else if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
3850 if (!_M_buffering())
3852 // Write pending characters if any
3853 if (!this->_M_used().empty())
3855 // Try to reserve from _M_out sink.
3856 if (auto __reserved = _M_out._M_reserve(__n))
3859 return _Sink<_CharT>::_M_reserve(__n);
3863 _M_bump(size_t __n) override
3865 // Ignore the written characters.
3868 // If reservation was made directy sink associated _M_out,
3869 // _M_bump will be called on that sink.
3870 _Sink<_CharT>::_M_bump(__n);
3876 [[
__gnu__::__always_inline__]]
3878 _Padding_sink(_Out __out, size_t __padwidth, size_t __maxwidth)
3879 : _M_padwidth(__padwidth), _M_maxwidth(__maxwidth),
3880 _M_out(std::move(__out)), _M_printwidth(0)
3881 {
_M_sync_discarding(); }
3883 [[
__gnu__::__always_inline__]]
3885 _Padding_sink(_Out __out, size_t __padwidth)
3886 : _Padding_sink(std::move(__out), __padwidth, (size_t)-1)
3890 _M_finish(_Align __align, char32_t __fill_char)
3892 // Handle any characters in the buffer.
3893 if (auto __rem = this->_M_used().size())
3897 else if (!_M_buffering())
3903 if (!_M_buffering() || !_M_force_update())
3904 // Characters were already written to _M_out.
3905 if (_M_printwidth >= _M_padwidth)
3906 return std::move(_M_out);
3908 const auto __str = this->view();
3909 if (_M_printwidth >= _M_padwidth)
3910 return __format::__write(std::move(_M_out), __str);
3912 const size_t __nfill = _M_padwidth - _M_printwidth;
3913 return __format::__write_padded(std::move(_M_out), __str,
3914 __align, __nfill, __fill_char);
3918 enum class _Arg_t : unsigned char {
3919 _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
3920 _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
3921 _Arg_i128, _Arg_u128, _Arg_float128,
3922 _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64,
3925#ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
3926 _Arg_ibm128 = _Arg_ldbl,
3927 _Arg_ieee128 = _Arg_float128,
3932 template<typename _Context>
3935 using _CharT = typename _Context::char_type;
3951 unsigned long long _M_ull;
3954#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
3955 long double _M_ldbl;
3958 __ieee128 _M_ieee128;
3960#ifdef __SIZEOF_FLOAT128__
3961 __float128 _M_float128;
3963 const _CharT* _M_str;
3964 basic_string_view<_CharT> _M_sv;
3966 _HandleBase _M_handle;
3967#ifdef __SIZEOF_INT128__
3969 unsigned __int128 _M_u128;
3971#ifdef __BFLT16_DIG__
3985 [[
__gnu__::__always_inline__]]
3986 _Arg_value() : _M_none() { }
3989 template<typename _Tp>
3990 _Arg_value(in_place_type_t<_Tp>, _Tp __val)
3991 {
_S_get<_Tp>() = __val; }
3994 template<typename _Tp, typename _Self>
3995 [[
__gnu__::__always_inline__]]
3997 _S_get(_Self& __u) noexcept
3999 if constexpr (is_same_v<_Tp, bool>)
4001 else if constexpr (is_same_v<_Tp, _CharT>)
4003 else if constexpr (is_same_v<_Tp, int>)
4005 else if constexpr (is_same_v<_Tp, unsigned>)
4007 else if constexpr (is_same_v<_Tp, long long>)
4009 else if constexpr (is_same_v<_Tp, unsigned long long>)
4011 else if constexpr (is_same_v<_Tp, float>)
4013 else if constexpr (is_same_v<_Tp, double>)
4015#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4016 else if constexpr (is_same_v<_Tp, long double>)
4019 else if constexpr (is_same_v<_Tp, __ibm128>)
4020 return __u._M_ibm128;
4021 else if constexpr (is_same_v<_Tp, __ieee128>)
4022 return __u._M_ieee128;
4024#ifdef __SIZEOF_FLOAT128__
4025 else if constexpr (is_same_v<_Tp, __float128>)
4026 return __u._M_float128;
4028 else if constexpr (is_same_v<_Tp, const _CharT*>)
4030 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4032 else if constexpr (is_same_v<_Tp, const void*>)
4034#ifdef __SIZEOF_INT128__
4035 else if constexpr (is_same_v<_Tp, __int128>)
4037 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4040#ifdef __BFLT16_DIG__
4041 else if constexpr (is_same_v<_Tp, __bflt16_t>)
4045 else if constexpr (is_same_v<_Tp, _Float16>)
4049 else if constexpr (is_same_v<_Tp, _Float32>)
4053 else if constexpr (is_same_v<_Tp, _Float64>)
4056 else if constexpr (derived_from<_Tp, _HandleBase>)
4057 return static_cast<_Tp&>(__u._M_handle);
4058 // Otherwise, ill-formed.
4061 template<typename _Tp>
4062 [[
__gnu__::__always_inline__]]
4065 {
return _S_get<_Tp>(*this); }
4067 template<typename _Tp>
4068 [[
__gnu__::__always_inline__]]
4070 _M_get() const noexcept
4071 {
return _S_get<_Tp>(*this); }
4073 template<typename _Tp>
4074 [[
__gnu__::__always_inline__]]
4076 _M_set(_Tp __v) noexcept
4078 if constexpr (derived_from<_Tp, _HandleBase>)
4079 std::construct_at(&_M_handle, __v);
4081 _S_get<_Tp>(*this) = __v;
4085 // [
format.arg.store]
, class template format-arg-store
4086 template<typename _Context, typename... _Args>
4089 template<typename _Visitor, typename _Ctx>
4090 decltype(auto) __visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4092 template<typename _Ch, typename _Tp>
4094 __to_arg_t_enum() noexcept;
4095}
// namespace __format
4098 template<typename _Context>
4099 class basic_format_arg
4101 using _CharT = typename _Context::char_type;
4103 template<typename _Tp>
4104 static constexpr bool __formattable
4105 = __format::__formattable_with<_Tp, _Context>;
4108 class handle : public __format::_Arg_value<_Context>::_HandleBase
4110 using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
4112 // Format as const if possible, to reduce instantiations.
4113 template<typename _Tp>
4114 using __maybe_const_t
4115 = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
4117 template<typename _Tq>
4119 _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
4120 _Context& __format_ctx, const void* __ptr)
4122 using _Td = remove_const_t<_Tq>;
4123 typename _Context::template formatter_type<_Td> __f;
4124 __parse_ctx.advance_to(__f.parse(__parse_ctx));
4125 _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
4126 __format_ctx.advance_to(__f.format(__val, __format_ctx));
4129 template<typename _Tp>
4131 handle(_Tp& __val) noexcept
4133 this->_M_ptr = __builtin_addressof(__val);
4134 auto __func = _S_format<__maybe_const_t<_Tp>>;
4135 this->_M_func = reinterpret_cast<void(*)()>(__func);
4138 friend class basic_format_arg<_Context>;
4141 handle(const handle&) = default;
4142 handle& operator=(const handle&) = default;
4144 [[
__gnu__::__always_inline__]]
4146 format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
4148 using _Func = void(*)(basic_format_parse_context<_CharT>&,
4149 _Context&, const void*);
4150 auto __f = reinterpret_cast<_Func>(this->_M_func);
4151 __f(__pc, __fc, this->_M_ptr);
4155 [[
__gnu__::__always_inline__]]
4156 basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
4158 [[
nodiscard,__gnu__::__always_inline__]]
4159 explicit operator bool() const noexcept
4160 {
return _M_type != __format::_Arg_none; }
4162#if __cpp_lib_format >= 202306L // >= C++26
4163 template<typename _Visitor>
4165 visit(this basic_format_arg __arg, _Visitor&& __vis)
4166 {
return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4168 template<typename _Res, typename _Visitor>
4170 visit(this basic_format_arg __arg, _Visitor&& __vis)
4171 {
return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type); }
4175 template<typename _Ctx>
4176 friend class basic_format_args;
4178 template<typename _Ctx, typename... _Args>
4179 friend class __format::_Arg_store;
4181 static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
4183 __format::_Arg_value<_Context> _M_val;
4184 __format::_Arg_t _M_type;
4186 // Transform incoming argument type to the type stored in _Arg_value.
4187 // e.g. short -> int, std::string -> std::string_view,
4188 // char[
3]
-> const char*.
4189 template<typename _Tp>
4190 static consteval auto
4193 using _Td = remove_const_t<_Tp>;
4194 if constexpr (is_same_v<_Td, bool>)
4195 return type_identity<bool>();
4196 else if constexpr (is_same_v<_Td, _CharT>)
4197 return type_identity<_CharT>();
4198 else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
4199 return type_identity<_CharT>();
4200#ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
4201 else if constexpr (is_same_v<_Td, __int128>)
4202 return type_identity<__int128>();
4203 else if constexpr (is_same_v<_Td, unsigned __int128>)
4204 return type_identity<unsigned __int128>();
4206 else if constexpr (__is_signed_integer<_Td>::value)
4208 if constexpr (sizeof(_Td) <= sizeof(int))
4209 return type_identity<int>();
4210 else if constexpr (sizeof(_Td) <= sizeof(long long))
4211 return type_identity<long long>();
4213 else if constexpr (__is_unsigned_integer<_Td>::value)
4215 if constexpr (sizeof(_Td) <= sizeof(unsigned))
4216 return type_identity<unsigned>();
4217 else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
4218 return type_identity<unsigned long long>();
4220 else if constexpr (is_same_v<_Td, float>)
4221 return type_identity<float>();
4222 else if constexpr (is_same_v<_Td, double>)
4223 return type_identity<double>();
4224#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4225 else if constexpr (is_same_v<_Td, long double>)
4226 return type_identity<long double>();
4228 else if constexpr (is_same_v<_Td, __ibm128>)
4229 return type_identity<__ibm128>();
4230 else if constexpr (is_same_v<_Td, __ieee128>)
4231 return type_identity<__ieee128>();
4233#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4234 else if constexpr (is_same_v<_Td, __float128>)
4235 return type_identity<__float128>();
4237#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4238 else if constexpr (is_same_v<_Td, __format::__bflt16_t>)
4239 return type_identity<__format::__bflt16_t>();
4241#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4242 else if constexpr (is_same_v<_Td, _Float16>)
4243 return type_identity<_Float16>();
4245#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4246 else if constexpr (is_same_v<_Td, _Float32>)
4247 return type_identity<_Float32>();
4249#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4250 else if constexpr (is_same_v<_Td, _Float64>)
4251 return type_identity<_Float64>();
4253 else if constexpr (__is_specialization_of<_Td, basic_string_view>
4254 || __is_specialization_of<_Td, basic_string>)
4256 if constexpr (is_same_v<typename _Td::value_type, _CharT>)
4257 return type_identity<basic_string_view<_CharT>>();
4259 return type_identity<handle>();
4261 else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
4262 return type_identity<const _CharT*>();
4263 else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
4264 return type_identity<const _CharT*>();
4265 else if constexpr (is_void_v<remove_pointer_t<_Td>>)
4266 return type_identity<const void*>();
4267 else if constexpr (is_same_v<_Td, nullptr_t>)
4268 return type_identity<const void*>();
4270 return type_identity<handle>();
4273 // Transform a formattable type to the appropriate storage type.
4274 template<typename _Tp>
4275 using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
4277 // Get the _Arg_t value corresponding to a normalized type.
4278 template<typename _Tp>
4279 static consteval __format::_Arg_t
4282 using namespace __format;
4283 if constexpr (is_same_v<_Tp, bool>)
4285 else if constexpr (is_same_v<_Tp, _CharT>)
4287 else if constexpr (is_same_v<_Tp, int>)
4289 else if constexpr (is_same_v<_Tp, unsigned>)
4291 else if constexpr (is_same_v<_Tp, long long>)
4293 else if constexpr (is_same_v<_Tp, unsigned long long>)
4295 else if constexpr (is_same_v<_Tp, float>)
4297 else if constexpr (is_same_v<_Tp, double>)
4299#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4300 else if constexpr (is_same_v<_Tp, long double>)
4303 // Don't use _Arg_ldbl for this target, it's ambiguous.
4304 else if constexpr (is_same_v<_Tp, __ibm128>)
4306 else if constexpr (is_same_v<_Tp, __ieee128>)
4307 return _Arg_ieee128;
4309#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4310 else if constexpr (is_same_v<_Tp, __float128>)
4311 return _Arg_float128;
4313#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4314 else if constexpr (is_same_v<_Tp, __format::__bflt16_t>)
4317#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4318 else if constexpr (is_same_v<_Tp, _Float16>)
4321#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4322 else if constexpr (is_same_v<_Tp, _Float32>)
4325#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4326 else if constexpr (is_same_v<_Tp, _Float64>)
4329 else if constexpr (is_same_v<_Tp, const _CharT*>)
4331 else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
4333 else if constexpr (is_same_v<_Tp, const void*>)
4335#ifdef __SIZEOF_INT128__
4336 else if constexpr (is_same_v<_Tp, __int128>)
4338 else if constexpr (is_same_v<_Tp, unsigned __int128>)
4341 else if constexpr (is_same_v<_Tp, handle>)
4345 template<typename _Tp>
4347 _M_set(_Tp __v) noexcept
4349 _M_type = _S_to_enum<_Tp>();
4353 template<typename _Tp>
4354 requires __format::__formattable_with<_Tp, _Context>
4356 basic_format_arg(_Tp& __v) noexcept
4358 using _Td = _Normalize<_Tp>;
4359 if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
4360 _M_set(_Td{
__v.data(), __v.size()}
);
4361 else if constexpr (is_same_v<remove_const_t<_Tp>, char>
4362 && is_same_v<_CharT, wchar_t>)
4363 _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
4365 _M_set(static_cast<_Td>(__v));
4368 template<typename _Ctx, typename... _Argz>
4370 make_format_args(_Argz&...) noexcept;
4372 template<typename _Visitor, typename _Ctx>
4373 friend decltype(auto)
4374 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
4376 template<typename _Visitor, typename _Ctx>
4377 friend decltype(auto)
4378 __format::__visit_format_arg(_Visitor&&, basic_format_arg<_Ctx>);
4380 template<typename _Ch, typename _Tp>
4381 friend consteval __format::_Arg_t
4382 __format::__to_arg_t_enum() noexcept;
4384 template<typename _Visitor>
4386 _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
4388 using namespace __format;
4392 return std::forward<_Visitor>(__vis)(_M_val._M_none);
4394 return std::forward<_Visitor>(__vis)(_M_val._M_bool);
4396 return std::forward<_Visitor>(__vis)(_M_val._M_c);
4398 return std::forward<_Visitor>(__vis)(_M_val._M_i);
4400 return std::forward<_Visitor>(__vis)(_M_val._M_u);
4402 return std::forward<_Visitor>(__vis)(_M_val._M_ll);
4404 return std::forward<_Visitor>(__vis)(_M_val._M_ull);
4405#if __glibcxx_to_chars // FIXME: need to be able to format these types!
4407 return std::forward<_Visitor>(__vis)(_M_val._M_flt);
4409 return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
4410#ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
4412 return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
4413#if defined(__SIZEOF_FLOAT128__) && _GLIBCXX_FORMAT_F128
4415 return std::forward<_Visitor>(__vis)(_M_val._M_float128);
4419 return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
4421 return std::forward<_Visitor>(__vis)(_M_val._M_ieee128);
4423#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4425 return std::forward<_Visitor>(__vis)(_M_val._M_bf16);
4427#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4429 return std::forward<_Visitor>(__vis)(_M_val._M_f16);
4431#if defined(__FLT32_DIG__) && defined(_GLIBCXX_FLOAT_IS_IEEE_BINARY32)
4433 return std::forward<_Visitor>(__vis)(_M_val._M_f32);
4435#if defined(__FLT64_DIG__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
4437 return std::forward<_Visitor>(__vis)(_M_val._M_f64);
4439#endif // __glibcxx_to_chars
4441 return std::forward<_Visitor>(__vis)(_M_val._M_str);
4443 return std::forward<_Visitor>(__vis)(_M_val._M_sv);
4445 return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
4448 auto& __h = static_cast<handle&>(_M_val._M_handle);
4449 return std::forward<_Visitor>(__vis)(__h);
4451#ifdef __SIZEOF_INT128__
4453 return std::forward<_Visitor>(__vis)(_M_val._M_i128);
4455 return std::forward<_Visitor>(__vis)(_M_val._M_u128);
4458 __builtin_unreachable();
4462 template<typename _Visitor>
4464 _M_visit_user(_Visitor&& __vis, __format::_Arg_t __type)
4466 return _M_visit([
&__vis]
<typename _Tp>(_Tp& __val) -> decltype(auto)
4468 constexpr bool __user_facing = __is_one_of<_Tp,
4469 monostate, bool, _CharT,
4470 int, unsigned int, long long int, unsigned long long int,
4471 float, double, long double,
4472 const _CharT*, basic_string_view<_CharT>,
4473 const void*, handle>::value;
4474 if constexpr (__user_facing)
4475 return std::forward<_Visitor>(__vis)(__val);
4479 return std::forward<_Visitor>(__vis)(__h);
4485 template<typename _Visitor, typename _Context>
4486 _GLIBCXX26_DEPRECATED_SUGGEST("std::basic_format_arg::visit")
4487 inline decltype(auto)
4488 visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
4490 return __arg._M_visit_user(std::forward<_Visitor>(__vis), __arg._M_type);
4493/// @
cond undocumented
4496 template<typename _Visitor, typename _Ctx>
4497 inline decltype(auto)
4498 __visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg)
4500 return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
4503 struct _WidthPrecVisitor
4505 template<typename _Tp>
4507 operator()(_Tp& __arg) const
4509 if constexpr (is_same_v<_Tp, monostate>)
4510 __format::__invalid_arg_id_in_format_string();
4511 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4512 // 3720.
Restrict the valid types of arg-id for width and precision
4513 // 3721.
Allow an arg-id with a value of zero for width
4514 else if constexpr (sizeof(_Tp) <= sizeof(long long))
4516 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4517 // 3720.
Restrict the valid types of arg-id for width and precision
4518 if constexpr (__is_unsigned_integer<_Tp>::value)
4520 else if constexpr (__is_signed_integer<_Tp>::value)
4524 __throw_format_error("format error: argument used for width or "
4525 "precision must be a non-negative integer");
4529#pragma GCC diagnostic push
4530#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4531 template<typename _Context>
4533 __int_from_arg(const basic_format_arg<_Context>& __arg)
4534 {
return __format::__visit_format_arg(_WidthPrecVisitor(), __arg); }
4536 // Pack _Arg_t enum values into a single 60-bit integer.
4537 template<int _Bits, size_t _Nm>
4539 __pack_arg_types(const array<_Arg_t, _Nm>& __types)
4541 __UINT64_TYPE__ __packed_types = 0;
4542 for (auto __i = __types.rbegin();
__i != __types.rend();
++__i)
4543 __packed_types = (__packed_types << _Bits) | (unsigned)*__i;
4544 return __packed_types;
4546}
// namespace __format
4549 template<typename _Context>
4550 class basic_format_args
4552 static constexpr int _S_packed_type_bits = 5;
// _Arg_t values [
0,20]
4553 static constexpr int _S_packed_type_mask = 0b11111;
4554 static constexpr int _S_max_packed_args = 12;
4556 static_assert( (unsigned)__format::_Arg_max_ <= (1u << _S_packed_type_bits) );
4558 template<typename... _Args>
4559 using _Store = __format::_Arg_store<_Context, _Args...>;
4561 template<typename _Ctx, typename... _Args>
4562 friend class __format::_Arg_store;
4564 using uint64_t = __UINT64_TYPE__;
4565 using _Format_arg = basic_format_arg<_Context>;
4566 using _Format_arg_val = __format::_Arg_value<_Context>;
4568 // If args are packed then the number of args is in _M_packed_size and
4569 // the packed types are in _M_unpacked_size, accessed via _M_type(i).
4570 // If args are not packed then the number of args is in _M_unpacked_size
4571 // and _M_packed_size is zero.
4572 uint64_t _M_packed_size : 4;
4573 uint64_t _M_unpacked_size : 60;
4576 const _Format_arg_val* _M_values;
// Active when _M_packed_size != 0
4577 const _Format_arg* _M_args;
// Active when _M_packed_size == 0
4581 _M_size() const noexcept
4582 {
return _M_packed_size ?
_M_packed_size : _M_unpacked_size; }
4584 typename __format::_Arg_t
4585 _M_type(size_t __i) const noexcept
4587 uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
4588 return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
4591 template<typename _Ctx, typename... _Args>
4593 make_format_args(_Args&...) noexcept;
4595 // An array of _Arg_t enums corresponding to _Args...
4596 template<typename... _Args>
4597 static consteval array<__format::_Arg_t, sizeof...(_Args)>
4599 {
return {
_Format_arg::template _S_to_enum<_Args>()...}; }
4602 template<typename... _Args>
4603 basic_format_args(const _Store<_Args...>& __store) noexcept;
4605 [[
nodiscard,__gnu__::__always_inline__]]
4606 basic_format_arg<_Context>
4607 get(size_t __i) const noexcept
4609 basic_format_arg<_Context> __arg;
4610 if (__i < _M_packed_size)
4612 __arg._M_type = _M_type(__i);
4613 __arg._M_val = _M_values[
__i];
4615 else if (_M_packed_size == 0 && __i < _M_unpacked_size)
4616 __arg = _M_args[
__i];
4621 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4622 // 3810.
CTAD for std::basic_format_args
4623 template<typename _Context, typename... _Args>
4624 basic_format_args(__format::_Arg_store<_Context, _Args...>)
4625 -> basic_format_args<_Context>;
4627 template<typename _Context, typename... _Args>
4629 make_format_args(_Args&... __fmt_args) noexcept;
4631 // An array of type-erased formatting arguments.
4632 template<typename _Context, typename... _Args>
4633 class __format::_Arg_store
4635 friend std::basic_format_args<_Context>;
4637 template<typename _Ctx, typename... _Argz>
4639#if _GLIBCXX_INLINE_VERSION
4640 __8:: // Needed for PR c++/59256
4642 make_format_args(_Argz&...) noexcept;
4644 // For a sufficiently small number of arguments we only store values.
4645 // basic_format_args can get the types from the _Args pack.
4646 static constexpr bool _S_values_only
4647 = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
4650 = __conditional_t<_S_values_only,
4651 __format::_Arg_value<_Context>,
4652 basic_format_arg<_Context>>;
4654 _Element_t _M_args[
sizeof...(_Args)];
4656 template<typename _Tp>
4658 _S_make_elt(_Tp& __v)
4660 using _Tq = remove_const_t<_Tp>;
4661 using _CharT = typename _Context::char_type;
4662 static_assert(is_default_constructible_v<formatter<_Tq, _CharT>>,
4663 "std::formatter must be specialized for the type "
4664 "of each format arg");
4665 using __format::__formattable_with;
4666 if constexpr (is_const_v<_Tp>)
4667 if constexpr (!__formattable_with<_Tp, _Context>)
4668 if constexpr (__formattable_with<_Tq, _Context>)
4669 static_assert(__formattable_with<_Tp, _Context>,
4670 "format arg must be non-const because its "
4671 "std::formatter specialization has a "
4672 "non-const reference parameter");
4673 basic_format_arg<_Context> __arg(__v);
4674 if constexpr (_S_values_only)
4675 return __arg._M_val;
4680 template<typename... _Tp>
4681 requires (sizeof...(_Tp) == sizeof...(_Args))
4682 [[
__gnu__::__always_inline__]]
4683 _Arg_store(_Tp&... __a) noexcept
4684 : _M_args{
_S_make_elt(__a)...}
4688 template<typename _Context>
4689 class __format::_Arg_store<_Context>
4692 template<typename _Context>
4693 template<typename... _Args>
4695 basic_format_args<_Context>::
4696 basic_format_args(const _Store<_Args...>& __store) noexcept
4698 if constexpr (sizeof...(_Args) == 0)
4701 _M_unpacked_size = 0;
4704 else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
4706 // The number of packed arguments:
4707 _M_packed_size = sizeof...(_Args);
4708 // The packed type enums:
4710 = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
4711 // The _Arg_value objects.
4712 _M_values = __store._M_args;
4716 // No packed arguments:
4718 // The number of unpacked arguments:
4719 _M_unpacked_size = sizeof...(_Args);
4720 // The basic_format_arg objects:
4721 _M_args = __store._M_args;
4725 /// Capture formatting arguments for use by `
std::vformat`
.
4726 template<typename _Context = format_context, typename... _Args>
4727 [[
nodiscard,__gnu__::__always_inline__]]
4729 make_format_args(_Args&... __fmt_args) noexcept
4731 using _Fmt_arg = basic_format_arg<_Context>;
4732 using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
4733 _Normalize<_Args>...>;
4734 return _Store(__fmt_args...);
4737#ifdef _GLIBCXX_USE_WCHAR_T
4738 /// Capture formatting arguments for use by `
std::vformat`
(for wide output).
4739 template<typename... _Args>
4740 [[
nodiscard,__gnu__::__always_inline__]]
4742 make_wformat_args(_Args&... __args) noexcept
4743 {
return std::make_format_args<wformat_context>(__args...); }
4746/// @
cond undocumented
4749 template<typename _Out, typename _CharT, typename _Context>
4751 __do_vformat_to(_Out, basic_string_view<_CharT>,
4752 const basic_format_args<_Context>&,
4753 const locale* = nullptr);
4755 template<typename _CharT> struct __formatter_chrono;
4757}
// namespace __format
4760 /** Context for std::format and similar functions.
4762 * A formatting context contains an output iterator and locale to use
4763 * for the formatting operations. Most programs will never need to use
4764 * this class template explicitly. For typical uses of `
std::format`
the
4765 * library will use the specializations `
std::format_context`
(for `
char`
)
4766 * and `
std::wformat_context`
(for `
wchar_t`
).
4768 * You are not allowed to define partial or explicit specializations of
4769 * this class template.
4773 template<typename _Out, typename _CharT>
4774 class basic_format_context
4776 static_assert( output_iterator<_Out, const _CharT&> );
4778 basic_format_args<basic_format_context> _M_args;
4780 __format::_Optional_locale _M_loc;
4782 basic_format_context(basic_format_args<basic_format_context> __args,
4784 : _M_args(__args), _M_out(std::move(__out))
4787 basic_format_context(basic_format_args<basic_format_context> __args,
4788 _Out __out, const std::locale& __loc)
4789 : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
4792 // _GLIBCXX_RESOLVE_LIB_DEFECTS
4793 // 4061.
Should std::basic_format_context be
4794 // default-constructible/copyable/movable?
4795 basic_format_context(const basic_format_context&) = delete;
4796 basic_format_context& operator=(const basic_format_context&) = delete;
4798 template<typename _Out2, typename _CharT2, typename _Context2>
4800 __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
4801 const basic_format_args<_Context2>&,
4804 friend __format::__formatter_chrono<_CharT>;
4807 ~basic_format_context() = default;
4809 using iterator = _Out;
4810 using char_type = _CharT;
4811 template<typename _Tp>
4812 using formatter_type = formatter<_Tp, _CharT>;
4815 basic_format_arg<basic_format_context>
4816 arg(size_t __id) const noexcept
4817 {
return _M_args.get(__id); }
4820 std::locale locale() {
return _M_loc.value(); }
4823 iterator out() {
return std::move(_M_out); }
4825 void advance_to(iterator __it) {
_M_out = std::move(__it); }
4829/// @
cond undocumented
4832 // Abstract base class defining an interface for scanning format strings.
4833 // Scan the characters in a format string, dividing it up into strings of
4834 // ordinary characters, escape sequences, and replacement fields.
4835 // Call virtual functions for derived classes to parse format-specifiers
4836 // or write formatted output.
4837 template<typename _CharT>
4840 using iterator = typename basic_format_parse_context<_CharT>::iterator;
4842 struct _Parse_context : basic_format_parse_context<_CharT>
4844 using basic_format_parse_context<_CharT>::basic_format_parse_context;
4845 const _Arg_t* _M_types = nullptr;
4849 _Scanner(basic_string_view<_CharT> __str, size_t __nargs = (size_t)-1)
4850 : _M_pc(__str, __nargs)
4853 constexpr iterator begin() const noexcept {
return _M_pc.begin(); }
4854 constexpr iterator end() const noexcept {
return _M_pc.
end(); }
4859 basic_string_view<_CharT> __fmt = _M_fmt_str();
4861 if (__fmt.size() == 2 && __fmt[
0]
== '{
' && __fmt[
1]
== '}
')
4863 _M_pc.advance_to(begin() + 1);
4864 _M_format_arg(_M_pc.next_arg_id());
4868 size_t __lbr = __fmt.find('{
');
4869 size_t __rbr = __fmt.find('}
');
4871 while (__fmt.size())
4873 auto __cmp = __lbr <=> __rbr;
4877 _M_pc.advance_to(end());
4882 if (__lbr + 1 == __fmt.size()
4883 || (__rbr == __fmt.npos && __fmt[
__lbr + 1]
!= '{
'))
4884 __format::__unmatched_left_brace_in_format_string();
4885 const bool __is_escape = __fmt[
__lbr + 1]
== '{
';
4886 iterator __last = begin() + __lbr + int(__is_escape);
4887 _M_on_chars(__last);
4888 _M_pc.advance_to(__last + 1);
4889 __fmt = _M_fmt_str();
4892 if (__rbr != __fmt.npos)
4894 __lbr = __fmt.find('{
');
4898 _M_on_replacement_field();
4899 __fmt = _M_fmt_str();
4900 __lbr = __fmt.find('{
');
4901 __rbr = __fmt.find('}
');
4906 if (++__rbr == __fmt.size() || __fmt[
__rbr]
!= '}
')
4907 __format::__unmatched_right_brace_in_format_string();
4908 iterator __last = begin() + __rbr;
4909 _M_on_chars(__last);
4910 _M_pc.advance_to(__last + 1);
4911 __fmt = _M_fmt_str();
4912 if (__lbr != __fmt.npos)
4914 __rbr = __fmt.find('}
');
4919 constexpr basic_string_view<_CharT>
4920 _M_fmt_str() const noexcept
4921 {
return {
begin(), end()}; }
4923 constexpr virtual void _M_on_chars(iterator) { }
4925 constexpr void _M_on_replacement_field()
4927 auto __next = begin();
4931 __id = _M_pc.next_arg_id();
4932 else if (*__next == ':')
4934 __id = _M_pc.next_arg_id();
4935 _M_pc.advance_to(++__next);
4939 auto [
__i, __ptr]
= __format::__parse_arg_id(begin(), end());
4940 if (!__ptr || !(*__ptr == '}
' || *__ptr == ':'))
4941 __format::__invalid_arg_id_in_format_string();
4942 _M_pc.check_arg_id(__id = __i);
4945 _M_pc.advance_to(++__ptr);
4948 _M_pc.advance_to(__ptr);
4950 _M_format_arg(__id);
4951 if (begin() == end() || *
begin() != '}')
4952 __format::__unmatched_left_brace_in_format_string();
4953 _M_pc.advance_to(begin() + 1);
// Move past '}
'
4956 constexpr virtual void _M_format_arg(size_t __id) = 0;
4959 // Process a format string and format the arguments in the context.
4960 template<typename _Out, typename _CharT>
4961 class _Formatting_scanner : public _Scanner<_CharT>
4964 _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
4965 basic_string_view<_CharT> __str)
4966 : _Scanner<_CharT>(__str), _M_fc(__fc)
4970 basic_format_context<_Out, _CharT>& _M_fc;
4972 using iterator = typename _Scanner<_CharT>::iterator;
4975 _M_on_chars(iterator __last) override
4977 basic_string_view<_CharT> __str(this->begin(), __last);
4978 _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
4982 _M_format_arg(size_t __id) override
4984 using _Context = basic_format_context<_Out, _CharT>;
4985 using handle = typename basic_format_arg<_Context>::handle;
4987 __format::__visit_format_arg([
this]
(auto& __arg) {
4988 using _Type = remove_reference_t<decltype(__arg)>;
4989 using _Formatter = typename _Context::template formatter_type<_Type>;
4990 if constexpr (is_same_v<_Type, monostate>)
4991 __format::__invalid_arg_id_in_format_string();
4992 else if constexpr (is_same_v<_Type, handle>)
4993 __arg.format(this->_M_pc, this->_M_fc);
4994 else if constexpr (is_default_constructible_v<_Formatter>)
4997 this->_M_pc.advance_to(__f.parse(this->_M_pc));
4998 this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
5001 static_assert(__format::__formattable_with<_Type, _Context>);
5002 }
, _M_fc.arg(__id));
5006 template<typename _CharT, typename _Tp>
5008 __to_arg_t_enum() noexcept
5010 using _Context = __format::__format_context<_CharT>;
5011 using _Fmt_arg = basic_format_arg<_Context>;
5012 using _NormalizedTp = typename _Fmt_arg::template _Normalize<_Tp>;
5013 return _Fmt_arg::template _S_to_enum<_NormalizedTp>();
5016 // Validate a format string for Args.
5017 template<typename _CharT, typename... _Args>
5018 class _Checking_scanner : public _Scanner<_CharT>
5021 (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
5022 "std::formatter must be specialized for each type being formatted");
5026 _Checking_scanner(basic_string_view<_CharT> __str)
5027 : _Scanner<_CharT>(__str, sizeof...(_Args))
5029#if __cpp_lib_format >= 202305L
5030 this->_M_pc._M_types = _M_types.data();
5036 _M_format_arg(size_t __id) override
5038 if constexpr (sizeof...(_Args) != 0)
5040 if (__id < sizeof...(_Args))
5042 _M_parse_format_spec<_Args...>(__id);
5046 __builtin_unreachable();
5049 template<typename _Tp, typename... _OtherArgs>
5051 _M_parse_format_spec(size_t __id)
5055 formatter<_Tp, _CharT> __f;
5056 this->_M_pc.advance_to(__f.parse(this->_M_pc));
5058 else if constexpr (sizeof...(_OtherArgs) != 0)
5059 _M_parse_format_spec<_OtherArgs...>(__id - 1);
5061 __builtin_unreachable();
5064#if __cpp_lib_format >= 202305L
5065 array<_Arg_t, sizeof...(_Args)>
5066 _M_types{ {
__format::__to_arg_t_enum<_CharT, _Args>()... } };
5070 template<typename _Out, typename _CharT, typename _Context>
5072 __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
5073 const basic_format_args<_Context>& __args,
5074 const locale* __loc)
5076 _Iter_sink<_CharT, _Out> __sink(std::move(__out));
5077 _Sink_iter<_CharT> __sink_out;
5079 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5080 __sink_out = __out;
// Already a sink iterator, safe to use post-move.
5082 __sink_out = __sink.out();
5084 if constexpr (is_same_v<_CharT, char>)
5085 // Fast path for "{}" format strings and simple format arg types.
5086 if (__fmt.size() == 2 && __fmt[
0]
== '{
' && __fmt[
1]
== '}
')
5088 bool __done = false;
5089 __format::__visit_format_arg([
&]
(auto& __arg) {
5090 using _Tp = remove_cvref_t<decltype(__arg)>;
5091 if constexpr (is_same_v<_Tp, bool>)
5093 size_t __len = 4 + !__arg;
5094 const char* __chars[]
= {
"false", "true" };
5095 if (auto __res = __sink_out._M_reserve(__len))
5097 __builtin_memcpy(__res.get(), __chars[
__arg]
, __len);
5098 __res._M_bump(__len);
5102 else if constexpr (is_same_v<_Tp, char>)
5104 if (auto __res = __sink_out._M_reserve(1))
5106 *__res.get() = __arg;
5111 else if constexpr (is_integral_v<_Tp>)
5113 make_unsigned_t<_Tp> __uval;
5114 const bool __neg = __arg < 0;
5116 __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
5119 const auto __n = __detail::__to_chars_len(__uval);
5120 if (auto __res = __sink_out._M_reserve(__n + __neg))
5122 auto __ptr = __res.get();
5124 __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
5126 __res._M_bump(__n + __neg);
5130 else if constexpr (is_convertible_v<_Tp, string_view>)
5132 string_view __sv = __arg;
5133 if (auto __res = __sink_out._M_reserve(__sv.size()))
5135 __builtin_memcpy(__res.get(), __sv.data(), __sv.size());
5136 __res._M_bump(__sv.size());
5144 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5147 return std::move(__sink)._M_finish().out;
5151 auto __ctx = __loc == nullptr
5152 ?
_Context(__args, __sink_out)
5153 : _Context(__args, __sink_out, *__loc);
5154 _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
5155 __scanner._M_scan();
5157 if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
5160 return std::move(__sink)._M_finish().out;
5162#pragma GCC diagnostic pop
5164}
// namespace __format
5167#if __cpp_lib_format >= 202305L // >= C++26
5168 /// @
cond undocumented
5169 // Common implementation of check_dynamic_spec{
,_string,_integral}
5170 template<typename _CharT>
5171 template<typename... _Ts>
5173 basic_format_parse_context<_CharT>::
5174 __check_dynamic_spec(size_t __id) noexcept
5176 if (__id >= _M_num_args)
5177 __format::__invalid_arg_id_in_format_string();
5178 if constexpr (sizeof...(_Ts) != 0)
5180 using _Parse_ctx = __format::_Scanner<_CharT>::_Parse_context;
5181 auto __arg = static_cast<_Parse_ctx*>(this)->_M_types[
__id];
5182 __format::_Arg_t __types[]
= {
5183 __format::__to_arg_t_enum<_CharT, _Ts>()...
5185 for (auto __t : __types)
5189 __invalid_dynamic_spec("arg(id) type does not match");
5194 template<typename _CharT, typename... _Args>
5195 template<typename _Tp>
5196 requires convertible_to<const _Tp&, basic_string_view<_CharT>>
5198 basic_format_string<_CharT, _Args...>::
5199 basic_format_string(const _Tp& __s)
5202 __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
5204 __scanner._M_scan();
5207 // [
format.functions]
, formatting functions
5209 template<typename _Out> requires output_iterator<_Out, const char&>
5210 [[
__gnu__::__always_inline__]]
5212 vformat_to(_Out __out, string_view __fmt, format_args __args)
5213 {
return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5215#ifdef _GLIBCXX_USE_WCHAR_T
5216 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5217 [[
__gnu__::__always_inline__]]
5219 vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
5220 {
return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
5223 template<typename _Out> requires output_iterator<_Out, const char&>
5224 [[
__gnu__::__always_inline__]]
5226 vformat_to(_Out __out, const locale& __loc, string_view __fmt,
5229 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5232#ifdef _GLIBCXX_USE_WCHAR_T
5233 template<typename _Out> requires output_iterator<_Out, const wchar_t&>
5234 [[
__gnu__::__always_inline__]]
5236 vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
5237 wformat_args __args)
5239 return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc);
5245 vformat(string_view __fmt, format_args __args)
5247 __format::_Str_sink<char> __buf;
5248 std::vformat_to(__buf.out(), __fmt, __args);
5249 return std::move(__buf).get();
5252#ifdef _GLIBCXX_USE_WCHAR_T
5255 vformat(wstring_view __fmt, wformat_args __args)
5257 __format::_Str_sink<wchar_t> __buf;
5258 std::vformat_to(__buf.out(), __fmt, __args);
5259 return std::move(__buf).get();
5265 vformat(const locale& __loc, string_view __fmt, format_args __args)
5267 __format::_Str_sink<char> __buf;
5268 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5269 return std::move(__buf).get();
5272#ifdef _GLIBCXX_USE_WCHAR_T
5275 vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
5277 __format::_Str_sink<wchar_t> __buf;
5278 std::vformat_to(__buf.out(), __loc, __fmt, __args);
5279 return std::move(__buf).get();
5283 template<typename... _Args>
5286 format(format_string<_Args...> __fmt, _Args&&... __args)
5287 {
return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
5289#ifdef _GLIBCXX_USE_WCHAR_T
5290 template<typename... _Args>
5293 format(wformat_string<_Args...> __fmt, _Args&&... __args)
5294 {
return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
5297 template<typename... _Args>
5300 format(const locale& __loc, format_string<_Args...> __fmt,
5303 return std::vformat(__loc, __fmt.get(),
5304 std::make_format_args(__args...));
5307#ifdef _GLIBCXX_USE_WCHAR_T
5308 template<typename... _Args>
5311 format(const locale& __loc, wformat_string<_Args...> __fmt,
5314 return std::vformat(__loc, __fmt.get(),
5315 std::make_wformat_args(__args...));
5319 template<typename _Out, typename... _Args>
5320 requires output_iterator<_Out, const char&>
5322 format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
5324 return std::vformat_to(std::move(__out), __fmt.get(),
5325 std::make_format_args(__args...));
5328#ifdef _GLIBCXX_USE_WCHAR_T
5329 template<typename _Out, typename... _Args>
5330 requires output_iterator<_Out, const wchar_t&>
5332 format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
5334 return std::vformat_to(std::move(__out), __fmt.get(),
5335 std::make_wformat_args(__args...));
5339 template<typename _Out, typename... _Args>
5340 requires output_iterator<_Out, const char&>
5342 format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
5345 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5346 std::make_format_args(__args...));
5349#ifdef _GLIBCXX_USE_WCHAR_T
5350 template<typename _Out, typename... _Args>
5351 requires output_iterator<_Out, const wchar_t&>
5353 format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
5356 return std::vformat_to(std::move(__out), __loc, __fmt.get(),
5357 std::make_wformat_args(__args...));
5361 template<typename _Out, typename... _Args>
5362 requires output_iterator<_Out, const char&>
5363 inline format_to_n_result<_Out>
5364 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5365 format_string<_Args...> __fmt, _Args&&... __args)
5367 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5368 std::vformat_to(__sink.out(), __fmt.get(),
5369 std::make_format_args(__args...));
5370 return std::move(__sink)._M_finish();
5373#ifdef _GLIBCXX_USE_WCHAR_T
5374 template<typename _Out, typename... _Args>
5375 requires output_iterator<_Out, const wchar_t&>
5376 inline format_to_n_result<_Out>
5377 format_to_n(_Out __out, iter_difference_t<_Out> __n,
5378 wformat_string<_Args...> __fmt, _Args&&... __args)
5380 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5381 std::vformat_to(__sink.out(), __fmt.get(),
5382 std::make_wformat_args(__args...));
5383 return std::move(__sink)._M_finish();
5387 template<typename _Out, typename... _Args>
5388 requires output_iterator<_Out, const char&>
5389 inline format_to_n_result<_Out>
5390 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5391 format_string<_Args...> __fmt, _Args&&... __args)
5393 __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
5394 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5395 std::make_format_args(__args...));
5396 return std::move(__sink)._M_finish();
5399#ifdef _GLIBCXX_USE_WCHAR_T
5400 template<typename _Out, typename... _Args>
5401 requires output_iterator<_Out, const wchar_t&>
5402 inline format_to_n_result<_Out>
5403 format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
5404 wformat_string<_Args...> __fmt, _Args&&... __args)
5406 __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
5407 std::vformat_to(__sink.out(), __loc, __fmt.get(),
5408 std::make_wformat_args(__args...));
5409 return std::move(__sink)._M_finish();
5413/// @
cond undocumented
5417 template<typename _CharT>
5418 class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
5421 _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
5423 [[
__gnu__::__always_inline__]]
5426 {
return this->_M_count + this->_M_used().size(); }
5429 template<typename _CharT>
5430 class _Counting_sink : public _Buf_sink<_CharT>
5432 size_t _M_count = 0;
5435 _M_overflow() override
5437 if (!std::is_constant_evaluated())
5438 _M_count += this->_M_used().size();
5443 _Counting_sink() = default;
5445 [[
__gnu__::__always_inline__]]
5449 _Counting_sink::_M_overflow();
5454}
// namespace __format
5457 template<typename... _Args>
5460 formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
5462 __format::_Counting_sink<char> __buf;
5463 std::vformat_to(__buf.out(), __fmt.get(),
5464 std::make_format_args(__args...));
5465 return __buf.count();
5468#ifdef _GLIBCXX_USE_WCHAR_T
5469 template<typename... _Args>
5472 formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
5474 __format::_Counting_sink<wchar_t> __buf;
5475 std::vformat_to(__buf.out(), __fmt.get(),
5476 std::make_wformat_args(__args...));
5477 return __buf.count();
5481 template<typename... _Args>
5484 formatted_size(const locale& __loc, format_string<_Args...> __fmt,
5487 __format::_Counting_sink<char> __buf;
5488 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5489 std::make_format_args(__args...));
5490 return __buf.count();
5493#ifdef _GLIBCXX_USE_WCHAR_T
5494 template<typename... _Args>
5497 formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
5500 __format::_Counting_sink<wchar_t> __buf;
5501 std::vformat_to(__buf.out(), __loc, __fmt.get(),
5502 std::make_wformat_args(__args...));
5503 return __buf.count();
5507#if __glibcxx_format_ranges // C++ >= 23 && HOSTED
5508 /// @
cond undocumented
5509 template<typename _Tp>
5510 consteval range_format
5513 using _Ref = ranges::range_reference_t<_Tp>;
5514 if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
5515 return range_format::disabled;
5516 else if constexpr (requires {
typename _Tp::key_type; }
)
5518 if constexpr (requires {
typename _Tp::mapped_type; }
)
5520 using _Up = remove_cvref_t<_Ref>;
5521 if constexpr (__is_pair<_Up>)
5522 return range_format::map;
5523 else if constexpr (__is_specialization_of<_Up, tuple>)
5524 if constexpr (tuple_size_v<_Up> == 2)
5525 return range_format::map;
5527 return range_format::set;
5530 return range_format::sequence;
5534 /// A constant determining how a range should be formatted.
5535 template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
5536 constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
5538/// @
cond undocumented
5541 template<typename _CharT, typename _Out, typename _Callback>
5542 typename basic_format_context
<_Out, _CharT>::iterator
5543 __format_padded(basic_format_context<_Out, _CharT>& __fc,
5544 const _Spec<_CharT>& __spec,
5547 if constexpr (is_same_v<_Out, _Drop_iter<_CharT>>)
5551 // This is required to implement formatting with padding,
5552 // as we need to format to temporary buffer, using the same iterator.
5553 static_assert(is_same_v<_Out, _Sink_iter<_CharT>>);
5555 const size_t __padwidth = __spec._M_get_width(__fc);
5556 if (__padwidth == 0)
5557 return __call(__fc);
5561 _Restore_out(basic_format_context<_Sink_iter<_CharT>, _CharT>& __fc)
5562 : _M_ctx(std::addressof(__fc)), _M_out(__fc.out())
5567 {
_M_ctx = nullptr; }
5572 _M_ctx->advance_to(_M_out);
5576 basic_format_context<_Sink_iter<_CharT>, _CharT>* _M_ctx;
5577 _Sink_iter<_CharT> _M_out;
5580 _Restore_out __restore(__fc);
5581 _Padding_sink<_Sink_iter<_CharT>, _CharT> __sink(__fc.out(), __padwidth);
5582 __fc.advance_to(__sink.out());
5584 __fc.advance_to(__sink._M_finish(__spec._M_align, __spec._M_fill));
5585 __restore._M_disarm();
5590 template<size_t _Pos, typename _Tp, typename _CharT>
5591 struct __indexed_formatter_storage
5596 basic_format_parse_context<_CharT> __pc({}
);
5597 if (_M_formatter.parse(__pc) != __pc.end())
5598 __format::__failed_to_parse_format_spec();
5601 template<typename _Out>
5603 _M_format(__maybe_const<_Tp, _CharT>& __elem,
5604 basic_format_context<_Out, _CharT>& __fc,
5605 basic_string_view<_CharT> __sep) const
5607 if constexpr (_Pos != 0)
5608 __fc.advance_to(__format::__write(__fc.out(), __sep));
5609 __fc.advance_to(_M_formatter.format(__elem, __fc));
5612 [[
__gnu__::__always_inline__]]
5616 if constexpr (__has_debug_format<formatter<_Tp, _CharT>>)
5617 _M_formatter.set_debug_format();
5621 formatter<_Tp, _CharT> _M_formatter;
5624 template<typename _CharT, typename... _Tps>
5625 class __tuple_formatter
5627 using _String_view = basic_string_view<_CharT>;
5628 using _Seps = __format::_Separators<_CharT>;
5632 set_separator(basic_string_view<_CharT> __sep) noexcept
5636 set_brackets(basic_string_view<_CharT> __open,
5637 basic_string_view<_CharT> __close) noexcept
5643 // We deviate from standard, that declares this as template accepting
5644 // unconstrained ParseContext type, which seems unimplementable.
5645 constexpr typename basic_format_parse_context<_CharT>::iterator
5646 parse(basic_format_parse_context<_CharT>& __pc)
5648 auto __first = __pc.begin();
5649 const auto __last = __pc.end();
5650 __format::_Spec<_CharT> __spec{};
5652 auto __finished = [
&]
5654 if (__first != __last && *__first != '}
')
5658 _M_felems._M_parse();
5659 _M_felems.set_debug_format();
5666 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5670 __first = __spec._M_parse_width(__first, __last, __pc);
5674 if (*__first == 'n')
5677 _M_open = _M_close = _String_view();
5679 else if (*__first == 'm')
5682 if constexpr (sizeof...(_Tps) == 2)
5684 _M_sep = _Seps::_S_colon();
5685 _M_open = _M_close = _String_view();
5688 __throw_format_error("format error: 'm' specifier requires range"
5689 " of pair or tuple of two elements");
5695 __format::__failed_to_parse_format_spec();
5699 template<typename _Tuple, typename _Out, size_t... _Ids>
5700 typename basic_format_context
<_Out, _CharT>::iterator
5701 _M_format(_Tuple& __tuple, index_sequence<_Ids...>,
5702 basic_format_context<_Out, _CharT>& __fc) const
5703 {
return _M_format_elems(std::get<_Ids>(__tuple)..., __fc); }
5705 template<typename _Out>
5706 typename basic_format_context
<_Out, _CharT>::iterator
5707 _M_format_elems(__maybe_const<_Tps, _CharT>&... __elems,
5708 basic_format_context<_Out, _CharT>& __fc) const
5710 return __format::__format_padded(
5712 [
this, &__elems...]
(basic_format_context<_Out, _CharT>& __nfc)
5714 __nfc.advance_to(__format::__write(__nfc.out(), _M_open));
5715 _M_felems._M_format(__elems..., __nfc, _M_sep);
5716 return __format::__write(__nfc.out(), _M_close);
5721 template<size_t... _Ids>
5722 struct __formatters_storage
5723 : __indexed_formatter_storage<_Ids, _Tps, _CharT>...
5725 template<size_t _Id, typename _Up>
5726 using _Base = __indexed_formatter_storage<_Id, _Up, _CharT>;
5731 (_Base<_Ids, _Tps>::_M_parse(), ...);
5734 template<typename _Out>
5736 _M_format(__maybe_const<_Tps, _CharT>&... __elems,
5737 basic_format_context<_Out, _CharT>& __fc,
5738 _String_view __sep) const
5740 (_Base<_Ids, _Tps>::_M_format(__elems, __fc, __sep), ...);
5746 (_Base<_Ids, _Tps>::set_debug_format(), ...);
5750 template<size_t... _Ids>
5752 _S_create_storage(index_sequence<_Ids...>)
5753 -> __formatters_storage<_Ids...>;
5755 = decltype(_S_create_storage(index_sequence_for<_Tps...>()));
5757 _Spec<_CharT> _M_spec{};
5758 _String_view _M_open = _Seps::_S_parens().substr(0, 1);
5759 _String_view _M_close = _Seps::_S_parens().substr(1, 1);
5760 _String_view _M_sep = _Seps::_S_comma();
5761 _Formatters _M_felems;
5764 template<typename _Tp>
5765 concept __is_map_formattable
5766 = __is_pair<_Tp> || (__is_tuple_v<_Tp> && tuple_size_v<_Tp> == 2);
5768}
// namespace __format
5771 // [
format.tuple]
Tuple formatter
5772 template<__format::__char _CharT, formattable<_CharT> _Fp,
5773 formattable<_CharT> _Sp>
5774 struct formatter<pair<_Fp, _Sp>, _CharT>
5775 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Fp>,
5776 remove_cvref_t<_Sp>>
5779 using __maybe_const_pair
5780 = __conditional_t<formattable<const _Fp, _CharT>
5781 && formattable<const _Sp, _CharT>,
5782 const pair<_Fp, _Sp>, pair<_Fp, _Sp>>;
5784 // We deviate from standard, that declares this as template accepting
5785 // unconstrained FormatContext type, which seems unimplementable.
5786 template<typename _Out>
5787 typename basic_format_context
<_Out, _CharT>::iterator
5788 format(__maybe_const_pair& __p,
5789 basic_format_context<_Out, _CharT>& __fc) const
5790 {
return this->_M_format_elems(__p.first, __p.second, __fc); }
5793 template<__format::__char _CharT, formattable<_CharT>... _Tps>
5794 struct formatter<tuple<_Tps...>, _CharT>
5795 : __format::__tuple_formatter<_CharT, remove_cvref_t<_Tps>...>
5798 using __maybe_const_tuple
5799 = __conditional_t<(formattable<const _Tps, _CharT> && ...),
5800 const tuple<_Tps...>, tuple<_Tps...>>;
5802 // We deviate from standard, that declares this as template accepting
5803 // unconstrained FormatContext type, which seems unimplementable.
5804 template<typename _Out>
5805 typename basic_format_context
<_Out, _CharT>::iterator
5806 format(__maybe_const_tuple& __t,
5807 basic_format_context<_Out, _CharT>& __fc) const
5808 {
return this->_M_format(__t, index_sequence_for<_Tps...>(), __fc); }
5811 // [
format.range.formatter]
, class template range_formatter
5812 template<typename _Tp, __format::__char _CharT>
5813 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
5814 class range_formatter
5816 using _String_view = basic_string_view<_CharT>;
5817 using _Seps = __format::_Separators<_CharT>;
5821 set_separator(basic_string_view<_CharT> __sep) noexcept
5825 set_brackets(basic_string_view<_CharT> __open,
5826 basic_string_view<_CharT> __close) noexcept
5832 constexpr formatter<_Tp, _CharT>&
5833 underlying() noexcept
5836 constexpr const formatter<_Tp, _CharT>&
5837 underlying() const noexcept
5840 // We deviate from standard, that declares this as template accepting
5841 // unconstrained ParseContext type, which seems unimplementable.
5842 constexpr typename basic_format_parse_context<_CharT>::iterator
5843 parse(basic_format_parse_context<_CharT>& __pc)
5845 auto __first = __pc.begin();
5846 const auto __last = __pc.end();
5847 __format::_Spec<_CharT> __spec{};
5848 bool __no_brace = false;
5850 auto __finished = [
&]
5851 {
return __first == __last || *__first == '}
'; };
5853 auto __finalize = [
&]
5859 auto __parse_val = [
&]
(_String_view __nfs = _String_view())
5861 basic_format_parse_context<_CharT> __npc(__nfs);
5862 if (_M_fval.parse(__npc) != __npc.end())
5863 __format::__failed_to_parse_format_spec();
5864 if constexpr (__format::__has_debug_format<formatter<_Tp, _CharT>>)
5865 _M_fval.set_debug_format();
5866 return __finalize();
5870 return __parse_val();
5872 __first = __spec._M_parse_fill_and_align(__first, __last, "{:");
5874 return __parse_val();
5876 __first = __spec._M_parse_width(__first, __last, __pc);
5878 return __parse_val();
5880 if (*__first == '?
')
5883 __spec._M_debug = true;
5884 if (__finished() || *__first != 's')
5885 __throw_format_error("format error: '?' is allowed only in"
5886 " combination with 's'");
5889 if (*__first == 's')
5892 if constexpr (same_as<_Tp, _CharT>)
5894 __spec._M_type = __format::_Pres_s;
5896 return __finalize();
5897 __throw_format_error("format error: element format specifier"
5898 " cannot be provided when 's' specifier is used");
5901 __throw_format_error("format error: 's' specifier requires"
5902 " range of character types");
5906 return __parse_val();
5908 if (*__first == 'n')
5911 _M_open = _M_close = _String_view();
5916 return __parse_val();
5918 if (*__first == 'm')
5920 _String_view __m(__first, 1);
5922 if constexpr (__format::__is_map_formattable<_Tp>)
5924 _M_sep = _Seps::_S_comma();
5927 _M_open = _Seps::_S_braces().substr(0, 1);
5928 _M_close = _Seps::_S_braces().substr(1, 1);
5931 return __parse_val(__m);
5932 __throw_format_error("format error: element format specifier"
5933 " cannot be provided when 'm' specifier is used");
5936 __throw_format_error("format error: 'm' specifier requires"
5937 " range of pairs or tuples of two elements");
5941 return __parse_val();
5943 if (*__first == ':')
5945 __pc.advance_to(++__first);
5946 __first = _M_fval.parse(__pc);
5950 return __finalize();
5952 __format::__failed_to_parse_format_spec();
5955 // We deviate from standard, that declares this as template accepting
5956 // unconstrained FormatContext type, which seems unimplementable.
5957 template<ranges::input_range _Rg, typename _Out>
5958 requires formattable<ranges::range_reference_t<_Rg>, _CharT> &&
5959 same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>, _Tp>
5960 typename basic_format_context
<_Out, _CharT>::iterator
5961 format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
5963 using _Range = remove_reference_t<_Rg>;
5964 if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
5965 return _M_format<const _Range>(__rg, __fc);
5967 return _M_format(__rg, __fc);
5971 template<ranges::input_range _Rg, typename _Out>
5972 typename basic_format_context
<_Out, _CharT>::iterator
5973 _M_format(_Rg& __rg, basic_format_context<_Out, _CharT>& __fc) const
5975 if constexpr (same_as<_Tp, _CharT>)
5976 if (_M_spec._M_type == __format::_Pres_s)
5978 __format::__formatter_str __fstr(_M_spec);
5979 return __fstr._M_format_range(__rg, __fc);
5981 return __format::__format_padded(
5983 [
this, &__rg]
(basic_format_context<_Out, _CharT>& __nfc)
5984 {
return _M_format_elems(__rg, __nfc); }
);
5988 template<ranges::input_range _Rg, typename _Out>
5989 typename basic_format_context
<_Out, _CharT>::iterator
5990 _M_format_elems(_Rg& __rg,
5991 basic_format_context<_Out, _CharT>& __fc) const
5993 auto __out = __format::__write(__fc.out(), _M_open);
5995 auto __first = ranges::begin(__rg);
5996 auto const __last = ranges::end(__rg);
5997 if (__first == __last)
5998 return __format::__write(__out, _M_close);
6000 __fc.advance_to(__out);
6001 __out = _M_fval.format(*__first, __fc);
6002 for (++__first;
__first != __last;
++__first)
6004 __out = __format::__write(__out, _M_sep);
6005 __fc.advance_to(__out);
6006 __out = _M_fval.format(*__first, __fc);
6009 return __format::__write(__out, _M_close);
6012 __format::_Spec<_CharT> _M_spec{};
6013 _String_view _M_open = _Seps::_S_squares().substr(0, 1);
6014 _String_view _M_close = _Seps::_S_squares().substr(1, 1);
6015 _String_view _M_sep = _Seps::_S_comma();
6016 formatter<_Tp, _CharT> _M_fval;
6019 // In standard this is shown as inheriting from specialization of
6020 // exposition only specialization for range-default-formatter for
6021 // each range_format. We opt for simpler implementation.
6022 // [
format.range.fmtmap]
, [
format.range.fmtset]
, [
format.range.fmtstr]
,
6023 // specializations for maps, sets, and strings
6024 template<ranges::input_range _Rg, __format::__char _CharT>
6025 requires (format_kind<_Rg> != range_format::disabled)
6026 && formattable<ranges::range_reference_t<_Rg>, _CharT>
6027 struct formatter<_Rg, _CharT>
6030 static const bool _S_range_format_is_string =
6031 (format_kind<_Rg> == range_format::string)
6032 || (format_kind<_Rg> == range_format::debug_string);
6033 using _Vt = remove_cvref_t<
6034 ranges::range_reference_t<
6035 __format::__maybe_const_range<_Rg, _CharT>>>;
6037 static consteval bool _S_is_correct()
6039 if constexpr (_S_range_format_is_string)
6040 static_assert(same_as<_Vt, _CharT>);
6044 static_assert(_S_is_correct());
6047 constexpr formatter() noexcept
6049 using _Seps = __format::_Separators<_CharT>;
6050 if constexpr (format_kind<_Rg> == range_format::map)
6052 static_assert(__format::__is_map_formattable<_Vt>);
6053 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6054 _Seps::_S_braces().substr(1, 1));
6055 _M_under.underlying().set_brackets({}
, {}
);
6056 _M_under.underlying().set_separator(_Seps::_S_colon());
6058 else if constexpr (format_kind<_Rg> == range_format::set)
6059 _M_under.set_brackets(_Seps::_S_braces().substr(0, 1),
6060 _Seps::_S_braces().substr(1, 1));
6064 set_separator(basic_string_view<_CharT> __sep) noexcept
6065 requires (format_kind<_Rg> == range_format::sequence)
6066 {
_M_under.set_separator(__sep); }
6069 set_brackets(basic_string_view<_CharT> __open,
6070 basic_string_view<_CharT> __close) noexcept
6071 requires (format_kind<_Rg> == range_format::sequence)
6072 {
_M_under.set_brackets(__open, __close); }
6074 // We deviate from standard, that declares this as template accepting
6075 // unconstrained ParseContext type, which seems unimplementable.
6076 constexpr typename basic_format_parse_context<_CharT>::iterator
6077 parse(basic_format_parse_context<_CharT>& __pc)
6079 auto __res = _M_under.parse(__pc);
6080 if constexpr (format_kind<_Rg> == range_format::debug_string)
6081 _M_under.set_debug_format();
6085 // We deviate from standard, that declares this as template accepting
6086 // unconstrained FormatContext type, which seems unimplementable.
6087 template<typename _Out>
6088 typename basic_format_context
<_Out, _CharT>::iterator
6089 format(__format::__maybe_const_range<_Rg, _CharT>& __rg,
6090 basic_format_context<_Out, _CharT>& __fc) const
6092 if constexpr (_S_range_format_is_string)
6093 return _M_under._M_format_range(__rg, __fc);
6095 return _M_under.format(__rg, __fc);
6099 using _Formatter_under
6100 = __conditional_t<_S_range_format_is_string,
6101 __format::__formatter_str<_CharT>,
6102 range_formatter<_Vt, _CharT>>;
6103 _Formatter_under _M_under;
6105#endif // C++23 formatting ranges
6106#undef _GLIBCXX_WIDEN
6108_GLIBCXX_END_NAMESPACE_VERSION
6110#endif // __cpp_lib_format
6111#pragma GCC diagnostic pop
6112#endif // _GLIBCXX_FORMAT