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_INTERNAL_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, avoiding invocation of any move, copy, or swap operations on
364 // individual elements.
365 //
366 // All iterators and references on the `flat_hash_set` remain valid, excepting
367 // for the past-the-end iterator, which is invalidated.
368 //
369 // `swap()` requires that the flat hash set's hashing and key equivalence
370 // functions be Swappable, and are exchanged using unqualified calls to
371 // non-member `swap()`. If the set's allocator has
372 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
373 // set to `true`, the allocators are also exchanged using an unqualified call
374 // to non-member `swap()`; otherwise, the allocators are not swapped.
375 using Base::swap;
376
377 // flat_hash_set::rehash(count)
378 //
379 // Rehashes the `flat_hash_set`, setting the number of slots to be at least
380 // the passed value. If the new number of slots increases the load factor more
381 // than the current maximum load factor
382 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
383 // will be at least `size()` / `max_load_factor()`.
384 //
385 // To force a rehash, pass rehash(0).
386 //
387 // NOTE: unlike behavior in `std::unordered_set`, references are also
388 // invalidated upon a `rehash()`.
389 using Base::rehash;
390
391 // flat_hash_set::reserve(count)
392 //
393 // Sets the number of slots in the `flat_hash_set` to the number needed to
394 // accommodate at least `count` total elements without exceeding the current
395 // maximum load factor, and may rehash the container if needed.
396 using Base::reserve;
397
398 // flat_hash_set::contains()
399 //
400 // Determines whether an element comparing equal to the given `key` exists
401 // within the `flat_hash_set`, returning `true` if so or `false` otherwise.
402 using Base::contains;
403
404 // flat_hash_set::count(const Key& key) const
405 //
406 // Returns the number of elements comparing equal to the given `key` within
407 // the `flat_hash_set`. note that this function will return either `1` or `0`
408 // since duplicate elements are not allowed within a `flat_hash_set`.
409 using Base::count;
410
411 // flat_hash_set::equal_range()
412 //
413 // Returns a closed range [first, last], defined by a `std::pair` of two
414 // iterators, containing all elements with the passed key in the
415 // `flat_hash_set`.
416 using Base::equal_range;
417
418 // flat_hash_set::find()
419 //
420 // Finds an element with the passed `key` within the `flat_hash_set`.
421 using Base::find;
422
423 // flat_hash_set::bucket_count()
424 //
425 // Returns the number of "buckets" within the `flat_hash_set`. Note that
426 // because a flat hash set contains all elements within its internal storage,
427 // this value simply equals the current capacity of the `flat_hash_set`.
428 using Base::bucket_count;
429
430 // flat_hash_set::load_factor()
431 //
432 // Returns the current load factor of the `flat_hash_set` (the average number
433 // of slots occupied with a value within the hash set).
434 using Base::load_factor;
435
436 // flat_hash_set::max_load_factor()
437 //
438 // Manages the maximum load factor of the `flat_hash_set`. Overloads are
439 // listed below.
440 //
441 // float flat_hash_set::max_load_factor()
442 //
443 // Returns the current maximum load factor of the `flat_hash_set`.
444 //
445 // void flat_hash_set::max_load_factor(float ml)
446 //
447 // Sets the maximum load factor of the `flat_hash_set` to the passed value.
448 //
449 // NOTE: This overload is provided only for API compatibility with the STL;
450 // `flat_hash_set` will ignore any set load factor and manage its rehashing
451 // internally as an implementation detail.
452 using Base::max_load_factor;
453
454 // flat_hash_set::get_allocator()
455 //
456 // Returns the allocator function associated with this `flat_hash_set`.
457 using Base::get_allocator;
458
459 // flat_hash_set::hash_function()
460 //
461 // Returns the hashing function used to hash the keys within this
462 // `flat_hash_set`.
463 using Base::hash_function;
464
465 // flat_hash_set::key_eq()
466 //
467 // Returns the function used for comparing keys equality.
468 using Base::key_eq;
469 };
470
471 // erase_if(flat_hash_set<>, Pred)
472 //
473 // Erases all elements that satisfy the predicate `pred` from the container `c`.
474 // Returns the number of erased elements.
475 template <typename T, typename H, typename E, typename A, typename Predicate>
erase_if(flat_hash_set<T,H,E,A> & c,Predicate pred)476 typename flat_hash_set<T, H, E, A>::size_type erase_if(
477 flat_hash_set<T, H, E, A>& c, Predicate pred) {
478 return container_internal::EraseIf(pred, &c);
479 }
480
481 namespace container_internal {
482
483 // c_for_each_fast(flat_hash_set<>, Function)
484 //
485 // Container-based version of the <algorithm> `std::for_each()` function to
486 // apply a function to a container's elements.
487 // There is no guarantees on the order of the function calls.
488 // Erasure and/or insertion of elements in the function is not allowed.
489 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)490 decay_t<Function> c_for_each_fast(const flat_hash_set<T, H, E, A>& c,
491 Function&& f) {
492 container_internal::ForEach(f, &c);
493 return f;
494 }
495 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)496 decay_t<Function> c_for_each_fast(flat_hash_set<T, H, E, A>& c, Function&& f) {
497 container_internal::ForEach(f, &c);
498 return f;
499 }
500 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)501 decay_t<Function> c_for_each_fast(flat_hash_set<T, H, E, A>&& c, Function&& f) {
502 container_internal::ForEach(f, &c);
503 return f;
504 }
505
506 } // namespace container_internal
507
508 namespace container_internal {
509
510 template <class T>
511 struct FlatHashSetPolicy {
512 using slot_type = T;
513 using key_type = T;
514 using init_type = T;
515 using constant_iterators = std::true_type;
516
517 template <class Allocator, class... Args>
constructFlatHashSetPolicy518 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
519 absl::allocator_traits<Allocator>::construct(*alloc, slot,
520 std::forward<Args>(args)...);
521 }
522
523 // Return std::true_type in case destroy is trivial.
524 template <class Allocator>
destroyFlatHashSetPolicy525 static auto destroy(Allocator* alloc, slot_type* slot) {
526 absl::allocator_traits<Allocator>::destroy(*alloc, slot);
527 return IsDestructionTrivial<Allocator, slot_type>();
528 }
529
elementFlatHashSetPolicy530 static T& element(slot_type* slot) { return *slot; }
531
532 template <class F, class... Args>
decltypeFlatHashSetPolicy533 static decltype(absl::container_internal::DecomposeValue(
534 std::declval<F>(), std::declval<Args>()...))
535 apply(F&& f, Args&&... args) {
536 return absl::container_internal::DecomposeValue(
537 std::forward<F>(f), std::forward<Args>(args)...);
538 }
539
space_usedFlatHashSetPolicy540 static size_t space_used(const T*) { return 0; }
541
542 template <class Hash>
get_hash_slot_fnFlatHashSetPolicy543 static constexpr HashSlotFn get_hash_slot_fn() {
544 return &TypeErasedApplyToSlotFn<Hash, T>;
545 }
546 };
547 } // namespace container_internal
548
549 namespace container_algorithm_internal {
550
551 // Specialization of trait in absl/algorithm/container.h
552 template <class Key, class Hash, class KeyEqual, class Allocator>
553 struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>>
554 : std::true_type {};
555
556 } // namespace container_algorithm_internal
557
558 ABSL_NAMESPACE_END
559 } // namespace absl
560
561 #endif // ABSL_CONTAINER_FLAT_HASH_SET_H_
562