Fix test failures introduced by PR #113697 (#116941)
[llvm-project.git] / llvm / unittests / ADT / STLExtrasTest.cpp
blob406ff2bc16073b79775f9a498907f262922c92ee
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 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/STLExtras.h"
10 #include "llvm/ADT/StringRef.h"
11 #include "gmock/gmock.h"
12 #include "gtest/gtest.h"
14 #include <array>
15 #include <climits>
16 #include <cstddef>
17 #include <initializer_list>
18 #include <iterator>
19 #include <list>
20 #include <tuple>
21 #include <type_traits>
22 #include <unordered_set>
23 #include <utility>
24 #include <vector>
26 using namespace llvm;
28 using testing::ElementsAre;
29 using testing::UnorderedElementsAre;
31 namespace {
33 int f(rank<0>) { return 0; }
34 int f(rank<1>) { return 1; }
35 int f(rank<2>) { return 2; }
36 int f(rank<4>) { return 4; }
38 TEST(STLExtrasTest, Rank) {
39 // We shouldn't get ambiguities and should select the overload of the same
40 // rank as the argument.
41 EXPECT_EQ(0, f(rank<0>()));
42 EXPECT_EQ(1, f(rank<1>()));
43 EXPECT_EQ(2, f(rank<2>()));
45 // This overload is missing so we end up back at 2.
46 EXPECT_EQ(2, f(rank<3>()));
48 // But going past 3 should work fine.
49 EXPECT_EQ(4, f(rank<4>()));
51 // And we can even go higher and just fall back to the last overload.
52 EXPECT_EQ(4, f(rank<5>()));
53 EXPECT_EQ(4, f(rank<6>()));
56 TEST(STLExtrasTest, EnumerateLValue) {
57 // Test that a simple LValue can be enumerated and gives correct results with
58 // multiple types, including the empty container.
59 std::vector<char> foo = {'a', 'b', 'c'};
60 typedef std::pair<std::size_t, char> CharPairType;
61 std::vector<CharPairType> CharResults;
63 for (auto [index, value] : llvm::enumerate(foo)) {
64 CharResults.emplace_back(index, value);
67 EXPECT_THAT(CharResults,
68 ElementsAre(CharPairType(0u, 'a'), CharPairType(1u, 'b'),
69 CharPairType(2u, 'c')));
71 // Test a const range of a different type.
72 typedef std::pair<std::size_t, int> IntPairType;
73 std::vector<IntPairType> IntResults;
74 const std::vector<int> bar = {1, 2, 3};
75 for (auto [index, value] : llvm::enumerate(bar)) {
76 IntResults.emplace_back(index, value);
78 EXPECT_THAT(IntResults, ElementsAre(IntPairType(0u, 1), IntPairType(1u, 2),
79 IntPairType(2u, 3)));
81 // Test an empty range.
82 IntResults.clear();
83 const std::vector<int> baz{};
84 for (auto [index, value] : llvm::enumerate(baz)) {
85 IntResults.emplace_back(index, value);
87 EXPECT_TRUE(IntResults.empty());
90 TEST(STLExtrasTest, EnumerateModifyLValue) {
91 // Test that you can modify the underlying entries of an lvalue range through
92 // the enumeration iterator.
93 std::vector<char> foo = {'a', 'b', 'c'};
95 for (auto X : llvm::enumerate(foo)) {
96 ++X.value();
98 EXPECT_THAT(foo, ElementsAre('b', 'c', 'd'));
100 // Also test if this works with structured bindings.
101 foo = {'a', 'b', 'c'};
103 for (auto [index, value] : llvm::enumerate(foo)) {
104 ++value;
106 EXPECT_THAT(foo, ElementsAre('b', 'c', 'd'));
109 TEST(STLExtrasTest, EnumerateRValueRef) {
110 // Test that an rvalue can be enumerated.
111 typedef std::pair<std::size_t, int> PairType;
112 std::vector<PairType> Results;
114 auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3});
116 for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) {
117 Results.emplace_back(X.index(), X.value());
120 EXPECT_THAT(Results,
121 ElementsAre(PairType(0u, 1), PairType(1u, 2), PairType(2u, 3)));
123 // Also test if this works with structured bindings.
124 Results.clear();
126 for (auto [index, value] : llvm::enumerate(std::vector<int>{1, 2, 3})) {
127 Results.emplace_back(index, value);
130 EXPECT_THAT(Results,
131 ElementsAre(PairType(0u, 1), PairType(1u, 2), PairType(2u, 3)));
134 TEST(STLExtrasTest, EnumerateModifyRValue) {
135 // Test that when enumerating an rvalue, modification still works (even if
136 // this isn't terribly useful, it at least shows that we haven't snuck an
137 // extra const in there somewhere.
138 typedef std::pair<std::size_t, char> PairType;
139 std::vector<PairType> Results;
141 for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
142 ++X.value();
143 Results.emplace_back(X.index(), X.value());
146 EXPECT_THAT(Results, ElementsAre(PairType(0u, '2'), PairType(1u, '3'),
147 PairType(2u, '4')));
149 // Also test if this works with structured bindings.
150 Results.clear();
152 for (auto [index, value] :
153 llvm::enumerate(std::vector<char>{'1', '2', '3'})) {
154 ++value;
155 Results.emplace_back(index, value);
158 EXPECT_THAT(Results, ElementsAre(PairType(0u, '2'), PairType(1u, '3'),
159 PairType(2u, '4')));
162 TEST(STLExtrasTest, EnumerateTwoRanges) {
163 using Tuple = std::tuple<size_t, int, bool>;
165 std::vector<int> Ints = {1, 2};
166 std::vector<bool> Bools = {true, false};
167 EXPECT_THAT(llvm::enumerate(Ints, Bools),
168 ElementsAre(Tuple(0, 1, true), Tuple(1, 2, false)));
170 // Check that we can modify the values when the temporary is a const
171 // reference.
172 for (const auto &[Idx, Int, Bool] : llvm::enumerate(Ints, Bools)) {
173 (void)Idx;
174 Bool = false;
175 Int = -1;
178 EXPECT_THAT(Ints, ElementsAre(-1, -1));
179 EXPECT_THAT(Bools, ElementsAre(false, false));
181 // Check that we can modify the values when the result gets copied.
182 for (auto [Idx, Bool, Int] : llvm::enumerate(Bools, Ints)) {
183 (void)Idx;
184 Int = 3;
185 Bool = true;
188 EXPECT_THAT(Ints, ElementsAre(3, 3));
189 EXPECT_THAT(Bools, ElementsAre(true, true));
191 // Check that we can modify the values through `.value()`.
192 size_t Iters = 0;
193 for (auto It : llvm::enumerate(Bools, Ints)) {
194 EXPECT_EQ(It.index(), Iters);
195 ++Iters;
197 std::get<0>(It.value()) = false;
198 std::get<1>(It.value()) = 4;
201 EXPECT_THAT(Ints, ElementsAre(4, 4));
202 EXPECT_THAT(Bools, ElementsAre(false, false));
205 TEST(STLExtrasTest, EnumerateThreeRanges) {
206 using Tuple = std::tuple<size_t, int, bool, char>;
208 std::vector<int> Ints = {1, 2};
209 std::vector<bool> Bools = {true, false};
210 char Chars[] = {'X', 'D'};
211 EXPECT_THAT(llvm::enumerate(Ints, Bools, Chars),
212 ElementsAre(Tuple(0, 1, true, 'X'), Tuple(1, 2, false, 'D')));
214 for (auto [Idx, Int, Bool, Char] : llvm::enumerate(Ints, Bools, Chars)) {
215 (void)Idx;
216 Int = 0;
217 Bool = true;
218 Char = '!';
221 EXPECT_THAT(Ints, ElementsAre(0, 0));
222 EXPECT_THAT(Bools, ElementsAre(true, true));
223 EXPECT_THAT(Chars, ElementsAre('!', '!'));
225 // Check that we can modify the values through `.values()`.
226 size_t Iters = 0;
227 for (auto It : llvm::enumerate(Ints, Bools, Chars)) {
228 EXPECT_EQ(It.index(), Iters);
229 ++Iters;
230 auto [Int, Bool, Char] = It.value();
231 Int = 42;
232 Bool = false;
233 Char = '$';
236 EXPECT_THAT(Ints, ElementsAre(42, 42));
237 EXPECT_THAT(Bools, ElementsAre(false, false));
238 EXPECT_THAT(Chars, ElementsAre('$', '$'));
241 TEST(STLExtrasTest, EnumerateTemporaries) {
242 using Tuple = std::tuple<size_t, int, bool>;
244 EXPECT_THAT(
245 llvm::enumerate(llvm::SmallVector<int>({1, 2, 3}),
246 std::vector<bool>({true, false, true})),
247 ElementsAre(Tuple(0, 1, true), Tuple(1, 2, false), Tuple(2, 3, true)));
249 size_t Iters = 0;
250 // This is fine from the point of view of range lifetimes because `zippy` will
251 // move all temporaries into its storage. No lifetime extension is necessary.
252 for (auto [Idx, Int, Bool] :
253 llvm::enumerate(llvm::SmallVector<int>({1, 2, 3}),
254 std::vector<bool>({true, false, true}))) {
255 EXPECT_EQ(Idx, Iters);
256 ++Iters;
257 Int = 0;
258 Bool = true;
261 Iters = 0;
262 // The same thing but with the result as a const reference.
263 for (const auto &[Idx, Int, Bool] :
264 llvm::enumerate(llvm::SmallVector<int>({1, 2, 3}),
265 std::vector<bool>({true, false, true}))) {
266 EXPECT_EQ(Idx, Iters);
267 ++Iters;
268 Int = 0;
269 Bool = true;
273 #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
274 TEST(STLExtrasTest, EnumerateDifferentLengths) {
275 std::vector<int> Ints = {0, 1};
276 bool Bools[] = {true, false, true};
277 std::string Chars = "abc";
278 EXPECT_DEATH(llvm::enumerate(Ints, Bools, Chars),
279 "Ranges have different length");
280 EXPECT_DEATH(llvm::enumerate(Bools, Ints, Chars),
281 "Ranges have different length");
282 EXPECT_DEATH(llvm::enumerate(Bools, Chars, Ints),
283 "Ranges have different length");
285 #endif
287 template <bool B> struct CanMove {};
288 template <> struct CanMove<false> {
289 CanMove(CanMove &&) = delete;
291 CanMove() = default;
292 CanMove(const CanMove &) = default;
295 template <bool B> struct CanCopy {};
296 template <> struct CanCopy<false> {
297 CanCopy(const CanCopy &) = delete;
299 CanCopy() = default;
300 CanCopy(CanCopy &&) = default;
303 template <bool Moveable, bool Copyable>
304 class Counted : CanMove<Moveable>, CanCopy<Copyable> {
305 int &C;
306 int &M;
307 int &D;
309 public:
310 explicit Counted(int &C, int &M, int &D) : C(C), M(M), D(D) {}
311 Counted(const Counted &O) : CanCopy<Copyable>(O), C(O.C), M(O.M), D(O.D) {
312 ++C;
314 Counted(Counted &&O)
315 : CanMove<Moveable>(std::move(O)), C(O.C), M(O.M), D(O.D) {
316 ++M;
318 ~Counted() { ++D; }
321 template <bool Moveable, bool Copyable>
322 struct Range : Counted<Moveable, Copyable> {
323 using Counted<Moveable, Copyable>::Counted;
324 int *begin() const { return nullptr; }
325 int *end() const { return nullptr; }
328 TEST(STLExtrasTest, EnumerateLifetimeSemanticsPRValue) {
329 int Copies = 0;
330 int Moves = 0;
331 int Destructors = 0;
333 auto E = enumerate(Range<true, false>(Copies, Moves, Destructors));
334 (void)E;
335 // Doesn't compile. rvalue ranges must be moveable.
336 // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
337 EXPECT_EQ(0, Copies);
338 EXPECT_EQ(1, Moves);
339 EXPECT_EQ(1, Destructors);
341 EXPECT_EQ(0, Copies);
342 EXPECT_EQ(1, Moves);
343 EXPECT_EQ(2, Destructors);
346 TEST(STLExtrasTest, EnumerateLifetimeSemanticsRValue) {
347 // With an rvalue, it should not be destroyed until the end of the scope.
348 int Copies = 0;
349 int Moves = 0;
350 int Destructors = 0;
352 Range<true, false> R(Copies, Moves, Destructors);
354 auto E = enumerate(std::move(R));
355 (void)E;
356 // Doesn't compile. rvalue ranges must be moveable.
357 // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors));
358 EXPECT_EQ(0, Copies);
359 EXPECT_EQ(1, Moves);
360 EXPECT_EQ(0, Destructors);
362 EXPECT_EQ(0, Copies);
363 EXPECT_EQ(1, Moves);
364 EXPECT_EQ(1, Destructors);
366 EXPECT_EQ(0, Copies);
367 EXPECT_EQ(1, Moves);
368 EXPECT_EQ(2, Destructors);
371 TEST(STLExtrasTest, EnumerateLifetimeSemanticsLValue) {
372 // With an lvalue, it should not be destroyed even after the end of the scope.
373 // lvalue ranges need be neither copyable nor moveable.
374 int Copies = 0;
375 int Moves = 0;
376 int Destructors = 0;
378 Range<false, false> R(Copies, Moves, Destructors);
380 auto E = enumerate(R);
381 (void)E;
382 EXPECT_EQ(0, Copies);
383 EXPECT_EQ(0, Moves);
384 EXPECT_EQ(0, Destructors);
386 EXPECT_EQ(0, Copies);
387 EXPECT_EQ(0, Moves);
388 EXPECT_EQ(0, Destructors);
390 EXPECT_EQ(0, Copies);
391 EXPECT_EQ(0, Moves);
392 EXPECT_EQ(1, Destructors);
395 namespace some_namespace {
396 struct some_struct {
397 std::vector<int> data;
398 std::string swap_val;
401 std::vector<int>::const_iterator begin(const some_struct &s) {
402 return s.data.begin();
405 std::vector<int>::const_iterator end(const some_struct &s) {
406 return s.data.end();
409 std::vector<int>::const_reverse_iterator rbegin(const some_struct &s) {
410 return s.data.rbegin();
413 std::vector<int>::const_reverse_iterator rend(const some_struct &s) {
414 return s.data.rend();
417 void swap(some_struct &lhs, some_struct &rhs) {
418 // make swap visible as non-adl swap would even seem to
419 // work with std::swap which defaults to moving
420 lhs.swap_val = "lhs";
421 rhs.swap_val = "rhs";
424 struct requires_move {};
425 int *begin(requires_move &&) { return nullptr; }
426 int *end(requires_move &&) { return nullptr; }
427 } // namespace some_namespace
429 TEST(STLExtrasTest, EnumerateCustomBeginEnd) {
430 // Check that `enumerate` uses ADL to find `begin`/`end` iterators
431 // of the enumerated type.
432 some_namespace::some_struct X{};
433 X.data = {1, 2, 3};
435 unsigned Iters = 0;
436 for (auto [Idx, Val] : enumerate(X)) {
437 EXPECT_EQ(Val, X.data[Idx]);
438 ++Iters;
440 EXPECT_EQ(Iters, 3u);
443 TEST(STLExtrasTest, CountAdaptor) {
444 std::vector<int> v;
446 v.push_back(1);
447 v.push_back(2);
448 v.push_back(1);
449 v.push_back(4);
450 v.push_back(3);
451 v.push_back(2);
452 v.push_back(1);
454 EXPECT_EQ(3, count(v, 1));
455 EXPECT_EQ(2, count(v, 2));
456 EXPECT_EQ(1, count(v, 3));
457 EXPECT_EQ(1, count(v, 4));
460 TEST(STLExtrasTest, for_each) {
461 std::vector<int> v{0, 1, 2, 3, 4};
462 int count = 0;
464 llvm::for_each(v, [&count](int) { ++count; });
465 EXPECT_EQ(5, count);
468 TEST(STLExtrasTest, ToVector) {
469 std::vector<char> v = {'a', 'b', 'c'};
470 auto Enumerated = to_vector<4>(enumerate(v));
471 ASSERT_EQ(3u, Enumerated.size());
472 for (size_t I = 0; I < v.size(); ++I) {
473 EXPECT_EQ(I, Enumerated[I].index());
474 EXPECT_EQ(v[I], Enumerated[I].value());
477 auto EnumeratedImplicitSize = to_vector(enumerate(v));
478 ASSERT_EQ(3u, EnumeratedImplicitSize.size());
479 for (size_t I = 0; I < v.size(); ++I) {
480 EXPECT_EQ(I, EnumeratedImplicitSize[I].index());
481 EXPECT_EQ(v[I], EnumeratedImplicitSize[I].value());
485 TEST(STLExtrasTest, ConcatRange) {
486 std::vector<int> Expected = {1, 2, 3, 4, 5, 6, 7, 8};
487 std::vector<int> Test;
489 std::vector<int> V1234 = {1, 2, 3, 4};
490 std::list<int> L56 = {5, 6};
491 SmallVector<int, 2> SV78 = {7, 8};
493 // Use concat across different sized ranges of different types with different
494 // iterators.
495 for (int &i : concat<int>(V1234, L56, SV78))
496 Test.push_back(i);
497 EXPECT_EQ(Expected, Test);
499 // Use concat between a temporary, an L-value, and an R-value to make sure
500 // complex lifetimes work well.
501 Test.clear();
502 for (int &i : concat<int>(std::vector<int>(V1234), L56, std::move(SV78)))
503 Test.push_back(i);
504 EXPECT_EQ(Expected, Test);
507 template <typename T> struct Iterator {
508 int i = 0;
509 T operator*() const { return i; }
510 Iterator &operator++() {
511 ++i;
512 return *this;
514 bool operator==(Iterator RHS) const { return i == RHS.i; }
517 template <typename T> struct RangeWithValueType {
518 int i;
519 RangeWithValueType(int i) : i(i) {}
520 Iterator<T> begin() { return Iterator<T>{0}; }
521 Iterator<T> end() { return Iterator<T>{i}; }
524 TEST(STLExtrasTest, ValueReturn) {
525 RangeWithValueType<int> R(1);
526 auto C = concat<int>(R, R);
527 auto I = C.begin();
528 ASSERT_NE(I, C.end());
529 static_assert(std::is_same_v<decltype((*I)), int>);
530 auto V = *I;
531 ASSERT_EQ(V, 0);
534 TEST(STLExtrasTest, ReferenceReturn) {
535 RangeWithValueType<const int&> R(1);
536 auto C = concat<const int>(R, R);
537 auto I = C.begin();
538 ASSERT_NE(I, C.end());
539 static_assert(std::is_same_v<decltype((*I)), const int &>);
540 auto V = *I;
541 ASSERT_EQ(V, 0);
544 TEST(STLExtrasTest, PartitionAdaptor) {
545 std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8};
547 auto I = partition(V, [](int i) { return i % 2 == 0; });
548 ASSERT_EQ(V.begin() + 4, I);
550 // Sort the two halves as partition may have messed with the order.
551 llvm::sort(V.begin(), I);
552 llvm::sort(I, V.end());
554 EXPECT_EQ(2, V[0]);
555 EXPECT_EQ(4, V[1]);
556 EXPECT_EQ(6, V[2]);
557 EXPECT_EQ(8, V[3]);
558 EXPECT_EQ(1, V[4]);
559 EXPECT_EQ(3, V[5]);
560 EXPECT_EQ(5, V[6]);
561 EXPECT_EQ(7, V[7]);
564 TEST(STLExtrasTest, EraseIf) {
565 std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8};
567 erase_if(V, [](int i) { return i % 2 == 0; });
568 EXPECT_EQ(4u, V.size());
569 EXPECT_EQ(1, V[0]);
570 EXPECT_EQ(3, V[1]);
571 EXPECT_EQ(5, V[2]);
572 EXPECT_EQ(7, V[3]);
575 TEST(STLExtrasTest, AppendRange) {
576 std::vector<int> V = {1, 2};
577 auto AppendVals1 = {3};
578 append_range(V, AppendVals1);
579 EXPECT_THAT(V, ElementsAre(1, 2, 3));
581 int AppendVals2[] = {4, 5};
582 append_range(V, AppendVals2);
583 EXPECT_THAT(V, ElementsAre(1, 2, 3, 4, 5));
585 std::string Str;
586 append_range(Str, "abc");
587 EXPECT_THAT(Str, ElementsAre('a', 'b', 'c', '\0'));
588 append_range(Str, "def");
589 EXPECT_THAT(Str, ElementsAre('a', 'b', 'c', '\0', 'd', 'e', 'f', '\0'));
592 TEST(STLExtrasTest, AppendValues) {
593 std::vector<int> Vals = {1, 2};
594 append_values(Vals, 3);
595 EXPECT_THAT(Vals, ElementsAre(1, 2, 3));
597 append_values(Vals, 4, 5);
598 EXPECT_THAT(Vals, ElementsAre(1, 2, 3, 4, 5));
600 std::vector<StringRef> Strs;
601 std::string A = "A";
602 std::string B = "B";
603 std::string C = "C";
604 append_values(Strs, A, B);
605 EXPECT_THAT(Strs, ElementsAre(A, B));
606 append_values(Strs, C);
607 EXPECT_THAT(Strs, ElementsAre(A, B, C));
609 std::unordered_set<int> Set;
610 append_values(Set, 1, 2);
611 EXPECT_THAT(Set, UnorderedElementsAre(1, 2));
612 append_values(Set, 3, 1);
613 EXPECT_THAT(Set, UnorderedElementsAre(1, 2, 3));
616 TEST(STLExtrasTest, ADLTest) {
617 some_namespace::some_struct s{{1, 2, 3, 4, 5}, ""};
618 some_namespace::some_struct s2{{2, 4, 6, 8, 10}, ""};
620 EXPECT_EQ(*adl_begin(s), 1);
621 EXPECT_EQ(*(adl_end(s) - 1), 5);
622 EXPECT_EQ(*adl_rbegin(s), 5);
623 EXPECT_EQ(*(adl_rend(s) - 1), 1);
625 adl_swap(s, s2);
626 EXPECT_EQ(s.swap_val, "lhs");
627 EXPECT_EQ(s2.swap_val, "rhs");
629 int count = 0;
630 llvm::for_each(s, [&count](int) { ++count; });
631 EXPECT_EQ(count, 5);
634 TEST(STLExtrasTest, ADLTestTemporaryRange) {
635 EXPECT_EQ(adl_begin(some_namespace::requires_move{}), nullptr);
636 EXPECT_EQ(adl_end(some_namespace::requires_move{}), nullptr);
639 TEST(STLExtrasTest, ADLTestConstexpr) {
640 // `std::begin`/`std::end` are marked as `constexpr`; check that
641 // `adl_begin`/`adl_end` also work in constant-evaluated contexts.
642 static constexpr int c_arr[] = {7, 8, 9};
643 static_assert(adl_begin(c_arr) == c_arr);
644 static_assert(adl_end(c_arr) == c_arr + 3);
646 static constexpr std::array<int, 2> std_arr = {1, 2};
647 static_assert(adl_begin(std_arr) == std_arr.begin());
648 static_assert(adl_end(std_arr) == std_arr.end());
649 SUCCEED();
652 struct FooWithMemberSize {
653 size_t size() const { return 42; }
654 auto begin() { return Data.begin(); }
655 auto end() { return Data.end(); }
657 std::set<int> Data;
660 namespace some_namespace {
661 struct FooWithFreeSize {
662 auto begin() { return Data.begin(); }
663 auto end() { return Data.end(); }
665 std::set<int> Data;
668 size_t size(const FooWithFreeSize &) { return 13; }
669 } // namespace some_namespace
671 TEST(STLExtrasTest, ADLSizeTest) {
672 FooWithMemberSize foo1;
673 EXPECT_EQ(adl_size(foo1), 42u);
675 some_namespace::FooWithFreeSize foo2;
676 EXPECT_EQ(adl_size(foo2), 13u);
678 static constexpr int c_arr[] = {1, 2, 3};
679 static_assert(adl_size(c_arr) == 3u);
681 static constexpr std::array<int, 4> cpp_arr = {};
682 static_assert(adl_size(cpp_arr) == 4u);
685 TEST(STLExtrasTest, DropBeginTest) {
686 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
688 for (int n = 0; n < 5; ++n) {
689 int i = n;
690 for (auto &v : drop_begin(vec, n)) {
691 EXPECT_EQ(v, i);
692 i += 1;
694 EXPECT_EQ(i, 5);
698 TEST(STLExtrasTest, DropBeginDefaultTest) {
699 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
701 int i = 1;
702 for (auto &v : drop_begin(vec)) {
703 EXPECT_EQ(v, i);
704 i += 1;
706 EXPECT_EQ(i, 5);
709 TEST(STLExtrasTest, DropEndTest) {
710 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
712 for (int n = 0; n < 5; ++n) {
713 int i = 0;
714 for (auto &v : drop_end(vec, n)) {
715 EXPECT_EQ(v, i);
716 i += 1;
718 EXPECT_EQ(i, 5 - n);
722 TEST(STLExtrasTest, DropEndDefaultTest) {
723 SmallVector<int, 5> vec{0, 1, 2, 3, 4};
725 int i = 0;
726 for (auto &v : drop_end(vec)) {
727 EXPECT_EQ(v, i);
728 i += 1;
730 EXPECT_EQ(i, 4);
733 TEST(STLExtrasTest, EarlyIncrementTest) {
734 std::list<int> L = {1, 2, 3, 4};
736 auto EIR = make_early_inc_range(L);
738 auto I = EIR.begin();
739 auto EI = EIR.end();
740 EXPECT_NE(I, EI);
742 EXPECT_EQ(1, *I);
743 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
744 #ifndef NDEBUG
745 // Repeated dereferences are not allowed.
746 EXPECT_DEATH(*I, "Cannot dereference");
747 // Comparison after dereference is not allowed.
748 EXPECT_DEATH((void)(I == EI), "Cannot compare");
749 EXPECT_DEATH((void)(I != EI), "Cannot compare");
750 #endif
751 #endif
753 ++I;
754 EXPECT_NE(I, EI);
755 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
756 #ifndef NDEBUG
757 // You cannot increment prior to dereference.
758 EXPECT_DEATH(++I, "Cannot increment");
759 #endif
760 #endif
761 EXPECT_EQ(2, *I);
762 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
763 #ifndef NDEBUG
764 // Repeated dereferences are not allowed.
765 EXPECT_DEATH(*I, "Cannot dereference");
766 #endif
767 #endif
769 // Inserting shouldn't break anything. We should be able to keep dereferencing
770 // the currrent iterator and increment. The increment to go to the "next"
771 // iterator from before we inserted.
772 L.insert(std::next(L.begin(), 2), -1);
773 ++I;
774 EXPECT_EQ(3, *I);
776 // Erasing the front including the current doesn't break incrementing.
777 L.erase(L.begin(), std::prev(L.end()));
778 ++I;
779 EXPECT_EQ(4, *I);
780 ++I;
781 EXPECT_EQ(EIR.end(), I);
784 // A custom iterator that returns a pointer when dereferenced. This is used to
785 // test make_early_inc_range with iterators that do not return a reference on
786 // dereferencing.
787 struct CustomPointerIterator
788 : public iterator_adaptor_base<CustomPointerIterator,
789 std::list<int>::iterator,
790 std::forward_iterator_tag> {
791 using base_type =
792 iterator_adaptor_base<CustomPointerIterator, std::list<int>::iterator,
793 std::forward_iterator_tag>;
795 explicit CustomPointerIterator(std::list<int>::iterator I) : base_type(I) {}
797 // Retrieve a pointer to the current int.
798 int *operator*() const { return &*base_type::wrapped(); }
801 // Make sure make_early_inc_range works with iterators that do not return a
802 // reference on dereferencing. The test is similar to EarlyIncrementTest, but
803 // uses CustomPointerIterator.
804 TEST(STLExtrasTest, EarlyIncrementTestCustomPointerIterator) {
805 std::list<int> L = {1, 2, 3, 4};
807 auto CustomRange = make_range(CustomPointerIterator(L.begin()),
808 CustomPointerIterator(L.end()));
809 auto EIR = make_early_inc_range(CustomRange);
811 auto I = EIR.begin();
812 auto EI = EIR.end();
813 EXPECT_NE(I, EI);
815 EXPECT_EQ(&*L.begin(), *I);
816 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
817 #ifndef NDEBUG
818 // Repeated dereferences are not allowed.
819 EXPECT_DEATH(*I, "Cannot dereference");
820 // Comparison after dereference is not allowed.
821 EXPECT_DEATH((void)(I == EI), "Cannot compare");
822 EXPECT_DEATH((void)(I != EI), "Cannot compare");
823 #endif
824 #endif
826 ++I;
827 EXPECT_NE(I, EI);
828 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
829 #ifndef NDEBUG
830 // You cannot increment prior to dereference.
831 EXPECT_DEATH(++I, "Cannot increment");
832 #endif
833 #endif
834 EXPECT_EQ(&*std::next(L.begin()), *I);
835 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
836 #ifndef NDEBUG
837 // Repeated dereferences are not allowed.
838 EXPECT_DEATH(*I, "Cannot dereference");
839 #endif
840 #endif
842 // Inserting shouldn't break anything. We should be able to keep dereferencing
843 // the currrent iterator and increment. The increment to go to the "next"
844 // iterator from before we inserted.
845 L.insert(std::next(L.begin(), 2), -1);
846 ++I;
847 EXPECT_EQ(&*std::next(L.begin(), 3), *I);
849 // Erasing the front including the current doesn't break incrementing.
850 L.erase(L.begin(), std::prev(L.end()));
851 ++I;
852 EXPECT_EQ(&*L.begin(), *I);
853 ++I;
854 EXPECT_EQ(EIR.end(), I);
857 TEST(STLExtrasTest, AllEqual) {
858 std::vector<int> V;
859 EXPECT_TRUE(all_equal(V));
861 V.push_back(1);
862 EXPECT_TRUE(all_equal(V));
864 V.push_back(1);
865 V.push_back(1);
866 EXPECT_TRUE(all_equal(V));
868 V.push_back(2);
869 EXPECT_FALSE(all_equal(V));
872 // Test to verify that all_equal works with a container that does not
873 // model the random access iterator concept.
874 TEST(STLExtrasTest, AllEqualNonRandomAccess) {
875 std::list<int> V;
876 static_assert(!std::is_convertible_v<
877 std::iterator_traits<decltype(V)::iterator>::iterator_category,
878 std::random_access_iterator_tag>);
879 EXPECT_TRUE(all_equal(V));
881 V.push_back(1);
882 EXPECT_TRUE(all_equal(V));
884 V.push_back(1);
885 V.push_back(1);
886 EXPECT_TRUE(all_equal(V));
888 V.push_back(2);
889 EXPECT_FALSE(all_equal(V));
892 TEST(STLExtrasTest, AllEqualInitializerList) {
893 EXPECT_TRUE(all_equal({1}));
894 EXPECT_TRUE(all_equal({1, 1}));
895 EXPECT_FALSE(all_equal({1, 2}));
896 EXPECT_FALSE(all_equal({2, 1}));
897 EXPECT_TRUE(all_equal({1, 1, 1}));
900 TEST(STLExtrasTest, to_address) {
901 int *V1 = new int;
902 EXPECT_EQ(V1, to_address(V1));
904 // Check fancy pointer overload for unique_ptr
905 std::unique_ptr<int> V2 = std::make_unique<int>(0);
906 EXPECT_EQ(V2.get(), llvm::to_address(V2));
908 V2.reset(V1);
909 EXPECT_EQ(V1, llvm::to_address(V2));
910 V2.release();
912 // Check fancy pointer overload for shared_ptr
913 std::shared_ptr<int> V3 = std::make_shared<int>(0);
914 std::shared_ptr<int> V4 = V3;
915 EXPECT_EQ(V3.get(), V4.get());
916 EXPECT_EQ(V3.get(), llvm::to_address(V3));
917 EXPECT_EQ(V4.get(), llvm::to_address(V4));
919 V3.reset(V1);
920 EXPECT_EQ(V1, llvm::to_address(V3));
923 TEST(STLExtrasTest, partition_point) {
924 std::vector<int> V = {1, 3, 5, 7, 9};
926 // Range version.
927 EXPECT_EQ(V.begin() + 3,
928 partition_point(V, [](unsigned X) { return X < 7; }));
929 EXPECT_EQ(V.begin(), partition_point(V, [](unsigned X) { return X < 1; }));
930 EXPECT_EQ(V.end(), partition_point(V, [](unsigned X) { return X < 50; }));
933 TEST(STLExtrasTest, hasSingleElement) {
934 const std::vector<int> V0 = {}, V1 = {1}, V2 = {1, 2};
935 const std::vector<int> V10(10);
937 EXPECT_EQ(hasSingleElement(V0), false);
938 EXPECT_EQ(hasSingleElement(V1), true);
939 EXPECT_EQ(hasSingleElement(V2), false);
940 EXPECT_EQ(hasSingleElement(V10), false);
943 TEST(STLExtrasTest, hasNItems) {
944 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
945 const std::list<int> V3 = {1, 3, 5};
947 EXPECT_TRUE(hasNItems(V0, 0));
948 EXPECT_FALSE(hasNItems(V0, 2));
949 EXPECT_TRUE(hasNItems(V1, 1));
950 EXPECT_FALSE(hasNItems(V1, 2));
952 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 3, [](int x) { return x < 10; }));
953 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 0, [](int x) { return x > 10; }));
954 EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
957 TEST(STLExtras, hasNItemsOrMore) {
958 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
959 const std::list<int> V3 = {1, 3, 5};
961 EXPECT_TRUE(hasNItemsOrMore(V1, 1));
962 EXPECT_FALSE(hasNItemsOrMore(V1, 2));
964 EXPECT_TRUE(hasNItemsOrMore(V2, 1));
965 EXPECT_TRUE(hasNItemsOrMore(V2, 2));
966 EXPECT_FALSE(hasNItemsOrMore(V2, 3));
968 EXPECT_TRUE(hasNItemsOrMore(V3, 3));
969 EXPECT_FALSE(hasNItemsOrMore(V3, 4));
971 EXPECT_TRUE(
972 hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x < 10; }));
973 EXPECT_FALSE(
974 hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x > 10; }));
975 EXPECT_TRUE(
976 hasNItemsOrMore(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
979 TEST(STLExtras, hasNItemsOrLess) {
980 const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2};
981 const std::list<int> V3 = {1, 3, 5};
983 EXPECT_TRUE(hasNItemsOrLess(V0, 0));
984 EXPECT_TRUE(hasNItemsOrLess(V0, 1));
985 EXPECT_TRUE(hasNItemsOrLess(V0, 2));
987 EXPECT_FALSE(hasNItemsOrLess(V1, 0));
988 EXPECT_TRUE(hasNItemsOrLess(V1, 1));
989 EXPECT_TRUE(hasNItemsOrLess(V1, 2));
991 EXPECT_FALSE(hasNItemsOrLess(V2, 0));
992 EXPECT_FALSE(hasNItemsOrLess(V2, 1));
993 EXPECT_TRUE(hasNItemsOrLess(V2, 2));
994 EXPECT_TRUE(hasNItemsOrLess(V2, 3));
996 EXPECT_FALSE(hasNItemsOrLess(V3, 0));
997 EXPECT_FALSE(hasNItemsOrLess(V3, 1));
998 EXPECT_FALSE(hasNItemsOrLess(V3, 2));
999 EXPECT_TRUE(hasNItemsOrLess(V3, 3));
1000 EXPECT_TRUE(hasNItemsOrLess(V3, 4));
1002 EXPECT_TRUE(
1003 hasNItemsOrLess(V3.begin(), V3.end(), 1, [](int x) { return x == 1; }));
1004 EXPECT_TRUE(
1005 hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 5; }));
1006 EXPECT_TRUE(
1007 hasNItemsOrLess(V3.begin(), V3.end(), 5, [](int x) { return x < 5; }));
1008 EXPECT_FALSE(
1009 hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 10; }));
1012 TEST(STLExtras, MoveRange) {
1013 class Foo {
1014 bool A;
1016 public:
1017 Foo() : A(true) {}
1018 Foo(const Foo &) = delete;
1019 Foo(Foo &&Other) : A(Other.A) { Other.A = false; }
1020 Foo &operator=(const Foo &) = delete;
1021 Foo &operator=(Foo &&Other) {
1022 if (this != &Other) {
1023 A = Other.A;
1024 Other.A = false;
1026 return *this;
1028 operator bool() const { return A; }
1030 SmallVector<Foo, 4U> V1, V2, V3, V4;
1031 auto HasVal = [](const Foo &Item) { return static_cast<bool>(Item); };
1032 auto Build = [&] {
1033 SmallVector<Foo, 4U> Foos;
1034 Foos.resize(4U);
1035 return Foos;
1038 V1.resize(4U);
1039 EXPECT_TRUE(llvm::all_of(V1, HasVal));
1041 llvm::move(V1, std::back_inserter(V2));
1043 // Ensure input container is same size, but its contents were moved out.
1044 EXPECT_EQ(V1.size(), 4U);
1045 EXPECT_TRUE(llvm::none_of(V1, HasVal));
1047 // Ensure output container has the contents of the input container.
1048 EXPECT_EQ(V2.size(), 4U);
1049 EXPECT_TRUE(llvm::all_of(V2, HasVal));
1051 llvm::move(std::move(V2), std::back_inserter(V3));
1053 EXPECT_TRUE(llvm::none_of(V2, HasVal));
1054 EXPECT_EQ(V3.size(), 4U);
1055 EXPECT_TRUE(llvm::all_of(V3, HasVal));
1057 llvm::move(Build(), std::back_inserter(V4));
1058 EXPECT_EQ(V4.size(), 4U);
1059 EXPECT_TRUE(llvm::all_of(V4, HasVal));
1062 TEST(STLExtras, Unique) {
1063 std::vector<int> V = {1, 5, 5, 4, 3, 3, 3};
1065 auto I = llvm::unique(V, [](int a, int b) { return a == b; });
1067 EXPECT_EQ(I, V.begin() + 4);
1069 EXPECT_EQ(1, V[0]);
1070 EXPECT_EQ(5, V[1]);
1071 EXPECT_EQ(4, V[2]);
1072 EXPECT_EQ(3, V[3]);
1075 TEST(STLExtras, UniqueNoPred) {
1076 std::vector<int> V = {1, 5, 5, 4, 3, 3, 3};
1078 auto I = llvm::unique(V);
1080 EXPECT_EQ(I, V.begin() + 4);
1082 EXPECT_EQ(1, V[0]);
1083 EXPECT_EQ(5, V[1]);
1084 EXPECT_EQ(4, V[2]);
1085 EXPECT_EQ(3, V[3]);
1088 TEST(STLExtrasTest, MakeVisitorOneCallable) {
1089 auto IdentityLambda = [](auto X) { return X; };
1090 auto IdentityVisitor = makeVisitor(IdentityLambda);
1091 EXPECT_EQ(IdentityLambda(1), IdentityVisitor(1));
1092 EXPECT_EQ(IdentityLambda(2.0f), IdentityVisitor(2.0f));
1093 EXPECT_TRUE((std::is_same<decltype(IdentityLambda(IdentityLambda)),
1094 decltype(IdentityLambda)>::value));
1095 EXPECT_TRUE((std::is_same<decltype(IdentityVisitor(IdentityVisitor)),
1096 decltype(IdentityVisitor)>::value));
1099 TEST(STLExtrasTest, MakeVisitorTwoCallables) {
1100 auto Visitor =
1101 makeVisitor([](int) { return 0; }, [](std::string) { return 1; });
1102 EXPECT_EQ(Visitor(42), 0);
1103 EXPECT_EQ(Visitor("foo"), 1);
1106 TEST(STLExtrasTest, MakeVisitorCallableMultipleOperands) {
1107 auto Second = makeVisitor([](int I, float F) { return F; },
1108 [](float F, int I) { return I; });
1109 EXPECT_EQ(Second(1.f, 1), 1);
1110 EXPECT_EQ(Second(1, 1.f), 1.f);
1113 TEST(STLExtrasTest, MakeVisitorDefaultCase) {
1115 auto Visitor = makeVisitor([](int I) { return I + 100; },
1116 [](float F) { return F * 2; },
1117 [](auto) { return -1; });
1118 EXPECT_EQ(Visitor(24), 124);
1119 EXPECT_EQ(Visitor(2.f), 4.f);
1120 EXPECT_EQ(Visitor(2.), -1);
1121 EXPECT_EQ(Visitor(Visitor), -1);
1124 auto Visitor = makeVisitor([](auto) { return -1; },
1125 [](int I) { return I + 100; },
1126 [](float F) { return F * 2; });
1127 EXPECT_EQ(Visitor(24), 124);
1128 EXPECT_EQ(Visitor(2.f), 4.f);
1129 EXPECT_EQ(Visitor(2.), -1);
1130 EXPECT_EQ(Visitor(Visitor), -1);
1134 template <bool Moveable, bool Copyable>
1135 struct Functor : Counted<Moveable, Copyable> {
1136 using Counted<Moveable, Copyable>::Counted;
1137 void operator()() {}
1140 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsPRValue) {
1141 int Copies = 0;
1142 int Moves = 0;
1143 int Destructors = 0;
1145 auto V = makeVisitor(Functor<true, false>(Copies, Moves, Destructors));
1146 (void)V;
1147 EXPECT_EQ(0, Copies);
1148 EXPECT_EQ(1, Moves);
1149 EXPECT_EQ(1, Destructors);
1151 EXPECT_EQ(0, Copies);
1152 EXPECT_EQ(1, Moves);
1153 EXPECT_EQ(2, Destructors);
1156 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsRValue) {
1157 int Copies = 0;
1158 int Moves = 0;
1159 int Destructors = 0;
1161 Functor<true, false> F(Copies, Moves, Destructors);
1163 auto V = makeVisitor(std::move(F));
1164 (void)V;
1165 EXPECT_EQ(0, Copies);
1166 EXPECT_EQ(1, Moves);
1167 EXPECT_EQ(0, Destructors);
1169 EXPECT_EQ(0, Copies);
1170 EXPECT_EQ(1, Moves);
1171 EXPECT_EQ(1, Destructors);
1173 EXPECT_EQ(0, Copies);
1174 EXPECT_EQ(1, Moves);
1175 EXPECT_EQ(2, Destructors);
1178 TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsLValue) {
1179 int Copies = 0;
1180 int Moves = 0;
1181 int Destructors = 0;
1183 Functor<true, true> F(Copies, Moves, Destructors);
1185 auto V = makeVisitor(F);
1186 (void)V;
1187 EXPECT_EQ(1, Copies);
1188 EXPECT_EQ(0, Moves);
1189 EXPECT_EQ(0, Destructors);
1191 EXPECT_EQ(1, Copies);
1192 EXPECT_EQ(0, Moves);
1193 EXPECT_EQ(1, Destructors);
1195 EXPECT_EQ(1, Copies);
1196 EXPECT_EQ(0, Moves);
1197 EXPECT_EQ(2, Destructors);
1200 TEST(STLExtrasTest, AllOfZip) {
1201 std::vector<int> v1 = {0, 4, 2, 1};
1202 std::vector<int> v2 = {1, 4, 3, 6};
1203 EXPECT_TRUE(all_of_zip(v1, v2, [](int v1, int v2) { return v1 <= v2; }));
1204 EXPECT_FALSE(all_of_zip(v1, v2, [](int L, int R) { return L < R; }));
1206 // Triple vectors
1207 std::vector<int> v3 = {1, 6, 5, 7};
1208 EXPECT_EQ(true, all_of_zip(v1, v2, v3, [](int a, int b, int c) {
1209 return a <= b && b <= c;
1210 }));
1211 EXPECT_EQ(false, all_of_zip(v1, v2, v3, [](int a, int b, int c) {
1212 return a < b && b < c;
1213 }));
1215 // Shorter vector should fail even with an always-true predicate.
1216 std::vector<int> v_short = {1, 4};
1217 EXPECT_EQ(false, all_of_zip(v1, v_short, [](int, int) { return true; }));
1218 EXPECT_EQ(false,
1219 all_of_zip(v1, v2, v_short, [](int, int, int) { return true; }));
1222 TEST(STLExtrasTest, TypesAreDistinct) {
1223 EXPECT_TRUE((llvm::TypesAreDistinct<>::value));
1224 EXPECT_TRUE((llvm::TypesAreDistinct<int>::value));
1225 EXPECT_FALSE((llvm::TypesAreDistinct<int, int>::value));
1226 EXPECT_TRUE((llvm::TypesAreDistinct<int, float>::value));
1227 EXPECT_FALSE((llvm::TypesAreDistinct<int, float, int>::value));
1228 EXPECT_TRUE((llvm::TypesAreDistinct<int, float, double>::value));
1229 EXPECT_FALSE((llvm::TypesAreDistinct<int, float, double, float>::value));
1230 EXPECT_TRUE((llvm::TypesAreDistinct<int, int *>::value));
1231 EXPECT_TRUE((llvm::TypesAreDistinct<int, int &>::value));
1232 EXPECT_TRUE((llvm::TypesAreDistinct<int, int &&>::value));
1233 EXPECT_TRUE((llvm::TypesAreDistinct<int, const int>::value));
1236 TEST(STLExtrasTest, FirstIndexOfType) {
1237 EXPECT_EQ((llvm::FirstIndexOfType<int, int>::value), 0u);
1238 EXPECT_EQ((llvm::FirstIndexOfType<int, int, int>::value), 0u);
1239 EXPECT_EQ((llvm::FirstIndexOfType<int, float, int>::value), 1u);
1240 EXPECT_EQ((llvm::FirstIndexOfType<int const *, float, int, int const *,
1241 const int>::value),
1242 2u);
1245 TEST(STLExtrasTest, TypeAtIndex) {
1246 EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int>>::value));
1247 EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int, float>>::value));
1248 EXPECT_TRUE((std::is_same<float, llvm::TypeAtIndex<1, int, float>>::value));
1249 EXPECT_TRUE(
1250 (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value));
1251 EXPECT_TRUE(
1252 (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value));
1253 EXPECT_TRUE(
1254 (std::is_same<double, llvm::TypeAtIndex<2, int, float, double>>::value));
1257 enum Doggos {
1258 Floofer,
1259 Woofer,
1260 SubWoofer,
1261 Pupper,
1262 Pupperino,
1263 Longboi,
1266 struct WooferCmp {
1267 // Not copyable.
1268 WooferCmp() = default;
1269 WooferCmp(const WooferCmp &) = delete;
1270 WooferCmp &operator=(const WooferCmp &) = delete;
1272 friend bool operator==(const Doggos &Doggo, const WooferCmp &) {
1273 return Doggo == Doggos::Woofer;
1277 TEST(STLExtrasTest, IsContainedInitializerList) {
1278 EXPECT_TRUE(is_contained({Woofer, SubWoofer}, Woofer));
1279 EXPECT_TRUE(is_contained({Woofer, SubWoofer}, SubWoofer));
1280 EXPECT_FALSE(is_contained({Woofer, SubWoofer}, Pupper));
1282 // Check that the initializer list type and the element type do not have to
1283 // match exactly.
1284 EXPECT_TRUE(is_contained({Floofer, Woofer, SubWoofer}, WooferCmp{}));
1285 EXPECT_FALSE(is_contained({Floofer, SubWoofer}, WooferCmp{}));
1287 EXPECT_TRUE(is_contained({"a", "bb", "ccc", "dddd"}, llvm::StringRef("ccc")));
1288 EXPECT_FALSE(is_contained({"a", "bb", "ccc", "dddd"}, llvm::StringRef("x")));
1290 static_assert(is_contained({Woofer, SubWoofer}, SubWoofer), "SubWoofer!");
1291 static_assert(!is_contained({Woofer, SubWoofer}, Pupper), "Missing Pupper!");
1293 EXPECT_TRUE(is_contained({1, 2, 3, 4}, 3));
1294 EXPECT_FALSE(is_contained({1, 2, 3, 4}, 5));
1296 static_assert(is_contained({1, 2, 3, 4}, 3), "It's there!");
1297 static_assert(!is_contained({1, 2, 3, 4}, 5), "It's not there :(");
1300 TEST(STLExtrasTest, IsContainedMemberContains) {
1301 // Check that `llvm::is_contained` uses the member `.contains()` when
1302 // available. Check that `.contains()` is preferred over `.find()`.
1303 struct Foo {
1304 bool contains(int) const {
1305 ++NumContainsCalls;
1306 return ContainsResult;
1308 int *begin() { return nullptr; }
1309 int *end() { return nullptr; }
1310 int *find(int) { return nullptr; }
1312 bool ContainsResult = false;
1313 mutable unsigned NumContainsCalls = 0;
1314 } Container;
1316 EXPECT_EQ(Container.NumContainsCalls, 0u);
1317 EXPECT_FALSE(is_contained(Container, 1));
1318 EXPECT_EQ(Container.NumContainsCalls, 1u);
1320 Container.ContainsResult = true;
1321 EXPECT_TRUE(is_contained(Container, 1));
1322 EXPECT_EQ(Container.NumContainsCalls, 2u);
1325 TEST(STLExtrasTest, IsContainedMemberFind) {
1326 // Check that `llvm::is_contained` uses the member `.find(x)` when available.
1327 struct Foo {
1328 auto begin() { return Data.begin(); }
1329 auto end() { return Data.end(); }
1330 auto find(int X) {
1331 ++NumFindCalls;
1332 return std::find(begin(), end(), X);
1335 std::vector<int> Data;
1336 mutable unsigned NumFindCalls = 0;
1337 } Container;
1339 Container.Data = {1, 2, 3};
1341 EXPECT_EQ(Container.NumFindCalls, 0u);
1342 EXPECT_TRUE(is_contained(Container, 1));
1343 EXPECT_TRUE(is_contained(Container, 3));
1344 EXPECT_EQ(Container.NumFindCalls, 2u);
1346 EXPECT_FALSE(is_contained(Container, 4));
1347 EXPECT_EQ(Container.NumFindCalls, 3u);
1350 TEST(STLExtrasTest, addEnumValues) {
1351 enum A { Zero = 0, One = 1 };
1352 enum B { IntMax = INT_MAX, ULongLongMax = ULLONG_MAX };
1353 enum class C : unsigned { Two = 2 };
1355 // Non-fixed underlying types, with same underlying types
1356 static_assert(addEnumValues(Zero, One) == 1,
1357 "addEnumValues(Zero, One) failed.");
1358 static_assert(addEnumValues(IntMax, ULongLongMax) ==
1359 INT_MAX + static_cast<unsigned long long>(ULLONG_MAX),
1360 "addEnumValues(IntMax, ULongLongMax) failed.");
1361 // Non-fixed underlying types, with different underlying types
1362 static_assert(addEnumValues(Zero, IntMax) == INT_MAX,
1363 "addEnumValues(Zero, IntMax) failed.");
1364 static_assert(addEnumValues(One, ULongLongMax) ==
1365 1 + static_cast<unsigned long long>(ULLONG_MAX),
1366 "addEnumValues(One, ULongLongMax) failed.");
1367 // Non-fixed underlying type enum and fixed underlying type enum, with same
1368 // underlying types
1369 static_assert(addEnumValues(One, C::Two) == 3,
1370 "addEnumValues(One, C::Two) failed.");
1371 // Non-fixed underlying type enum and fixed underlying type enum, with
1372 // different underlying types
1373 static_assert(addEnumValues(ULongLongMax, C::Two) ==
1374 static_cast<unsigned long long>(ULLONG_MAX) + 2,
1375 "addEnumValues(ULongLongMax, C::Two) failed.");
1378 TEST(STLExtrasTest, LessFirst) {
1380 std::pair<int, int> A(0, 1);
1381 std::pair<int, int> B(1, 0);
1382 EXPECT_TRUE(less_first()(A, B));
1383 EXPECT_FALSE(less_first()(B, A));
1387 std::tuple<int, int> A(0, 1);
1388 std::tuple<int, int> B(1, 0);
1389 EXPECT_TRUE(less_first()(A, B));
1390 EXPECT_FALSE(less_first()(B, A));
1394 TEST(STLExtrasTest, LessSecond) {
1396 std::pair<int, int> A(0, 1);
1397 std::pair<int, int> B(1, 0);
1398 EXPECT_FALSE(less_second()(A, B));
1399 EXPECT_TRUE(less_second()(B, A));
1403 std::tuple<int, int> A(0, 1);
1404 std::tuple<int, int> B(1, 0);
1405 EXPECT_FALSE(less_second()(A, B));
1406 EXPECT_TRUE(less_second()(B, A));
1410 TEST(STLExtrasTest, Mismatch) {
1412 const int MMIndex = 5;
1413 StringRef First = "FooBar";
1414 StringRef Second = "FooBaz";
1415 auto [MMFirst, MMSecond] = mismatch(First, Second);
1416 EXPECT_EQ(MMFirst, First.begin() + MMIndex);
1417 EXPECT_EQ(MMSecond, Second.begin() + MMIndex);
1421 SmallVector<int> First = {0, 1, 2};
1422 SmallVector<int> Second = {0, 1, 2, 3};
1423 auto [MMFirst, MMSecond] = mismatch(First, Second);
1424 EXPECT_EQ(MMFirst, First.end());
1425 EXPECT_EQ(MMSecond, Second.begin() + 3);
1429 SmallVector<int> First = {0, 1};
1430 SmallVector<int> Empty;
1431 auto [MMFirst, MMEmpty] = mismatch(First, Empty);
1432 EXPECT_EQ(MMFirst, First.begin());
1433 EXPECT_EQ(MMEmpty, Empty.begin());
1437 struct Foo;
1438 struct Bar {};
1440 static_assert(is_incomplete_v<Foo>, "Foo is incomplete");
1441 static_assert(!is_incomplete_v<Bar>, "Bar is defined");
1443 } // namespace