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