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