ranges-test.cc 24 KB

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