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