1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/test/to_vector.h"
6
7 #include <set>
8
9 #include "base/containers/flat_set.h"
10 #include "testing/gmock/include/gmock/gmock.h"
11 #include "testing/gtest/include/gtest/gtest.h"
12
13 namespace base::test {
14
15 template <class C>
IdentityTest()16 void IdentityTest() {
17 C c = {1, 2, 3, 4, 5};
18 auto vec = ToVector(c);
19 EXPECT_THAT(vec, testing::ElementsAre(1, 2, 3, 4, 5));
20 }
21
22 template <class C>
ProjectionTest()23 void ProjectionTest() {
24 C c = {1, 2, 3, 4, 5};
25 auto vec = ToVector(c, [](int x) { return x + 1; });
26 EXPECT_THAT(vec, testing::ElementsAre(2, 3, 4, 5, 6));
27 }
28
TEST(ToVectorTest,Identity)29 TEST(ToVectorTest, Identity) {
30 IdentityTest<std::vector<int>>();
31 IdentityTest<std::set<int>>();
32 IdentityTest<int[]>();
33 IdentityTest<base::flat_set<int>>();
34 }
35
TEST(ToVectorTest,Projection)36 TEST(ToVectorTest, Projection) {
37 ProjectionTest<std::vector<int>>();
38 ProjectionTest<std::set<int>>();
39 ProjectionTest<int[]>();
40 ProjectionTest<base::flat_set<int>>();
41 }
42
TEST(ToVectorTest,MoveOnly)43 TEST(ToVectorTest, MoveOnly) {
44 struct MoveOnly {
45 MoveOnly() = default;
46
47 MoveOnly(const MoveOnly&) = delete;
48 MoveOnly& operator=(const MoveOnly&) = delete;
49
50 MoveOnly(MoveOnly&&) = default;
51 MoveOnly& operator=(MoveOnly&&) = default;
52 };
53
54 std::vector<MoveOnly> vec(/*size=*/10);
55 auto mapped_vec = ToVector(std::move(vec),
56 [](MoveOnly& value) { return std::move(value); });
57 EXPECT_EQ(mapped_vec.size(), 10U);
58 }
59
60 template <typename C, typename Proj, typename T>
61 constexpr bool CorrectlyProjected =
62 std::is_same_v<T,
63 typename decltype(ToVector(
64 std::declval<C>(),
65 std::declval<Proj>()))::value_type>;
66
TEST(ToVectorTest,CorrectlyProjected)67 TEST(ToVectorTest, CorrectlyProjected) {
68 // Tests that projected types are deduced correctly.
69 constexpr auto proj = [](const auto& value) -> const auto& { return value; };
70 static_assert(CorrectlyProjected<std::vector<std::string>, decltype(proj),
71 std::string>);
72 static_assert(
73 CorrectlyProjected<std::set<std::string>, decltype(&std::string::length),
74 std::size_t>);
75 }
76
77 } // namespace base::test
78