2
0

ranges-test.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Formatting library for C++ - the core API
  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. #include "fmt/ranges.h"
  12. #include <map>
  13. #include <queue>
  14. #include <stack>
  15. #include <string>
  16. #include <utility>
  17. #include <vector>
  18. #include "gtest/gtest.h"
  19. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 601
  20. # define FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
  21. #endif
  22. #if !FMT_MSC_VERSION || FMT_MSC_VERSION > 1910
  23. # define FMT_RANGES_TEST_ENABLE_JOIN
  24. # define FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
  25. #endif
  26. #ifdef FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
  27. TEST(ranges_test, format_array) {
  28. int arr[] = {1, 2, 3, 5, 7, 11};
  29. EXPECT_EQ(fmt::format("{}", arr), "[1, 2, 3, 5, 7, 11]");
  30. }
  31. TEST(ranges_test, format_2d_array) {
  32. int arr[][2] = {{1, 2}, {3, 5}, {7, 11}};
  33. EXPECT_EQ(fmt::format("{}", arr), "[[1, 2], [3, 5], [7, 11]]");
  34. }
  35. TEST(ranges_test, format_array_of_literals) {
  36. const char* arr[] = {"1234", "abcd"};
  37. EXPECT_EQ(fmt::format("{}", arr), "[\"1234\", \"abcd\"]");
  38. EXPECT_EQ(fmt::format("{:n}", arr), "\"1234\", \"abcd\"");
  39. EXPECT_EQ(fmt::format("{:n:}", arr), "1234, abcd");
  40. }
  41. #endif // FMT_RANGES_TEST_ENABLE_C_STYLE_ARRAY
  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 vvc = std::vector<std::vector<char>>{vc, vc};
  49. EXPECT_EQ(fmt::format("{}", vc), "['a', 'b', 'c']");
  50. EXPECT_EQ(fmt::format("{}", vvc), "[['a', 'b', 'c'], ['a', 'b', 'c']]");
  51. EXPECT_EQ(fmt::format("{:n}", vvc), "['a', 'b', 'c'], ['a', 'b', 'c']");
  52. EXPECT_EQ(fmt::format("{:n:n}", vvc), "'a', 'b', 'c', 'a', 'b', 'c'");
  53. EXPECT_EQ(fmt::format("{:n:n:}", vvc), "a, b, c, a, b, c");
  54. }
  55. TEST(ranges_test, format_vector2) {
  56. auto v = std::vector<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:n:#x}", v), "0x1, 0x2, 0x3, 0x5, 0x7, 0xb");
  60. }
  61. TEST(ranges_test, format_map) {
  62. auto m = std::map<std::string, int>{{"one", 1}, {"two", 2}};
  63. EXPECT_EQ(fmt::format("{}", m), "{\"one\": 1, \"two\": 2}");
  64. EXPECT_EQ(fmt::format("{:n}", m), "\"one\": 1, \"two\": 2");
  65. }
  66. TEST(ranges_test, format_set) {
  67. EXPECT_EQ(fmt::format("{}", std::set<std::string>{"one", "two"}),
  68. "{\"one\", \"two\"}");
  69. }
  70. // Models std::flat_set close enough to test if no ambiguous lookup of a
  71. // formatter happens due to the flat_set type matching is_set and
  72. // is_container_adaptor_like
  73. template <typename T> class flat_set {
  74. public:
  75. using key_type = T;
  76. using container_type = std::vector<T>;
  77. using iterator = typename std::vector<T>::iterator;
  78. using const_iterator = typename std::vector<T>::const_iterator;
  79. template <typename... Ts>
  80. explicit flat_set(Ts&&... args) : c{std::forward<Ts>(args)...} {}
  81. iterator begin() { return c.begin(); }
  82. const_iterator begin() const { return c.begin(); }
  83. iterator end() { return c.end(); }
  84. const_iterator end() const { return c.end(); }
  85. private:
  86. std::vector<T> c;
  87. };
  88. TEST(ranges_test, format_flat_set) {
  89. EXPECT_EQ(fmt::format("{}", flat_set<std::string>{"one", "two"}),
  90. "{\"one\", \"two\"}");
  91. }
  92. namespace adl {
  93. struct box {
  94. int value;
  95. };
  96. auto begin(const box& b) -> const int* { return &b.value; }
  97. auto end(const box& b) -> const int* { return &b.value + 1; }
  98. } // namespace adl
  99. TEST(ranges_test, format_adl_begin_end) {
  100. auto b = adl::box{42};
  101. EXPECT_EQ(fmt::format("{}", b), "[42]");
  102. }
  103. TEST(ranges_test, format_pair) {
  104. auto p = std::pair<int, float>(42, 1.5f);
  105. EXPECT_EQ(fmt::format("{}", p), "(42, 1.5)");
  106. }
  107. struct unformattable {};
  108. TEST(ranges_test, format_tuple) {
  109. auto t =
  110. std::tuple<int, float, std::string, char>(42, 1.5f, "this is tuple", 'i');
  111. EXPECT_EQ(fmt::format("{}", t), "(42, 1.5, \"this is tuple\", 'i')");
  112. EXPECT_EQ(fmt::format("{}", std::tuple<>()), "()");
  113. EXPECT_TRUE((fmt::is_formattable<std::tuple<>>::value));
  114. EXPECT_FALSE((fmt::is_formattable<unformattable>::value));
  115. EXPECT_FALSE((fmt::is_formattable<std::tuple<unformattable>>::value));
  116. EXPECT_FALSE((fmt::is_formattable<std::tuple<unformattable, int>>::value));
  117. EXPECT_FALSE((fmt::is_formattable<std::tuple<int, unformattable>>::value));
  118. EXPECT_FALSE(
  119. (fmt::is_formattable<std::tuple<unformattable, unformattable>>::value));
  120. EXPECT_TRUE((fmt::is_formattable<std::tuple<int, float>>::value));
  121. }
  122. struct not_default_formattable {};
  123. struct bad_format {};
  124. FMT_BEGIN_NAMESPACE
  125. template <> struct formatter<not_default_formattable> {
  126. auto parse(format_parse_context&) -> const char* { throw bad_format(); }
  127. auto format(not_default_formattable, format_context& ctx)
  128. -> format_context::iterator {
  129. return ctx.out();
  130. }
  131. };
  132. FMT_END_NAMESPACE
  133. TEST(ranges_test, tuple_parse_calls_element_parse) {
  134. auto f = fmt::formatter<std::tuple<not_default_formattable>>();
  135. auto ctx = fmt::format_parse_context("");
  136. EXPECT_THROW(f.parse(ctx), bad_format);
  137. }
  138. #ifdef FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
  139. struct tuple_like {
  140. int i;
  141. std::string str;
  142. template <size_t N> fmt::enable_if_t<N == 0, int> get() const noexcept {
  143. return i;
  144. }
  145. template <size_t N>
  146. fmt::enable_if_t<N == 1, fmt::string_view> get() const noexcept {
  147. return str;
  148. }
  149. };
  150. template <size_t N>
  151. auto get(const tuple_like& t) noexcept -> decltype(t.get<N>()) {
  152. return t.get<N>();
  153. }
  154. namespace std {
  155. template <>
  156. struct tuple_size<tuple_like> : std::integral_constant<size_t, 2> {};
  157. template <size_t N> struct tuple_element<N, tuple_like> {
  158. using type = decltype(std::declval<tuple_like>().get<N>());
  159. };
  160. } // namespace std
  161. TEST(ranges_test, format_struct) {
  162. auto t = tuple_like{42, "foo"};
  163. EXPECT_EQ(fmt::format("{}", t), "(42, \"foo\")");
  164. }
  165. #endif // FMT_RANGES_TEST_ENABLE_FORMAT_STRUCT
  166. TEST(ranges_test, format_to) {
  167. char buf[10];
  168. auto end = fmt::format_to(buf, "{}", std::vector<int>{1, 2, 3});
  169. *end = '\0';
  170. EXPECT_STREQ(buf, "[1, 2, 3]");
  171. }
  172. template <typename Char> struct path_like {
  173. const path_like* begin() const;
  174. const path_like* end() const;
  175. operator std::basic_string<Char>() const;
  176. };
  177. TEST(ranges_test, disabled_range_formatting_of_path) {
  178. // Range formatting of path is disabled because of infinite recursion
  179. // (path element is itself a path).
  180. EXPECT_EQ((fmt::range_format_kind<path_like<char>, char>::value),
  181. fmt::range_format::disabled);
  182. EXPECT_EQ((fmt::range_format_kind<path_like<wchar_t>, char>::value),
  183. fmt::range_format::disabled);
  184. }
  185. // A range that provides non-const only begin()/end() to test fmt::join
  186. // handles that.
  187. //
  188. // Some ranges (e.g. those produced by range-v3's views::filter()) can cache
  189. // information during iteration so they only provide non-const begin()/end().
  190. template <typename T> class non_const_only_range {
  191. private:
  192. std::vector<T> vec;
  193. public:
  194. using const_iterator = typename ::std::vector<T>::const_iterator;
  195. template <typename... Args>
  196. explicit non_const_only_range(Args&&... args)
  197. : vec(std::forward<Args>(args)...) {}
  198. const_iterator begin() { return vec.begin(); }
  199. const_iterator end() { return vec.end(); }
  200. };
  201. template <typename T> class noncopyable_range {
  202. private:
  203. std::vector<T> vec;
  204. public:
  205. using iterator = typename ::std::vector<T>::iterator;
  206. template <typename... Args>
  207. explicit noncopyable_range(Args&&... args)
  208. : vec(std::forward<Args>(args)...) {}
  209. noncopyable_range(noncopyable_range const&) = delete;
  210. noncopyable_range(noncopyable_range&) = delete;
  211. iterator begin() { return vec.begin(); }
  212. iterator end() { return vec.end(); }
  213. };
  214. TEST(ranges_test, range) {
  215. noncopyable_range<int> w(3u, 0);
  216. EXPECT_EQ(fmt::format("{}", w), "[0, 0, 0]");
  217. EXPECT_EQ(fmt::format("{}", noncopyable_range<int>(3u, 0)), "[0, 0, 0]");
  218. non_const_only_range<int> x(3u, 0);
  219. EXPECT_EQ(fmt::format("{}", x), "[0, 0, 0]");
  220. EXPECT_EQ(fmt::format("{}", non_const_only_range<int>(3u, 0)), "[0, 0, 0]");
  221. auto y = std::vector<int>(3u, 0);
  222. EXPECT_EQ(fmt::format("{}", y), "[0, 0, 0]");
  223. EXPECT_EQ(fmt::format("{}", std::vector<int>(3u, 0)), "[0, 0, 0]");
  224. const auto z = std::vector<int>(3u, 0);
  225. EXPECT_EQ(fmt::format("{}", z), "[0, 0, 0]");
  226. }
  227. enum test_enum { foo };
  228. auto format_as(test_enum e) -> int { return e; }
  229. TEST(ranges_test, enum_range) {
  230. auto v = std::vector<test_enum>{test_enum::foo};
  231. EXPECT_EQ(fmt::format("{}", v), "[0]");
  232. }
  233. #if !FMT_MSC_VERSION
  234. TEST(ranges_test, unformattable_range) {
  235. EXPECT_FALSE((fmt::has_formatter<std::vector<unformattable>,
  236. fmt::format_context>::value));
  237. }
  238. #endif
  239. #ifdef FMT_RANGES_TEST_ENABLE_JOIN
  240. TEST(ranges_test, join_tuple) {
  241. // Value tuple args.
  242. auto t1 = std::tuple<char, int, float>('a', 1, 2.0f);
  243. EXPECT_EQ(fmt::format("({})", fmt::join(t1, ", ")), "(a, 1, 2)");
  244. // Testing lvalue tuple args.
  245. int x = 4;
  246. auto t2 = std::tuple<char, int&>('b', x);
  247. EXPECT_EQ(fmt::format("{}", fmt::join(t2, " + ")), "b + 4");
  248. // Empty tuple.
  249. auto t3 = std::tuple<>();
  250. EXPECT_EQ(fmt::format("{}", fmt::join(t3, "|")), "");
  251. // Single element tuple.
  252. auto t4 = std::tuple<float>(4.0f);
  253. EXPECT_EQ(fmt::format("{}", fmt::join(t4, "/")), "4");
  254. # if FMT_TUPLE_JOIN_SPECIFIERS
  255. // Specs applied to each element.
  256. auto t5 = std::tuple<int, int, long>(-3, 100, 1);
  257. EXPECT_EQ(fmt::format("{:+03}", fmt::join(t5, ", ")), "-03, +100, +01");
  258. auto t6 = std::tuple<float, double, long double>(3, 3.14, 3.1415);
  259. EXPECT_EQ(fmt::format("{:5.5f}", fmt::join(t6, ", ")),
  260. "3.00000, 3.14000, 3.14150");
  261. // Testing lvalue tuple args.
  262. int y = -1;
  263. auto t7 = std::tuple<int, int&, const int&>(3, y, y);
  264. EXPECT_EQ(fmt::format("{:03}", fmt::join(t7, ", ")), "003, -01, -01");
  265. # endif
  266. }
  267. TEST(ranges_test, join_initializer_list) {
  268. EXPECT_EQ(fmt::format("{}", fmt::join({1, 2, 3}, ", ")), "1, 2, 3");
  269. EXPECT_EQ(fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " ")),
  270. "fmt rocks !");
  271. }
  272. struct zstring_sentinel {};
  273. bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; }
  274. bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; }
  275. struct zstring {
  276. const char* p;
  277. const char* begin() const { return p; }
  278. zstring_sentinel end() const { return {}; }
  279. };
  280. # ifdef __cpp_lib_ranges
  281. struct cpp20_only_range {
  282. struct iterator {
  283. int val = 0;
  284. using value_type = int;
  285. using difference_type = std::ptrdiff_t;
  286. using iterator_concept = std::input_iterator_tag;
  287. iterator() = default;
  288. iterator(int i) : val(i) {}
  289. int operator*() const { return val; }
  290. iterator& operator++() {
  291. ++val;
  292. return *this;
  293. }
  294. void operator++(int) { ++*this; }
  295. bool operator==(const iterator& rhs) const { return val == rhs.val; }
  296. };
  297. int lo;
  298. int hi;
  299. iterator begin() const { return iterator(lo); }
  300. iterator end() const { return iterator(hi); }
  301. };
  302. static_assert(std::input_iterator<cpp20_only_range::iterator>);
  303. # endif
  304. TEST(ranges_test, join_sentinel) {
  305. auto hello = zstring{"hello"};
  306. EXPECT_EQ(fmt::format("{}", hello), "['h', 'e', 'l', 'l', 'o']");
  307. EXPECT_EQ(fmt::format("{::}", hello), "[h, e, l, l, o]");
  308. EXPECT_EQ(fmt::format("{}", fmt::join(hello, "_")), "h_e_l_l_o");
  309. }
  310. TEST(ranges_test, join_range) {
  311. noncopyable_range<int> w(3u, 0);
  312. EXPECT_EQ(fmt::format("{}", fmt::join(w, ",")), "0,0,0");
  313. EXPECT_EQ(fmt::format("{}", fmt::join(noncopyable_range<int>(3u, 0), ",")),
  314. "0,0,0");
  315. non_const_only_range<int> x(3u, 0);
  316. EXPECT_EQ(fmt::format("{}", fmt::join(x, ",")), "0,0,0");
  317. EXPECT_EQ(fmt::format("{}", fmt::join(non_const_only_range<int>(3u, 0), ",")),
  318. "0,0,0");
  319. auto y = std::vector<int>(3u, 0);
  320. EXPECT_EQ(fmt::format("{}", fmt::join(y, ",")), "0,0,0");
  321. EXPECT_EQ(fmt::format("{}", fmt::join(std::vector<int>(3u, 0), ",")),
  322. "0,0,0");
  323. const auto z = std::vector<int>(3u, 0);
  324. EXPECT_EQ(fmt::format("{}", fmt::join(z, ",")), "0,0,0");
  325. # ifdef __cpp_lib_ranges
  326. EXPECT_EQ(fmt::format("{}", cpp20_only_range{.lo = 0, .hi = 5}),
  327. "[0, 1, 2, 3, 4]");
  328. EXPECT_EQ(
  329. fmt::format("{}", fmt::join(cpp20_only_range{.lo = 0, .hi = 5}, ",")),
  330. "0,1,2,3,4");
  331. # endif
  332. }
  333. #endif // FMT_RANGES_TEST_ENABLE_JOIN
  334. TEST(ranges_test, is_printable) {
  335. using fmt::detail::is_printable;
  336. EXPECT_TRUE(is_printable(0x0323));
  337. EXPECT_FALSE(is_printable(0x0378));
  338. EXPECT_FALSE(is_printable(0x110000));
  339. }
  340. TEST(ranges_test, escape) {
  341. using vec = std::vector<std::string>;
  342. EXPECT_EQ(fmt::format("{}", vec{"\n\r\t\"\\"}), "[\"\\n\\r\\t\\\"\\\\\"]");
  343. EXPECT_EQ(fmt::format("{}", vec{"\x07"}), "[\"\\x07\"]");
  344. EXPECT_EQ(fmt::format("{}", vec{"\x7f"}), "[\"\\x7f\"]");
  345. EXPECT_EQ(fmt::format("{}", vec{"n\xcc\x83"}), "[\"n\xcc\x83\"]");
  346. if (fmt::detail::is_utf8()) {
  347. EXPECT_EQ(fmt::format("{}", vec{"\xcd\xb8"}), "[\"\\u0378\"]");
  348. // Unassigned Unicode code points.
  349. EXPECT_EQ(fmt::format("{}", vec{"\xf0\xaa\x9b\x9e"}), "[\"\\U0002a6de\"]");
  350. // Broken utf-8.
  351. EXPECT_EQ(fmt::format("{}", vec{"\xf4\x8f\xbf\xc0"}),
  352. "[\"\\xf4\\x8f\\xbf\\xc0\"]");
  353. EXPECT_EQ(fmt::format("{}", vec{"\xf0\x28"}), "[\"\\xf0(\"]");
  354. EXPECT_EQ(fmt::format("{}", vec{"\xe1\x28"}), "[\"\\xe1(\"]");
  355. EXPECT_EQ(fmt::format("{}", vec{std::string("\xf0\x28\0\0anything", 12)}),
  356. "[\"\\xf0(\\x00\\x00anything\"]");
  357. // Correct utf-8.
  358. EXPECT_EQ(fmt::format("{}", vec{"🦄"}), "[\"🦄\"]");
  359. }
  360. EXPECT_EQ(fmt::format("{}", std::vector<std::vector<char>>{{'x'}}),
  361. "[['x']]");
  362. EXPECT_EQ(fmt::format("{}", std::tuple<std::vector<char>>{{'x'}}), "(['x'])");
  363. }
  364. template <typename R> struct fmt_ref_view {
  365. R* r;
  366. auto begin() const -> decltype(r->begin()) { return r->begin(); }
  367. auto end() const -> decltype(r->end()) { return r->end(); }
  368. };
  369. TEST(ranges_test, range_of_range_of_mixed_const) {
  370. std::vector<std::vector<int>> v = {{1, 2, 3}, {4, 5}};
  371. EXPECT_EQ(fmt::format("{}", v), "[[1, 2, 3], [4, 5]]");
  372. fmt_ref_view<decltype(v)> r{&v};
  373. EXPECT_EQ(fmt::format("{}", r), "[[1, 2, 3], [4, 5]]");
  374. }
  375. TEST(ranges_test, vector_char) {
  376. EXPECT_EQ(fmt::format("{}", std::vector<char>{'a', 'b'}), "['a', 'b']");
  377. }
  378. TEST(ranges_test, container_adaptor) {
  379. {
  380. using fmt::detail::is_container_adaptor_like;
  381. using T = std::nullptr_t;
  382. static_assert(is_container_adaptor_like<std::stack<T>>::value, "");
  383. static_assert(is_container_adaptor_like<std::queue<T>>::value, "");
  384. static_assert(is_container_adaptor_like<std::priority_queue<T>>::value, "");
  385. static_assert(!is_container_adaptor_like<std::vector<T>>::value, "");
  386. }
  387. {
  388. auto s = std::stack<int>();
  389. s.push(1);
  390. s.push(2);
  391. EXPECT_EQ(fmt::format("{}", s), "[1, 2]");
  392. EXPECT_EQ(fmt::format("{}", const_cast<const decltype(s)&>(s)), "[1, 2]");
  393. }
  394. {
  395. auto q = std::queue<int>();
  396. q.push(1);
  397. q.push(2);
  398. EXPECT_EQ(fmt::format("{}", q), "[1, 2]");
  399. }
  400. {
  401. auto q = std::priority_queue<int>();
  402. q.push(3);
  403. q.push(1);
  404. q.push(2);
  405. q.push(4);
  406. EXPECT_EQ(fmt::format("{}", q), "[4, 3, 2, 1]");
  407. }
  408. {
  409. auto s = std::stack<char, std::string>();
  410. s.push('a');
  411. s.push('b');
  412. // See https://cplusplus.github.io/LWG/issue3881.
  413. EXPECT_EQ(fmt::format("{}", s), "['a', 'b']");
  414. }
  415. {
  416. struct my_container_adaptor {
  417. using value_type = int;
  418. using container_type = std::vector<value_type>;
  419. void push(const value_type& v) { c.push_back(v); }
  420. protected:
  421. container_type c;
  422. };
  423. auto m = my_container_adaptor();
  424. m.push(1);
  425. m.push(2);
  426. EXPECT_EQ(fmt::format("{}", m), "[1, 2]");
  427. }
  428. }