1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/container/flat_hash_map.h"
16
17 #include <memory>
18
19 #include "absl/container/internal/hash_generator_testing.h"
20 #include "absl/container/internal/unordered_map_constructor_test.h"
21 #include "absl/container/internal/unordered_map_lookup_test.h"
22 #include "absl/container/internal/unordered_map_members_test.h"
23 #include "absl/container/internal/unordered_map_modifiers_test.h"
24 #include "absl/types/any.h"
25
26 namespace absl {
27 ABSL_NAMESPACE_BEGIN
28 namespace container_internal {
29 namespace {
30 using ::absl::container_internal::hash_internal::Enum;
31 using ::absl::container_internal::hash_internal::EnumClass;
32 using ::testing::_;
33 using ::testing::IsEmpty;
34 using ::testing::Pair;
35 using ::testing::UnorderedElementsAre;
36
37 template <class K, class V>
38 using Map = flat_hash_map<K, V, StatefulTestingHash, StatefulTestingEqual,
39 Alloc<std::pair<const K, V>>>;
40
41 static_assert(!std::is_standard_layout<NonStandardLayout>(), "");
42
43 using MapTypes =
44 ::testing::Types<Map<int, int>, Map<std::string, int>,
45 Map<Enum, std::string>, Map<EnumClass, int>,
46 Map<int, NonStandardLayout>, Map<NonStandardLayout, int>>;
47
48 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ConstructorTest, MapTypes);
49 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, LookupTest, MapTypes);
50 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, MembersTest, MapTypes);
51 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ModifiersTest, MapTypes);
52
53 using UniquePtrMapTypes = ::testing::Types<Map<int, std::unique_ptr<int>>>;
54
55 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, UniquePtrModifiersTest,
56 UniquePtrMapTypes);
57
TEST(FlatHashMap,StandardLayout)58 TEST(FlatHashMap, StandardLayout) {
59 struct Int {
60 explicit Int(size_t value) : value(value) {}
61 Int() : value(0) { ADD_FAILURE(); }
62 Int(const Int& other) : value(other.value) { ADD_FAILURE(); }
63 Int(Int&&) = default;
64 bool operator==(const Int& other) const { return value == other.value; }
65 size_t value;
66 };
67 static_assert(std::is_standard_layout<Int>(), "");
68
69 struct Hash {
70 size_t operator()(const Int& obj) const { return obj.value; }
71 };
72
73 // Verify that neither the key nor the value get default-constructed or
74 // copy-constructed.
75 {
76 flat_hash_map<Int, Int, Hash> m;
77 m.try_emplace(Int(1), Int(2));
78 m.try_emplace(Int(3), Int(4));
79 m.erase(Int(1));
80 m.rehash(2 * m.bucket_count());
81 }
82 {
83 flat_hash_map<Int, Int, Hash> m;
84 m.try_emplace(Int(1), Int(2));
85 m.try_emplace(Int(3), Int(4));
86 m.erase(Int(1));
87 m.clear();
88 }
89 }
90
91 // gcc becomes unhappy if this is inside the method, so pull it out here.
92 struct balast {};
93
TEST(FlatHashMap,IteratesMsan)94 TEST(FlatHashMap, IteratesMsan) {
95 // Because SwissTable randomizes on pointer addresses, we keep old tables
96 // around to ensure we don't reuse old memory.
97 std::vector<absl::flat_hash_map<int, balast>> garbage;
98 for (int i = 0; i < 100; ++i) {
99 absl::flat_hash_map<int, balast> t;
100 for (int j = 0; j < 100; ++j) {
101 t[j];
102 for (const auto& p : t) EXPECT_THAT(p, Pair(_, _));
103 }
104 garbage.push_back(std::move(t));
105 }
106 }
107
108 // Demonstration of the "Lazy Key" pattern. This uses heterogeneous insert to
109 // avoid creating expensive key elements when the item is already present in the
110 // map.
111 struct LazyInt {
LazyIntabsl::container_internal::__anonf63f9aa50111::LazyInt112 explicit LazyInt(size_t value, int* tracker)
113 : value(value), tracker(tracker) {}
114
operator size_tabsl::container_internal::__anonf63f9aa50111::LazyInt115 explicit operator size_t() const {
116 ++*tracker;
117 return value;
118 }
119
120 size_t value;
121 int* tracker;
122 };
123
124 struct Hash {
125 using is_transparent = void;
126 int* tracker;
operator ()absl::container_internal::__anonf63f9aa50111::Hash127 size_t operator()(size_t obj) const {
128 ++*tracker;
129 return obj;
130 }
operator ()absl::container_internal::__anonf63f9aa50111::Hash131 size_t operator()(const LazyInt& obj) const {
132 ++*tracker;
133 return obj.value;
134 }
135 };
136
137 struct Eq {
138 using is_transparent = void;
operator ()absl::container_internal::__anonf63f9aa50111::Eq139 bool operator()(size_t lhs, size_t rhs) const {
140 return lhs == rhs;
141 }
operator ()absl::container_internal::__anonf63f9aa50111::Eq142 bool operator()(size_t lhs, const LazyInt& rhs) const {
143 return lhs == rhs.value;
144 }
145 };
146
TEST(FlatHashMap,LazyKeyPattern)147 TEST(FlatHashMap, LazyKeyPattern) {
148 // hashes are only guaranteed in opt mode, we use assertions to track internal
149 // state that can cause extra calls to hash.
150 int conversions = 0;
151 int hashes = 0;
152 flat_hash_map<size_t, size_t, Hash, Eq> m(0, Hash{&hashes});
153 m.reserve(3);
154
155 m[LazyInt(1, &conversions)] = 1;
156 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 1)));
157 EXPECT_EQ(conversions, 1);
158 #ifdef NDEBUG
159 EXPECT_EQ(hashes, 1);
160 #endif
161
162 m[LazyInt(1, &conversions)] = 2;
163 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2)));
164 EXPECT_EQ(conversions, 1);
165 #ifdef NDEBUG
166 EXPECT_EQ(hashes, 2);
167 #endif
168
169 m.try_emplace(LazyInt(2, &conversions), 3);
170 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
171 EXPECT_EQ(conversions, 2);
172 #ifdef NDEBUG
173 EXPECT_EQ(hashes, 3);
174 #endif
175
176 m.try_emplace(LazyInt(2, &conversions), 4);
177 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
178 EXPECT_EQ(conversions, 2);
179 #ifdef NDEBUG
180 EXPECT_EQ(hashes, 4);
181 #endif
182 }
183
TEST(FlatHashMap,BitfieldArgument)184 TEST(FlatHashMap, BitfieldArgument) {
185 union {
186 int n : 1;
187 };
188 n = 0;
189 flat_hash_map<int, int> m;
190 m.erase(n);
191 m.count(n);
192 m.prefetch(n);
193 m.find(n);
194 m.contains(n);
195 m.equal_range(n);
196 m.insert_or_assign(n, n);
197 m.insert_or_assign(m.end(), n, n);
198 m.try_emplace(n);
199 m.try_emplace(m.end(), n);
200 m.at(n);
201 m[n];
202 }
203
TEST(FlatHashMap,MergeExtractInsert)204 TEST(FlatHashMap, MergeExtractInsert) {
205 // We can't test mutable keys, or non-copyable keys with flat_hash_map.
206 // Test that the nodes have the proper API.
207 absl::flat_hash_map<int, int> m = {{1, 7}, {2, 9}};
208 auto node = m.extract(1);
209 EXPECT_TRUE(node);
210 EXPECT_EQ(node.key(), 1);
211 EXPECT_EQ(node.mapped(), 7);
212 EXPECT_THAT(m, UnorderedElementsAre(Pair(2, 9)));
213
214 node.mapped() = 17;
215 m.insert(std::move(node));
216 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 17), Pair(2, 9)));
217 }
218
FirstIsEven(std::pair<const int,int> p)219 bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; }
220
TEST(FlatHashMap,EraseIf)221 TEST(FlatHashMap, EraseIf) {
222 // Erase all elements.
223 {
224 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
225 erase_if(s, [](std::pair<const int, int>) { return true; });
226 EXPECT_THAT(s, IsEmpty());
227 }
228 // Erase no elements.
229 {
230 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
231 erase_if(s, [](std::pair<const int, int>) { return false; });
232 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3),
233 Pair(4, 4), Pair(5, 5)));
234 }
235 // Erase specific elements.
236 {
237 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
238 erase_if(s,
239 [](std::pair<const int, int> kvp) { return kvp.first % 2 == 1; });
240 EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4)));
241 }
242 // Predicate is function reference.
243 {
244 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
245 erase_if(s, FirstIsEven);
246 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
247 }
248 // Predicate is function pointer.
249 {
250 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
251 erase_if(s, &FirstIsEven);
252 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
253 }
254 }
255
256 } // namespace
257 } // namespace container_internal
258 ABSL_NAMESPACE_END
259 } // namespace absl
260