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