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_set.h
17 // -----------------------------------------------------------------------------
18 //
19 // An `absl::node_hash_set<T>` is an unordered associative container designed to
20 // be a more efficient replacement for `std::unordered_set`. Like
21 // `unordered_set`, search, insertion, and deletion of map elements can be done
22 // as an `O(1)` operation. However, `node_hash_set` (and other unordered
23 // associative containers known as the collection of Abseil "Swiss tables")
24 // contain other optimizations that result in both memory and computation
25 // advantages.
26 //
27 // In most cases, your default choice for a hash table should be a map of type
28 // `flat_hash_map` or a set of type `flat_hash_set`. However, if you need
29 // pointer stability, a `node_hash_set` should be your preferred choice. As
30 // well, if you are migrating your code from using `std::unordered_set`, a
31 // `node_hash_set` should be an easy migration. Consider migrating to
32 // `node_hash_set` and perhaps converting to a more efficient `flat_hash_set`
33 // upon further review.
34 
35 #ifndef ABSL_CONTAINER_NODE_HASH_SET_H_
36 #define ABSL_CONTAINER_NODE_HASH_SET_H_
37 
38 #include <type_traits>
39 
40 #include "absl/algorithm/container.h"
41 #include "absl/container/internal/hash_function_defaults.h"  // IWYU pragma: export
42 #include "absl/container/internal/node_hash_policy.h"
43 #include "absl/container/internal/raw_hash_set.h"  // IWYU pragma: export
44 #include "absl/memory/memory.h"
45 
46 namespace absl {
47 ABSL_NAMESPACE_BEGIN
48 namespace container_internal {
49 template <typename T>
50 struct NodeHashSetPolicy;
51 }  // namespace container_internal
52 
53 // -----------------------------------------------------------------------------
54 // absl::node_hash_set
55 // -----------------------------------------------------------------------------
56 //
57 // An `absl::node_hash_set<T>` is an unordered associative container which
58 // has been optimized for both speed and memory footprint in most common use
59 // cases. Its interface is similar to that of `std::unordered_set<T>` with the
60 // following notable differences:
61 //
62 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
63 //   `insert()`, provided that the map is provided a compatible heterogeneous
64 //   hashing function and equality operator.
65 // * Contains a `capacity()` member function indicating the number of element
66 //   slots (open, deleted, and empty) within the hash set.
67 // * Returns `void` from the `erase(iterator)` overload.
68 //
69 // By default, `node_hash_set` uses the `absl::Hash` hashing framework.
70 // All fundamental and Abseil types that support the `absl::Hash` framework have
71 // a compatible equality operator for comparing insertions into `node_hash_set`.
72 // If your type is not yet supported by the `absl::Hash` framework, see
73 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
74 // types.
75 //
76 // Example:
77 //
78 //   // Create a node hash set of three strings
79 //   absl::node_hash_map<std::string, std::string> ducks =
80 //     {"huey", "dewey", "louie"};
81 //
82 //  // Insert a new element into the node hash map
83 //  ducks.insert("donald"};
84 //
85 //  // Force a rehash of the node hash map
86 //  ducks.rehash(0);
87 //
88 //  // See if "dewey" is present
89 //  if (ducks.contains("dewey")) {
90 //    std::cout << "We found dewey!" << std::endl;
91 //  }
92 template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
93           class Eq = absl::container_internal::hash_default_eq<T>,
94           class Alloc = std::allocator<T>>
95 class node_hash_set
96     : public absl::container_internal::raw_hash_set<
97           absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> {
98   using Base = typename node_hash_set::raw_hash_set;
99 
100  public:
101   // Constructors and Assignment Operators
102   //
103   // A node_hash_set supports the same overload set as `std::unordered_map`
104   // for construction and assignment:
105   //
106   // *  Default constructor
107   //
108   //    // No allocation for the table's elements is made.
109   //    absl::node_hash_set<std::string> set1;
110   //
111   // * Initializer List constructor
112   //
113   //   absl::node_hash_set<std::string> set2 =
114   //       {{"huey"}, {"dewey"}, {"louie"}};
115   //
116   // * Copy constructor
117   //
118   //   absl::node_hash_set<std::string> set3(set2);
119   //
120   // * Copy assignment operator
121   //
122   //  // Hash functor and Comparator are copied as well
123   //  absl::node_hash_set<std::string> set4;
124   //  set4 = set3;
125   //
126   // * Move constructor
127   //
128   //   // Move is guaranteed efficient
129   //   absl::node_hash_set<std::string> set5(std::move(set4));
130   //
131   // * Move assignment operator
132   //
133   //   // May be efficient if allocators are compatible
134   //   absl::node_hash_set<std::string> set6;
135   //   set6 = std::move(set5);
136   //
137   // * Range constructor
138   //
139   //   std::vector<std::string> v = {"a", "b"};
140   //   absl::node_hash_set<std::string> set7(v.begin(), v.end());
node_hash_set()141   node_hash_set() {}
142   using Base::Base;
143 
144   // node_hash_set::begin()
145   //
146   // Returns an iterator to the beginning of the `node_hash_set`.
147   using Base::begin;
148 
149   // node_hash_set::cbegin()
150   //
151   // Returns a const iterator to the beginning of the `node_hash_set`.
152   using Base::cbegin;
153 
154   // node_hash_set::cend()
155   //
156   // Returns a const iterator to the end of the `node_hash_set`.
157   using Base::cend;
158 
159   // node_hash_set::end()
160   //
161   // Returns an iterator to the end of the `node_hash_set`.
162   using Base::end;
163 
164   // node_hash_set::capacity()
165   //
166   // Returns the number of element slots (assigned, deleted, and empty)
167   // available within the `node_hash_set`.
168   //
169   // NOTE: this member function is particular to `absl::node_hash_set` and is
170   // not provided in the `std::unordered_map` API.
171   using Base::capacity;
172 
173   // node_hash_set::empty()
174   //
175   // Returns whether or not the `node_hash_set` is empty.
176   using Base::empty;
177 
178   // node_hash_set::max_size()
179   //
180   // Returns the largest theoretical possible number of elements within a
181   // `node_hash_set` under current memory constraints. This value can be thought
182   // of the largest value of `std::distance(begin(), end())` for a
183   // `node_hash_set<T>`.
184   using Base::max_size;
185 
186   // node_hash_set::size()
187   //
188   // Returns the number of elements currently within the `node_hash_set`.
189   using Base::size;
190 
191   // node_hash_set::clear()
192   //
193   // Removes all elements from the `node_hash_set`. Invalidates any references,
194   // pointers, or iterators referring to contained elements.
195   //
196   // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
197   // the underlying buffer call `erase(begin(), end())`.
198   using Base::clear;
199 
200   // node_hash_set::erase()
201   //
202   // Erases elements within the `node_hash_set`. Erasing does not trigger a
203   // rehash. Overloads are listed below.
204   //
205   // void erase(const_iterator pos):
206   //
207   //   Erases the element at `position` of the `node_hash_set`, returning
208   //   `void`.
209   //
210   //   NOTE: this return behavior is different than that of STL containers in
211   //   general and `std::unordered_map` in particular.
212   //
213   // iterator erase(const_iterator first, const_iterator last):
214   //
215   //   Erases the elements in the open interval [`first`, `last`), returning an
216   //   iterator pointing to `last`.
217   //
218   // size_type erase(const key_type& key):
219   //
220   //   Erases the element with the matching key, if it exists.
221   using Base::erase;
222 
223   // node_hash_set::insert()
224   //
225   // Inserts an element of the specified value into the `node_hash_set`,
226   // returning an iterator pointing to the newly inserted element, provided that
227   // an element with the given key does not already exist. If rehashing occurs
228   // due to the insertion, all iterators are invalidated. Overloads are listed
229   // below.
230   //
231   // std::pair<iterator,bool> insert(const T& value):
232   //
233   //   Inserts a value into the `node_hash_set`. Returns a pair consisting of an
234   //   iterator to the inserted element (or to the element that prevented the
235   //   insertion) and a bool denoting whether the insertion took place.
236   //
237   // std::pair<iterator,bool> insert(T&& value):
238   //
239   //   Inserts a moveable value into the `node_hash_set`. Returns a pair
240   //   consisting of an iterator to the inserted element (or to the element that
241   //   prevented the insertion) and a bool denoting whether the insertion took
242   //   place.
243   //
244   // iterator insert(const_iterator hint, const T& value):
245   // iterator insert(const_iterator hint, T&& value):
246   //
247   //   Inserts a value, using the position of `hint` as a non-binding suggestion
248   //   for where to begin the insertion search. Returns an iterator to the
249   //   inserted element, or to the existing element that prevented the
250   //   insertion.
251   //
252   // void insert(InputIterator first, InputIterator last):
253   //
254   //   Inserts a range of values [`first`, `last`).
255   //
256   //   NOTE: Although the STL does not specify which element may be inserted if
257   //   multiple keys compare equivalently, for `node_hash_set` we guarantee the
258   //   first match is inserted.
259   //
260   // void insert(std::initializer_list<T> ilist):
261   //
262   //   Inserts the elements within the initializer list `ilist`.
263   //
264   //   NOTE: Although the STL does not specify which element may be inserted if
265   //   multiple keys compare equivalently within the initializer list, for
266   //   `node_hash_set` we guarantee the first match is inserted.
267   using Base::insert;
268 
269   // node_hash_set::emplace()
270   //
271   // Inserts an element of the specified value by constructing it in-place
272   // within the `node_hash_set`, provided that no element with the given key
273   // already exists.
274   //
275   // The element may be constructed even if there already is an element with the
276   // key in the container, in which case the newly constructed element will be
277   // destroyed immediately.
278   //
279   // If rehashing occurs due to the insertion, all iterators are invalidated.
280   using Base::emplace;
281 
282   // node_hash_set::emplace_hint()
283   //
284   // Inserts an element of the specified value by constructing it in-place
285   // within the `node_hash_set`, using the position of `hint` as a non-binding
286   // suggestion for where to begin the insertion search, and only inserts
287   // provided that no element with the given key already exists.
288   //
289   // The element may be constructed even if there already is an element with the
290   // key in the container, in which case the newly constructed element will be
291   // destroyed immediately.
292   //
293   // If rehashing occurs due to the insertion, all iterators are invalidated.
294   using Base::emplace_hint;
295 
296   // node_hash_set::extract()
297   //
298   // Extracts the indicated element, erasing it in the process, and returns it
299   // as a C++17-compatible node handle. Overloads are listed below.
300   //
301   // node_type extract(const_iterator position):
302   //
303   //   Extracts the element at the indicated position and returns a node handle
304   //   owning that extracted data.
305   //
306   // node_type extract(const key_type& x):
307   //
308   //   Extracts the element with the key matching the passed key value and
309   //   returns a node handle owning that extracted data. If the `node_hash_set`
310   //   does not contain an element with a matching key, this function returns an
311   // empty node handle.
312   using Base::extract;
313 
314   // node_hash_set::merge()
315   //
316   // Extracts elements from a given `source` flat hash map into this
317   // `node_hash_set`. If the destination `node_hash_set` already contains an
318   // element with an equivalent key, that element is not extracted.
319   using Base::merge;
320 
321   // node_hash_set::swap(node_hash_set& other)
322   //
323   // Exchanges the contents of this `node_hash_set` with those of the `other`
324   // flat hash map, avoiding invocation of any move, copy, or swap operations on
325   // individual elements.
326   //
327   // All iterators and references on the `node_hash_set` remain valid, excepting
328   // for the past-the-end iterator, which is invalidated.
329   //
330   // `swap()` requires that the flat hash set's hashing and key equivalence
331   // functions be Swappable, and are exchaged using unqualified calls to
332   // non-member `swap()`. If the map's allocator has
333   // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
334   // set to `true`, the allocators are also exchanged using an unqualified call
335   // to non-member `swap()`; otherwise, the allocators are not swapped.
336   using Base::swap;
337 
338   // node_hash_set::rehash(count)
339   //
340   // Rehashes the `node_hash_set`, setting the number of slots to be at least
341   // the passed value. If the new number of slots increases the load factor more
342   // than the current maximum load factor
343   // (`count` < `size()` / `max_load_factor()`), then the new number of slots
344   // will be at least `size()` / `max_load_factor()`.
345   //
346   // To force a rehash, pass rehash(0).
347   //
348   // NOTE: unlike behavior in `std::unordered_set`, references are also
349   // invalidated upon a `rehash()`.
350   using Base::rehash;
351 
352   // node_hash_set::reserve(count)
353   //
354   // Sets the number of slots in the `node_hash_set` to the number needed to
355   // accommodate at least `count` total elements without exceeding the current
356   // maximum load factor, and may rehash the container if needed.
357   using Base::reserve;
358 
359   // node_hash_set::contains()
360   //
361   // Determines whether an element comparing equal to the given `key` exists
362   // within the `node_hash_set`, returning `true` if so or `false` otherwise.
363   using Base::contains;
364 
365   // node_hash_set::count(const Key& key) const
366   //
367   // Returns the number of elements comparing equal to the given `key` within
368   // the `node_hash_set`. note that this function will return either `1` or `0`
369   // since duplicate elements are not allowed within a `node_hash_set`.
370   using Base::count;
371 
372   // node_hash_set::equal_range()
373   //
374   // Returns a closed range [first, last], defined by a `std::pair` of two
375   // iterators, containing all elements with the passed key in the
376   // `node_hash_set`.
377   using Base::equal_range;
378 
379   // node_hash_set::find()
380   //
381   // Finds an element with the passed `key` within the `node_hash_set`.
382   using Base::find;
383 
384   // node_hash_set::bucket_count()
385   //
386   // Returns the number of "buckets" within the `node_hash_set`. Note that
387   // because a flat hash map contains all elements within its internal storage,
388   // this value simply equals the current capacity of the `node_hash_set`.
389   using Base::bucket_count;
390 
391   // node_hash_set::load_factor()
392   //
393   // Returns the current load factor of the `node_hash_set` (the average number
394   // of slots occupied with a value within the hash map).
395   using Base::load_factor;
396 
397   // node_hash_set::max_load_factor()
398   //
399   // Manages the maximum load factor of the `node_hash_set`. Overloads are
400   // listed below.
401   //
402   // float node_hash_set::max_load_factor()
403   //
404   //   Returns the current maximum load factor of the `node_hash_set`.
405   //
406   // void node_hash_set::max_load_factor(float ml)
407   //
408   //   Sets the maximum load factor of the `node_hash_set` to the passed value.
409   //
410   //   NOTE: This overload is provided only for API compatibility with the STL;
411   //   `node_hash_set` will ignore any set load factor and manage its rehashing
412   //   internally as an implementation detail.
413   using Base::max_load_factor;
414 
415   // node_hash_set::get_allocator()
416   //
417   // Returns the allocator function associated with this `node_hash_set`.
418   using Base::get_allocator;
419 
420   // node_hash_set::hash_function()
421   //
422   // Returns the hashing function used to hash the keys within this
423   // `node_hash_set`.
424   using Base::hash_function;
425 
426   // node_hash_set::key_eq()
427   //
428   // Returns the function used for comparing keys equality.
429   using Base::key_eq;
430 
431   ABSL_DEPRECATED("Call `hash_function()` instead.")
hash_funct()432   typename Base::hasher hash_funct() { return this->hash_function(); }
433 
434   ABSL_DEPRECATED("Call `rehash()` instead.")
resize(typename Base::size_type hint)435   void resize(typename Base::size_type hint) { this->rehash(hint); }
436 };
437 
438 // erase_if(node_hash_set<>, Pred)
439 //
440 // Erases all elements that satisfy the predicate `pred` from the container `c`.
441 template <typename T, typename H, typename E, typename A, typename Predicate>
erase_if(node_hash_set<T,H,E,A> & c,Predicate pred)442 void erase_if(node_hash_set<T, H, E, A>& c, Predicate pred) {
443   container_internal::EraseIf(pred, &c);
444 }
445 
446 namespace container_internal {
447 
448 template <class T>
449 struct NodeHashSetPolicy
450     : absl::container_internal::node_hash_policy<T&, NodeHashSetPolicy<T>> {
451   using key_type = T;
452   using init_type = T;
453   using constant_iterators = std::true_type;
454 
455   template <class Allocator, class... Args>
new_elementNodeHashSetPolicy456   static T* new_element(Allocator* alloc, Args&&... args) {
457     using ValueAlloc =
458         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
459     ValueAlloc value_alloc(*alloc);
460     T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
461     absl::allocator_traits<ValueAlloc>::construct(value_alloc, res,
462                                                   std::forward<Args>(args)...);
463     return res;
464   }
465 
466   template <class Allocator>
delete_elementNodeHashSetPolicy467   static void delete_element(Allocator* alloc, T* elem) {
468     using ValueAlloc =
469         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
470     ValueAlloc value_alloc(*alloc);
471     absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
472     absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
473   }
474 
475   template <class F, class... Args>
decltypeNodeHashSetPolicy476   static decltype(absl::container_internal::DecomposeValue(
477       std::declval<F>(), std::declval<Args>()...))
478   apply(F&& f, Args&&... args) {
479     return absl::container_internal::DecomposeValue(
480         std::forward<F>(f), std::forward<Args>(args)...);
481   }
482 
element_space_usedNodeHashSetPolicy483   static size_t element_space_used(const T*) { return sizeof(T); }
484 };
485 }  // namespace container_internal
486 
487 namespace container_algorithm_internal {
488 
489 // Specialization of trait in absl/algorithm/container.h
490 template <class Key, class Hash, class KeyEqual, class Allocator>
491 struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
492     : std::true_type {};
493 
494 }  // namespace container_algorithm_internal
495 ABSL_NAMESPACE_END
496 }  // namespace absl
497 
498 #endif  // ABSL_CONTAINER_NODE_HASH_SET_H_
499