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 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 detail {
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 <size_t... N> using index_sequence = std::index_sequence<N...>;
122 template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
123 #else
124 template <typename T, T... N> struct integer_sequence {
125   using value_type = T;
126 
127   static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
128 };
129 
130 template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
131 
132 template <typename T, size_t N, T... Ns>
133 struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
134 template <typename T, T... Ns>
135 struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
136 
137 template <size_t N>
138 using make_index_sequence = make_integer_sequence<size_t, N>;
139 #endif
140 
141 template <class Tuple, class F, size_t... Is>
142 void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
143   using std::get;
144   // using free function get<I>(T) now.
145   const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
146   (void)_;  // blocks warnings
147 }
148 
149 template <class T>
150 FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
151     T const&) {
152   return {};
153 }
154 
155 template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
156   const auto indexes = get_indexes(tup);
157   for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
158 }
159 
160 template <typename Range>
161 using value_type = remove_cvref_t<decltype(*std::declval<Range>().begin())>;
162 
163 template <typename Arg, FMT_ENABLE_IF(!is_like_std_string<
164                                       typename std::decay<Arg>::type>::value)>
165 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
166   return add_space ? " {}" : "{}";
167 }
168 
169 template <typename Arg, FMT_ENABLE_IF(is_like_std_string<
170                                       typename std::decay<Arg>::type>::value)>
171 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
172   return add_space ? " \"{}\"" : "\"{}\"";
173 }
174 
175 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) {
176   return add_space ? " \"{}\"" : "\"{}\"";
177 }
178 FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) {
179   return add_space ? L" \"{}\"" : L"\"{}\"";
180 }
181 
182 FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) {
183   return add_space ? " '{}'" : "'{}'";
184 }
185 FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
186   return add_space ? L" '{}'" : L"'{}'";
187 }
188 }  // namespace detail
189 
190 template <typename T> struct is_tuple_like {
191   static FMT_CONSTEXPR_DECL const bool value =
192       detail::is_tuple_like_<T>::value && !detail::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 = detail::copy(formatting.delimiter, out);
206       }
207       out = format_to(out,
208                       detail::format_str_quoted(
209                           (formatting.add_delimiter_spaces && i > 0), v),
210                       v);
211       ++i;
212     }
213 
214     formatting_tuple<Char>& formatting;
215     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     size_t i = 0;
232     detail::copy(formatting.prefix, out);
233 
234     detail::for_each(values, format_each<FormatContext>{formatting, i, out});
235     if (formatting.add_prepostfix_space) {
236       *out++ = ' ';
237     }
238     detail::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       detail::is_range_<T>::value && !detail::is_like_std_string<T>::value &&
247       !std::is_convertible<T, std::basic_string<Char>>::value &&
248       !std::is_constructible<detail::std_string_view<Char>, T>::value;
249 };
250 
251 template <typename T, typename Char>
252 struct formatter<
253     T, Char,
254     enable_if_t<fmt::is_range<T, Char>::value
255 // Workaround a bug in MSVC 2017 and earlier.
256 #if !FMT_MSC_VER || FMT_MSC_VER >= 1927
257                 &&
258                 (has_formatter<detail::value_type<T>, format_context>::value ||
259                  detail::has_fallback_formatter<detail::value_type<T>,
260                                                 format_context>::value)
261 #endif
262                 >> {
263   formatting_range<Char> formatting;
264 
265   template <typename ParseContext>
266   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
267     return formatting.parse(ctx);
268   }
269 
270   template <typename FormatContext>
271   typename FormatContext::iterator format(const T& values, FormatContext& ctx) {
272     auto out = detail::copy(formatting.prefix, ctx.out());
273     size_t i = 0;
274     auto it = values.begin();
275     auto end = values.end();
276     for (; it != end; ++it) {
277       if (i > 0) {
278         if (formatting.add_prepostfix_space) *out++ = ' ';
279         out = detail::copy(formatting.delimiter, out);
280       }
281       out = format_to(out,
282                       detail::format_str_quoted(
283                           (formatting.add_delimiter_spaces && i > 0), *it),
284                       *it);
285       if (++i > formatting.range_length_limit) {
286         out = format_to(out, " ... <other elements>");
287         break;
288       }
289     }
290     if (formatting.add_prepostfix_space) *out++ = ' ';
291     return detail::copy(formatting.postfix, out);
292   }
293 };
294 
295 template <typename Char, typename... T> struct tuple_arg_join : detail::view {
296   const std::tuple<T...>& tuple;
297   basic_string_view<Char> sep;
298 
299   tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s)
300       : tuple{t}, sep{s} {}
301 };
302 
303 template <typename Char, typename... T>
304 struct formatter<tuple_arg_join<Char, T...>, Char> {
305   template <typename ParseContext>
306   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
307     return ctx.begin();
308   }
309 
310   template <typename FormatContext>
311   typename FormatContext::iterator format(
312       const tuple_arg_join<Char, T...>& value, FormatContext& ctx) {
313     return format(value, ctx, detail::make_index_sequence<sizeof...(T)>{});
314   }
315 
316  private:
317   template <typename FormatContext, size_t... N>
318   typename FormatContext::iterator format(
319       const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
320       detail::index_sequence<N...>) {
321     return format_args(value, ctx, std::get<N>(value.tuple)...);
322   }
323 
324   template <typename FormatContext>
325   typename FormatContext::iterator format_args(
326       const tuple_arg_join<Char, T...>&, FormatContext& ctx) {
327     // NOTE: for compilers that support C++17, this empty function instantiation
328     // can be replaced with a constexpr branch in the variadic overload.
329     return ctx.out();
330   }
331 
332   template <typename FormatContext, typename Arg, typename... Args>
333   typename FormatContext::iterator format_args(
334       const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
335       const Arg& arg, const Args&... args) {
336     using base = formatter<typename std::decay<Arg>::type, Char>;
337     auto out = ctx.out();
338     out = base{}.format(arg, ctx);
339     if (sizeof...(Args) > 0) {
340       out = std::copy(value.sep.begin(), value.sep.end(), out);
341       ctx.advance_to(out);
342       return format_args(value, ctx, args...);
343     }
344     return out;
345   }
346 };
347 
348 /**
349   \rst
350   Returns an object that formats `tuple` with elements separated by `sep`.
351 
352   **Example**::
353 
354     std::tuple<int, char> t = {1, 'a'};
355     fmt::print("{}", fmt::join(t, ", "));
356     // Output: "1, a"
357   \endrst
358  */
359 template <typename... T>
360 FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple,
361                                               string_view sep) {
362   return {tuple, sep};
363 }
364 
365 template <typename... T>
366 FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple,
367                                                  wstring_view sep) {
368   return {tuple, sep};
369 }
370 
371 /**
372   \rst
373   Returns an object that formats `initializer_list` with elements separated by
374   `sep`.
375 
376   **Example**::
377 
378     fmt::print("{}", fmt::join({1, 2, 3}, ", "));
379     // Output: "1, 2, 3"
380   \endrst
381  */
382 template <typename T>
383 arg_join<const T*, const T*, char> join(std::initializer_list<T> list,
384                                         string_view sep) {
385   return join(std::begin(list), std::end(list), sep);
386 }
387 
388 template <typename T>
389 arg_join<const T*, const T*, wchar_t> join(std::initializer_list<T> list,
390                                            wstring_view sep) {
391   return join(std::begin(list), std::end(list), sep);
392 }
393 
394 FMT_END_NAMESPACE
395 
396 #endif  // FMT_RANGES_H_
397