xref: /aosp_15_r20/external/fmtlib/test/ranges-test.cc (revision 5c90c05cd622c0a81b57953a4d343e0e489f2e08)
1 // Formatting library for C++ - ranges tests
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 
8 #include "fmt/ranges.h"
9 
10 #include <array>
11 #include <list>
12 #include <map>
13 #include <numeric>
14 #include <queue>
15 #include <stack>
16 #include <string>
17 #include <utility>
18 #include <vector>
19 
20 #if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<ranges>)
21 #  include <ranges>
22 #endif
23 
24 #include "fmt/format.h"
25 #include "gtest/gtest.h"
26 
27 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 601
28 #  define FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
29 #endif
30 
31 #if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1910
32 #  define FMT_RANGES_TEST_ENABLE_JOIN
33 #  define FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
34 #endif
35 
36 #ifdef FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
TEST(ranges_test,format_array)37 TEST(ranges_test, format_array) {
38   int arr[] = {1, 2, 3, 5, 7, 11};
39   EXPECT_EQ(fmt::format("{}", arr), "[1, 2, 3, 5, 7, 11]");
40 }
41 
TEST(ranges_test,format_2d_array)42 TEST(ranges_test, format_2d_array) {
43   int arr[][2] = {{1, 2}, {3, 5}, {7, 11}};
44   EXPECT_EQ(fmt::format("{}", arr), "[[1, 2], [3, 5], [7, 11]]");
45 }
46 
TEST(ranges_test,format_array_of_literals)47 TEST(ranges_test, format_array_of_literals) {
48   const char* arr[] = {"1234", "abcd"};
49   EXPECT_EQ(fmt::format("{}", arr), "[\"1234\", \"abcd\"]");
50   EXPECT_EQ(fmt::format("{:n}", arr), "\"1234\", \"abcd\"");
51   EXPECT_EQ(fmt::format("{:n:}", arr), "1234, abcd");
52 }
53 #endif  // FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
54 
TEST(ranges_test,format_vector)55 TEST(ranges_test, format_vector) {
56   auto v = std::vector<int>{1, 2, 3, 5, 7, 11};
57   EXPECT_EQ(fmt::format("{}", v), "[1, 2, 3, 5, 7, 11]");
58   EXPECT_EQ(fmt::format("{::#x}", v), "[0x1, 0x2, 0x3, 0x5, 0x7, 0xb]");
59   EXPECT_EQ(fmt::format("{:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb");
60 
61   auto vc = std::vector<char>{'a', 'b', 'c'};
62   auto vec = std::vector<char>{'a', '\n', '\t'};
63   auto vvc = std::vector<std::vector<char>>{vc, vc};
64   EXPECT_EQ(fmt::format("{}", vc), "['a', 'b', 'c']");
65   EXPECT_EQ(fmt::format("{:s}", vc), "\"abc\"");
66   EXPECT_EQ(fmt::format("{:?s}", vec), "\"a\\n\\t\"");
67   EXPECT_EQ(fmt::format("{:s}", vec), "\"a\n\t\"");
68   EXPECT_EQ(fmt::format("{::s}", vvc), "[\"abc\", \"abc\"]");
69   EXPECT_EQ(fmt::format("{}", vvc), "[['a', 'b', 'c'], ['a', 'b', 'c']]");
70   EXPECT_EQ(fmt::format("{:n}", vvc), "['a', 'b', 'c'], ['a', 'b', 'c']");
71   EXPECT_EQ(fmt::format("{:n:n}", vvc), "'a', 'b', 'c', 'a', 'b', 'c'");
72   EXPECT_EQ(fmt::format("{:n:n:}", vvc), "a, b, c, a, b, c");
73 }
74 
TEST(ranges_test,format_nested_vector)75 TEST(ranges_test, format_nested_vector) {
76   auto v = std::vector<std::vector<int>>{{1, 2}, {3, 5}, {7, 11}};
77   EXPECT_EQ(fmt::format("{}", v), "[[1, 2], [3, 5], [7, 11]]");
78   EXPECT_EQ(fmt::format("{:::#x}", v), "[[0x1, 0x2], [0x3, 0x5], [0x7, 0xb]]");
79   EXPECT_EQ(fmt::format("{:n:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb");
80 }
81 
TEST(ranges_test,to_string_vector)82 TEST(ranges_test, to_string_vector) {
83   auto v = std::vector<std::string>{"a", "b", "c"};
84   EXPECT_EQ(fmt::to_string(v), "[\"a\", \"b\", \"c\"]");
85 }
86 
TEST(ranges_test,format_map)87 TEST(ranges_test, format_map) {
88   auto m = std::map<std::string, int>{{"one", 1}, {"two", 2}};
89   EXPECT_EQ(fmt::format("{}", m), "{\"one\": 1, \"two\": 2}");
90   EXPECT_EQ(fmt::format("{:n}", m), "\"one\": 1, \"two\": 2");
91 }
92 
93 struct test_map_value {};
94 
95 FMT_BEGIN_NAMESPACE
96 template <> struct formatter<test_map_value> : formatter<string_view> {
formatformatter97   auto format(test_map_value, format_context& ctx) const
98       -> format_context::iterator {
99     return formatter<string_view>::format("foo", ctx);
100   }
101 };
102 
103 template <typename K>
104 struct formatter<std::pair<K, test_map_value>> : formatter<string_view> {
formatformatter105   auto format(std::pair<K, test_map_value>, format_context& ctx) const
106       -> format_context::iterator {
107     return ctx.out();
108   }
109 };
110 
111 template <typename K>
112 struct is_tuple_formattable<std::pair<K, test_map_value>, char>
113     : std::false_type {};
114 
115 FMT_END_NAMESPACE
116 
TEST(ranges_test,format_map_custom_pair)117 TEST(ranges_test, format_map_custom_pair) {
118   EXPECT_EQ(fmt::format("{}", std::map<int, test_map_value>{{42, {}}}),
119             "{42: \"foo\"}");
120 }
121 
TEST(ranges_test,format_set)122 TEST(ranges_test, format_set) {
123   EXPECT_EQ(fmt::format("{}", std::set<std::string>{"one", "two"}),
124             "{\"one\", \"two\"}");
125 }
126 
127 // Models std::flat_set close enough to test if no ambiguous lookup of a
128 // formatter happens due to the flat_set type matching is_set and
129 // is_container_adaptor_like.
130 template <typename T> class flat_set {
131  public:
132   using key_type = T;
133   using container_type = std::vector<T>;
134 
135   using iterator = typename std::vector<T>::iterator;
136   using const_iterator = typename std::vector<T>::const_iterator;
137 
138   template <typename... Ts>
flat_set(Ts &&...args)139   explicit flat_set(Ts&&... args) : c{std::forward<Ts>(args)...} {}
140 
begin()141   auto begin() -> iterator { return c.begin(); }
end()142   auto end() -> iterator { return c.end(); }
143 
begin() const144   auto begin() const -> const_iterator { return c.begin(); }
end() const145   auto end() const -> const_iterator { return c.end(); }
146 
147  private:
148   std::vector<T> c;
149 };
150 
TEST(ranges_test,format_flat_set)151 TEST(ranges_test, format_flat_set) {
152   EXPECT_EQ(fmt::format("{}", flat_set<std::string>{"one", "two"}),
153             "{\"one\", \"two\"}");
154 }
155 
156 namespace adl {
157 struct box {
158   int value;
159 };
160 
begin(const box & b)161 auto begin(const box& b) -> const int* { return &b.value; }
end(const box & b)162 auto end(const box& b) -> const int* { return &b.value + 1; }
163 }  // namespace adl
164 
TEST(ranges_test,format_adl_begin_end)165 TEST(ranges_test, format_adl_begin_end) {
166   auto b = adl::box{42};
167   EXPECT_EQ(fmt::format("{}", b), "[42]");
168 }
169 
TEST(ranges_test,format_pair)170 TEST(ranges_test, format_pair) {
171   auto p = std::pair<int, float>(42, 1.5f);
172   EXPECT_EQ(fmt::format("{}", p), "(42, 1.5)");
173   EXPECT_EQ(fmt::format("{:}", p), "(42, 1.5)");
174   EXPECT_EQ(fmt::format("{:n}", p), "421.5");
175 }
176 
177 struct unformattable {};
178 
TEST(ranges_test,format_tuple)179 TEST(ranges_test, format_tuple) {
180   auto t =
181       std::tuple<int, float, std::string, char>(42, 1.5f, "this is tuple", 'i');
182   EXPECT_EQ(fmt::format("{}", t), "(42, 1.5, \"this is tuple\", 'i')");
183   EXPECT_EQ(fmt::format("{:n}", t), "421.5\"this is tuple\"'i'");
184 
185   EXPECT_EQ(fmt::format("{}", std::tuple<>()), "()");
186 
187   EXPECT_TRUE((fmt::is_formattable<std::tuple<>>::value));
188   EXPECT_FALSE((fmt::is_formattable<unformattable>::value));
189   EXPECT_FALSE((fmt::is_formattable<std::tuple<unformattable>>::value));
190   EXPECT_FALSE((fmt::is_formattable<std::tuple<unformattable, int>>::value));
191   EXPECT_FALSE((fmt::is_formattable<std::tuple<int, unformattable>>::value));
192   EXPECT_FALSE(
193       (fmt::is_formattable<std::tuple<unformattable, unformattable>>::value));
194   EXPECT_TRUE((fmt::is_formattable<std::tuple<int, float>>::value));
195 }
196 
197 struct not_default_formattable {};
198 struct bad_format {};
199 
200 FMT_BEGIN_NAMESPACE
201 template <> struct formatter<not_default_formattable> {
parseformatter202   auto parse(format_parse_context&) -> const char* { throw bad_format(); }
formatformatter203   auto format(not_default_formattable, format_context& ctx)
204       -> format_context::iterator {
205     return ctx.out();
206   }
207 };
208 FMT_END_NAMESPACE
209 
TEST(ranges_test,tuple_parse_calls_element_parse)210 TEST(ranges_test, tuple_parse_calls_element_parse) {
211   auto f = fmt::formatter<std::tuple<not_default_formattable>>();
212   auto ctx = fmt::format_parse_context("");
213   EXPECT_THROW(f.parse(ctx), bad_format);
214 }
215 
216 #ifdef FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
217 struct tuple_like {
218   int i;
219   std::string str;
220 
221   template <size_t N>
gettuple_like222   auto get() const noexcept -> fmt::enable_if_t<N == 0, int> {
223     return i;
224   }
225   template <size_t N>
gettuple_like226   auto get() const noexcept -> fmt::enable_if_t<N == 1, fmt::string_view> {
227     return str;
228   }
229 };
230 
231 template <size_t N>
get(const tuple_like & t)232 auto get(const tuple_like& t) noexcept -> decltype(t.get<N>()) {
233   return t.get<N>();
234 }
235 
236 namespace std {
237 template <>
238 struct tuple_size<tuple_like> : std::integral_constant<size_t, 2> {};
239 
240 template <size_t N> struct tuple_element<N, tuple_like> {
241   using type = decltype(std::declval<tuple_like>().get<N>());
242 };
243 }  // namespace std
244 
TEST(ranges_test,format_struct)245 TEST(ranges_test, format_struct) {
246   auto t = tuple_like{42, "foo"};
247   EXPECT_EQ(fmt::format("{}", t), "(42, \"foo\")");
248 }
249 #endif  // FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
250 
TEST(ranges_test,format_to)251 TEST(ranges_test, format_to) {
252   char buf[10];
253   auto end = fmt::format_to(buf, "{}", std::vector<int>{1, 2, 3});
254   *end = '\0';
255   EXPECT_STREQ(buf, "[1, 2, 3]");
256 }
257 
258 template <typename Char> struct path_like {
259   auto begin() const -> const path_like*;
260   auto end() const -> const path_like*;
261 
262   operator std::basic_string<Char>() const;
263 };
264 
TEST(ranges_test,disabled_range_formatting_of_path)265 TEST(ranges_test, disabled_range_formatting_of_path) {
266   // Range formatting of path is disabled because of infinite recursion
267   // (path element is itself a path).
268   EXPECT_EQ((fmt::range_format_kind<path_like<char>, char>::value),
269             fmt::range_format::disabled);
270   EXPECT_EQ((fmt::range_format_kind<path_like<wchar_t>, char>::value),
271             fmt::range_format::disabled);
272 }
273 
274 struct vector_string : std::vector<char> {
275   using base = std::vector<char>;
276   using base::base;
277 };
278 struct vector_debug_string : std::vector<char> {
279   using base = std::vector<char>;
280   using base::base;
281 };
282 FMT_BEGIN_NAMESPACE
283 template <>
284 struct range_format_kind<vector_string, char>
285     : std::integral_constant<range_format, range_format::string> {};
286 template <>
287 struct range_format_kind<vector_debug_string, char>
288     : std::integral_constant<range_format, range_format::debug_string> {};
289 FMT_END_NAMESPACE
290 
TEST(ranges_test,range_format_string)291 TEST(ranges_test, range_format_string) {
292   const vector_string v{'f', 'o', 'o'};
293   EXPECT_EQ(fmt::format("{}", v), "foo");
294 }
295 
TEST(ranges_test,range_format_debug_string)296 TEST(ranges_test, range_format_debug_string) {
297   const vector_debug_string v{'f', 'o', 'o'};
298   EXPECT_EQ(fmt::format("{}", v), "\"foo\"");
299 }
300 
301 // A range that provides non-const only begin()/end() to test fmt::join
302 // handles that.
303 //
304 // Some ranges (e.g. those produced by range-v3's views::filter()) can cache
305 // information during iteration so they only provide non-const begin()/end().
306 template <typename T> class non_const_only_range {
307  private:
308   std::vector<T> vec;
309 
310  public:
311   using const_iterator = typename ::std::vector<T>::const_iterator;
312 
313   template <typename... Args>
non_const_only_range(Args &&...args)314   explicit non_const_only_range(Args&&... args)
315       : vec(std::forward<Args>(args)...) {}
316 
begin()317   auto begin() -> const_iterator { return vec.begin(); }
end()318   auto end() -> const_iterator { return vec.end(); }
319 };
320 
321 template <typename T> class noncopyable_range {
322  private:
323   std::vector<T> vec;
324 
325  public:
326   using iterator = typename ::std::vector<T>::iterator;
327 
328   template <typename... Args>
noncopyable_range(Args &&...args)329   explicit noncopyable_range(Args&&... args)
330       : vec(std::forward<Args>(args)...) {}
331 
332   noncopyable_range(noncopyable_range const&) = delete;
333   noncopyable_range(noncopyable_range&) = delete;
334 
begin()335   auto begin() -> iterator { return vec.begin(); }
end()336   auto end() -> iterator { return vec.end(); }
337 };
338 
TEST(ranges_test,range)339 TEST(ranges_test, range) {
340   auto&& w = noncopyable_range<int>(3u, 0);
341   EXPECT_EQ(fmt::format("{}", w), "[0, 0, 0]");
342   EXPECT_EQ(fmt::format("{}", noncopyable_range<int>(3u, 0)), "[0, 0, 0]");
343 
344   auto x = non_const_only_range<int>(3u, 0);
345   EXPECT_EQ(fmt::format("{}", x), "[0, 0, 0]");
346   EXPECT_EQ(fmt::format("{}", non_const_only_range<int>(3u, 0)), "[0, 0, 0]");
347 
348   auto y = std::vector<int>(3u, 0);
349   EXPECT_EQ(fmt::format("{}", y), "[0, 0, 0]");
350   EXPECT_EQ(fmt::format("{}", std::vector<int>(3u, 0)), "[0, 0, 0]");
351 
352   const auto z = std::vector<int>(3u, 0);
353   EXPECT_EQ(fmt::format("{}", z), "[0, 0, 0]");
354 }
355 
356 enum test_enum { foo, bar };
format_as(test_enum e)357 auto format_as(test_enum e) -> int { return e; }
358 
TEST(ranges_test,enum_range)359 TEST(ranges_test, enum_range) {
360   auto v = std::vector<test_enum>{test_enum::foo};
361   EXPECT_EQ(fmt::format("{}", v), "[0]");
362 }
363 
364 #if !FMT_MSC_VERSION
TEST(ranges_test,unformattable_range)365 TEST(ranges_test, unformattable_range) {
366   EXPECT_FALSE((fmt::is_formattable<std::vector<unformattable>, char>::value));
367 }
368 #endif
369 
TEST(ranges_test,join)370 TEST(ranges_test, join) {
371   using fmt::join;
372   int v1[3] = {1, 2, 3};
373   auto v2 = std::vector<float>();
374   v2.push_back(1.2f);
375   v2.push_back(3.4f);
376   void* v3[2] = {&v1[0], &v1[1]};
377 
378   EXPECT_EQ(fmt::format("({})", join(v1, v1 + 3, ", ")), "(1, 2, 3)");
379   EXPECT_EQ(fmt::format("({})", join(v1, v1 + 1, ", ")), "(1)");
380   EXPECT_EQ(fmt::format("({})", join(v1, v1, ", ")), "()");
381   EXPECT_EQ(fmt::format("({:03})", join(v1, v1 + 3, ", ")), "(001, 002, 003)");
382   EXPECT_EQ("(+01.20, +03.40)",
383             fmt::format("({:+06.2f})", join(v2.begin(), v2.end(), ", ")));
384 
385   EXPECT_EQ(fmt::format("{0:{1}}", join(v1, v1 + 3, ", "), 1), "1, 2, 3");
386 
387   EXPECT_EQ(fmt::format("{}, {}", v3[0], v3[1]),
388             fmt::format("{}", join(v3, v3 + 2, ", ")));
389 
390   EXPECT_EQ(fmt::format("({})", join(v1, ", ")), "(1, 2, 3)");
391   EXPECT_EQ(fmt::format("({:+06.2f})", join(v2, ", ")), "(+01.20, +03.40)");
392 
393   auto v4 = std::vector<test_enum>{foo, bar, foo};
394   EXPECT_EQ(fmt::format("{}", join(v4, " ")), "0 1 0");
395 }
396 
397 #ifdef __cpp_lib_byte
TEST(ranges_test,join_bytes)398 TEST(ranges_test, join_bytes) {
399   auto v = std::vector<std::byte>{std::byte(1), std::byte(2), std::byte(3)};
400   EXPECT_EQ(fmt::format("{}", fmt::join(v, ", ")), "1, 2, 3");
401 }
402 #endif
403 
404 #ifdef FMT_RANGES_TEST_ENABLE_JOIN
TEST(ranges_test,join_tuple)405 TEST(ranges_test, join_tuple) {
406   // Value tuple args.
407   auto t1 = std::tuple<char, int, float>('a', 1, 2.0f);
408   EXPECT_EQ(fmt::format("({})", fmt::join(t1, ", ")), "(a, 1, 2)");
409 
410   // Testing lvalue tuple args.
411   int x = 4;
412   auto t2 = std::tuple<char, int&>('b', x);
413   EXPECT_EQ(fmt::format("{}", fmt::join(t2, " + ")), "b + 4");
414 
415   // Empty tuple.
416   auto t3 = std::tuple<>();
417   EXPECT_EQ(fmt::format("{}", fmt::join(t3, "|")), "");
418 
419   // Single element tuple.
420   auto t4 = std::tuple<float>(4.0f);
421   EXPECT_EQ(fmt::format("{}", fmt::join(t4, "/")), "4");
422 
423 #  if FMT_TUPLE_JOIN_SPECIFIERS
424   // Specs applied to each element.
425   auto t5 = std::tuple<int, int, long>(-3, 100, 1);
426   EXPECT_EQ(fmt::format("{:+03}", fmt::join(t5, ", ")), "-03, +100, +01");
427 
428   auto t6 = std::tuple<float, double, long double>(3, 3.14, 3.1415);
429   EXPECT_EQ(fmt::format("{:5.5f}", fmt::join(t6, ", ")),
430             "3.00000, 3.14000, 3.14150");
431 
432   // Testing lvalue tuple args.
433   int y = -1;
434   auto t7 = std::tuple<int, int&, const int&>(3, y, y);
435   EXPECT_EQ(fmt::format("{:03}", fmt::join(t7, ", ")), "003, -01, -01");
436 #  endif
437 }
438 
TEST(ranges_test,join_initializer_list)439 TEST(ranges_test, join_initializer_list) {
440   EXPECT_EQ(fmt::format("{}", fmt::join({1, 2, 3}, ", ")), "1, 2, 3");
441   EXPECT_EQ(fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " ")),
442             "fmt rocks !");
443 }
444 
445 struct zstring_sentinel {};
446 
operator ==(const char * p,zstring_sentinel)447 bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; }
operator !=(const char * p,zstring_sentinel)448 bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; }
449 
450 struct zstring {
451   const char* p;
beginzstring452   auto begin() const -> const char* { return p; }
endzstring453   auto end() const -> zstring_sentinel { return {}; }
454 };
455 
456 #  ifdef __cpp_lib_ranges
457 struct cpp20_only_range {
458   struct iterator {
459     int val = 0;
460 
461     using value_type = int;
462     using difference_type = std::ptrdiff_t;
463     using iterator_concept = std::input_iterator_tag;
464 
465     iterator() = default;
iteratorcpp20_only_range::iterator466     iterator(int i) : val(i) {}
operator *cpp20_only_range::iterator467     auto operator*() const -> int { return val; }
operator ++cpp20_only_range::iterator468     auto operator++() -> iterator& {
469       ++val;
470       return *this;
471     }
operator ++cpp20_only_range::iterator472     void operator++(int) { ++*this; }
operator ==cpp20_only_range::iterator473     auto operator==(const iterator& rhs) const -> bool {
474       return val == rhs.val;
475     }
476   };
477 
478   int lo;
479   int hi;
480 
begincpp20_only_range481   auto begin() const -> iterator { return iterator(lo); }
endcpp20_only_range482   auto end() const -> iterator { return iterator(hi); }
483 };
484 
485 static_assert(std::input_iterator<cpp20_only_range::iterator>);
486 #  endif
487 
TEST(ranges_test,join_sentinel)488 TEST(ranges_test, join_sentinel) {
489   auto hello = zstring{"hello"};
490   EXPECT_EQ(fmt::format("{}", hello), "['h', 'e', 'l', 'l', 'o']");
491   EXPECT_EQ(fmt::format("{::}", hello), "[h, e, l, l, o]");
492   EXPECT_EQ(fmt::format("{}", fmt::join(hello, "_")), "h_e_l_l_o");
493 }
494 
TEST(ranges_test,join_range)495 TEST(ranges_test, join_range) {
496   auto&& w = noncopyable_range<int>(3u, 0);
497   EXPECT_EQ(fmt::format("{}", fmt::join(w, ",")), "0,0,0");
498   EXPECT_EQ(fmt::format("{}", fmt::join(noncopyable_range<int>(3u, 0), ",")),
499             "0,0,0");
500 
501   auto x = non_const_only_range<int>(3u, 0);
502   EXPECT_EQ(fmt::format("{}", fmt::join(x, ",")), "0,0,0");
503   EXPECT_EQ(fmt::format("{}", fmt::join(non_const_only_range<int>(3u, 0), ",")),
504             "0,0,0");
505 
506   auto y = std::vector<int>(3u, 0);
507   EXPECT_EQ(fmt::format("{}", fmt::join(y, ",")), "0,0,0");
508   EXPECT_EQ(fmt::format("{}", fmt::join(std::vector<int>(3u, 0), ",")),
509             "0,0,0");
510 
511   const auto z = std::vector<int>(3u, 0);
512   EXPECT_EQ(fmt::format("{}", fmt::join(z, ",")), "0,0,0");
513 
514 #  ifdef __cpp_lib_ranges
515   EXPECT_EQ(fmt::format("{}", cpp20_only_range{.lo = 0, .hi = 5}),
516             "[0, 1, 2, 3, 4]");
517   EXPECT_EQ(
518       fmt::format("{}", fmt::join(cpp20_only_range{.lo = 0, .hi = 5}, ",")),
519       "0,1,2,3,4");
520 #  endif
521 }
522 
523 namespace adl {
524 struct vec {
525   int n[2] = {42, 43};
526 };
527 
begin(const vec & v)528 auto begin(const vec& v) -> const int* { return v.n; }
end(const vec & v)529 auto end(const vec& v) -> const int* { return v.n + 2; }
530 }  // namespace adl
531 
TEST(ranges_test,format_join_adl_begin_end)532 TEST(ranges_test, format_join_adl_begin_end) {
533   EXPECT_EQ(fmt::format("{}", fmt::join(adl::vec(), "/")), "42/43");
534 }
535 
536 #endif  // FMT_RANGES_TEST_ENABLE_JOIN
537 
538 #if defined(__cpp_lib_ranges) && __cpp_lib_ranges >= 202207L
TEST(ranges_test,nested_ranges)539 TEST(ranges_test, nested_ranges) {
540   auto l = std::list{1, 2, 3};
541   auto r = std::views::iota(0, 3) | std::views::transform([&l](auto i) {
542              return std::views::take(std::ranges::subrange(l), i);
543            }) |
544            std::views::transform(std::views::reverse);
545   EXPECT_EQ(fmt::format("{}", r), "[[], [1], [2, 1]]");
546 }
547 #endif
548 
TEST(ranges_test,is_printable)549 TEST(ranges_test, is_printable) {
550   using fmt::detail::is_printable;
551   EXPECT_TRUE(is_printable(0x0323));
552   EXPECT_FALSE(is_printable(0x0378));
553   EXPECT_FALSE(is_printable(0x110000));
554 }
555 
TEST(ranges_test,escape)556 TEST(ranges_test, escape) {
557   using vec = std::vector<std::string>;
558   EXPECT_EQ(fmt::format("{}", vec{"\n\r\t\"\\"}), "[\"\\n\\r\\t\\\"\\\\\"]");
559   EXPECT_EQ(fmt::format("{}", vec{"\x07"}), "[\"\\x07\"]");
560   EXPECT_EQ(fmt::format("{}", vec{"\x7f"}), "[\"\\x7f\"]");
561   EXPECT_EQ(fmt::format("{}", vec{"n\xcc\x83"}), "[\"n\xcc\x83\"]");
562 
563   if (fmt::detail::use_utf8) {
564     EXPECT_EQ(fmt::format("{}", vec{"\xcd\xb8"}), "[\"\\u0378\"]");
565     // Unassigned Unicode code points.
566     EXPECT_EQ(fmt::format("{}", vec{"\xf0\xaa\x9b\x9e"}), "[\"\\U0002a6de\"]");
567     // Broken utf-8.
568     EXPECT_EQ(fmt::format("{}", vec{"\xf4\x8f\xbf\xc0"}),
569               "[\"\\xf4\\x8f\\xbf\\xc0\"]");
570     EXPECT_EQ(fmt::format("{}", vec{"\xf0\x28"}), "[\"\\xf0(\"]");
571     EXPECT_EQ(fmt::format("{}", vec{"\xe1\x28"}), "[\"\\xe1(\"]");
572     EXPECT_EQ(fmt::format("{}", vec{std::string("\xf0\x28\0\0anything", 12)}),
573               "[\"\\xf0(\\x00\\x00anything\"]");
574 
575     // Correct utf-8.
576     EXPECT_EQ(fmt::format("{}", vec{"��"}), "[\"��\"]");
577   }
578 
579   EXPECT_EQ(fmt::format("{}", std::vector<std::vector<char>>{{'x'}}),
580             "[['x']]");
581 
582 // Disabled due to a clang 17 bug: https://github.com/fmtlib/fmt/issues/4144.
583 #if FMT_CLANG_VERSION >= 1800
584   EXPECT_EQ(fmt::format("{}", std::tuple<std::vector<char>>{{'x'}}), "(['x'])");
585 #endif
586 }
587 
588 template <typename R> struct fmt_ref_view {
589   R* r;
590 
beginfmt_ref_view591   auto begin() const -> decltype(r->begin()) { return r->begin(); }
endfmt_ref_view592   auto end() const -> decltype(r->end()) { return r->end(); }
593 };
594 
TEST(ranges_test,range_of_range_of_mixed_const)595 TEST(ranges_test, range_of_range_of_mixed_const) {
596   auto v = std::vector<std::vector<int>>{{1, 2, 3}, {4, 5}};
597   EXPECT_EQ(fmt::format("{}", v), "[[1, 2, 3], [4, 5]]");
598 
599   auto r = fmt_ref_view<decltype(v)>{&v};
600   EXPECT_EQ(fmt::format("{}", r), "[[1, 2, 3], [4, 5]]");
601 }
602 
TEST(ranges_test,vector_char)603 TEST(ranges_test, vector_char) {
604   EXPECT_EQ(fmt::format("{}", std::vector<char>{'a', 'b'}), "['a', 'b']");
605 }
606 
TEST(ranges_test,container_adaptor)607 TEST(ranges_test, container_adaptor) {
608   {
609     using fmt::detail::is_container_adaptor_like;
610     using T = std::nullptr_t;
611     static_assert(is_container_adaptor_like<std::stack<T>>::value, "");
612     static_assert(is_container_adaptor_like<std::queue<T>>::value, "");
613     static_assert(is_container_adaptor_like<std::priority_queue<T>>::value, "");
614     static_assert(!is_container_adaptor_like<std::vector<T>>::value, "");
615   }
616 
617   {
618     auto s = std::stack<int>();
619     s.push(1);
620     s.push(2);
621     EXPECT_EQ(fmt::format("{}", s), "[1, 2]");
622     EXPECT_EQ(fmt::format("{}", const_cast<const decltype(s)&>(s)), "[1, 2]");
623   }
624 
625   {
626     auto q = std::queue<int>();
627     q.push(1);
628     q.push(2);
629     EXPECT_EQ(fmt::format("{}", q), "[1, 2]");
630   }
631 
632   {
633     auto q = std::priority_queue<int>();
634     q.push(3);
635     q.push(1);
636     q.push(2);
637     q.push(4);
638     EXPECT_EQ(fmt::format("{}", q), "[4, 3, 2, 1]");
639   }
640 
641   {
642     auto s = std::stack<char, std::string>();
643     s.push('a');
644     s.push('b');
645     // See https://cplusplus.github.io/LWG/issue3881.
646     EXPECT_EQ(fmt::format("{}", s), "['a', 'b']");
647   }
648 
649   {
650     struct my_container_adaptor {
651       using value_type = int;
652       using container_type = std::vector<value_type>;
653       void push(const value_type& v) { c.push_back(v); }
654 
655      protected:
656       container_type c;
657     };
658 
659     auto m = my_container_adaptor();
660     m.push(1);
661     m.push(2);
662     EXPECT_EQ(fmt::format("{}", m), "[1, 2]");
663   }
664 }
665 
666 struct tieable {
667   int a = 3;
668   double b = 0.42;
669 };
670 
format_as(const tieable & t)671 auto format_as(const tieable& t) -> std::tuple<int, double> {
672   return std::tie(t.a, t.b);
673 }
674 
TEST(ranges_test,format_as_tie)675 TEST(ranges_test, format_as_tie) {
676   EXPECT_EQ(fmt::format("{}", tieable()), "(3, 0.42)");
677 }
678 
679 struct lvalue_qualified_begin_end {
680   int arr[5] = {1, 2, 3, 4, 5};
681 
beginlvalue_qualified_begin_end682   auto begin() & -> const int* { return arr; }
endlvalue_qualified_begin_end683   auto end() & -> const int* { return arr + 5; }
684 };
685 
TEST(ranges_test,lvalue_qualified_begin_end)686 TEST(ranges_test, lvalue_qualified_begin_end) {
687   EXPECT_EQ(fmt::format("{}", lvalue_qualified_begin_end{}), "[1, 2, 3, 4, 5]");
688 }
689 
690 #if !defined(__cpp_lib_ranges) || __cpp_lib_ranges <= 202106L
691 #  define ENABLE_STD_VIEWS_TESTS 0
692 #elif FMT_CLANG_VERSION
693 #  if FMT_CLANG_VERSION > 1500
694 #    define ENABLE_STD_VIEWS_TESTS 1
695 #  else
696 #    define ENABLE_STD_VIEWS_TESTS 0
697 #  endif
698 #else
699 #  define ENABLE_STD_VIEWS_TESTS 1
700 #endif
701 
702 #if ENABLE_STD_VIEWS_TESTS
TEST(ranges_test,input_range_join)703 TEST(ranges_test, input_range_join) {
704   auto iss = std::istringstream("1 2 3 4 5");
705   auto view = std::views::istream<std::string>(iss);
706   EXPECT_EQ("1, 2, 3, 4, 5",
707             fmt::format("{}", fmt::join(view.begin(), view.end(), ", ")));
708 }
709 
TEST(ranges_test,input_range_join_overload)710 TEST(ranges_test, input_range_join_overload) {
711   auto iss = std::istringstream("1 2 3 4 5");
712   EXPECT_EQ(
713       "1.2.3.4.5",
714       fmt::format("{}", fmt::join(std::views::istream<std::string>(iss), ".")));
715 }
716 
717 namespace views_filter_view_test {
718 struct codec_mask {
719   static constexpr auto codecs = std::array{0, 1, 2, 3};
720   int except = 0;
721 };
722 
format_as(codec_mask mask)723 auto format_as(codec_mask mask) {
724   // Careful not to capture param by reference here, it will dangle.
725   return codec_mask::codecs |
726          std::views::filter([mask](auto c) { return c != mask.except; });
727 }
728 }  // namespace views_filter_view_test
729 
TEST(ranges_test,format_as_with_ranges_mutable_begin_end)730 TEST(ranges_test, format_as_with_ranges_mutable_begin_end) {
731   using namespace views_filter_view_test;
732   {
733     auto make_filter_view = []() {
734       return codec_mask::codecs |
735              std::views::filter([](auto c) { return c != 2; });
736     };
737     auto r = make_filter_view();
738     EXPECT_EQ("[0, 1, 3]", fmt::format("{}", r));
739     EXPECT_EQ("[0, 1, 3]", fmt::format("{}", make_filter_view()));
740   }
741 
742   {
743     auto mask = codec_mask{2};
744     const auto const_mask = codec_mask{2};
745 
746     EXPECT_EQ("[0, 1, 3]", fmt::format("{}", mask));
747     EXPECT_EQ("[0, 1, 3]", fmt::format("{}", const_mask));
748     EXPECT_EQ("[0, 1, 3]", fmt::format("{}", codec_mask{2}));
749   }
750 }
751 
752 #endif
753 
TEST(ranges_test,std_istream_iterator_join)754 TEST(ranges_test, std_istream_iterator_join) {
755   auto&& iss = std::istringstream("1 2 3 4 5");
756   auto first = std::istream_iterator<int>(iss);
757   auto last = std::istream_iterator<int>();
758   EXPECT_EQ("1, 2, 3, 4, 5", fmt::format("{}", fmt::join(first, last, ", ")));
759 }
760 
761 // Mirrors C++20 std::ranges::basic_istream_view::iterator.
762 struct noncopyable_istream_iterator : std::istream_iterator<int> {
763   using base = std::istream_iterator<int>;
noncopyable_istream_iteratornoncopyable_istream_iterator764   explicit noncopyable_istream_iterator(std::istringstream& iss) : base{iss} {}
765   noncopyable_istream_iterator(const noncopyable_istream_iterator&) = delete;
766   noncopyable_istream_iterator(noncopyable_istream_iterator&&) = default;
767 };
768 static_assert(!std::is_copy_constructible<noncopyable_istream_iterator>::value,
769               "");
770 
TEST(ranges_test,movable_only_istream_iter_join)771 TEST(ranges_test, movable_only_istream_iter_join) {
772   auto&& iss = std::istringstream("1 2 3 4 5");
773   auto first = noncopyable_istream_iterator(iss);
774   auto last = std::istream_iterator<int>();
775   EXPECT_EQ("1, 2, 3, 4, 5",
776             fmt::format("{}", fmt::join(std::move(first), last, ", ")));
777 }
778 
779 struct movable_iter_range {
780   std::istringstream iss{"1 2 3 4 5"};
beginmovable_iter_range781   noncopyable_istream_iterator begin() {
782     return noncopyable_istream_iterator{iss};
783   }
endmovable_iter_range784   std::istream_iterator<int> end() { return {}; }
785 };
786 
TEST(ranges_test,movable_only_istream_iter_join2)787 TEST(ranges_test, movable_only_istream_iter_join2) {
788   EXPECT_EQ("[1, 2, 3, 4, 5]", fmt::format("{}", movable_iter_range{}));
789 }
790 
791 struct not_range {
beginnot_range792   void begin() const {}
endnot_range793   void end() const {}
794 };
795 static_assert(!fmt::is_formattable<not_range>{}, "");
796