1 // Formatting library for C++ - experimental range support
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 //
8 // Copyright (c) 2018 - present, Remotion (Igor Schulz)
9 // All Rights Reserved
10 // {fmt} support for ranges, containers and types tuple interface.
11
12 #ifndef FMT_RANGES_H_
13 #define FMT_RANGES_H_
14
15 #include <initializer_list>
16 #include <type_traits>
17
18 #include "format.h"
19
20 // output only up to N items from the range.
21 #ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT
22 # define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256
23 #endif
24
25 FMT_BEGIN_NAMESPACE
26
27 template <typename Char> struct formatting_base {
28 template <typename ParseContext>
29 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
30 return ctx.begin();
31 }
32 };
33
34 template <typename Char, typename Enable = void>
35 struct formatting_range : formatting_base<Char> {
36 static FMT_CONSTEXPR_DECL const std::size_t range_length_limit =
37 FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the
38 // range.
39 Char prefix;
40 Char delimiter;
41 Char postfix;
formatting_rangeformatting_range42 formatting_range() : prefix('{'), delimiter(','), postfix('}') {}
43 static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
44 static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
45 };
46
47 template <typename Char, typename Enable = void>
48 struct formatting_tuple : formatting_base<Char> {
49 Char prefix;
50 Char delimiter;
51 Char postfix;
formatting_tupleformatting_tuple52 formatting_tuple() : prefix('('), delimiter(','), postfix(')') {}
53 static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
54 static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
55 };
56
57 namespace internal {
58
59 template <typename RangeT, typename OutputIterator>
copy(const RangeT & range,OutputIterator out)60 OutputIterator copy(const RangeT& range, OutputIterator out) {
61 for (auto it = range.begin(), end = range.end(); it != end; ++it)
62 *out++ = *it;
63 return out;
64 }
65
66 template <typename OutputIterator>
copy(const char * str,OutputIterator out)67 OutputIterator copy(const char* str, OutputIterator out) {
68 while (*str) *out++ = *str++;
69 return out;
70 }
71
72 template <typename OutputIterator>
copy(char ch,OutputIterator out)73 OutputIterator copy(char ch, OutputIterator out) {
74 *out++ = ch;
75 return out;
76 }
77
78 /// Return true value if T has std::string interface, like std::string_view.
79 template <typename T> class is_like_std_string {
80 template <typename U>
81 static auto check(U* p)
82 -> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
83 template <typename> static void check(...);
84
85 public:
86 static FMT_CONSTEXPR_DECL const bool value =
87 is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
88 };
89
90 template <typename Char>
91 struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {};
92
93 template <typename... Ts> struct conditional_helper {};
94
95 template <typename T, typename _ = void> struct is_range_ : std::false_type {};
96
97 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
98 template <typename T>
99 struct is_range_<
100 T, conditional_t<false,
101 conditional_helper<decltype(std::declval<T>().begin()),
102 decltype(std::declval<T>().end())>,
103 void>> : std::true_type {};
104 #endif
105
106 /// tuple_size and tuple_element check.
107 template <typename T> class is_tuple_like_ {
108 template <typename U>
109 static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
110 template <typename> static void check(...);
111
112 public:
113 static FMT_CONSTEXPR_DECL const bool value =
114 !std::is_void<decltype(check<T>(nullptr))>::value;
115 };
116
117 // Check for integer_sequence
118 #if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
119 template <typename T, T... N>
120 using integer_sequence = std::integer_sequence<T, N...>;
121 template <std::size_t... N> using index_sequence = std::index_sequence<N...>;
122 template <std::size_t N>
123 using make_index_sequence = std::make_index_sequence<N>;
124 #else
125 template <typename T, T... N> struct integer_sequence {
126 using value_type = T;
127
128 static FMT_CONSTEXPR std::size_t size() { return sizeof...(N); }
129 };
130
131 template <std::size_t... N>
132 using index_sequence = integer_sequence<std::size_t, N...>;
133
134 template <typename T, std::size_t N, T... Ns>
135 struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
136 template <typename T, T... Ns>
137 struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
138
139 template <std::size_t N>
140 using make_index_sequence = make_integer_sequence<std::size_t, N>;
141 #endif
142
143 template <class Tuple, class F, size_t... Is>
144 void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
145 using std::get;
146 // using free function get<I>(T) now.
147 const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
148 (void)_; // blocks warnings
149 }
150
151 template <class T>
152 FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
153 T const&) {
154 return {};
155 }
156
157 template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
158 const auto indexes = get_indexes(tup);
159 for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
160 }
161
162 template <typename Arg, FMT_ENABLE_IF(!is_like_std_string<
163 typename std::decay<Arg>::type>::value)>
164 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
165 return add_space ? " {}" : "{}";
166 }
167
168 template <typename Arg, FMT_ENABLE_IF(is_like_std_string<
169 typename std::decay<Arg>::type>::value)>
170 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
171 return add_space ? " \"{}\"" : "\"{}\"";
172 }
173
174 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) {
175 return add_space ? " \"{}\"" : "\"{}\"";
176 }
177 FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) {
178 return add_space ? L" \"{}\"" : L"\"{}\"";
179 }
180
181 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) {
182 return add_space ? " '{}'" : "'{}'";
183 }
184 FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
185 return add_space ? L" '{}'" : L"'{}'";
186 }
187
188 } // namespace internal
189
190 template <typename T> struct is_tuple_like {
191 static FMT_CONSTEXPR_DECL const bool value =
192 internal::is_tuple_like_<T>::value && !internal::is_range_<T>::value;
193 };
194
195 template <typename TupleT, typename Char>
196 struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
197 private:
198 // C++11 generic lambda for format()
199 template <typename FormatContext> struct format_each {
200 template <typename T> void operator()(const T& v) {
201 if (i > 0) {
202 if (formatting.add_prepostfix_space) {
203 *out++ = ' ';
204 }
205 out = internal::copy(formatting.delimiter, out);
206 }
207 out = format_to(out,
208 internal::format_str_quoted(
209 (formatting.add_delimiter_spaces && i > 0), v),
210 v);
211 ++i;
212 }
213
214 formatting_tuple<Char>& formatting;
215 std::size_t& i;
216 typename std::add_lvalue_reference<decltype(
217 std::declval<FormatContext>().out())>::type out;
218 };
219
220 public:
221 formatting_tuple<Char> formatting;
222
223 template <typename ParseContext>
224 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
225 return formatting.parse(ctx);
226 }
227
228 template <typename FormatContext = format_context>
229 auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
230 auto out = ctx.out();
231 std::size_t i = 0;
232 internal::copy(formatting.prefix, out);
233
234 internal::for_each(values, format_each<FormatContext>{formatting, i, out});
235 if (formatting.add_prepostfix_space) {
236 *out++ = ' ';
237 }
238 internal::copy(formatting.postfix, out);
239
240 return ctx.out();
241 }
242 };
243
244 template <typename T, typename Char> struct is_range {
245 static FMT_CONSTEXPR_DECL const bool value =
246 internal::is_range_<T>::value &&
247 !internal::is_like_std_string<T>::value &&
248 !std::is_convertible<T, std::basic_string<Char>>::value &&
249 !std::is_constructible<internal::std_string_view<Char>, T>::value;
250 };
251
252 template <typename RangeT, typename Char>
253 struct formatter<RangeT, Char,
254 enable_if_t<fmt::is_range<RangeT, Char>::value>> {
255 formatting_range<Char> formatting;
256
257 template <typename ParseContext>
258 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
259 return formatting.parse(ctx);
260 }
261
262 template <typename FormatContext>
263 typename FormatContext::iterator format(const RangeT& values,
264 FormatContext& ctx) {
265 auto out = internal::copy(formatting.prefix, ctx.out());
266 std::size_t i = 0;
267 for (auto it = values.begin(), end = values.end(); it != end; ++it) {
268 if (i > 0) {
269 if (formatting.add_prepostfix_space) *out++ = ' ';
270 out = internal::copy(formatting.delimiter, out);
271 }
272 out = format_to(out,
273 internal::format_str_quoted(
274 (formatting.add_delimiter_spaces && i > 0), *it),
275 *it);
276 if (++i > formatting.range_length_limit) {
277 out = format_to(out, " ... <other elements>");
278 break;
279 }
280 }
281 if (formatting.add_prepostfix_space) *out++ = ' ';
282 return internal::copy(formatting.postfix, out);
283 }
284 };
285
286 template <typename Char, typename... T> struct tuple_arg_join : internal::view {
287 const std::tuple<T...>& tuple;
288 basic_string_view<Char> sep;
289
290 tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s)
291 : tuple{t}, sep{s} {}
292 };
293
294 template <typename Char, typename... T>
295 struct formatter<tuple_arg_join<Char, T...>, Char> {
296 template <typename ParseContext>
297 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
298 return ctx.begin();
299 }
300
301 template <typename FormatContext>
302 typename FormatContext::iterator format(
303 const tuple_arg_join<Char, T...>& value, FormatContext& ctx) {
304 return format(value, ctx, internal::make_index_sequence<sizeof...(T)>{});
305 }
306
307 private:
308 template <typename FormatContext, size_t... N>
309 typename FormatContext::iterator format(
310 const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
311 internal::index_sequence<N...>) {
312 return format_args(value, ctx, std::get<N>(value.tuple)...);
313 }
314
315 template <typename FormatContext>
316 typename FormatContext::iterator format_args(
317 const tuple_arg_join<Char, T...>&, FormatContext& ctx) {
318 // NOTE: for compilers that support C++17, this empty function instantiation
319 // can be replaced with a constexpr branch in the variadic overload.
320 return ctx.out();
321 }
322
323 template <typename FormatContext, typename Arg, typename... Args>
324 typename FormatContext::iterator format_args(
325 const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
326 const Arg& arg, const Args&... args) {
327 using base = formatter<typename std::decay<Arg>::type, Char>;
328 auto out = ctx.out();
329 out = base{}.format(arg, ctx);
330 if (sizeof...(Args) > 0) {
331 out = std::copy(value.sep.begin(), value.sep.end(), out);
332 ctx.advance_to(out);
333 return format_args(value, ctx, args...);
334 }
335 return out;
336 }
337 };
338
339 /**
340 \rst
341 Returns an object that formats `tuple` with elements separated by `sep`.
342
343 **Example**::
344
345 std::tuple<int, char> t = {1, 'a'};
346 fmt::print("{}", fmt::join(t, ", "));
347 // Output: "1, a"
348 \endrst
349 */
350 template <typename... T>
351 FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple,
352 string_view sep) {
353 return {tuple, sep};
354 }
355
356 template <typename... T>
357 FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple,
358 wstring_view sep) {
359 return {tuple, sep};
360 }
361
362 /**
363 \rst
364 Returns an object that formats `initializer_list` with elements separated by
365 `sep`.
366
367 **Example**::
368
369 fmt::print("{}", fmt::join({1, 2, 3}, ", "));
370 // Output: "1, 2, 3"
371 \endrst
372 */
373 template <typename T>
374 arg_join<internal::iterator_t<const std::initializer_list<T>>, char> join(
375 std::initializer_list<T> list, string_view sep) {
376 return join(std::begin(list), std::end(list), sep);
377 }
378
379 template <typename T>
380 arg_join<internal::iterator_t<const std::initializer_list<T>>, wchar_t> join(
381 std::initializer_list<T> list, wstring_view sep) {
382 return join(std::begin(list), std::end(list), sep);
383 }
384
385 FMT_END_NAMESPACE
386
387 #endif // FMT_RANGES_H_
388