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