• 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, returning the
229   //   number of elements erased (0 or 1).
230   using Base::erase;
231 
232   // node_hash_map::insert()
233   //
234   // Inserts an element of the specified value into the `node_hash_map`,
235   // returning an iterator pointing to the newly inserted element, provided that
236   // an element with the given key does not already exist. If rehashing occurs
237   // due to the insertion, all iterators are invalidated. Overloads are listed
238   // below.
239   //
240   // std::pair<iterator,bool> insert(const init_type& value):
241   //
242   //   Inserts a value into the `node_hash_map`. Returns a pair consisting of an
243   //   iterator to the inserted element (or to the element that prevented the
244   //   insertion) and a `bool` denoting whether the insertion took place.
245   //
246   // std::pair<iterator,bool> insert(T&& value):
247   // std::pair<iterator,bool> insert(init_type&& value):
248   //
249   //   Inserts a moveable value into the `node_hash_map`. Returns a `std::pair`
250   //   consisting of an iterator to the inserted element (or to the element that
251   //   prevented the insertion) and a `bool` denoting whether the insertion took
252   //   place.
253   //
254   // iterator insert(const_iterator hint, const init_type& value):
255   // iterator insert(const_iterator hint, T&& value):
256   // iterator insert(const_iterator hint, init_type&& value);
257   //
258   //   Inserts a value, using the position of `hint` as a non-binding suggestion
259   //   for where to begin the insertion search. Returns an iterator to the
260   //   inserted element, or to the existing element that prevented the
261   //   insertion.
262   //
263   // void insert(InputIterator first, InputIterator last):
264   //
265   //   Inserts a range of values [`first`, `last`).
266   //
267   //   NOTE: Although the STL does not specify which element may be inserted if
268   //   multiple keys compare equivalently, for `node_hash_map` we guarantee the
269   //   first match is inserted.
270   //
271   // void insert(std::initializer_list<init_type> ilist):
272   //
273   //   Inserts the elements within the initializer list `ilist`.
274   //
275   //   NOTE: Although the STL does not specify which element may be inserted if
276   //   multiple keys compare equivalently within the initializer list, for
277   //   `node_hash_map` we guarantee the first match is inserted.
278   using Base::insert;
279 
280   // node_hash_map::insert_or_assign()
281   //
282   // Inserts an element of the specified value into the `node_hash_map` provided
283   // that a value with the given key does not already exist, or replaces it with
284   // the element value if a key for that value already exists, returning an
285   // iterator pointing to the newly inserted element. If rehashing occurs due to
286   // the insertion, all iterators are invalidated. Overloads are listed
287   // below.
288   //
289   // std::pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
290   // std::pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
291   //
292   //   Inserts/Assigns (or moves) the element of the specified key into the
293   //   `node_hash_map`.
294   //
295   // iterator insert_or_assign(const_iterator hint,
296   //                           const init_type& k, T&& obj):
297   // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
298   //
299   //   Inserts/Assigns (or moves) the element of the specified key into the
300   //   `node_hash_map` using the position of `hint` as a non-binding suggestion
301   //   for where to begin the insertion search.
302   using Base::insert_or_assign;
303 
304   // node_hash_map::emplace()
305   //
306   // Inserts an element of the specified value by constructing it in-place
307   // within the `node_hash_map`, provided that no element with the given key
308   // already exists.
309   //
310   // The element may be constructed even if there already is an element with the
311   // key in the container, in which case the newly constructed element will be
312   // destroyed immediately. Prefer `try_emplace()` unless your key is not
313   // copyable or moveable.
314   //
315   // If rehashing occurs due to the insertion, all iterators are invalidated.
316   using Base::emplace;
317 
318   // node_hash_map::emplace_hint()
319   //
320   // Inserts an element of the specified value by constructing it in-place
321   // within the `node_hash_map`, using the position of `hint` as a non-binding
322   // suggestion for where to begin the insertion search, and only inserts
323   // provided that no element with the given key already exists.
324   //
325   // The element may be constructed even if there already is an element with the
326   // key in the container, in which case the newly constructed element will be
327   // destroyed immediately. Prefer `try_emplace()` unless your key is not
328   // copyable or moveable.
329   //
330   // If rehashing occurs due to the insertion, all iterators are invalidated.
331   using Base::emplace_hint;
332 
333   // node_hash_map::try_emplace()
334   //
335   // Inserts an element of the specified value by constructing it in-place
336   // within the `node_hash_map`, provided that no element with the given key
337   // already exists. Unlike `emplace()`, if an element with the given key
338   // already exists, we guarantee that no element is constructed.
339   //
340   // If rehashing occurs due to the insertion, all iterators are invalidated.
341   // Overloads are listed below.
342   //
343   //   std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
344   //   std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
345   //
346   // Inserts (via copy or move) the element of the specified key into the
347   // `node_hash_map`.
348   //
349   //   iterator try_emplace(const_iterator hint,
350   //                        const init_type& k, Args&&... args):
351   //   iterator try_emplace(const_iterator hint, init_type&& k, Args&&... args):
352   //
353   // Inserts (via copy or move) the element of the specified key into the
354   // `node_hash_map` using the position of `hint` as a non-binding suggestion
355   // for where to begin the insertion search.
356   //
357   // All `try_emplace()` overloads make the same guarantees regarding rvalue
358   // arguments as `std::unordered_map::try_emplace()`, namely that these
359   // functions will not move from rvalue arguments if insertions do not happen.
360   using Base::try_emplace;
361 
362   // node_hash_map::extract()
363   //
364   // Extracts the indicated element, erasing it in the process, and returns it
365   // as a C++17-compatible node handle. Overloads are listed below.
366   //
367   // node_type extract(const_iterator position):
368   //
369   //   Extracts the key,value pair of the element at the indicated position and
370   //   returns a node handle owning that extracted data.
371   //
372   // node_type extract(const key_type& x):
373   //
374   //   Extracts the key,value pair of the element with a key matching the passed
375   //   key value and returns a node handle owning that extracted data. If the
376   //   `node_hash_map` does not contain an element with a matching key, this
377   //   function returns an empty node handle.
378   //
379   // NOTE: when compiled in an earlier version of C++ than C++17,
380   // `node_type::key()` returns a const reference to the key instead of a
381   // mutable reference. We cannot safely return a mutable reference without
382   // std::launder (which is not available before C++17).
383   using Base::extract;
384 
385   // node_hash_map::merge()
386   //
387   // Extracts elements from a given `source` node hash map into this
388   // `node_hash_map`. If the destination `node_hash_map` already contains an
389   // element with an equivalent key, that element is not extracted.
390   using Base::merge;
391 
392   // node_hash_map::swap(node_hash_map& other)
393   //
394   // Exchanges the contents of this `node_hash_map` with those of the `other`
395   // node hash map, avoiding invocation of any move, copy, or swap operations on
396   // individual elements.
397   //
398   // All iterators and references on the `node_hash_map` remain valid, excepting
399   // for the past-the-end iterator, which is invalidated.
400   //
401   // `swap()` requires that the node hash map's hashing and key equivalence
402   // functions be Swappable, and are exchaged using unqualified calls to
403   // non-member `swap()`. If the map's allocator has
404   // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
405   // set to `true`, the allocators are also exchanged using an unqualified call
406   // to non-member `swap()`; otherwise, the allocators are not swapped.
407   using Base::swap;
408 
409   // node_hash_map::rehash(count)
410   //
411   // Rehashes the `node_hash_map`, setting the number of slots to be at least
412   // the passed value. If the new number of slots increases the load factor more
413   // than the current maximum load factor
414   // (`count` < `size()` / `max_load_factor()`), then the new number of slots
415   // will be at least `size()` / `max_load_factor()`.
416   //
417   // To force a rehash, pass rehash(0).
418   using Base::rehash;
419 
420   // node_hash_map::reserve(count)
421   //
422   // Sets the number of slots in the `node_hash_map` to the number needed to
423   // accommodate at least `count` total elements without exceeding the current
424   // maximum load factor, and may rehash the container if needed.
425   using Base::reserve;
426 
427   // node_hash_map::at()
428   //
429   // Returns a reference to the mapped value of the element with key equivalent
430   // to the passed key.
431   using Base::at;
432 
433   // node_hash_map::contains()
434   //
435   // Determines whether an element with a key comparing equal to the given `key`
436   // exists within the `node_hash_map`, returning `true` if so or `false`
437   // otherwise.
438   using Base::contains;
439 
440   // node_hash_map::count(const Key& key) const
441   //
442   // Returns the number of elements with a key comparing equal to the given
443   // `key` within the `node_hash_map`. note that this function will return
444   // either `1` or `0` since duplicate keys are not allowed within a
445   // `node_hash_map`.
446   using Base::count;
447 
448   // node_hash_map::equal_range()
449   //
450   // Returns a closed range [first, last], defined by a `std::pair` of two
451   // iterators, containing all elements with the passed key in the
452   // `node_hash_map`.
453   using Base::equal_range;
454 
455   // node_hash_map::find()
456   //
457   // Finds an element with the passed `key` within the `node_hash_map`.
458   using Base::find;
459 
460   // node_hash_map::operator[]()
461   //
462   // Returns a reference to the value mapped to the passed key within the
463   // `node_hash_map`, performing an `insert()` if the key does not already
464   // exist. If an insertion occurs and results in a rehashing of the container,
465   // all iterators are invalidated. Otherwise iterators are not affected and
466   // references are not invalidated. Overloads are listed below.
467   //
468   // T& operator[](const Key& key):
469   //
470   //   Inserts an init_type object constructed in-place if the element with the
471   //   given key does not exist.
472   //
473   // T& operator[](Key&& key):
474   //
475   //   Inserts an init_type object constructed in-place provided that an element
476   //   with the given key does not exist.
477   using Base::operator[];
478 
479   // node_hash_map::bucket_count()
480   //
481   // Returns the number of "buckets" within the `node_hash_map`.
482   using Base::bucket_count;
483 
484   // node_hash_map::load_factor()
485   //
486   // Returns the current load factor of the `node_hash_map` (the average number
487   // of slots occupied with a value within the hash map).
488   using Base::load_factor;
489 
490   // node_hash_map::max_load_factor()
491   //
492   // Manages the maximum load factor of the `node_hash_map`. Overloads are
493   // listed below.
494   //
495   // float node_hash_map::max_load_factor()
496   //
497   //   Returns the current maximum load factor of the `node_hash_map`.
498   //
499   // void node_hash_map::max_load_factor(float ml)
500   //
501   //   Sets the maximum load factor of the `node_hash_map` to the passed value.
502   //
503   //   NOTE: This overload is provided only for API compatibility with the STL;
504   //   `node_hash_map` will ignore any set load factor and manage its rehashing
505   //   internally as an implementation detail.
506   using Base::max_load_factor;
507 
508   // node_hash_map::get_allocator()
509   //
510   // Returns the allocator function associated with this `node_hash_map`.
511   using Base::get_allocator;
512 
513   // node_hash_map::hash_function()
514   //
515   // Returns the hashing function used to hash the keys within this
516   // `node_hash_map`.
517   using Base::hash_function;
518 
519   // node_hash_map::key_eq()
520   //
521   // Returns the function used for comparing keys equality.
522   using Base::key_eq;
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