Debian Codegraph @

llvm/unittests/ADT/IteratorTest.cpp

raw
1 //===- IteratorTest.cpp - Unit tests for iterator utilities ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ADT/iterator.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/ilist.h"
14 #include "gmock/gmock.h"
15 #include "gtest/gtest.h"
16 #include <optional>
17 #include <type_traits>
18 #include <vector>
19
20 using namespace llvm;
21 using testing::ElementsAre;
22
23 namespace {
24
25 namespace adl_test {
26 struct WithFreeBeginEnd {
27 int data[3] = {21, 22, 23};
28 };
29
30 auto begin(const WithFreeBeginEnd &X) { return std::begin(X.data); }
31 auto end(const WithFreeBeginEnd &X) { return std::end(X.data); }
32
33 struct WithFreeRBeginREnd {
34 int data[3] = {42, 43, 44};
35 };
36
37 auto rbegin(const WithFreeRBeginREnd &X) { return std::rbegin(X.data); }
38 auto rend(const WithFreeRBeginREnd &X) { return std::rend(X.data); }
39 } // namespace adl_test
40
41 template <int> struct Shadow;
42
43 struct WeirdIter
44 : llvm::iterator_facade_base<WeirdIter, std::input_iterator_tag, Shadow<0>,
45 Shadow<1>, Shadow<2>, Shadow<3>> {};
46
47 struct AdaptedIter : iterator_adaptor_base<AdaptedIter, WeirdIter> {};
48
49 // Test that iterator_adaptor_base forwards typedefs, if value_type is
50 // unchanged.
51 static_assert(std::is_same_v<typename AdaptedIter::value_type, Shadow<0>>, "");
52 static_assert(std::is_same_v<typename AdaptedIter::difference_type, Shadow<1>>,
53 "");
54 static_assert(std::is_same_v<typename AdaptedIter::pointer, Shadow<2>>, "");
55 static_assert(std::is_same_v<typename AdaptedIter::reference, Shadow<3>>, "");
56
57 // Ensure that pointe{e,r}_iterator adaptors correctly forward the category of
58 // the underlying iterator.
59
60 using RandomAccessIter = SmallVectorImpl<int*>::iterator;
61 using BidiIter = ilist<int*>::iterator;
62
63 template<class T>
64 using pointee_iterator_defaulted = pointee_iterator<T>;
65 template<class T>
66 using pointer_iterator_defaulted = pointer_iterator<T>;
67
68 // Ensures that an iterator and its adaptation have the same iterator_category.
69 template<template<typename> class A, typename It>
70 using IsAdaptedIterCategorySame =
71 std::is_same<typename std::iterator_traits<It>::iterator_category,
72 typename std::iterator_traits<A<It>>::iterator_category>;
73
74 // Check that dereferencing works correctly adapting pointers and proxies.
75 template <class T>
76 struct PointerWrapper : public iterator_adaptor_base<PointerWrapper<T>, T *> {
77 PointerWrapper(T *I) : PointerWrapper::iterator_adaptor_base(I) {}
78 };
79 struct IntProxy {
80 int &I;
81 IntProxy(int &I) : I(I) {}
82 void operator=(int NewValue) { I = NewValue; }
83 };
84 struct ConstIntProxy {
85 const int &I;
86 ConstIntProxy(const int &I) : I(I) {}
87 };
88 template <class T, class ProxyT>
89 struct PointerProxyWrapper
90 : public iterator_adaptor_base<PointerProxyWrapper<T, ProxyT>, T *,
91 std::random_access_iterator_tag, T,
92 ptrdiff_t, T *, ProxyT> {
93 PointerProxyWrapper(T *I) : PointerProxyWrapper::iterator_adaptor_base(I) {}
94 };
95 using IntIterator = PointerWrapper<int>;
96 using ConstIntIterator = PointerWrapper<const int>;
97 using IntProxyIterator = PointerProxyWrapper<int, IntProxy>;
98 using ConstIntProxyIterator = PointerProxyWrapper<const int, ConstIntProxy>;
99
100 // There should only be a single (const-qualified) operator*, operator->, and
101 // operator[]. This test confirms that there isn't a non-const overload. Rather
102 // than adding those, users should double-check that T, PointerT, and ReferenceT
103 // have the right constness, and/or make fields mutable.
104 static_assert(&IntIterator::operator* == &IntIterator::operator*, "");
105 static_assert(&IntIterator::operator-> == &IntIterator::operator->, "");
106 static_assert(&IntIterator::operator[] == &IntIterator::operator[], "");
107
108 template <class T, std::enable_if_t<std::is_assignable_v<T, int>, bool> = false>
109 constexpr bool canAssignFromInt(T &&) {
110 return true;
111 }
112 template <class T,
113 std::enable_if_t<!std::is_assignable_v<T, int>, bool> = false>
114 constexpr bool canAssignFromInt(T &&) {
115 return false;
116 }
117
118 TEST(IteratorAdaptorTest, Dereference) {
119 int Number = 1;
120
121 // Construct some iterators and check whether they can be assigned to.
122 IntIterator I(&Number);
123 const IntIterator IC(&Number);
124 ConstIntIterator CI(&Number);
125 const ConstIntIterator CIC(&Number);
126 EXPECT_EQ(true, canAssignFromInt(*I)); // int *
127 EXPECT_EQ(true, canAssignFromInt(*IC)); // int *const
128 EXPECT_EQ(false, canAssignFromInt(*CI)); // const int *
129 EXPECT_EQ(false, canAssignFromInt(*CIC)); // const int *const
130
131 // Prove that dereference and assignment work.
132 EXPECT_EQ(1, *I);
133 EXPECT_EQ(1, *IC);
134 EXPECT_EQ(1, *CI);
135 EXPECT_EQ(1, *CIC);
136 *I = 2;
137 EXPECT_EQ(2, Number);
138 *IC = 3;
139 EXPECT_EQ(3, Number);
140
141 // Construct some proxy iterators and check whether they can be assigned to.
142 IntProxyIterator P(&Number);
143 const IntProxyIterator PC(&Number);
144 ConstIntProxyIterator CP(&Number);
145 const ConstIntProxyIterator CPC(&Number);
146 EXPECT_EQ(true, canAssignFromInt(*P)); // int *
147 EXPECT_EQ(true, canAssignFromInt(*PC)); // int *const
148 EXPECT_EQ(false, canAssignFromInt(*CP)); // const int *
149 EXPECT_EQ(false, canAssignFromInt(*CPC)); // const int *const
150
151 // Prove that dereference and assignment work.
152 EXPECT_EQ(3, (*P).I);
153 EXPECT_EQ(3, (*PC).I);
154 EXPECT_EQ(3, (*CP).I);
155 EXPECT_EQ(3, (*CPC).I);
156 *P = 4;
157 EXPECT_EQ(4, Number);
158 *PC = 5;
159 EXPECT_EQ(5, Number);
160 }
161
162 // pointeE_iterator
163 static_assert(IsAdaptedIterCategorySame<pointee_iterator_defaulted,
164 RandomAccessIter>::value, "");
165 static_assert(IsAdaptedIterCategorySame<pointee_iterator_defaulted,
166 BidiIter>::value, "");
167 // pointeR_iterator
168 static_assert(IsAdaptedIterCategorySame<pointer_iterator_defaulted,
169 RandomAccessIter>::value, "");
170 static_assert(IsAdaptedIterCategorySame<pointer_iterator_defaulted,
171 BidiIter>::value, "");
172
173 TEST(PointeeIteratorTest, Basic) {
174 int arr[4] = {1, 2, 3, 4};
175 SmallVector<int *, 4> V;
176 V.push_back(&arr[0]);
177 V.push_back(&arr[1]);
178 V.push_back(&arr[2]);
179 V.push_back(&arr[3]);
180
181 typedef pointee_iterator<SmallVectorImpl<int *>::const_iterator>
182 test_iterator;
183
184 test_iterator Begin, End;
185 Begin = V.begin();
186 End = test_iterator(V.end());
187
188 test_iterator I = Begin;
189 for (int i = 0; i < 4; ++i) {
190 EXPECT_EQ(*V[i], *I);
191
192 EXPECT_EQ(I, Begin + i);
193 EXPECT_EQ(I, std::next(Begin, i));
194 test_iterator J = Begin;
195 J += i;
196 EXPECT_EQ(I, J);
197 EXPECT_EQ(*V[i], Begin[i]);
198
199 EXPECT_NE(I, End);
200 EXPECT_GT(End, I);
201 EXPECT_LT(I, End);
202 EXPECT_GE(I, Begin);
203 EXPECT_LE(Begin, I);
204
205 EXPECT_EQ(i, I - Begin);
206 EXPECT_EQ(i, std::distance(Begin, I));
207 EXPECT_EQ(Begin, I - i);
208
209 test_iterator K = I++;
210 EXPECT_EQ(K, std::prev(I));
211 }
212 EXPECT_EQ(End, I);
213 }
214
215 TEST(PointeeIteratorTest, SmartPointer) {
216 SmallVector<std::unique_ptr<int>, 4> V;
217 V.push_back(std::make_unique<int>(1));
218 V.push_back(std::make_unique<int>(2));
219 V.push_back(std::make_unique<int>(3));
220 V.push_back(std::make_unique<int>(4));
221
222 typedef pointee_iterator<
223 SmallVectorImpl<std::unique_ptr<int>>::const_iterator>
224 test_iterator;
225
226 test_iterator Begin, End;
227 Begin = V.begin();
228 End = test_iterator(V.end());
229
230 test_iterator I = Begin;
231 for (int i = 0; i < 4; ++i) {
232 EXPECT_EQ(*V[i], *I);
233
234 EXPECT_EQ(I, Begin + i);
235 EXPECT_EQ(I, std::next(Begin, i));
236 test_iterator J = Begin;
237 J += i;
238 EXPECT_EQ(I, J);
239 EXPECT_EQ(*V[i], Begin[i]);
240
241 EXPECT_NE(I, End);
242 EXPECT_GT(End, I);
243 EXPECT_LT(I, End);
244 EXPECT_GE(I, Begin);
245 EXPECT_LE(Begin, I);
246
247 EXPECT_EQ(i, I - Begin);
248 EXPECT_EQ(i, std::distance(Begin, I));
249 EXPECT_EQ(Begin, I - i);
250
251 test_iterator K = I++;
252 EXPECT_EQ(K, std::prev(I));
253 }
254 EXPECT_EQ(End, I);
255 }
256
257 TEST(PointeeIteratorTest, Range) {
258 int A[] = {1, 2, 3, 4};
259 SmallVector<int *, 4> V{&A[0], &A[1], &A[2], &A[3]};
260
261 int I = 0;
262 for (int II : make_pointee_range(V))
263 EXPECT_EQ(A[I++], II);
264 }
265
266 TEST(PointeeIteratorTest, PointeeType) {
267 struct S {
268 int X;
269 bool operator==(const S &RHS) const { return X == RHS.X; };
270 };
271 S A[] = {S{0}, S{1}};
272 SmallVector<S *, 2> V{&A[0], &A[1]};
273
274 pointee_iterator<SmallVectorImpl<S *>::const_iterator, const S> I = V.begin();
275 for (int j = 0; j < 2; ++j, ++I) {
276 EXPECT_EQ(*V[j], *I);
277 }
278 }
279
280 TEST(FilterIteratorTest, Lambda) {
281 auto IsOdd = [](int N) { return N % 2 == 1; };
282 int A[] = {0, 1, 2, 3, 4, 5, 6};
283 auto Range = make_filter_range(A, IsOdd);
284 SmallVector<int, 3> Actual(Range.begin(), Range.end());
285 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
286 }
287
288 TEST(FilterIteratorTest, Enumerate) {
289 auto IsOdd = [](auto N) { return N.value() % 2 == 1; };
290 int A[] = {0, 1, 2, 3, 4, 5, 6};
291 auto Enumerate = llvm::enumerate(A);
292 SmallVector<int> Actual;
293 for (const auto &IndexedValue : make_filter_range(Enumerate, IsOdd))
294 Actual.push_back(IndexedValue.value());
295 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
296 }
297
298 TEST(FilterIteratorTest, CallableObject) {
299 int Counter = 0;
300 struct Callable {
301 int &Counter;
302
303 Callable(int &Counter) : Counter(Counter) {}
304
305 bool operator()(int N) {
306 Counter++;
307 return N % 2 == 1;
308 }
309 };
310 Callable IsOdd(Counter);
311 int A[] = {0, 1, 2, 3, 4, 5, 6};
312 auto Range = make_filter_range(A, IsOdd);
313 EXPECT_EQ(2, Counter);
314 SmallVector<int, 3> Actual(Range.begin(), Range.end());
315 EXPECT_GE(Counter, 7);
316 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
317 }
318
319 TEST(FilterIteratorTest, FunctionPointer) {
320 bool (*IsOdd)(int) = [](int N) { return N % 2 == 1; };
321 int A[] = {0, 1, 2, 3, 4, 5, 6};
322 auto Range = make_filter_range(A, IsOdd);
323 SmallVector<int, 3> Actual(Range.begin(), Range.end());
324 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
325 }
326
327 TEST(FilterIteratorTest, Composition) {
328 auto IsOdd = [](int N) { return N % 2 == 1; };
329 std::unique_ptr<int> A[] = {std::make_unique<int>(0), std::make_unique<int>(1),
330 std::make_unique<int>(2), std::make_unique<int>(3),
331 std::make_unique<int>(4), std::make_unique<int>(5),
332 std::make_unique<int>(6)};
333 using PointeeIterator = pointee_iterator<std::unique_ptr<int> *>;
334 auto Range = make_filter_range(
335 make_range(PointeeIterator(std::begin(A)), PointeeIterator(std::end(A))),
336 IsOdd);
337 SmallVector<int, 3> Actual(Range.begin(), Range.end());
338 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
339 }
340
341 TEST(FilterIteratorTest, InputIterator) {
342 struct InputIterator
343 : iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag> {
344 InputIterator(int *It) : InputIterator::iterator_adaptor_base(It) {}
345 };
346
347 auto IsOdd = [](int N) { return N % 2 == 1; };
348 int A[] = {0, 1, 2, 3, 4, 5, 6};
349 auto Range = make_filter_range(
350 make_range(InputIterator(std::begin(A)), InputIterator(std::end(A))),
351 IsOdd);
352 SmallVector<int, 3> Actual(Range.begin(), Range.end());
353 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
354 }
355
356 TEST(FilterIteratorTest, ReverseFilterRange) {
357 auto IsOdd = [](int N) { return N % 2 == 1; };
358 int A[] = {0, 1, 2, 3, 4, 5, 6};
359
360 // Check basic reversal.
361 auto Range = reverse(make_filter_range(A, IsOdd));
362 SmallVector<int, 3> Actual(Range.begin(), Range.end());
363 EXPECT_EQ((SmallVector<int, 3>{5, 3, 1}), Actual);
364
365 // Check that the reverse of the reverse is the original.
366 auto Range2 = reverse(reverse(make_filter_range(A, IsOdd)));
367 SmallVector<int, 3> Actual2(Range2.begin(), Range2.end());
368 EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual2);
369
370 // Check empty ranges.
371 auto Range3 = reverse(make_filter_range(ArrayRef<int>(), IsOdd));
372 SmallVector<int, 0> Actual3(Range3.begin(), Range3.end());
373 EXPECT_EQ((SmallVector<int, 0>{}), Actual3);
374
375 // Check that we don't skip the first element, provided it isn't filtered
376 // away.
377 auto IsEven = [](int N) { return N % 2 == 0; };
378 auto Range4 = reverse(make_filter_range(A, IsEven));
379 SmallVector<int, 4> Actual4(Range4.begin(), Range4.end());
380 EXPECT_EQ((SmallVector<int, 4>{6, 4, 2, 0}), Actual4);
381 }
382
383 TEST(FilterIteratorTest, ADL) {
384 // Make sure that we use the `begin`/`end` functions
385 // from `adl_test`, using ADL.
386 adl_test::WithFreeBeginEnd R;
387 auto IsOdd = [](int N) { return N % 2 != 0; };
388 EXPECT_THAT(make_filter_range(R, IsOdd), ElementsAre(21, 23));
389 }
390
391 TEST(PointerIterator, Basic) {
392 int A[] = {1, 2, 3, 4};
393 pointer_iterator<int *> Begin(std::begin(A)), End(std::end(A));
394 EXPECT_EQ(A, *Begin);
395 ++Begin;
396 EXPECT_EQ(A + 1, *Begin);
397 ++Begin;
398 EXPECT_EQ(A + 2, *Begin);
399 ++Begin;
400 EXPECT_EQ(A + 3, *Begin);
401 ++Begin;
402 EXPECT_EQ(Begin, End);
403 }
404
405 TEST(PointerIterator, Const) {
406 int A[] = {1, 2, 3, 4};
407 const pointer_iterator<int *> Begin(std::begin(A));
408 EXPECT_EQ(A, *Begin);
409 EXPECT_EQ(A + 1, std::next(*Begin, 1));
410 EXPECT_EQ(A + 2, std::next(*Begin, 2));
411 EXPECT_EQ(A + 3, std::next(*Begin, 3));
412 EXPECT_EQ(A + 4, std::next(*Begin, 4));
413 }
414
415 TEST(PointerIterator, Range) {
416 int A[] = {1, 2, 3, 4};
417 int I = 0;
418 for (int *P : make_pointer_range(A))
419 EXPECT_EQ(A + I++, P);
420 }
421
422 TEST(ReverseTest, ADL) {
423 // Check that we can find the rbegin/rend functions via ADL.
424 adl_test::WithFreeRBeginREnd Foo;
425 EXPECT_THAT(reverse(Foo), ElementsAre(44, 43, 42));
426 }
427
428 TEST(ZipIteratorTest, Basic) {
429 using namespace std;
430 const SmallVector<unsigned, 6> pi{3, 1, 4, 1, 5, 9};
431 SmallVector<bool, 6> odd{1, 1, 0, 1, 1, 1};
432 const char message[] = "yynyyy\0";
433 std::array<int, 2> shortArr = {42, 43};
434
435 for (auto tup : zip(pi, odd, message)) {
436 EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup));
437 EXPECT_EQ(get<0>(tup) & 0x01 ? 'y' : 'n', get<2>(tup));
438 }
439
440 // Note the rvalue.
441 for (auto tup : zip(pi, SmallVector<bool, 0>{1, 1, 0, 1, 1})) {
442 EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup));
443 }
444
445 // Iterate until we run out elements in the *shortest* range.
446 for (auto [idx, elem] : enumerate(zip(odd, shortArr))) {
447 EXPECT_LT(idx, static_cast<size_t>(2));
448 }
449 for (auto [idx, elem] : enumerate(zip(shortArr, odd))) {
450 EXPECT_LT(idx, static_cast<size_t>(2));
451 }
452 }
453
454 TEST(ZipIteratorTest, ZipEqualBasic) {
455 const SmallVector<unsigned, 6> pi = {3, 1, 4, 1, 5, 8};
456 const SmallVector<bool, 6> vals = {1, 1, 0, 1, 1, 0};
457 unsigned iters = 0;
458
459 for (auto [lhs, rhs] : zip_equal(vals, pi)) {
460 EXPECT_EQ(lhs, rhs & 0x01);
461 ++iters;
462 }
463
464 EXPECT_EQ(iters, 6u);
465 }
466
467 template <typename T>
468 constexpr bool IsConstRef =
469 std::is_reference_v<T> && std::is_const_v<std::remove_reference_t<T>>;
470
471 template <typename T>
472 constexpr bool IsBoolConstRef =
473 std::is_same_v<llvm::remove_cvref_t<T>, std::vector<bool>::const_reference>;
474
475 /// Returns a `const` copy of the passed value. The `const` on the returned
476 /// value is intentional here so that `MakeConst` can be used in range-for
477 /// loops.
478 template <typename T> const T MakeConst(T &&value) {
479 return std::forward<T>(value);
480 }
481
482 TEST(ZipIteratorTest, ZipEqualConstCorrectness) {
483 const std::vector<unsigned> c_first = {3, 1, 4};
484 std::vector<unsigned> first = c_first;
485 const SmallVector<bool> c_second = {1, 1, 0};
486 SmallVector<bool> second = c_second;
487
488 for (auto [a, b, c, d] : zip_equal(c_first, first, c_second, second)) {
489 b = 0;
490 d = true;
491 static_assert(IsConstRef<decltype(a)>);
492 static_assert(!IsConstRef<decltype(b)>);
493 static_assert(IsConstRef<decltype(c)>);
494 static_assert(!IsConstRef<decltype(d)>);
495 }
496
497 EXPECT_THAT(first, ElementsAre(0, 0, 0));
498 EXPECT_THAT(second, ElementsAre(true, true, true));
499
500 std::vector<bool> nemesis = {true, false, true};
501 const std::vector<bool> c_nemesis = nemesis;
502
503 for (auto &&[a, b, c, d] : zip_equal(first, c_first, nemesis, c_nemesis)) {
504 a = 2;
505 c = true;
506 static_assert(!IsConstRef<decltype(a)>);
507 static_assert(IsConstRef<decltype(b)>);
508 static_assert(!IsBoolConstRef<decltype(c)>);
509 static_assert(IsBoolConstRef<decltype(d)>);
510 }
511
512 EXPECT_THAT(first, ElementsAre(2, 2, 2));
513 EXPECT_THAT(nemesis, ElementsAre(true, true, true));
514
515 unsigned iters = 0;
516 for (const auto &[a, b, c, d] :
517 zip_equal(first, c_first, nemesis, c_nemesis)) {
518 static_assert(!IsConstRef<decltype(a)>);
519 static_assert(IsConstRef<decltype(b)>);
520 static_assert(!IsBoolConstRef<decltype(c)>);
521 static_assert(IsBoolConstRef<decltype(d)>);
522 ++iters;
523 }
524 EXPECT_EQ(iters, 3u);
525 iters = 0;
526
527 for (const auto &[a, b, c, d] :
528 MakeConst(zip_equal(first, c_first, nemesis, c_nemesis))) {
529 static_assert(!IsConstRef<decltype(a)>);
530 static_assert(IsConstRef<decltype(b)>);
531 static_assert(!IsBoolConstRef<decltype(c)>);
532 static_assert(IsBoolConstRef<decltype(d)>);
533 ++iters;
534 }
535 EXPECT_EQ(iters, 3u);
536 }
537
538 TEST(ZipIteratorTest, ZipEqualTemporaries) {
539 unsigned iters = 0;
540
541 // These temporary ranges get moved into the `tuple<...> storage;` inside
542 // `zippy`. From then on, we can use references obtained from this storage to
543 // access them. This does not rely on any lifetime extensions on the
544 // temporaries passed to `zip_equal`.
545 for (auto [a, b, c] : zip_equal(SmallVector<int>{1, 2, 3}, std::string("abc"),
546 std::vector<bool>{true, false, true})) {
547 a = 3;
548 b = 'c';
549 c = false;
550 static_assert(!IsConstRef<decltype(a)>);
551 static_assert(!IsConstRef<decltype(b)>);
552 static_assert(!IsBoolConstRef<decltype(c)>);
553 ++iters;
554 }
555 EXPECT_EQ(iters, 3u);
556 iters = 0;
557
558 for (auto [a, b, c] :
559 MakeConst(zip_equal(SmallVector<int>{1, 2, 3}, std::string("abc"),
560 std::vector<bool>{true, false, true}))) {
561 static_assert(IsConstRef<decltype(a)>);
562 static_assert(IsConstRef<decltype(b)>);
563 static_assert(IsBoolConstRef<decltype(c)>);
564 ++iters;
565 }
566 EXPECT_EQ(iters, 3u);
567 }
568
569 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
570 // Check that an assertion is triggered when ranges passed to `zip_equal` differ
571 // in length.
572 TEST(ZipIteratorTest, ZipEqualNotEqual) {
573 const SmallVector<unsigned, 6> pi = {3, 1, 4, 1, 5, 8};
574 const SmallVector<bool, 2> vals = {1, 1};
575
576 EXPECT_DEATH(zip_equal(pi, vals), "Iteratees do not have equal length");
577 EXPECT_DEATH(zip_equal(vals, pi), "Iteratees do not have equal length");
578 EXPECT_DEATH(zip_equal(pi, pi, vals), "Iteratees do not have equal length");
579 EXPECT_DEATH(zip_equal(vals, vals, pi), "Iteratees do not have equal length");
580 }
581 #endif
582
583 TEST(ZipIteratorTest, ZipFirstBasic) {
584 using namespace std;
585 const SmallVector<unsigned, 6> pi{3, 1, 4, 1, 5, 9};
586 unsigned iters = 0;
587
588 for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) {
589 EXPECT_EQ(get<0>(tup), get<1>(tup) & 0x01);
590 iters += 1;
591 }
592
593 EXPECT_EQ(iters, 4u);
594 }
595
596 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
597 // Make sure that we can detect when the first range is not the shortest.
598 TEST(ZipIteratorTest, ZipFirstNotShortest) {
599 const std::array<unsigned, 6> longer = {};
600 const std::array<unsigned, 4> shorter = {};
601
602 EXPECT_DEATH(zip_first(longer, shorter),
603 "First iteratee is not the shortest");
604 EXPECT_DEATH(zip_first(longer, shorter, longer),
605 "First iteratee is not the shortest");
606 EXPECT_DEATH(zip_first(longer, longer, shorter),
607 "First iteratee is not the shortest");
608 }
609 #endif
610
611 TEST(ZipIteratorTest, ZipLongestBasic) {
612 using namespace std;
613 const vector<unsigned> pi{3, 1, 4, 1, 5, 9};
614 const vector<StringRef> e{"2", "7", "1", "8"};
615
616 {
617 // Check left range longer than right.
618 const vector<tuple<optional<unsigned>, optional<StringRef>>> expected{
619 make_tuple(3, StringRef("2")), make_tuple(1, StringRef("7")),
620 make_tuple(4, StringRef("1")), make_tuple(1, StringRef("8")),
621 make_tuple(5, std::nullopt), make_tuple(9, std::nullopt)};
622 size_t iters = 0;
623 for (auto tup : zip_longest(pi, e)) {
624 EXPECT_EQ(tup, expected[iters]);
625 iters += 1;
626 }
627 EXPECT_EQ(iters, expected.size());
628 }
629
630 {
631 // Check right range longer than left.
632 const vector<tuple<optional<StringRef>, optional<unsigned>>> expected{
633 make_tuple(StringRef("2"), 3), make_tuple(StringRef("7"), 1),
634 make_tuple(StringRef("1"), 4), make_tuple(StringRef("8"), 1),
635 make_tuple(std::nullopt, 5), make_tuple(std::nullopt, 9)};
636 size_t iters = 0;
637 for (auto tup : zip_longest(e, pi)) {
638 EXPECT_EQ(tup, expected[iters]);
639 iters += 1;
640 }
641 EXPECT_EQ(iters, expected.size());
642 }
643 }
644
645 TEST(ZipIteratorTest, Mutability) {
646 using namespace std;
647 const SmallVector<unsigned, 4> pi{3, 1, 4, 1, 5, 9};
648 char message[] = "hello zip\0";
649
650 for (auto tup : zip(pi, message, message)) {
651 EXPECT_EQ(get<1>(tup), get<2>(tup));
652 get<2>(tup) = get<0>(tup) & 0x01 ? 'y' : 'n';
653 }
654
655 // note the rvalue
656 for (auto tup : zip(message, "yynyyyzip\0")) {
657 EXPECT_EQ(get<0>(tup), get<1>(tup));
658 }
659 }
660
661 TEST(ZipIteratorTest, ZipFirstMutability) {
662 using namespace std;
663 vector<unsigned> pi{3, 1, 4, 1, 5, 9};
664 unsigned iters = 0;
665
666 for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) {
667 get<1>(tup) = get<0>(tup);
668 iters += 1;
669 }
670
671 EXPECT_EQ(iters, 4u);
672
673 for (auto tup : zip_first(SmallVector<bool, 0>{1, 1, 0, 1}, pi)) {
674 EXPECT_EQ(get<0>(tup), get<1>(tup));
675 }
676 }
677
678 TEST(ZipIteratorTest, Filter) {
679 using namespace std;
680 vector<unsigned> pi{3, 1, 4, 1, 5, 9};
681
682 unsigned iters = 0;
683 // pi is length 6, but the zip RHS is length 7.
684 auto zipped = zip_first(pi, vector<bool>{1, 1, 0, 1, 1, 1, 0});
685 for (auto tup : make_filter_range(
686 zipped, [](decltype(zipped)::value_type t) { return get<1>(t); })) {
687 EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup));
688 get<0>(tup) += 1;
689 iters += 1;
690 }
691
692 // Should have skipped pi[2].
693 EXPECT_EQ(iters, 5u);
694
695 // Ensure that in-place mutation works.
696 EXPECT_TRUE(all_of(pi, [](unsigned n) { return (n & 0x01) == 0; }));
697 }
698
699 TEST(ZipIteratorTest, Reverse) {
700 using namespace std;
701 vector<unsigned> ascending{0, 1, 2, 3, 4, 5};
702
703 auto zipped = zip_first(ascending, vector<bool>{0, 1, 0, 1, 0, 1});
704 unsigned last = 6;
705 for (auto tup : reverse(zipped)) {
706 // Check that this is in reverse.
707 EXPECT_LT(get<0>(tup), last);
708 last = get<0>(tup);
709 EXPECT_EQ(get<0>(tup) & 0x01, get<1>(tup));
710 }
711
712 auto odds = [](decltype(zipped)::value_type tup) { return get<1>(tup); };
713 last = 6;
714 for (auto tup : make_filter_range(reverse(zipped), odds)) {
715 EXPECT_LT(get<0>(tup), last);
716 last = get<0>(tup);
717 EXPECT_TRUE(get<0>(tup) & 0x01);
718 get<0>(tup) += 1;
719 }
720
721 // Ensure that in-place mutation works.
722 EXPECT_TRUE(all_of(ascending, [](unsigned n) { return (n & 0x01) == 0; }));
723 }
724
725 // Int iterator that keeps track of the number of its copies.
726 struct CountingIntIterator : IntIterator {
727 unsigned *cnt;
728
729 CountingIntIterator(int *it, unsigned &counter)
730 : IntIterator(it), cnt(&counter) {}
731
732 CountingIntIterator(const CountingIntIterator &other)
733 : IntIterator(other.I), cnt(other.cnt) {
734 ++(*cnt);
735 }
736 CountingIntIterator &operator=(const CountingIntIterator &other) {
737 this->I = other.I;
738 this->cnt = other.cnt;
739 ++(*cnt);
740 return *this;
741 }
742 };
743
744 // Check that the iterators do not get copied with each `zippy` iterator
745 // increment.
746 TEST(ZipIteratorTest, IteratorCopies) {
747 std::vector<int> ints(1000, 42);
748 unsigned total_copy_count = 0;
749 CountingIntIterator begin(ints.data(), total_copy_count);
750 CountingIntIterator end(ints.data() + ints.size(), total_copy_count);
751
752 size_t iters = 0;
753 auto zippy = zip_equal(ints, llvm::make_range(begin, end));
754 const unsigned creation_copy_count = total_copy_count;
755
756 for (auto [a, b] : zippy) {
757 EXPECT_EQ(a, b);
758 ++iters;
759 }
760 EXPECT_EQ(iters, ints.size());
761
762 // We expect the number of copies to be much smaller than the number of loop
763 // iterations.
764 unsigned loop_copy_count = total_copy_count - creation_copy_count;
765 EXPECT_LT(loop_copy_count, 10u);
766 }
767
768 TEST(RangeTest, Distance) {
769 std::vector<int> v1;
770 std::vector<int> v2{1, 2, 3};
771
772 EXPECT_EQ(std::distance(v1.begin(), v1.end()), size(v1));
773 EXPECT_EQ(std::distance(v2.begin(), v2.end()), size(v2));
774 }
775
776 TEST(RangeSizeTest, CommonRangeTypes) {
777 SmallVector<int> v1 = {1, 2, 3};
778 EXPECT_EQ(range_size(v1), 3u);
779
780 std::map<int, int> m1 = {{1, 1}, {2, 2}};
781 EXPECT_EQ(range_size(m1), 2u);
782
783 auto it_range = llvm::make_range(m1.begin(), m1.end());
784 EXPECT_EQ(range_size(it_range), 2u);
785
786 static constexpr int c_arr[5] = {};
787 static_assert(range_size(c_arr) == 5u);
788
789 static constexpr std::array<int, 6> cpp_arr = {};
790 static_assert(range_size(cpp_arr) == 6u);
791 }
792
793 struct FooWithMemberSize {
794 size_t size() const { return 42; }
795 auto begin() { return Data.begin(); }
796 auto end() { return Data.end(); }
797
798 std::set<int> Data;
799 };
800
801 TEST(RangeSizeTest, MemberSize) {
802 // Make sure that member `.size()` is preferred over the free fuction and
803 // `std::distance`.
804 FooWithMemberSize container;
805 EXPECT_EQ(range_size(container), 42u);
806 }
807
808 struct FooWithFreeSize {
809 friend size_t size(const FooWithFreeSize &) { return 13; }
810 auto begin() { return Data.begin(); }
811 auto end() { return Data.end(); }
812
813 std::set<int> Data;
814 };
815
816 TEST(RangeSizeTest, FreeSize) {
817 // Make sure that `size(x)` is preferred over `std::distance`.
818 FooWithFreeSize container;
819 EXPECT_EQ(range_size(container), 13u);
820 }
821
822 struct FooWithDistance {
823 auto begin() { return Data.begin(); }
824 auto end() { return Data.end(); }
825
826 std::set<int> Data;
827 };
828
829 TEST(RangeSizeTest, Distance) {
830 // Make sure that we can fall back to `std::distance` even the iterator is not
831 // random-access.
832 FooWithDistance container;
833 EXPECT_EQ(range_size(container), 0u);
834 container.Data = {1, 2, 3, 4};
835 EXPECT_EQ(range_size(container), 4u);
836 }
837 } // anonymous namespace