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