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, returning the
221   //   number of elements erased (0 or 1).
222   using Base::erase;
223 
224   // node_hash_set::insert()
225   //
226   // Inserts an element of the specified value into the `node_hash_set`,
227   // returning an iterator pointing to the newly inserted element, provided that
228   // an element with the given key does not already exist. If rehashing occurs
229   // due to the insertion, all iterators are invalidated. Overloads are listed
230   // below.
231   //
232   // std::pair<iterator,bool> insert(const T& value):
233   //
234   //   Inserts a value into the `node_hash_set`. Returns a pair consisting of an
235   //   iterator to the inserted element (or to the element that prevented the
236   //   insertion) and a bool denoting whether the insertion took place.
237   //
238   // std::pair<iterator,bool> insert(T&& value):
239   //
240   //   Inserts a moveable value into the `node_hash_set`. Returns a pair
241   //   consisting of an iterator to the inserted element (or to the element that
242   //   prevented the insertion) and a bool denoting whether the insertion took
243   //   place.
244   //
245   // iterator insert(const_iterator hint, const T& value):
246   // iterator insert(const_iterator hint, T&& value):
247   //
248   //   Inserts a value, using the position of `hint` as a non-binding suggestion
249   //   for where to begin the insertion search. Returns an iterator to the
250   //   inserted element, or to the existing element that prevented the
251   //   insertion.
252   //
253   // void insert(InputIterator first, InputIterator last):
254   //
255   //   Inserts a range of values [`first`, `last`).
256   //
257   //   NOTE: Although the STL does not specify which element may be inserted if
258   //   multiple keys compare equivalently, for `node_hash_set` we guarantee the
259   //   first match is inserted.
260   //
261   // void insert(std::initializer_list<T> ilist):
262   //
263   //   Inserts the elements within the initializer list `ilist`.
264   //
265   //   NOTE: Although the STL does not specify which element may be inserted if
266   //   multiple keys compare equivalently within the initializer list, for
267   //   `node_hash_set` we guarantee the first match is inserted.
268   using Base::insert;
269 
270   // node_hash_set::emplace()
271   //
272   // Inserts an element of the specified value by constructing it in-place
273   // within the `node_hash_set`, provided that no element with the given key
274   // already exists.
275   //
276   // The element may be constructed even if there already is an element with the
277   // key in the container, in which case the newly constructed element will be
278   // destroyed immediately.
279   //
280   // If rehashing occurs due to the insertion, all iterators are invalidated.
281   using Base::emplace;
282 
283   // node_hash_set::emplace_hint()
284   //
285   // Inserts an element of the specified value by constructing it in-place
286   // within the `node_hash_set`, using the position of `hint` as a non-binding
287   // suggestion for where to begin the insertion search, and only inserts
288   // provided that no element with the given key already exists.
289   //
290   // The element may be constructed even if there already is an element with the
291   // key in the container, in which case the newly constructed element will be
292   // destroyed immediately.
293   //
294   // If rehashing occurs due to the insertion, all iterators are invalidated.
295   using Base::emplace_hint;
296 
297   // node_hash_set::extract()
298   //
299   // Extracts the indicated element, erasing it in the process, and returns it
300   // as a C++17-compatible node handle. Overloads are listed below.
301   //
302   // node_type extract(const_iterator position):
303   //
304   //   Extracts the element at the indicated position and returns a node handle
305   //   owning that extracted data.
306   //
307   // node_type extract(const key_type& x):
308   //
309   //   Extracts the element with the key matching the passed key value and
310   //   returns a node handle owning that extracted data. If the `node_hash_set`
311   //   does not contain an element with a matching key, this function returns an
312   // empty node handle.
313   using Base::extract;
314 
315   // node_hash_set::merge()
316   //
317   // Extracts elements from a given `source` flat hash map into this
318   // `node_hash_set`. If the destination `node_hash_set` already contains an
319   // element with an equivalent key, that element is not extracted.
320   using Base::merge;
321 
322   // node_hash_set::swap(node_hash_set& other)
323   //
324   // Exchanges the contents of this `node_hash_set` with those of the `other`
325   // flat hash map, avoiding invocation of any move, copy, or swap operations on
326   // individual elements.
327   //
328   // All iterators and references on the `node_hash_set` remain valid, excepting
329   // for the past-the-end iterator, which is invalidated.
330   //
331   // `swap()` requires that the flat hash set's hashing and key equivalence
332   // functions be Swappable, and are exchaged using unqualified calls to
333   // non-member `swap()`. If the map's allocator has
334   // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
335   // set to `true`, the allocators are also exchanged using an unqualified call
336   // to non-member `swap()`; otherwise, the allocators are not swapped.
337   using Base::swap;
338 
339   // node_hash_set::rehash(count)
340   //
341   // Rehashes the `node_hash_set`, setting the number of slots to be at least
342   // the passed value. If the new number of slots increases the load factor more
343   // than the current maximum load factor
344   // (`count` < `size()` / `max_load_factor()`), then the new number of slots
345   // will be at least `size()` / `max_load_factor()`.
346   //
347   // To force a rehash, pass rehash(0).
348   //
349   // NOTE: unlike behavior in `std::unordered_set`, references are also
350   // invalidated upon a `rehash()`.
351   using Base::rehash;
352 
353   // node_hash_set::reserve(count)
354   //
355   // Sets the number of slots in the `node_hash_set` to the number needed to
356   // accommodate at least `count` total elements without exceeding the current
357   // maximum load factor, and may rehash the container if needed.
358   using Base::reserve;
359 
360   // node_hash_set::contains()
361   //
362   // Determines whether an element comparing equal to the given `key` exists
363   // within the `node_hash_set`, returning `true` if so or `false` otherwise.
364   using Base::contains;
365 
366   // node_hash_set::count(const Key& key) const
367   //
368   // Returns the number of elements comparing equal to the given `key` within
369   // the `node_hash_set`. note that this function will return either `1` or `0`
370   // since duplicate elements are not allowed within a `node_hash_set`.
371   using Base::count;
372 
373   // node_hash_set::equal_range()
374   //
375   // Returns a closed range [first, last], defined by a `std::pair` of two
376   // iterators, containing all elements with the passed key in the
377   // `node_hash_set`.
378   using Base::equal_range;
379 
380   // node_hash_set::find()
381   //
382   // Finds an element with the passed `key` within the `node_hash_set`.
383   using Base::find;
384 
385   // node_hash_set::bucket_count()
386   //
387   // Returns the number of "buckets" within the `node_hash_set`. Note that
388   // because a flat hash map contains all elements within its internal storage,
389   // this value simply equals the current capacity of the `node_hash_set`.
390   using Base::bucket_count;
391 
392   // node_hash_set::load_factor()
393   //
394   // Returns the current load factor of the `node_hash_set` (the average number
395   // of slots occupied with a value within the hash map).
396   using Base::load_factor;
397 
398   // node_hash_set::max_load_factor()
399   //
400   // Manages the maximum load factor of the `node_hash_set`. Overloads are
401   // listed below.
402   //
403   // float node_hash_set::max_load_factor()
404   //
405   //   Returns the current maximum load factor of the `node_hash_set`.
406   //
407   // void node_hash_set::max_load_factor(float ml)
408   //
409   //   Sets the maximum load factor of the `node_hash_set` to the passed value.
410   //
411   //   NOTE: This overload is provided only for API compatibility with the STL;
412   //   `node_hash_set` will ignore any set load factor and manage its rehashing
413   //   internally as an implementation detail.
414   using Base::max_load_factor;
415 
416   // node_hash_set::get_allocator()
417   //
418   // Returns the allocator function associated with this `node_hash_set`.
419   using Base::get_allocator;
420 
421   // node_hash_set::hash_function()
422   //
423   // Returns the hashing function used to hash the keys within this
424   // `node_hash_set`.
425   using Base::hash_function;
426 
427   // node_hash_set::key_eq()
428   //
429   // Returns the function used for comparing keys equality.
430   using Base::key_eq;
431 };
432 
433 // erase_if(node_hash_set<>, Pred)
434 //
435 // Erases all elements that satisfy the predicate `pred` from the container `c`.
436 template <typename T, typename H, typename E, typename A, typename Predicate>
erase_if(node_hash_set<T,H,E,A> & c,Predicate pred)437 void erase_if(node_hash_set<T, H, E, A>& c, Predicate pred) {
438   container_internal::EraseIf(pred, &c);
439 }
440 
441 namespace container_internal {
442 
443 template <class T>
444 struct NodeHashSetPolicy
445     : absl::container_internal::node_hash_policy<T&, NodeHashSetPolicy<T>> {
446   using key_type = T;
447   using init_type = T;
448   using constant_iterators = std::true_type;
449 
450   template <class Allocator, class... Args>
new_elementNodeHashSetPolicy451   static T* new_element(Allocator* alloc, Args&&... args) {
452     using ValueAlloc =
453         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
454     ValueAlloc value_alloc(*alloc);
455     T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
456     absl::allocator_traits<ValueAlloc>::construct(value_alloc, res,
457                                                   std::forward<Args>(args)...);
458     return res;
459   }
460 
461   template <class Allocator>
delete_elementNodeHashSetPolicy462   static void delete_element(Allocator* alloc, T* elem) {
463     using ValueAlloc =
464         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
465     ValueAlloc value_alloc(*alloc);
466     absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
467     absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
468   }
469 
470   template <class F, class... Args>
decltypeNodeHashSetPolicy471   static decltype(absl::container_internal::DecomposeValue(
472       std::declval<F>(), std::declval<Args>()...))
473   apply(F&& f, Args&&... args) {
474     return absl::container_internal::DecomposeValue(
475         std::forward<F>(f), std::forward<Args>(args)...);
476   }
477 
element_space_usedNodeHashSetPolicy478   static size_t element_space_used(const T*) { return sizeof(T); }
479 };
480 }  // namespace container_internal
481 
482 namespace container_algorithm_internal {
483 
484 // Specialization of trait in absl/algorithm/container.h
485 template <class Key, class Hash, class KeyEqual, class Allocator>
486 struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
487     : std::true_type {};
488 
489 }  // namespace container_algorithm_internal
490 ABSL_NAMESPACE_END
491 }  // namespace absl
492 
493 #endif  // ABSL_CONTAINER_NODE_HASH_SET_H_
494