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