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 // -----------------------------------------------------------------------------
16 // File: flat_hash_map.h
17 // -----------------------------------------------------------------------------
18 //
19 // An `absl::flat_hash_map<K, V>` is an unordered associative container of
20 // unique keys and associated values designed to be a more efficient replacement
21 // for `std::unordered_map`. Like `unordered_map`, search, insertion, and
22 // deletion of map elements can be done as an `O(1)` operation. However,
23 // `flat_hash_map` (and other unordered associative containers known as the
24 // collection of Abseil "Swiss tables") contain other optimizations that result
25 // in both memory and computation advantages.
26 //
27 // In most cases, your default choice for a hash map should be a map of type
28 // `flat_hash_map`.
29
30 #ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_
31 #define ABSL_CONTAINER_FLAT_HASH_MAP_H_
32
33 #include <cstddef>
34 #include <new>
35 #include <type_traits>
36 #include <utility>
37
38 #include "absl/algorithm/container.h"
39 #include "absl/base/macros.h"
40 #include "absl/container/internal/container_memory.h"
41 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
42 #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
43 #include "absl/memory/memory.h"
44
45 namespace absl {
46 ABSL_NAMESPACE_BEGIN
47 namespace container_internal {
48 template <class K, class V>
49 struct FlatHashMapPolicy;
50 } // namespace container_internal
51
52 // -----------------------------------------------------------------------------
53 // absl::flat_hash_map
54 // -----------------------------------------------------------------------------
55 //
56 // An `absl::flat_hash_map<K, V>` is an unordered associative container which
57 // has been optimized for both speed and memory footprint in most common use
58 // cases. Its interface is similar to that of `std::unordered_map<K, V>` with
59 // the following notable differences:
60 //
61 // * Requires keys that are CopyConstructible
62 // * Requires values that are MoveConstructible
63 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
64 // `insert()`, provided that the map is provided a compatible heterogeneous
65 // hashing function and equality operator.
66 // * Invalidates any references and pointers to elements within the table after
67 // `rehash()`.
68 // * Contains a `capacity()` member function indicating the number of element
69 // slots (open, deleted, and empty) within the hash map.
70 // * Returns `void` from the `erase(iterator)` overload.
71 //
72 // By default, `flat_hash_map` uses the `absl::Hash` hashing framework.
73 // All fundamental and Abseil types that support the `absl::Hash` framework have
74 // a compatible equality operator for comparing insertions into `flat_hash_map`.
75 // If your type is not yet supported by the `absl::Hash` framework, see
76 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
77 // types.
78 //
79 // Using `absl::flat_hash_map` at interface boundaries in dynamically loaded
80 // libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
81 // be randomized across dynamically loaded libraries.
82 //
83 // NOTE: A `flat_hash_map` stores its value types directly inside its
84 // implementation array to avoid memory indirection. Because a `flat_hash_map`
85 // is designed to move data when rehashed, map values will not retain pointer
86 // stability. If you require pointer stability, or if your values are large,
87 // consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead.
88 // If your types are not moveable or you require pointer stability for keys,
89 // consider `absl::node_hash_map`.
90 //
91 // Example:
92 //
93 // // Create a flat hash map of three strings (that map to strings)
94 // absl::flat_hash_map<std::string, std::string> ducks =
95 // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
96 //
97 // // Insert a new element into the flat hash map
98 // ducks.insert({"d", "donald"});
99 //
100 // // Force a rehash of the flat hash map
101 // ducks.rehash(0);
102 //
103 // // Find the element with the key "b"
104 // std::string search_key = "b";
105 // auto result = ducks.find(search_key);
106 // if (result != ducks.end()) {
107 // std::cout << "Result: " << result->second << std::endl;
108 // }
109 template <class K, class V,
110 class Hash = absl::container_internal::hash_default_hash<K>,
111 class Eq = absl::container_internal::hash_default_eq<K>,
112 class Allocator = std::allocator<std::pair<const K, V>>>
113 class flat_hash_map : public absl::container_internal::raw_hash_map<
114 absl::container_internal::FlatHashMapPolicy<K, V>,
115 Hash, Eq, Allocator> {
116 using Base = typename flat_hash_map::raw_hash_map;
117
118 public:
119 // Constructors and Assignment Operators
120 //
121 // A flat_hash_map supports the same overload set as `std::unordered_map`
122 // for construction and assignment:
123 //
124 // * Default constructor
125 //
126 // // No allocation for the table's elements is made.
127 // absl::flat_hash_map<int, std::string> map1;
128 //
129 // * Initializer List constructor
130 //
131 // absl::flat_hash_map<int, std::string> map2 =
132 // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
133 //
134 // * Copy constructor
135 //
136 // absl::flat_hash_map<int, std::string> map3(map2);
137 //
138 // * Copy assignment operator
139 //
140 // // Hash functor and Comparator are copied as well
141 // absl::flat_hash_map<int, std::string> map4;
142 // map4 = map3;
143 //
144 // * Move constructor
145 //
146 // // Move is guaranteed efficient
147 // absl::flat_hash_map<int, std::string> map5(std::move(map4));
148 //
149 // * Move assignment operator
150 //
151 // // May be efficient if allocators are compatible
152 // absl::flat_hash_map<int, std::string> map6;
153 // map6 = std::move(map5);
154 //
155 // * Range constructor
156 //
157 // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
158 // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end());
flat_hash_map()159 flat_hash_map() {}
160 using Base::Base;
161
162 // flat_hash_map::begin()
163 //
164 // Returns an iterator to the beginning of the `flat_hash_map`.
165 using Base::begin;
166
167 // flat_hash_map::cbegin()
168 //
169 // Returns a const iterator to the beginning of the `flat_hash_map`.
170 using Base::cbegin;
171
172 // flat_hash_map::cend()
173 //
174 // Returns a const iterator to the end of the `flat_hash_map`.
175 using Base::cend;
176
177 // flat_hash_map::end()
178 //
179 // Returns an iterator to the end of the `flat_hash_map`.
180 using Base::end;
181
182 // flat_hash_map::capacity()
183 //
184 // Returns the number of element slots (assigned, deleted, and empty)
185 // available within the `flat_hash_map`.
186 //
187 // NOTE: this member function is particular to `absl::flat_hash_map` and is
188 // not provided in the `std::unordered_map` API.
189 using Base::capacity;
190
191 // flat_hash_map::empty()
192 //
193 // Returns whether or not the `flat_hash_map` is empty.
194 using Base::empty;
195
196 // flat_hash_map::max_size()
197 //
198 // Returns the largest theoretical possible number of elements within a
199 // `flat_hash_map` under current memory constraints. This value can be thought
200 // of the largest value of `std::distance(begin(), end())` for a
201 // `flat_hash_map<K, V>`.
202 using Base::max_size;
203
204 // flat_hash_map::size()
205 //
206 // Returns the number of elements currently within the `flat_hash_map`.
207 using Base::size;
208
209 // flat_hash_map::clear()
210 //
211 // Removes all elements from the `flat_hash_map`. Invalidates any references,
212 // pointers, or iterators referring to contained elements.
213 //
214 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
215 // the underlying buffer call `erase(begin(), end())`.
216 using Base::clear;
217
218 // flat_hash_map::erase()
219 //
220 // Erases elements within the `flat_hash_map`. Erasing does not trigger a
221 // rehash. Overloads are listed below.
222 //
223 // void erase(const_iterator pos):
224 //
225 // Erases the element at `position` of the `flat_hash_map`, returning
226 // `void`.
227 //
228 // NOTE: returning `void` in this case is different than that of STL
229 // containers in general and `std::unordered_map` in particular (which
230 // return an iterator to the element following the erased element). If that
231 // iterator is needed, simply post increment the iterator:
232 //
233 // map.erase(it++);
234 //
235 // iterator erase(const_iterator first, const_iterator last):
236 //
237 // Erases the elements in the open interval [`first`, `last`), returning an
238 // iterator pointing to `last`.
239 //
240 // size_type erase(const key_type& key):
241 //
242 // Erases the element with the matching key, if it exists, returning the
243 // number of elements erased (0 or 1).
244 using Base::erase;
245
246 // flat_hash_map::insert()
247 //
248 // Inserts an element of the specified value into the `flat_hash_map`,
249 // returning an iterator pointing to the newly inserted element, provided that
250 // an element with the given key does not already exist. If rehashing occurs
251 // due to the insertion, all iterators are invalidated. Overloads are listed
252 // below.
253 //
254 // std::pair<iterator,bool> insert(const init_type& value):
255 //
256 // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an
257 // iterator to the inserted element (or to the element that prevented the
258 // insertion) and a bool denoting whether the insertion took place.
259 //
260 // std::pair<iterator,bool> insert(T&& value):
261 // std::pair<iterator,bool> insert(init_type&& value):
262 //
263 // Inserts a moveable value into the `flat_hash_map`. Returns a pair
264 // consisting of an iterator to the inserted element (or to the element that
265 // prevented the insertion) and a bool denoting whether the insertion took
266 // place.
267 //
268 // iterator insert(const_iterator hint, const init_type& value):
269 // iterator insert(const_iterator hint, T&& value):
270 // iterator insert(const_iterator hint, init_type&& value);
271 //
272 // Inserts a value, using the position of `hint` as a non-binding suggestion
273 // for where to begin the insertion search. Returns an iterator to the
274 // inserted element, or to the existing element that prevented the
275 // insertion.
276 //
277 // void insert(InputIterator first, InputIterator last):
278 //
279 // Inserts a range of values [`first`, `last`).
280 //
281 // NOTE: Although the STL does not specify which element may be inserted if
282 // multiple keys compare equivalently, for `flat_hash_map` we guarantee the
283 // first match is inserted.
284 //
285 // void insert(std::initializer_list<init_type> ilist):
286 //
287 // Inserts the elements within the initializer list `ilist`.
288 //
289 // NOTE: Although the STL does not specify which element may be inserted if
290 // multiple keys compare equivalently within the initializer list, for
291 // `flat_hash_map` we guarantee the first match is inserted.
292 using Base::insert;
293
294 // flat_hash_map::insert_or_assign()
295 //
296 // Inserts an element of the specified value into the `flat_hash_map` provided
297 // that a value with the given key does not already exist, or replaces it with
298 // the element value if a key for that value already exists, returning an
299 // iterator pointing to the newly inserted element. If rehashing occurs due
300 // to the insertion, all existing iterators are invalidated. Overloads are
301 // listed below.
302 //
303 // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
304 // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
305 //
306 // Inserts/Assigns (or moves) the element of the specified key into the
307 // `flat_hash_map`.
308 //
309 // iterator insert_or_assign(const_iterator hint,
310 // const init_type& k, T&& obj):
311 // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
312 //
313 // Inserts/Assigns (or moves) the element of the specified key into the
314 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
315 // for where to begin the insertion search.
316 using Base::insert_or_assign;
317
318 // flat_hash_map::emplace()
319 //
320 // Inserts an element of the specified value by constructing it in-place
321 // within the `flat_hash_map`, provided that no element with the given key
322 // already exists.
323 //
324 // The element may be constructed even if there already is an element with the
325 // key in the container, in which case the newly constructed element will be
326 // destroyed immediately. Prefer `try_emplace()` unless your key is not
327 // copyable or moveable.
328 //
329 // If rehashing occurs due to the insertion, all iterators are invalidated.
330 using Base::emplace;
331
332 // flat_hash_map::emplace_hint()
333 //
334 // Inserts an element of the specified value by constructing it in-place
335 // within the `flat_hash_map`, using the position of `hint` as a non-binding
336 // suggestion for where to begin the insertion search, and only inserts
337 // provided that no element with the given key already exists.
338 //
339 // The element may be constructed even if there already is an element with the
340 // key in the container, in which case the newly constructed element will be
341 // destroyed immediately. Prefer `try_emplace()` unless your key is not
342 // copyable or moveable.
343 //
344 // If rehashing occurs due to the insertion, all iterators are invalidated.
345 using Base::emplace_hint;
346
347 // flat_hash_map::try_emplace()
348 //
349 // Inserts an element of the specified value by constructing it in-place
350 // within the `flat_hash_map`, provided that no element with the given key
351 // already exists. Unlike `emplace()`, if an element with the given key
352 // already exists, we guarantee that no element is constructed.
353 //
354 // If rehashing occurs due to the insertion, all iterators are invalidated.
355 // Overloads are listed below.
356 //
357 // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
358 // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
359 //
360 // Inserts (via copy or move) the element of the specified key into the
361 // `flat_hash_map`.
362 //
363 // iterator try_emplace(const_iterator hint,
364 // const key_type& k, Args&&... args):
365 // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
366 //
367 // Inserts (via copy or move) the element of the specified key into the
368 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
369 // for where to begin the insertion search.
370 //
371 // All `try_emplace()` overloads make the same guarantees regarding rvalue
372 // arguments as `std::unordered_map::try_emplace()`, namely that these
373 // functions will not move from rvalue arguments if insertions do not happen.
374 using Base::try_emplace;
375
376 // flat_hash_map::extract()
377 //
378 // Extracts the indicated element, erasing it in the process, and returns it
379 // as a C++17-compatible node handle. Overloads are listed below.
380 //
381 // node_type extract(const_iterator position):
382 //
383 // Extracts the key,value pair of the element at the indicated position and
384 // returns a node handle owning that extracted data.
385 //
386 // node_type extract(const key_type& x):
387 //
388 // Extracts the key,value pair of the element with a key matching the passed
389 // key value and returns a node handle owning that extracted data. If the
390 // `flat_hash_map` does not contain an element with a matching key, this
391 // function returns an empty node handle.
392 //
393 // NOTE: when compiled in an earlier version of C++ than C++17,
394 // `node_type::key()` returns a const reference to the key instead of a
395 // mutable reference. We cannot safely return a mutable reference without
396 // std::launder (which is not available before C++17).
397 using Base::extract;
398
399 // flat_hash_map::merge()
400 //
401 // Extracts elements from a given `source` flat hash map into this
402 // `flat_hash_map`. If the destination `flat_hash_map` already contains an
403 // element with an equivalent key, that element is not extracted.
404 using Base::merge;
405
406 // flat_hash_map::swap(flat_hash_map& other)
407 //
408 // Exchanges the contents of this `flat_hash_map` with those of the `other`
409 // flat hash map, avoiding invocation of any move, copy, or swap operations on
410 // individual elements.
411 //
412 // All iterators and references on the `flat_hash_map` remain valid, excepting
413 // for the past-the-end iterator, which is invalidated.
414 //
415 // `swap()` requires that the flat hash map's hashing and key equivalence
416 // functions be Swappable, and are exchanged using unqualified calls to
417 // non-member `swap()`. If the map's allocator has
418 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
419 // set to `true`, the allocators are also exchanged using an unqualified call
420 // to non-member `swap()`; otherwise, the allocators are not swapped.
421 using Base::swap;
422
423 // flat_hash_map::rehash(count)
424 //
425 // Rehashes the `flat_hash_map`, setting the number of slots to be at least
426 // the passed value. If the new number of slots increases the load factor more
427 // than the current maximum load factor
428 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
429 // will be at least `size()` / `max_load_factor()`.
430 //
431 // To force a rehash, pass rehash(0).
432 //
433 // NOTE: unlike behavior in `std::unordered_map`, references are also
434 // invalidated upon a `rehash()`.
435 using Base::rehash;
436
437 // flat_hash_map::reserve(count)
438 //
439 // Sets the number of slots in the `flat_hash_map` to the number needed to
440 // accommodate at least `count` total elements without exceeding the current
441 // maximum load factor, and may rehash the container if needed.
442 using Base::reserve;
443
444 // flat_hash_map::at()
445 //
446 // Returns a reference to the mapped value of the element with key equivalent
447 // to the passed key.
448 using Base::at;
449
450 // flat_hash_map::contains()
451 //
452 // Determines whether an element with a key comparing equal to the given `key`
453 // exists within the `flat_hash_map`, returning `true` if so or `false`
454 // otherwise.
455 using Base::contains;
456
457 // flat_hash_map::count(const Key& key) const
458 //
459 // Returns the number of elements with a key comparing equal to the given
460 // `key` within the `flat_hash_map`. note that this function will return
461 // either `1` or `0` since duplicate keys are not allowed within a
462 // `flat_hash_map`.
463 using Base::count;
464
465 // flat_hash_map::equal_range()
466 //
467 // Returns a closed range [first, last], defined by a `std::pair` of two
468 // iterators, containing all elements with the passed key in the
469 // `flat_hash_map`.
470 using Base::equal_range;
471
472 // flat_hash_map::find()
473 //
474 // Finds an element with the passed `key` within the `flat_hash_map`.
475 using Base::find;
476
477 // flat_hash_map::operator[]()
478 //
479 // Returns a reference to the value mapped to the passed key within the
480 // `flat_hash_map`, performing an `insert()` if the key does not already
481 // exist.
482 //
483 // If an insertion occurs and results in a rehashing of the container, all
484 // iterators are invalidated. Otherwise iterators are not affected and
485 // references are not invalidated. Overloads are listed below.
486 //
487 // T& operator[](const Key& key):
488 //
489 // Inserts an init_type object constructed in-place if the element with the
490 // given key does not exist.
491 //
492 // T& operator[](Key&& key):
493 //
494 // Inserts an init_type object constructed in-place provided that an element
495 // with the given key does not exist.
496 using Base::operator[];
497
498 // flat_hash_map::bucket_count()
499 //
500 // Returns the number of "buckets" within the `flat_hash_map`. Note that
501 // because a flat hash map contains all elements within its internal storage,
502 // this value simply equals the current capacity of the `flat_hash_map`.
503 using Base::bucket_count;
504
505 // flat_hash_map::load_factor()
506 //
507 // Returns the current load factor of the `flat_hash_map` (the average number
508 // of slots occupied with a value within the hash map).
509 using Base::load_factor;
510
511 // flat_hash_map::max_load_factor()
512 //
513 // Manages the maximum load factor of the `flat_hash_map`. Overloads are
514 // listed below.
515 //
516 // float flat_hash_map::max_load_factor()
517 //
518 // Returns the current maximum load factor of the `flat_hash_map`.
519 //
520 // void flat_hash_map::max_load_factor(float ml)
521 //
522 // Sets the maximum load factor of the `flat_hash_map` to the passed value.
523 //
524 // NOTE: This overload is provided only for API compatibility with the STL;
525 // `flat_hash_map` will ignore any set load factor and manage its rehashing
526 // internally as an implementation detail.
527 using Base::max_load_factor;
528
529 // flat_hash_map::get_allocator()
530 //
531 // Returns the allocator function associated with this `flat_hash_map`.
532 using Base::get_allocator;
533
534 // flat_hash_map::hash_function()
535 //
536 // Returns the hashing function used to hash the keys within this
537 // `flat_hash_map`.
538 using Base::hash_function;
539
540 // flat_hash_map::key_eq()
541 //
542 // Returns the function used for comparing keys equality.
543 using Base::key_eq;
544 };
545
546 // erase_if(flat_hash_map<>, Pred)
547 //
548 // Erases all elements that satisfy the predicate `pred` from the container `c`.
549 // Returns the number of erased elements.
550 template <typename K, typename V, typename H, typename E, typename A,
551 typename Predicate>
erase_if(flat_hash_map<K,V,H,E,A> & c,Predicate pred)552 typename flat_hash_map<K, V, H, E, A>::size_type erase_if(
553 flat_hash_map<K, V, H, E, A>& c, Predicate pred) {
554 return container_internal::EraseIf(pred, &c);
555 }
556
557 namespace container_internal {
558
559 template <class K, class V>
560 struct FlatHashMapPolicy {
561 using slot_policy = container_internal::map_slot_policy<K, V>;
562 using slot_type = typename slot_policy::slot_type;
563 using key_type = K;
564 using mapped_type = V;
565 using init_type = std::pair</*non const*/ key_type, mapped_type>;
566
567 template <class Allocator, class... Args>
constructFlatHashMapPolicy568 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
569 slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
570 }
571
572 template <class Allocator>
destroyFlatHashMapPolicy573 static void destroy(Allocator* alloc, slot_type* slot) {
574 slot_policy::destroy(alloc, slot);
575 }
576
577 template <class Allocator>
transferFlatHashMapPolicy578 static void transfer(Allocator* alloc, slot_type* new_slot,
579 slot_type* old_slot) {
580 slot_policy::transfer(alloc, new_slot, old_slot);
581 }
582
583 template <class F, class... Args>
decltypeFlatHashMapPolicy584 static decltype(absl::container_internal::DecomposePair(
585 std::declval<F>(), std::declval<Args>()...))
586 apply(F&& f, Args&&... args) {
587 return absl::container_internal::DecomposePair(std::forward<F>(f),
588 std::forward<Args>(args)...);
589 }
590
space_usedFlatHashMapPolicy591 static size_t space_used(const slot_type*) { return 0; }
592
elementFlatHashMapPolicy593 static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
594
valueFlatHashMapPolicy595 static V& value(std::pair<const K, V>* kv) { return kv->second; }
valueFlatHashMapPolicy596 static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
597 };
598
599 } // namespace container_internal
600
601 namespace container_algorithm_internal {
602
603 // Specialization of trait in absl/algorithm/container.h
604 template <class Key, class T, class Hash, class KeyEqual, class Allocator>
605 struct IsUnorderedContainer<
606 absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
607
608 } // namespace container_algorithm_internal
609
610 ABSL_NAMESPACE_END
611 } // namespace absl
612
613 #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_
614