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