1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___FORMAT_FORMATTER_TUPLE_H
11#define _LIBCPP___FORMAT_FORMATTER_TUPLE_H
12
13#include <__algorithm/ranges_copy.h>
14#include <__chrono/statically_widen.h>
15#include <__config>
16#include <__format/buffer.h>
17#include <__format/fmt_char_type.h>
18#include <__format/format_context.h>
19#include <__format/format_error.h>
20#include <__format/format_parse_context.h>
21#include <__format/formattable.h>
22#include <__format/formatter.h>
23#include <__format/formatter_output.h>
24#include <__format/parser_std_format_spec.h>
25#include <__type_traits/remove_cvref.h>
26#include <__utility/integer_sequence.h>
27#include <__utility/pair.h>
28#include <string_view>
29#include <tuple>
30
31#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
32# pragma GCC system_header
33#endif
34
35#if _LIBCPP_STD_VER >= 23
36
37_LIBCPP_BEGIN_NAMESPACE_STD
38
39template <__fmt_char_type _CharT, class _Tuple, formattable<_CharT>... _Args>
40struct __formatter_tuple {
41 constexpr void set_separator(basic_string_view<_CharT> __separator) noexcept { __separator_ = __separator; }
42 constexpr void
43 set_brackets(basic_string_view<_CharT> __opening_bracket, basic_string_view<_CharT> __closing_bracket) noexcept {
44 __opening_bracket_ = __opening_bracket;
45 __closing_bracket_ = __closing_bracket;
46 }
47
48 template <class _ParseContext>
49 constexpr typename _ParseContext::iterator parse(_ParseContext& __ctx) {
50 auto __begin = __parser_.__parse(__ctx, __format_spec::__fields_tuple);
51
52 auto __end = __ctx.end();
53 // Note 'n' is part of the type here
54 if (__parser_.__clear_brackets_)
55 set_brackets(opening_bracket: {}, closing_bracket: {});
56 else if (__begin != __end && *__begin == _CharT('m')) {
57 if constexpr (sizeof...(_Args) == 2) {
58 set_separator(_LIBCPP_STATICALLY_WIDEN(_CharT, ": "));
59 set_brackets(opening_bracket: {}, closing_bracket: {});
60 ++__begin;
61 } else
62 std::__throw_format_error(s: "Type m requires a pair or a tuple with two elements");
63 }
64
65 if (__begin != __end && *__begin != _CharT('}'))
66 std::__throw_format_error(s: "The format specifier should consume the input or end with a '}'");
67
68 __ctx.advance_to(__begin);
69
70 // [format.tuple]/7
71 // ... For each element e in underlying_, if e.set_debug_format()
72 // is a valid expression, calls e.set_debug_format().
73 std::__for_each_index_sequence(make_index_sequence<sizeof...(_Args)>(), [&]<size_t _Index> {
74 auto& __formatter = std::get<_Index>(__underlying_);
75 __formatter.parse(__ctx);
76 // Unlike the range_formatter we don't guard against evil parsers. Since
77 // this format-spec never has a format-spec for the underlying type
78 // adding the test would give additional overhead.
79 std::__set_debug_format(__formatter);
80 });
81
82 return __begin;
83 }
84
85 template <class _FormatContext>
86 typename _FormatContext::iterator
87 format(conditional_t<(formattable<const _Args, _CharT> && ...), const _Tuple&, _Tuple&> __tuple,
88 _FormatContext& __ctx) const {
89 __format_spec::__parsed_specifications<_CharT> __specs = __parser_.__get_parsed_std_specifications(__ctx);
90
91 if (!__specs.__has_width())
92 return __format_tuple(__tuple, __ctx);
93
94 // The size of the buffer needed is:
95 // - open bracket characters
96 // - close bracket character
97 // - n elements where every element may have a different size
98 // - (n -1) separators
99 // The size of the element is hard to predict, knowing the type helps but
100 // it depends on the format-spec. As an initial estimate we guess 6
101 // characters.
102 // Typically both brackets are 1 character and the separator is 2
103 // characters. Which means there will be
104 // (n - 1) * 2 + 1 + 1 = n * 2 character
105 // So estimate 8 times the range size as buffer.
106 __format::__retarget_buffer<_CharT> __buffer{8 * tuple_size_v<_Tuple>};
107 basic_format_context<typename __format::__retarget_buffer<_CharT>::__iterator, _CharT> __c{
108 __buffer.__make_output_iterator(), __ctx};
109
110 __format_tuple(__tuple, __c);
111
112 return __formatter::__write_string_no_precision(basic_string_view{__buffer.__view()}, __ctx.out(), __specs);
113 }
114
115 template <class _FormatContext>
116 typename _FormatContext::iterator __format_tuple(auto&& __tuple, _FormatContext& __ctx) const {
117 __ctx.advance_to(std::ranges::copy(__opening_bracket_, __ctx.out()).out);
118
119 std::__for_each_index_sequence(make_index_sequence<sizeof...(_Args)>(), [&]<size_t _Index> {
120 if constexpr (_Index)
121 __ctx.advance_to(std::ranges::copy(__separator_, __ctx.out()).out);
122 __ctx.advance_to(std::get<_Index>(__underlying_).format(std::get<_Index>(__tuple), __ctx));
123 });
124
125 return std::ranges::copy(__closing_bracket_, __ctx.out()).out;
126 }
127
128 __format_spec::__parser<_CharT> __parser_ = {
129 __format_spec::__parser_data<_CharT>{.__alignment_ = __format_spec::__alignment::__left}};
130
131private:
132 tuple<formatter<remove_cvref_t<_Args>, _CharT>...> __underlying_;
133 basic_string_view<_CharT> __separator_ = _LIBCPP_STATICALLY_WIDEN(_CharT, ", ");
134 basic_string_view<_CharT> __opening_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "(");
135 basic_string_view<_CharT> __closing_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, ")");
136};
137
138template <__fmt_char_type _CharT, formattable<_CharT>... _Args>
139struct formatter<pair<_Args...>, _CharT> : public __formatter_tuple<_CharT, pair<_Args...>, _Args...> {};
140
141template <__fmt_char_type _CharT, formattable<_CharT>... _Args>
142struct formatter<tuple<_Args...>, _CharT> : public __formatter_tuple<_CharT, tuple<_Args...>, _Args...> {};
143
144_LIBCPP_END_NAMESPACE_STD
145
146#endif // _LIBCPP_STD_VER >= 23
147
148#endif // _LIBCPP___FORMAT_FORMATTER_TUPLE_H
149