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 <cstddef>
18 #include <memory>
19 #include <type_traits>
20 #include <utility>
21 #include <vector>
22
23 #include "gtest/gtest.h"
24 #include "absl/container/internal/hash_generator_testing.h"
25 #include "absl/container/internal/test_allocator.h"
26 #include "absl/container/internal/unordered_map_constructor_test.h"
27 #include "absl/container/internal/unordered_map_lookup_test.h"
28 #include "absl/container/internal/unordered_map_members_test.h"
29 #include "absl/container/internal/unordered_map_modifiers_test.h"
30 #include "absl/log/check.h"
31 #include "absl/meta/type_traits.h"
32 #include "absl/types/any.h"
33
34 namespace absl {
35 ABSL_NAMESPACE_BEGIN
36 namespace container_internal {
37 namespace {
38 using ::absl::container_internal::hash_internal::Enum;
39 using ::absl::container_internal::hash_internal::EnumClass;
40 using ::testing::_;
41 using ::testing::IsEmpty;
42 using ::testing::Pair;
43 using ::testing::UnorderedElementsAre;
44
45 // Check that absl::flat_hash_map works in a global constructor.
46 struct BeforeMain {
BeforeMainabsl::container_internal::__anonb19194e00111::BeforeMain47 BeforeMain() {
48 absl::flat_hash_map<int, int> x;
49 x.insert({1, 1});
50 CHECK(x.find(0) == x.end()) << "x should not contain 0";
51 auto it = x.find(1);
52 CHECK(it != x.end()) << "x should contain 1";
53 CHECK(it->second) << "1 should map to 1";
54 }
55 };
56 const BeforeMain before_main;
57
58 template <class K, class V>
59 using Map = flat_hash_map<K, V, StatefulTestingHash, StatefulTestingEqual,
60 Alloc<std::pair<const K, V>>>;
61
62 static_assert(!std::is_standard_layout<NonStandardLayout>(), "");
63
64 using MapTypes =
65 ::testing::Types<Map<int, int>, Map<std::string, int>,
66 Map<Enum, std::string>, Map<EnumClass, int>,
67 Map<int, NonStandardLayout>, Map<NonStandardLayout, int>>;
68
69 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ConstructorTest, MapTypes);
70 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, LookupTest, MapTypes);
71 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, MembersTest, MapTypes);
72 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ModifiersTest, MapTypes);
73
74 using UniquePtrMapTypes = ::testing::Types<Map<int, std::unique_ptr<int>>>;
75
76 INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, UniquePtrModifiersTest,
77 UniquePtrMapTypes);
78
TEST(FlatHashMap,StandardLayout)79 TEST(FlatHashMap, StandardLayout) {
80 struct Int {
81 explicit Int(size_t value) : value(value) {}
82 Int() : value(0) { ADD_FAILURE(); }
83 Int(const Int& other) : value(other.value) { ADD_FAILURE(); }
84 Int(Int&&) = default;
85 bool operator==(const Int& other) const { return value == other.value; }
86 size_t value;
87 };
88 static_assert(std::is_standard_layout<Int>(), "");
89
90 struct Hash {
91 size_t operator()(const Int& obj) const { return obj.value; }
92 };
93
94 // Verify that neither the key nor the value get default-constructed or
95 // copy-constructed.
96 {
97 flat_hash_map<Int, Int, Hash> m;
98 m.try_emplace(Int(1), Int(2));
99 m.try_emplace(Int(3), Int(4));
100 m.erase(Int(1));
101 m.rehash(2 * m.bucket_count());
102 }
103 {
104 flat_hash_map<Int, Int, Hash> m;
105 m.try_emplace(Int(1), Int(2));
106 m.try_emplace(Int(3), Int(4));
107 m.erase(Int(1));
108 m.clear();
109 }
110 }
111
TEST(FlatHashMap,Relocatability)112 TEST(FlatHashMap, Relocatability) {
113 static_assert(absl::is_trivially_relocatable<int>::value, "");
114 static_assert(
115 absl::is_trivially_relocatable<std::pair<const int, int>>::value, "");
116 static_assert(
117 std::is_same<decltype(absl::container_internal::FlatHashMapPolicy<
118 int, int>::transfer<std::allocator<char>>(nullptr,
119 nullptr,
120 nullptr)),
121 std::true_type>::value,
122 "");
123
124 struct NonRelocatable {
125 NonRelocatable() = default;
126 NonRelocatable(NonRelocatable&&) {}
127 NonRelocatable& operator=(NonRelocatable&&) { return *this; }
128 void* self = nullptr;
129 };
130
131 EXPECT_FALSE(absl::is_trivially_relocatable<NonRelocatable>::value);
132 EXPECT_TRUE(
133 (std::is_same<decltype(absl::container_internal::FlatHashMapPolicy<
134 int, NonRelocatable>::
135 transfer<std::allocator<char>>(nullptr, nullptr,
136 nullptr)),
137 std::false_type>::value));
138 }
139
140 // gcc becomes unhappy if this is inside the method, so pull it out here.
141 struct balast {};
142
TEST(FlatHashMap,IteratesMsan)143 TEST(FlatHashMap, IteratesMsan) {
144 // Because SwissTable randomizes on pointer addresses, we keep old tables
145 // around to ensure we don't reuse old memory.
146 std::vector<absl::flat_hash_map<int, balast>> garbage;
147 for (int i = 0; i < 100; ++i) {
148 absl::flat_hash_map<int, balast> t;
149 for (int j = 0; j < 100; ++j) {
150 t[j];
151 for (const auto& p : t) EXPECT_THAT(p, Pair(_, _));
152 }
153 garbage.push_back(std::move(t));
154 }
155 }
156
157 // Demonstration of the "Lazy Key" pattern. This uses heterogeneous insert to
158 // avoid creating expensive key elements when the item is already present in the
159 // map.
160 struct LazyInt {
LazyIntabsl::container_internal::__anonb19194e00111::LazyInt161 explicit LazyInt(size_t value, int* tracker)
162 : value(value), tracker(tracker) {}
163
operator size_tabsl::container_internal::__anonb19194e00111::LazyInt164 explicit operator size_t() const {
165 ++*tracker;
166 return value;
167 }
168
169 size_t value;
170 int* tracker;
171 };
172
173 struct Hash {
174 using is_transparent = void;
175 int* tracker;
operator ()absl::container_internal::__anonb19194e00111::Hash176 size_t operator()(size_t obj) const {
177 ++*tracker;
178 return obj;
179 }
operator ()absl::container_internal::__anonb19194e00111::Hash180 size_t operator()(const LazyInt& obj) const {
181 ++*tracker;
182 return obj.value;
183 }
184 };
185
186 struct Eq {
187 using is_transparent = void;
operator ()absl::container_internal::__anonb19194e00111::Eq188 bool operator()(size_t lhs, size_t rhs) const { return lhs == rhs; }
operator ()absl::container_internal::__anonb19194e00111::Eq189 bool operator()(size_t lhs, const LazyInt& rhs) const {
190 return lhs == rhs.value;
191 }
192 };
193
TEST(FlatHashMap,LazyKeyPattern)194 TEST(FlatHashMap, LazyKeyPattern) {
195 // hashes are only guaranteed in opt mode, we use assertions to track internal
196 // state that can cause extra calls to hash.
197 int conversions = 0;
198 int hashes = 0;
199 flat_hash_map<size_t, size_t, Hash, Eq> m(0, Hash{&hashes});
200 m.reserve(3);
201
202 m[LazyInt(1, &conversions)] = 1;
203 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 1)));
204 EXPECT_EQ(conversions, 1);
205 #ifdef NDEBUG
206 EXPECT_EQ(hashes, 1);
207 #endif
208
209 m[LazyInt(1, &conversions)] = 2;
210 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2)));
211 EXPECT_EQ(conversions, 1);
212 #ifdef NDEBUG
213 EXPECT_EQ(hashes, 2);
214 #endif
215
216 m.try_emplace(LazyInt(2, &conversions), 3);
217 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
218 EXPECT_EQ(conversions, 2);
219 #ifdef NDEBUG
220 EXPECT_EQ(hashes, 3);
221 #endif
222
223 m.try_emplace(LazyInt(2, &conversions), 4);
224 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
225 EXPECT_EQ(conversions, 2);
226 #ifdef NDEBUG
227 EXPECT_EQ(hashes, 4);
228 #endif
229 }
230
TEST(FlatHashMap,BitfieldArgument)231 TEST(FlatHashMap, BitfieldArgument) {
232 union {
233 int n : 1;
234 };
235 n = 0;
236 flat_hash_map<int, int> m;
237 m.erase(n);
238 m.count(n);
239 m.prefetch(n);
240 m.find(n);
241 m.contains(n);
242 m.equal_range(n);
243 m.insert_or_assign(n, n);
244 m.insert_or_assign(m.end(), n, n);
245 m.try_emplace(n);
246 m.try_emplace(m.end(), n);
247 m.at(n);
248 m[n];
249 }
250
TEST(FlatHashMap,MergeExtractInsert)251 TEST(FlatHashMap, MergeExtractInsert) {
252 // We can't test mutable keys, or non-copyable keys with flat_hash_map.
253 // Test that the nodes have the proper API.
254 absl::flat_hash_map<int, int> m = {{1, 7}, {2, 9}};
255 auto node = m.extract(1);
256 EXPECT_TRUE(node);
257 EXPECT_EQ(node.key(), 1);
258 EXPECT_EQ(node.mapped(), 7);
259 EXPECT_THAT(m, UnorderedElementsAre(Pair(2, 9)));
260
261 node.mapped() = 17;
262 m.insert(std::move(node));
263 EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 17), Pair(2, 9)));
264 }
265
FirstIsEven(std::pair<const int,int> p)266 bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; }
267
TEST(FlatHashMap,EraseIf)268 TEST(FlatHashMap, EraseIf) {
269 // Erase all elements.
270 {
271 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
272 EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return true; }), 5);
273 EXPECT_THAT(s, IsEmpty());
274 }
275 // Erase no elements.
276 {
277 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
278 EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return false; }), 0);
279 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3),
280 Pair(4, 4), Pair(5, 5)));
281 }
282 // Erase specific elements.
283 {
284 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
285 EXPECT_EQ(erase_if(s,
286 [](std::pair<const int, int> kvp) {
287 return kvp.first % 2 == 1;
288 }),
289 3);
290 EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4)));
291 }
292 // Predicate is function reference.
293 {
294 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
295 EXPECT_EQ(erase_if(s, FirstIsEven), 2);
296 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
297 }
298 // Predicate is function pointer.
299 {
300 flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
301 EXPECT_EQ(erase_if(s, &FirstIsEven), 2);
302 EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
303 }
304 }
305
306 // This test requires std::launder for mutable key access in node handles.
307 #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
TEST(FlatHashMap,NodeHandleMutableKeyAccess)308 TEST(FlatHashMap, NodeHandleMutableKeyAccess) {
309 flat_hash_map<std::string, std::string> map;
310
311 map["key1"] = "mapped";
312
313 auto nh = map.extract(map.begin());
314 nh.key().resize(3);
315 map.insert(std::move(nh));
316
317 EXPECT_THAT(map, testing::ElementsAre(Pair("key", "mapped")));
318 }
319 #endif
320
TEST(FlatHashMap,Reserve)321 TEST(FlatHashMap, Reserve) {
322 // Verify that if we reserve(size() + n) then we can perform n insertions
323 // without a rehash, i.e., without invalidating any references.
324 for (size_t trial = 0; trial < 20; ++trial) {
325 for (size_t initial = 3; initial < 100; ++initial) {
326 // Fill in `initial` entries, then erase 2 of them, then reserve space for
327 // two inserts and check for reference stability while doing the inserts.
328 flat_hash_map<size_t, size_t> map;
329 for (size_t i = 0; i < initial; ++i) {
330 map[i] = i;
331 }
332 map.erase(0);
333 map.erase(1);
334 map.reserve(map.size() + 2);
335 size_t& a2 = map[2];
336 // In the event of a failure, asan will complain in one of these two
337 // assignments.
338 map[initial] = a2;
339 map[initial + 1] = a2;
340 // Fail even when not under asan:
341 size_t& a2new = map[2];
342 EXPECT_EQ(&a2, &a2new);
343 }
344 }
345 }
346
TEST(FlatHashMap,RecursiveTypeCompiles)347 TEST(FlatHashMap, RecursiveTypeCompiles) {
348 struct RecursiveType {
349 flat_hash_map<int, RecursiveType> m;
350 };
351 RecursiveType t;
352 t.m[0] = RecursiveType{};
353 }
354
TEST(FlatHashMap,FlatHashMapPolicyDestroyReturnsTrue)355 TEST(FlatHashMap, FlatHashMapPolicyDestroyReturnsTrue) {
356 EXPECT_TRUE(
357 (decltype(FlatHashMapPolicy<int, char>::destroy<std::allocator<char>>(
358 nullptr, nullptr))()));
359 EXPECT_FALSE(
360 (decltype(FlatHashMapPolicy<int, char>::destroy<CountingAllocator<char>>(
361 nullptr, nullptr))()));
362 EXPECT_FALSE((decltype(FlatHashMapPolicy<int, std::unique_ptr<int>>::destroy<
363 std::allocator<char>>(nullptr, nullptr))()));
364 }
365
366 } // namespace
367 } // namespace container_internal
368 ABSL_NAMESPACE_END
369 } // namespace absl
370