1 //===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===//
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/STLExtras.h"
10 #include "gtest/gtest.h"
11
12 #include <climits>
13 #include <list>
14 #include <vector>
15
16 using namespace llvm;
17
18 namespace {
19
f(rank<0>)20 int f(rank<0>) { return 0; }
f(rank<1>)21 int f(rank<1>) { return 1; }
f(rank<2>)22 int f(rank<2>) { return 2; }
f(rank<4>)23 int f(rank<4>) { return 4; }
24
TEST(STLExtrasTest,Rank)25 TEST(STLExtrasTest, Rank) {
26 // We shouldn't get ambiguities and should select the overload of the same
27 // rank as the argument.
28 EXPECT_EQ(0, f(rank<0>()));
29 EXPECT_EQ(1, f(rank<1>()));
30 EXPECT_EQ(2, f(rank<2>()));
31
32 // This overload is missing so we end up back at 2.
33 EXPECT_EQ(2, f(rank<3>()));
34
35 // But going past 3 should work fine.
36 EXPECT_EQ(4, f(rank<4>()));
37
38 // And we can even go higher and just fall back to the last overload.
39 EXPECT_EQ(4, f(rank<5>()));
40 EXPECT_EQ(4, f(rank<6>()));
41 }
42
TEST(STLExtrasTest,EnumerateLValue)43 TEST(STLExtrasTest, EnumerateLValue) {
44 // Test that a simple LValue can be enumerated and gives correct results with
45 // multiple types, including the empty container.
46 std::vector<char> foo = {'a', 'b', 'c'};
47 typedef std::pair<std::size_t, char> CharPairType;
48 std::vector<CharPairType> CharResults;
49
50 for (auto X : llvm::enumerate(foo)) {
51 CharResults.emplace_back(X.index(), X.value());
52 }
53 ASSERT_EQ(3u, CharResults.size());
54 EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]);
55 EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]);
56 EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]);
57
58 // Test a const range of a different type.
59 typedef std::pair<std::size_t, int> IntPairType;
60 std::vector<IntPairType> IntResults;
61 const std::vector<int> bar = {1, 2, 3};
62 for (auto X : llvm::enumerate(bar)) {
63 IntResults.emplace_back(X.index(), X.value());
64 }
65 ASSERT_EQ(3u, IntResults.size());
66 EXPECT_EQ(IntPairType(0u, 1), IntResults[0]);
67 EXPECT_EQ(IntPairType(1u, 2), IntResults[1]);
68 EXPECT_EQ(IntPairType(2u, 3), IntResults[2]);
69
70 // Test an empty range.
71 IntResults.clear();
72 const std::vector<int> baz{};
73 for (auto X : llvm::enumerate(baz)) {
74 IntResults.emplace_back(X.index(), X.value());
75 }
76 EXPECT_TRUE(IntResults.empty());
77 }
78
TEST(STLExtrasTest,EnumerateModifyLValue)79 TEST(STLExtrasTest, EnumerateModifyLValue) {
80 // Test that you can modify the underlying entries of an lvalue range through
81 // the enumeration iterator.
82 std::vector<char> foo = {'a', 'b', 'c'};
83
84 for (auto X : llvm::enumerate(foo)) {
85 ++X.value();
86 }
87 EXPECT_EQ('b', foo[0]);
88 EXPECT_EQ('c', foo[1]);
89 EXPECT_EQ('d', foo[2]);
90 }
91
TEST(STLExtrasTest,EnumerateRValueRef)92 TEST(STLExtrasTest, EnumerateRValueRef) {
93 // Test that an rvalue can be enumerated.
94 typedef std::pair<std::size_t, int> PairType;
95 std::vector<PairType> Results;
96
97 auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
98
99 for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
100 Results.emplace_back(X.index(), X.value());
101 }
102
103 ASSERT_EQ(3u, Results.size());
104 EXPECT_EQ(PairType(0u, 1), Results[0]);
105 EXPECT_EQ(PairType(1u, 2), Results[1]);
106 EXPECT_EQ(PairType(2u, 3), Results[2]);
107 }
108
TEST(STLExtrasTest,EnumerateModifyRValue)109 TEST(STLExtrasTest, EnumerateModifyRValue) {
110 // Test that when enumerating an rvalue, modification still works (even if
111 // this isn't terribly useful, it at least shows that we haven't snuck an
112 // extra const in there somewhere.
113 typedef std::pair<std::size_t, char> PairType;
114 std::vector<PairType> Results;
115
116 for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
117 ++X.value();
118 Results.emplace_back(X.index(), X.value());
119 }
120
121 ASSERT_EQ(3u, Results.size());
122 EXPECT_EQ(PairType(0u, '2'), Results[0]);
123 EXPECT_EQ(PairType(1u, '3'), Results[1]);
124 EXPECT_EQ(PairType(2u, '4'), Results[2]);
125 }
126
127 template <bool B> struct CanMove {};
128 template <> struct CanMove<false> {
129 CanMove(CanMove &&) = delete;
130
131 CanMove() = default;
132 CanMove(const CanMove &) = default;
133 };
134
135 template <bool B> struct CanCopy {};
136 template <> struct CanCopy<false> {
137 CanCopy(const CanCopy &) = delete;
138
139 CanCopy() = default;
140 CanCopy(CanCopy &&) = default;
141 };
142
143 template <bool Moveable, bool Copyable>
144 class Counted : CanMove<Moveable>, CanCopy<Copyable> {
145 int &C;
146 int &M;
147 int &D;
148
149 public:
Counted(int & C,int & M,int & D)150 explicit Counted(int &C, int &M, int &D) : C(C), M(M), D(D) {}
Counted(const Counted & O)151 Counted(const Counted &O) : CanCopy<Copyable>(O), C(O.C), M(O.M), D(O.D) {
152 ++C;
153 }
Counted(Counted && O)154 Counted(Counted &&O)
155 : CanMove<Moveable>(std::move(O)), C(O.C), M(O.M), D(O.D) {
156 ++M;
157 }
~Counted()158 ~Counted() { ++D; }
159 };
160
161 template <bool Moveable, bool Copyable>
162 struct Range : Counted<Moveable, Copyable> {
163 using Counted<Moveable, Copyable>::Counted;
begin__anon9f9e6dce0111::Range164 int *begin() { return nullptr; }
end__anon9f9e6dce0111::Range165 int *end() { return nullptr; }
166 };
167
TEST(STLExtrasTest,EnumerateLifetimeSemanticsPRValue)168 TEST(STLExtrasTest, EnumerateLifetimeSemanticsPRValue) {
169 int Copies = 0;
170 int Moves = 0;
171 int Destructors = 0;
172 {
173 auto E = enumerate(Range<true, false>(Copies, Moves, Destructors));
174 (void)E;
175 // Doesn't compile. rvalue ranges must be moveable.
176 // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
177 EXPECT_EQ(0, Copies);
178 EXPECT_EQ(1, Moves);
179 EXPECT_EQ(1, Destructors);
180 }
181 EXPECT_EQ(0, Copies);
182 EXPECT_EQ(1, Moves);
183 EXPECT_EQ(2, Destructors);
184 }
185
TEST(STLExtrasTest,EnumerateLifetimeSemanticsRValue)186 TEST(STLExtrasTest, EnumerateLifetimeSemanticsRValue) {
187 // With an rvalue, it should not be destroyed until the end of the scope.
188 int Copies = 0;
189 int Moves = 0;
190 int Destructors = 0;
191 {
192 Range<true, false> R(Copies, Moves, Destructors);
193 {
194 auto E = enumerate(std::move(R));
195 (void)E;
196 // Doesn't compile. rvalue ranges must be moveable.
197 // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
198 EXPECT_EQ(0, Copies);
199 EXPECT_EQ(1, Moves);
200 EXPECT_EQ(0, Destructors);
201 }
202 EXPECT_EQ(0, Copies);
203 EXPECT_EQ(1, Moves);
204 EXPECT_EQ(1, Destructors);
205 }
206 EXPECT_EQ(0, Copies);
207 EXPECT_EQ(1, Moves);
208 EXPECT_EQ(2, Destructors);
209 }
210
TEST(STLExtrasTest,EnumerateLifetimeSemanticsLValue)211 TEST(STLExtrasTest, EnumerateLifetimeSemanticsLValue) {
212 // With an lvalue, it should not be destroyed even after the end of the scope.
213 // lvalue ranges need be neither copyable nor moveable.
214 int Copies = 0;
215 int Moves = 0;
216 int Destructors = 0;
217 {
218 Range<false, false> R(Copies, Moves, Destructors);
219 {
220 auto E = enumerate(R);
221 (void)E;
222 EXPECT_EQ(0, Copies);
223 EXPECT_EQ(0, Moves);
224 EXPECT_EQ(0, Destructors);
225 }
226 EXPECT_EQ(0, Copies);
227 EXPECT_EQ(0, Moves);
228 EXPECT_EQ(0, Destructors);
229 }
230 EXPECT_EQ(0, Copies);
231 EXPECT_EQ(0, Moves);
232 EXPECT_EQ(1, Destructors);
233 }
234
TEST(STLExtrasTest,ApplyTuple)235 TEST(STLExtrasTest, ApplyTuple) {
236 auto T = std::make_tuple(1, 3, 7);
237 auto U = llvm::apply_tuple(
238 [](int A, int B, int C) { return std::make_tuple(A - B, B - C, C - A); },
239 T);
240
241 EXPECT_EQ(-2, std::get<0>(U));
242 EXPECT_EQ(-4, std::get<1>(U));
243 EXPECT_EQ(6, std::get<2>(U));
244
245 auto V = llvm::apply_tuple(
246 [](int A, int B, int C) {
247 return std::make_tuple(std::make_pair(A, char('A' + A)),
248 std::make_pair(B, char('A' + B)),
249 std::make_pair(C, char('A' + C)));
250 },
251 T);
252
253 EXPECT_EQ(std::make_pair(1, 'B'), std::get<0>(V));
254 EXPECT_EQ(std::make_pair(3, 'D'), std::get<1>(V));
255 EXPECT_EQ(std::make_pair(7, 'H'), std::get<2>(V));
256 }
257
258 class apply_variadic {
apply_one(int X)259 static int apply_one(int X) { return X + 1; }
apply_one(char C)260 static char apply_one(char C) { return C + 1; }
apply_one(StringRef S)261 static StringRef apply_one(StringRef S) { return S.drop_back(); }
262
263 public:
operator ()(Ts &&...Items)264 template <typename... Ts> auto operator()(Ts &&... Items) {
265 return std::make_tuple(apply_one(Items)...);
266 }
267 };
268
TEST(STLExtrasTest,ApplyTupleVariadic)269 TEST(STLExtrasTest, ApplyTupleVariadic) {
270 auto Items = std::make_tuple(1, llvm::StringRef("Test"), 'X');
271 auto Values = apply_tuple(apply_variadic(), Items);
272
273 EXPECT_EQ(2, std::get<0>(Values));
274 EXPECT_EQ("Tes", std::get<1>(Values));
275 EXPECT_EQ('Y', std::get<2>(Values));
276 }
277
TEST(STLExtrasTest,CountAdaptor)278 TEST(STLExtrasTest, CountAdaptor) {
279 std::vector<int> v;
280
281 v.push_back(1);
282 v.push_back(2);
283 v.push_back(1);
284 v.push_back(4);
285 v.push_back(3);
286 v.push_back(2);
287 v.push_back(1);
288
289 EXPECT_EQ(3, count(v, 1));
290 EXPECT_EQ(2, count(v, 2));
291 EXPECT_EQ(1, count(v, 3));
292 EXPECT_EQ(1, count(v, 4));
293 }
294
TEST(STLExtrasTest,for_each)295 TEST(STLExtrasTest, for_each) {
296 std::vector<int> v{0, 1, 2, 3, 4};
297 int count = 0;
298
299 llvm::for_each(v, [&count](int) { ++count; });
300 EXPECT_EQ(5, count);
301 }
302
TEST(STLExtrasTest,ToVector)303 TEST(STLExtrasTest, ToVector) {
304 std::vector<char> v = {'a', 'b', 'c'};
305 auto Enumerated = to_vector<4>(enumerate(v));
306 ASSERT_EQ(3u, Enumerated.size());
307 for (size_t I = 0; I < v.size(); ++I) {
308 EXPECT_EQ(I, Enumerated[I].index());
309 EXPECT_EQ(v[I], Enumerated[I].value());
310 }
311
312 auto EnumeratedImplicitSize = to_vector(enumerate(v));
313 ASSERT_EQ(3u, EnumeratedImplicitSize.size());
314 for (size_t I = 0; I < v.size(); ++I) {
315 EXPECT_EQ(I, EnumeratedImplicitSize[I].index());
316 EXPECT_EQ(v[I], EnumeratedImplicitSize[I].value());
317 }
318 }
319
TEST(STLExtrasTest,ConcatRange)320 TEST(STLExtrasTest, ConcatRange) {
321 std::vector<int> Expected = {1, 2, 3, 4, 5, 6, 7, 8};
322 std::vector<int> Test;
323
324 std::vector<int> V1234 = {1, 2, 3, 4};
325 std::list<int> L56 = {5, 6};
326 SmallVector<int, 2> SV78 = {7, 8};
327
328 // Use concat across different sized ranges of different types with different
329 // iterators.
330 for (int &i : concat<int>(V1234, L56, SV78))
331 Test.push_back(i);
332 EXPECT_EQ(Expected, Test);
333
334 // Use concat between a temporary, an L-value, and an R-value to make sure
335 // complex lifetimes work well.
336 Test.clear();
337 for (int &i : concat<int>(std::vector<int>(V1234), L56, std::move(SV78)))
338 Test.push_back(i);
339 EXPECT_EQ(Expected, Test);
340 }
341
TEST(STLExtrasTest,PartitionAdaptor)342 TEST(STLExtrasTest, PartitionAdaptor) {
343 std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8};
344
345 auto I = partition(V, [](int i) { return i % 2 == 0; });
346 ASSERT_EQ(V.begin() + 4, I);
347
348 // Sort the two halves as partition may have messed with the order.
349 llvm::sort(V.begin(), I);
350 llvm::sort(I, V.end());
351
352 EXPECT_EQ(2, V[0]);
353 EXPECT_EQ(4, V[1]);
354 EXPECT_EQ(6, V[2]);
355 EXPECT_EQ(8, V[3]);
356 EXPECT_EQ(1, V[4]);
357 EXPECT_EQ(3, V[5]);
358 EXPECT_EQ(5, V[6]);
359 EXPECT_EQ(7, V[7]);
360 }
361
TEST(STLExtrasTest,EraseIf)362 TEST(STLExtrasTest, EraseIf) {
363 std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8};
364
365 erase_if(V, [](int i) { return i % 2 == 0; });
366 EXPECT_EQ(4u, V.size());
367 EXPECT_EQ(1, V[0]);
368 EXPECT_EQ(3, V[1]);
369 EXPECT_EQ(5, V[2]);
370 EXPECT_EQ(7, V[3]);
371 }
372
TEST(STLExtrasTest,AppendRange)373 TEST(STLExtrasTest, AppendRange) {
374 auto AppendVals = {3};
375 std::vector<int> V = {1, 2};
376 append_range(V, AppendVals);
377 EXPECT_EQ(1, V[0]);
378 EXPECT_EQ(2, V[1]);
379 EXPECT_EQ(3, V[2]);
380 }
381
382 namespace some_namespace {
383 struct some_struct {
384 std::vector<int> data;
385 std::string swap_val;
386 };
387
begin(const some_struct & s)388 std::vector<int>::const_iterator begin(const some_struct &s) {
389 return s.data.begin();
390 }
391
end(const some_struct & s)392 std::vector<int>::const_iterator end(const some_struct &s) {
393 return s.data.end();
394 }
395
swap(some_struct & lhs,some_struct & rhs)396 void swap(some_struct &lhs, some_struct &rhs) {
397 // make swap visible as non-adl swap would even seem to
398 // work with std::swap which defaults to moving
399 lhs.swap_val = "lhs";
400 rhs.swap_val = "rhs";
401 }
402 } // namespace some_namespace
403
TEST(STLExtrasTest,ADLTest)404 TEST(STLExtrasTest, ADLTest) {
405 some_namespace::some_struct s{{1, 2, 3, 4, 5}, ""};
406 some_namespace::some_struct s2{{2, 4, 6, 8, 10}, ""};
407
408 EXPECT_EQ(*adl_begin(s), 1);
409 EXPECT_EQ(*(adl_end(s) - 1), 5);
410
411 adl_swap(s, s2);
412 EXPECT_EQ(s.swap_val, "lhs");
413 EXPECT_EQ(s2.swap_val, "rhs");
414
415 int count = 0;
416 llvm::for_each(s, [&count](int) { ++count; });
417 EXPECT_EQ(5, count);
418 }
419
TEST(STLExtrasTest,EmptyTest)420 TEST(STLExtrasTest, EmptyTest) {
421 std::vector<void*> V;
422 EXPECT_TRUE(llvm::empty(V));
423 V.push_back(nullptr);
424 EXPECT_FALSE(llvm::empty(V));
425
426 std::initializer_list<int> E = {};
427 std::initializer_list<int> NotE = {7, 13, 42};
428 EXPECT_TRUE(llvm::empty(E));
429 EXPECT_FALSE(llvm::empty(NotE));
430
431 auto R0 = make_range(V.begin(), V.begin());
432 EXPECT_TRUE(llvm::empty(R0));
433 auto R1 = make_range(V.begin(), V.end());
434 EXPECT_FALSE(llvm::empty(R1));
435 }
436
TEST(STLExtrasTest,DropBeginTest)437 TEST(STLExtrasTest, DropBeginTest) {
438 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
439
440 for (int n = 0; n < 5; ++n) {
441 int i = n;
442 for (auto &v : drop_begin(vec, n)) {
443 EXPECT_EQ(v, i);
444 i += 1;
445 }
446 EXPECT_EQ(i, 5);
447 }
448 }
449
TEST(STLExtrasTest,DropBeginDefaultTest)450 TEST(STLExtrasTest, DropBeginDefaultTest) {
451 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
452
453 int i = 1;
454 for (auto &v : drop_begin(vec)) {
455 EXPECT_EQ(v, i);
456 i += 1;
457 }
458 EXPECT_EQ(i, 5);
459 }
460
TEST(STLExtrasTest,DropEndTest)461 TEST(STLExtrasTest, DropEndTest) {
462 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
463
464 for (int n = 0; n < 5; ++n) {
465 int i = 0;
466 for (auto &v : drop_end(vec, n)) {
467 EXPECT_EQ(v, i);
468 i += 1;
469 }
470 EXPECT_EQ(i, 5 - n);
471 }
472 }
473
TEST(STLExtrasTest,DropEndDefaultTest)474 TEST(STLExtrasTest, DropEndDefaultTest) {
475 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
476
477 int i = 0;
478 for (auto &v : drop_end(vec)) {
479 EXPECT_EQ(v, i);
480 i += 1;
481 }
482 EXPECT_EQ(i, 4);
483 }
484
TEST(STLExtrasTest,EarlyIncrementTest)485 TEST(STLExtrasTest, EarlyIncrementTest) {
486 std::list<int> L = {1, 2, 3, 4};
487
488 auto EIR = make_early_inc_range(L);
489
490 auto I = EIR.begin();
491 auto EI = EIR.end();
492 EXPECT_NE(I, EI);
493
494 EXPECT_EQ(1, *I);
495 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
496 #ifndef NDEBUG
497 // Repeated dereferences are not allowed.
498 EXPECT_DEATH(*I, "Cannot dereference");
499 // Comparison after dereference is not allowed.
500 EXPECT_DEATH((void)(I == EI), "Cannot compare");
501 EXPECT_DEATH((void)(I != EI), "Cannot compare");
502 #endif
503 #endif
504
505 ++I;
506 EXPECT_NE(I, EI);
507 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
508 #ifndef NDEBUG
509 // You cannot increment prior to dereference.
510 EXPECT_DEATH(++I, "Cannot increment");
511 #endif
512 #endif
513 EXPECT_EQ(2, *I);
514 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
515 #ifndef NDEBUG
516 // Repeated dereferences are not allowed.
517 EXPECT_DEATH(*I, "Cannot dereference");
518 #endif
519 #endif
520
521 // Inserting shouldn't break anything. We should be able to keep dereferencing
522 // the currrent iterator and increment. The increment to go to the "next"
523 // iterator from before we inserted.
524 L.insert(std::next(L.begin(), 2), -1);
525 ++I;
526 EXPECT_EQ(3, *I);
527
528 // Erasing the front including the current doesn't break incrementing.
529 L.erase(L.begin(), std::prev(L.end()));
530 ++I;
531 EXPECT_EQ(4, *I);
532 ++I;
533 EXPECT_EQ(EIR.end(), I);
534 }
535
536 // A custom iterator that returns a pointer when dereferenced. This is used to
537 // test make_early_inc_range with iterators that do not return a reference on
538 // dereferencing.
539 struct CustomPointerIterator
540 : public iterator_adaptor_base<CustomPointerIterator,
541 std::list<int>::iterator,
542 std::forward_iterator_tag> {
543 using base_type =
544 iterator_adaptor_base<CustomPointerIterator, std::list<int>::iterator,
545 std::forward_iterator_tag>;
546
CustomPointerIterator__anon9f9e6dce0111::CustomPointerIterator547 explicit CustomPointerIterator(std::list<int>::iterator I) : base_type(I) {}
548
549 // Retrieve a pointer to the current int.
operator *__anon9f9e6dce0111::CustomPointerIterator550 int *operator*() const { return &*base_type::wrapped(); }
551 };
552
553 // Make sure make_early_inc_range works with iterators that do not return a
554 // reference on dereferencing. The test is similar to EarlyIncrementTest, but
555 // uses CustomPointerIterator.
TEST(STLExtrasTest,EarlyIncrementTestCustomPointerIterator)556 TEST(STLExtrasTest, EarlyIncrementTestCustomPointerIterator) {
557 std::list<int> L = {1, 2, 3, 4};
558
559 auto CustomRange = make_range(CustomPointerIterator(L.begin()),
560 CustomPointerIterator(L.end()));
561 auto EIR = make_early_inc_range(CustomRange);
562
563 auto I = EIR.begin();
564 auto EI = EIR.end();
565 EXPECT_NE(I, EI);
566
567 EXPECT_EQ(&*L.begin(), *I);
568 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
569 #ifndef NDEBUG
570 // Repeated dereferences are not allowed.
571 EXPECT_DEATH(*I, "Cannot dereference");
572 // Comparison after dereference is not allowed.
573 EXPECT_DEATH((void)(I == EI), "Cannot compare");
574 EXPECT_DEATH((void)(I != EI), "Cannot compare");
575 #endif
576 #endif
577
578 ++I;
579 EXPECT_NE(I, EI);
580 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
581 #ifndef NDEBUG
582 // You cannot increment prior to dereference.
583 EXPECT_DEATH(++I, "Cannot increment");
584 #endif
585 #endif
586 EXPECT_EQ(&*std::next(L.begin()), *I);
587 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
588 #ifndef NDEBUG
589 // Repeated dereferences are not allowed.
590 EXPECT_DEATH(*I, "Cannot dereference");
591 #endif
592 #endif
593
594 // Inserting shouldn't break anything. We should be able to keep dereferencing
595 // the currrent iterator and increment. The increment to go to the "next"
596 // iterator from before we inserted.
597 L.insert(std::next(L.begin(), 2), -1);
598 ++I;
599 EXPECT_EQ(&*std::next(L.begin(), 3), *I);
600
601 // Erasing the front including the current doesn't break incrementing.
602 L.erase(L.begin(), std::prev(L.end()));
603 ++I;
604 EXPECT_EQ(&*L.begin(), *I);
605 ++I;
606 EXPECT_EQ(EIR.end(), I);
607 }
608
TEST(STLExtrasTest,splat)609 TEST(STLExtrasTest, splat) {
610 std::vector<int> V;
611 EXPECT_FALSE(is_splat(V));
612
613 V.push_back(1);
614 EXPECT_TRUE(is_splat(V));
615
616 V.push_back(1);
617 V.push_back(1);
618 EXPECT_TRUE(is_splat(V));
619
620 V.push_back(2);
621 EXPECT_FALSE(is_splat(V));
622 }
623
TEST(STLExtrasTest,to_address)624 TEST(STLExtrasTest, to_address) {
625 int *V1 = new int;
626 EXPECT_EQ(V1, to_address(V1));
627
628 // Check fancy pointer overload for unique_ptr
629 std::unique_ptr<int> V2 = std::make_unique<int>(0);
630 EXPECT_EQ(V2.get(), llvm::to_address(V2));
631
632 V2.reset(V1);
633 EXPECT_EQ(V1, llvm::to_address(V2));
634 V2.release();
635
636 // Check fancy pointer overload for shared_ptr
637 std::shared_ptr<int> V3 = std::make_shared<int>(0);
638 std::shared_ptr<int> V4 = V3;
639 EXPECT_EQ(V3.get(), V4.get());
640 EXPECT_EQ(V3.get(), llvm::to_address(V3));
641 EXPECT_EQ(V4.get(), llvm::to_address(V4));
642
643 V3.reset(V1);
644 EXPECT_EQ(V1, llvm::to_address(V3));
645 }
646
TEST(STLExtrasTest,partition_point)647 TEST(STLExtrasTest, partition_point) {
648 std::vector<int> V = {1, 3, 5, 7, 9};
649
650 // Range version.
651 EXPECT_EQ(V.begin() + 3,
652 partition_point(V, [](unsigned X) { return X < 7; }));
653 EXPECT_EQ(V.begin(), partition_point(V, [](unsigned X) { return X < 1; }));
654 EXPECT_EQ(V.end(), partition_point(V, [](unsigned X) { return X < 50; }));
655 }
656
TEST(STLExtrasTest,hasSingleElement)657 TEST(STLExtrasTest, hasSingleElement) {
658 const std::vector<int> V0 = {}, V1 = {1}, V2 = {1, 2};
659 const std::vector<int> V10(10);
660
661 EXPECT_EQ(hasSingleElement(V0), false);
662 EXPECT_EQ(hasSingleElement(V1), true);
663 EXPECT_EQ(hasSingleElement(V2), false);
664 EXPECT_EQ(hasSingleElement(V10), false);
665 }
666
TEST(STLExtrasTest,hasNItems)667 TEST(STLExtrasTest, hasNItems) {
668 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
669 const std::list<int> V3 = {1, 3, 5};
670
671 EXPECT_TRUE(hasNItems(V0, 0));
672 EXPECT_FALSE(hasNItems(V0, 2));
673 EXPECT_TRUE(hasNItems(V1, 1));
674 EXPECT_FALSE(hasNItems(V1, 2));
675
676 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 3, [](int x) { return x < 10; }));
677 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 0, [](int x) { return x > 10; }));
678 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
679 }
680
TEST(STLExtras,hasNItemsOrMore)681 TEST(STLExtras, hasNItemsOrMore) {
682 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
683 const std::list<int> V3 = {1, 3, 5};
684
685 EXPECT_TRUE(hasNItemsOrMore(V1, 1));
686 EXPECT_FALSE(hasNItemsOrMore(V1, 2));
687
688 EXPECT_TRUE(hasNItemsOrMore(V2, 1));
689 EXPECT_TRUE(hasNItemsOrMore(V2, 2));
690 EXPECT_FALSE(hasNItemsOrMore(V2, 3));
691
692 EXPECT_TRUE(hasNItemsOrMore(V3, 3));
693 EXPECT_FALSE(hasNItemsOrMore(V3, 4));
694
695 EXPECT_TRUE(
696 hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x < 10; }));
697 EXPECT_FALSE(
698 hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x > 10; }));
699 EXPECT_TRUE(
700 hasNItemsOrMore(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
701 }
702
TEST(STLExtras,hasNItemsOrLess)703 TEST(STLExtras, hasNItemsOrLess) {
704 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
705 const std::list<int> V3 = {1, 3, 5};
706
707 EXPECT_TRUE(hasNItemsOrLess(V0, 0));
708 EXPECT_TRUE(hasNItemsOrLess(V0, 1));
709 EXPECT_TRUE(hasNItemsOrLess(V0, 2));
710
711 EXPECT_FALSE(hasNItemsOrLess(V1, 0));
712 EXPECT_TRUE(hasNItemsOrLess(V1, 1));
713 EXPECT_TRUE(hasNItemsOrLess(V1, 2));
714
715 EXPECT_FALSE(hasNItemsOrLess(V2, 0));
716 EXPECT_FALSE(hasNItemsOrLess(V2, 1));
717 EXPECT_TRUE(hasNItemsOrLess(V2, 2));
718 EXPECT_TRUE(hasNItemsOrLess(V2, 3));
719
720 EXPECT_FALSE(hasNItemsOrLess(V3, 0));
721 EXPECT_FALSE(hasNItemsOrLess(V3, 1));
722 EXPECT_FALSE(hasNItemsOrLess(V3, 2));
723 EXPECT_TRUE(hasNItemsOrLess(V3, 3));
724 EXPECT_TRUE(hasNItemsOrLess(V3, 4));
725
726 EXPECT_TRUE(
727 hasNItemsOrLess(V3.begin(), V3.end(), 1, [](int x) { return x == 1; }));
728 EXPECT_TRUE(
729 hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
730 EXPECT_TRUE(
731 hasNItemsOrLess(V3.begin(), V3.end(), 5, [](int x) { return x < 5; }));
732 EXPECT_FALSE(
733 hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 10; }));
734 }
735
TEST(STLExtras,MoveRange)736 TEST(STLExtras, MoveRange) {
737 class Foo {
738 bool A;
739
740 public:
741 Foo() : A(true) {}
742 Foo(const Foo &) = delete;
743 Foo(Foo &&Other) : A(Other.A) { Other.A = false; }
744 Foo &operator=(const Foo &) = delete;
745 Foo &operator=(Foo &&Other) {
746 if (this != &Other) {
747 A = Other.A;
748 Other.A = false;
749 }
750 return *this;
751 }
752 operator bool() const { return A; }
753 };
754 SmallVector<Foo, 4U> V1, V2, V3, V4;
755 auto HasVal = [](const Foo &Item) { return static_cast<bool>(Item); };
756 auto Build = [&] {
757 SmallVector<Foo, 4U> Foos;
758 Foos.resize(4U);
759 return Foos;
760 };
761
762 V1.resize(4U);
763 EXPECT_TRUE(llvm::all_of(V1, HasVal));
764
765 llvm::move(V1, std::back_inserter(V2));
766
767 // Ensure input container is same size, but its contents were moved out.
768 EXPECT_EQ(V1.size(), 4U);
769 EXPECT_TRUE(llvm::none_of(V1, HasVal));
770
771 // Ensure output container has the contents of the input container.
772 EXPECT_EQ(V2.size(), 4U);
773 EXPECT_TRUE(llvm::all_of(V2, HasVal));
774
775 llvm::move(std::move(V2), std::back_inserter(V3));
776
777 EXPECT_TRUE(llvm::none_of(V2, HasVal));
778 EXPECT_EQ(V3.size(), 4U);
779 EXPECT_TRUE(llvm::all_of(V3, HasVal));
780
781 llvm::move(Build(), std::back_inserter(V4));
782 EXPECT_EQ(V4.size(), 4U);
783 EXPECT_TRUE(llvm::all_of(V4, HasVal));
784 }
785
TEST(STLExtras,Unique)786 TEST(STLExtras, Unique) {
787 std::vector<int> V = {1, 5, 5, 4, 3, 3, 3};
788
789 auto I = llvm::unique(V, [](int a, int b) { return a == b; });
790
791 EXPECT_EQ(I, V.begin() + 4);
792
793 EXPECT_EQ(1, V[0]);
794 EXPECT_EQ(5, V[1]);
795 EXPECT_EQ(4, V[2]);
796 EXPECT_EQ(3, V[3]);
797 }
798
TEST(STLExtrasTest,MakeVisitorOneCallable)799 TEST(STLExtrasTest, MakeVisitorOneCallable) {
800 auto IdentityLambda = [](auto X) { return X; };
801 auto IdentityVisitor = makeVisitor(IdentityLambda);
802 EXPECT_EQ(IdentityLambda(1), IdentityVisitor(1));
803 EXPECT_EQ(IdentityLambda(2.0f), IdentityVisitor(2.0f));
804 EXPECT_TRUE((std::is_same<decltype(IdentityLambda(IdentityLambda)),
805 decltype(IdentityLambda)>::value));
806 EXPECT_TRUE((std::is_same<decltype(IdentityVisitor(IdentityVisitor)),
807 decltype(IdentityVisitor)>::value));
808 }
809
TEST(STLExtrasTest,MakeVisitorTwoCallables)810 TEST(STLExtrasTest, MakeVisitorTwoCallables) {
811 auto Visitor =
812 makeVisitor([](int) { return 0; }, [](std::string) { return 1; });
813 EXPECT_EQ(Visitor(42), 0);
814 EXPECT_EQ(Visitor("foo"), 1);
815 }
816
TEST(STLExtrasTest,MakeVisitorCallableMultipleOperands)817 TEST(STLExtrasTest, MakeVisitorCallableMultipleOperands) {
818 auto Second = makeVisitor([](int I, float F) { return F; },
819 [](float F, int I) { return I; });
820 EXPECT_EQ(Second(1.f, 1), 1);
821 EXPECT_EQ(Second(1, 1.f), 1.f);
822 }
823
TEST(STLExtrasTest,MakeVisitorDefaultCase)824 TEST(STLExtrasTest, MakeVisitorDefaultCase) {
825 {
826 auto Visitor = makeVisitor([](int I) { return I + 100; },
827 [](float F) { return F * 2; },
828 [](auto) { return -1; });
829 EXPECT_EQ(Visitor(24), 124);
830 EXPECT_EQ(Visitor(2.f), 4.f);
831 EXPECT_EQ(Visitor(2.), -1);
832 EXPECT_EQ(Visitor(Visitor), -1);
833 }
834 {
835 auto Visitor = makeVisitor([](auto) { return -1; },
836 [](int I) { return I + 100; },
837 [](float F) { return F * 2; });
838 EXPECT_EQ(Visitor(24), 124);
839 EXPECT_EQ(Visitor(2.f), 4.f);
840 EXPECT_EQ(Visitor(2.), -1);
841 EXPECT_EQ(Visitor(Visitor), -1);
842 }
843 }
844
845 template <bool Moveable, bool Copyable>
846 struct Functor : Counted<Moveable, Copyable> {
847 using Counted<Moveable, Copyable>::Counted;
operator ()__anon9f9e6dce0111::Functor848 void operator()() {}
849 };
850
TEST(STLExtrasTest,MakeVisitorLifetimeSemanticsPRValue)851 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsPRValue) {
852 int Copies = 0;
853 int Moves = 0;
854 int Destructors = 0;
855 {
856 auto V = makeVisitor(Functor<true, false>(Copies, Moves, Destructors));
857 (void)V;
858 EXPECT_EQ(0, Copies);
859 EXPECT_EQ(1, Moves);
860 EXPECT_EQ(1, Destructors);
861 }
862 EXPECT_EQ(0, Copies);
863 EXPECT_EQ(1, Moves);
864 EXPECT_EQ(2, Destructors);
865 }
866
TEST(STLExtrasTest,MakeVisitorLifetimeSemanticsRValue)867 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsRValue) {
868 int Copies = 0;
869 int Moves = 0;
870 int Destructors = 0;
871 {
872 Functor<true, false> F(Copies, Moves, Destructors);
873 {
874 auto V = makeVisitor(std::move(F));
875 (void)V;
876 EXPECT_EQ(0, Copies);
877 EXPECT_EQ(1, Moves);
878 EXPECT_EQ(0, Destructors);
879 }
880 EXPECT_EQ(0, Copies);
881 EXPECT_EQ(1, Moves);
882 EXPECT_EQ(1, Destructors);
883 }
884 EXPECT_EQ(0, Copies);
885 EXPECT_EQ(1, Moves);
886 EXPECT_EQ(2, Destructors);
887 }
888
TEST(STLExtrasTest,MakeVisitorLifetimeSemanticsLValue)889 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsLValue) {
890 int Copies = 0;
891 int Moves = 0;
892 int Destructors = 0;
893 {
894 Functor<true, true> F(Copies, Moves, Destructors);
895 {
896 auto V = makeVisitor(F);
897 (void)V;
898 EXPECT_EQ(1, Copies);
899 EXPECT_EQ(0, Moves);
900 EXPECT_EQ(0, Destructors);
901 }
902 EXPECT_EQ(1, Copies);
903 EXPECT_EQ(0, Moves);
904 EXPECT_EQ(1, Destructors);
905 }
906 EXPECT_EQ(1, Copies);
907 EXPECT_EQ(0, Moves);
908 EXPECT_EQ(2, Destructors);
909 }
910
TEST(STLExtrasTest,AllOfZip)911 TEST(STLExtrasTest, AllOfZip) {
912 std::vector<int> v1 = {0, 4, 2, 1};
913 std::vector<int> v2 = {1, 4, 3, 6};
914 EXPECT_TRUE(all_of_zip(v1, v2, [](int v1, int v2) { return v1 <= v2; }));
915 EXPECT_FALSE(all_of_zip(v1, v2, [](int L, int R) { return L < R; }));
916
917 // Triple vectors
918 std::vector<int> v3 = {1, 6, 5, 7};
919 EXPECT_EQ(true, all_of_zip(v1, v2, v3, [](int a, int b, int c) {
920 return a <= b && b <= c;
921 }));
922 EXPECT_EQ(false, all_of_zip(v1, v2, v3, [](int a, int b, int c) {
923 return a < b && b < c;
924 }));
925
926 // Shorter vector should fail even with an always-true predicate.
927 std::vector<int> v_short = {1, 4};
928 EXPECT_EQ(false, all_of_zip(v1, v_short, [](int, int) { return true; }));
929 EXPECT_EQ(false,
930 all_of_zip(v1, v2, v_short, [](int, int, int) { return true; }));
931 }
932
TEST(STLExtrasTest,TypesAreDistinct)933 TEST(STLExtrasTest, TypesAreDistinct) {
934 EXPECT_TRUE((llvm::TypesAreDistinct<>::value));
935 EXPECT_TRUE((llvm::TypesAreDistinct<int>::value));
936 EXPECT_FALSE((llvm::TypesAreDistinct<int, int>::value));
937 EXPECT_TRUE((llvm::TypesAreDistinct<int, float>::value));
938 EXPECT_FALSE((llvm::TypesAreDistinct<int, float, int>::value));
939 EXPECT_TRUE((llvm::TypesAreDistinct<int, float, double>::value));
940 EXPECT_FALSE((llvm::TypesAreDistinct<int, float, double, float>::value));
941 EXPECT_TRUE((llvm::TypesAreDistinct<int, int *>::value));
942 EXPECT_TRUE((llvm::TypesAreDistinct<int, int &>::value));
943 EXPECT_TRUE((llvm::TypesAreDistinct<int, int &&>::value));
944 EXPECT_TRUE((llvm::TypesAreDistinct<int, const int>::value));
945 }
946
TEST(STLExtrasTest,FirstIndexOfType)947 TEST(STLExtrasTest, FirstIndexOfType) {
948 EXPECT_EQ((llvm::FirstIndexOfType<int, int>::value), 0u);
949 EXPECT_EQ((llvm::FirstIndexOfType<int, int, int>::value), 0u);
950 EXPECT_EQ((llvm::FirstIndexOfType<int, float, int>::value), 1u);
951 EXPECT_EQ((llvm::FirstIndexOfType<int const *, float, int, int const *,
952 const int>::value),
953 2u);
954 }
955
TEST(STLExtrasTest,TypeAtIndex)956 TEST(STLExtrasTest, TypeAtIndex) {
957 EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int>>::value));
958 EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int, float>>::value));
959 EXPECT_TRUE((std::is_same<float, llvm::TypeAtIndex<1, int, float>>::value));
960 EXPECT_TRUE(
961 (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value));
962 EXPECT_TRUE(
963 (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value));
964 EXPECT_TRUE(
965 (std::is_same<double, llvm::TypeAtIndex<2, int, float, double>>::value));
966 }
967
968 enum Doggos {
969 Floofer,
970 Woofer,
971 SubWoofer,
972 Pupper,
973 Pupperino,
974 Longboi,
975 };
976
TEST(STLExtrasTest,IsContainedInitializerList)977 TEST(STLExtrasTest, IsContainedInitializerList) {
978 EXPECT_TRUE(is_contained({Woofer, SubWoofer}, Woofer));
979 EXPECT_TRUE(is_contained({Woofer, SubWoofer}, SubWoofer));
980 EXPECT_FALSE(is_contained({Woofer, SubWoofer}, Pupper));
981 EXPECT_FALSE(is_contained({}, Longboi));
982
983 static_assert(is_contained({Woofer, SubWoofer}, SubWoofer), "SubWoofer!");
984 static_assert(!is_contained({Woofer, SubWoofer}, Pupper), "Missing Pupper!");
985
986 EXPECT_TRUE(is_contained({1, 2, 3, 4}, 3));
987 EXPECT_FALSE(is_contained({1, 2, 3, 4}, 5));
988
989 static_assert(is_contained({1, 2, 3, 4}, 3), "It's there!");
990 static_assert(!is_contained({1, 2, 3, 4}, 5), "It's not there :(");
991 }
992
TEST(STLExtrasTest,addEnumValues)993 TEST(STLExtrasTest, addEnumValues) {
994 enum A { Zero = 0, One = 1 };
995 enum B { IntMax = INT_MAX, ULongLongMax = ULLONG_MAX };
996 enum class C : unsigned { Two = 2 };
997
998 // Non-fixed underlying types, with same underlying types
999 static_assert(addEnumValues(Zero, One) == 1,
1000 "addEnumValues(Zero, One) failed.");
1001 static_assert(addEnumValues(IntMax, ULongLongMax) ==
1002 INT_MAX + static_cast<unsigned long long>(ULLONG_MAX),
1003 "addEnumValues(IntMax, ULongLongMax) failed.");
1004 // Non-fixed underlying types, with different underlying types
1005 static_assert(addEnumValues(Zero, IntMax) == INT_MAX,
1006 "addEnumValues(Zero, IntMax) failed.");
1007 static_assert(addEnumValues(One, ULongLongMax) ==
1008 1 + static_cast<unsigned long long>(ULLONG_MAX),
1009 "addEnumValues(One, ULongLongMax) failed.");
1010 // Non-fixed underlying type enum and fixed underlying type enum, with same
1011 // underlying types
1012 static_assert(addEnumValues(One, C::Two) == 3,
1013 "addEnumValues(One, C::Two) failed.");
1014 // Non-fixed underlying type enum and fixed underlying type enum, with
1015 // different underlying types
1016 static_assert(addEnumValues(ULongLongMax, C::Two) ==
1017 static_cast<unsigned long long>(ULLONG_MAX) + 2,
1018 "addEnumValues(ULongLongMax, C::Two) failed.");
1019 }
1020
1021 } // namespace
1022