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