1 // Copyright 2018 The Abseil Authors.
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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.
15 // -----------------------------------------------------------------------------
16 // File: node_hash_set.h
17 // -----------------------------------------------------------------------------
19 // An `absl::node_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 map elements can be done
22 // as an `O(1)` operation. However, `node_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
27 // In most cases, your default choice for a hash table should be a map of type
28 // `flat_hash_map` or a set of type `flat_hash_set`. However, if you need
29 // pointer stability, a `node_hash_set` should be your preferred choice. As
30 // well, if you are migrating your code from using `std::unordered_set`, a
31 // `node_hash_set` should be an easy migration. Consider migrating to
32 // `node_hash_set` and perhaps converting to a more efficient `flat_hash_set`
33 // upon further review.
35 #ifndef ABSL_CONTAINER_NODE_HASH_SET_H_
36 #define ABSL_CONTAINER_NODE_HASH_SET_H_
38 #include <type_traits>
40 #include "absl/algorithm/container.h"
41 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
42 #include "absl/container/internal/node_hash_policy.h"
43 #include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
44 #include "absl/memory/memory.h"
47 namespace container_internal {
49 struct NodeHashSetPolicy;
50 } // namespace container_internal
52 // -----------------------------------------------------------------------------
53 // absl::node_hash_set
54 // -----------------------------------------------------------------------------
56 // An `absl::node_hash_set<T>` is an unordered associative container which
57 // has been optimized for both speed and memory footprint in most common use
58 // cases. Its interface is similar to that of `std::unordered_set<T>` with the
59 // following notable differences:
61 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
62 // `insert()`, provided that the map is provided a compatible heterogeneous
63 // hashing function and equality operator.
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.
68 // By default, `node_hash_set` uses the `absl::Hash` hashing framework.
69 // All fundamental and Abseil types that support the `absl::Hash` framework have
70 // a compatible equality operator for comparing insertions into `node_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
77 // // Create a node hash set of three strings
78 // absl::node_hash_map<std::string, std::string> ducks =
79 // {"huey", "dewey"}, "louie"};
81 // // Insert a new element into the node hash map
82 // ducks.insert("donald"};
84 // // Force a rehash of the node hash map
87 // // See if "dewey" is present
88 // if (ducks.contains("dewey")) {
89 // std::cout << "We found dewey!" << std::endl;
91 template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
92 class Eq = absl::container_internal::hash_default_eq<T>,
93 class Alloc = std::allocator<T>>
95 : public absl::container_internal::raw_hash_set<
96 absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> {
97 using Base = typename node_hash_set::raw_hash_set;
100 // Constructors and Assignment Operators
102 // A node_hash_set supports the same overload set as `std::unordered_map`
103 // for construction and assignment:
105 // * Default constructor
107 // // No allocation for the table's elements is made.
108 // absl::node_hash_set<std::string> set1;
110 // * Initializer List constructor
112 // absl::node_hash_set<std::string> set2 =
113 // {{"huey"}, {"dewey"}, {"louie"},};
115 // * Copy constructor
117 // absl::node_hash_set<std::string> set3(set2);
119 // * Copy assignment operator
121 // // Hash functor and Comparator are copied as well
122 // absl::node_hash_set<std::string> set4;
125 // * Move constructor
127 // // Move is guaranteed efficient
128 // absl::node_hash_set<std::string> set5(std::move(set4));
130 // * Move assignment operator
132 // // May be efficient if allocators are compatible
133 // absl::node_hash_set<std::string> set6;
134 // set6 = std::move(set5);
136 // * Range constructor
138 // std::vector<std::string> v = {"a", "b"};
139 // absl::node_hash_set<std::string> set7(v.begin(), v.end());
143 // node_hash_set::begin()
145 // Returns an iterator to the beginning of the `node_hash_set`.
148 // node_hash_set::cbegin()
150 // Returns a const iterator to the beginning of the `node_hash_set`.
153 // node_hash_set::cend()
155 // Returns a const iterator to the end of the `node_hash_set`.
158 // node_hash_set::end()
160 // Returns an iterator to the end of the `node_hash_set`.
163 // node_hash_set::capacity()
165 // Returns the number of element slots (assigned, deleted, and empty)
166 // available within the `node_hash_set`.
168 // NOTE: this member function is particular to `absl::node_hash_set` and is
169 // not provided in the `std::unordered_map` API.
170 using Base::capacity;
172 // node_hash_set::empty()
174 // Returns whether or not the `node_hash_set` is empty.
177 // node_hash_set::max_size()
179 // Returns the largest theoretical possible number of elements within a
180 // `node_hash_set` under current memory constraints. This value can be thought
181 // of the largest value of `std::distance(begin(), end())` for a
182 // `node_hash_set<T>`.
183 using Base::max_size;
185 // node_hash_set::size()
187 // Returns the number of elements currently within the `node_hash_set`.
190 // node_hash_set::clear()
192 // Removes all elements from the `node_hash_set`. Invalidates any references,
193 // pointers, or iterators referring to contained elements.
195 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
196 // the underlying buffer call `erase(begin(), end())`.
199 // node_hash_set::erase()
201 // Erases elements within the `node_hash_set`. Erasing does not trigger a
202 // rehash. Overloads are listed below.
204 // void erase(const_iterator pos):
206 // Erases the element at `position` of the `node_hash_set`, returning
209 // NOTE: this return behavior is different than that of STL containers in
210 // general and `std::unordered_map` in particular.
212 // iterator erase(const_iterator first, const_iterator last):
214 // Erases the elements in the open interval [`first`, `last`), returning an
215 // iterator pointing to `last`.
217 // size_type erase(const key_type& key):
219 // Erases the element with the matching key, if it exists.
222 // node_hash_set::insert()
224 // Inserts an element of the specified value into the `node_hash_set`,
225 // returning an iterator pointing to the newly inserted element, provided that
226 // an element with the given key does not already exist. If rehashing occurs
227 // due to the insertion, all iterators are invalidated. Overloads are listed
230 // std::pair<iterator,bool> insert(const T& value):
232 // Inserts a value into the `node_hash_set`. Returns a pair consisting of an
233 // iterator to the inserted element (or to the element that prevented the
234 // insertion) and a bool denoting whether the insertion took place.
236 // std::pair<iterator,bool> insert(T&& value):
238 // Inserts a moveable value into the `node_hash_set`. Returns a pair
239 // consisting of an iterator to the inserted element (or to the element that
240 // prevented the insertion) and a bool denoting whether the insertion took
243 // iterator insert(const_iterator hint, const T& value):
244 // iterator insert(const_iterator hint, T&& value):
246 // Inserts a value, using the position of `hint` as a non-binding suggestion
247 // for where to begin the insertion search. Returns an iterator to the
248 // inserted element, or to the existing element that prevented the
251 // void insert(InputIterator first, InputIterator last):
253 // Inserts a range of values [`first`, `last`).
255 // NOTE: Although the STL does not specify which element may be inserted if
256 // multiple keys compare equivalently, for `node_hash_set` we guarantee the
257 // first match is inserted.
259 // void insert(std::initializer_list<T> ilist):
261 // Inserts the elements within the initializer list `ilist`.
263 // NOTE: Although the STL does not specify which element may be inserted if
264 // multiple keys compare equivalently within the initializer list, for
265 // `node_hash_set` we guarantee the first match is inserted.
268 // node_hash_set::emplace()
270 // Inserts an element of the specified value by constructing it in-place
271 // within the `node_hash_set`, provided that no element with the given key
274 // The element may be constructed even if there already is an element with the
275 // key in the container, in which case the newly constructed element will be
276 // destroyed immediately.
278 // If rehashing occurs due to the insertion, all iterators are invalidated.
281 // node_hash_set::emplace_hint()
283 // Inserts an element of the specified value by constructing it in-place
284 // within the `node_hash_set`, using the position of `hint` as a non-binding
285 // suggestion for where to begin the insertion search, and only inserts
286 // provided that no element with the given key already exists.
288 // The element may be constructed even if there already is an element with the
289 // key in the container, in which case the newly constructed element will be
290 // destroyed immediately.
292 // If rehashing occurs due to the insertion, all iterators are invalidated.
293 using Base::emplace_hint;
295 // node_hash_set::extract()
297 // Extracts the indicated element, erasing it in the process, and returns it
298 // as a C++17-compatible node handle. Overloads are listed below.
300 // node_type extract(const_iterator position):
302 // Extracts the element at the indicated position and returns a node handle
303 // owning that extracted data.
305 // node_type extract(const key_type& x):
307 // Extracts the element with the key matching the passed key value and
308 // returns a node handle owning that extracted data. If the `node_hash_set`
309 // does not contain an element with a matching key, this function returns an
310 // empty node handle.
313 // node_hash_set::merge()
315 // Extracts elements from a given `source` flat hash map into this
316 // `node_hash_set`. If the destination `node_hash_set` already contains an
317 // element with an equivalent key, that element is not extracted.
320 // node_hash_set::swap(node_hash_set& other)
322 // Exchanges the contents of this `node_hash_set` with those of the `other`
323 // flat hash map, avoiding invocation of any move, copy, or swap operations on
324 // individual elements.
326 // All iterators and references on the `node_hash_set` remain valid, excepting
327 // for the past-the-end iterator, which is invalidated.
329 // `swap()` requires that the flat hash set's hashing and key equivalence
330 // functions be Swappable, and are exchaged using unqualified calls to
331 // non-member `swap()`. If the map's allocator has
332 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
333 // set to `true`, the allocators are also exchanged using an unqualified call
334 // to non-member `swap()`; otherwise, the allocators are not swapped.
337 // node_hash_set::rehash(count)
339 // Rehashes the `node_hash_set`, setting the number of slots to be at least
340 // the passed value. If the new number of slots increases the load factor more
341 // than the current maximum load factor
342 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
343 // will be at least `size()` / `max_load_factor()`.
345 // To force a rehash, pass rehash(0).
347 // NOTE: unlike behavior in `std::unordered_set`, references are also
348 // invalidated upon a `rehash()`.
351 // node_hash_set::reserve(count)
353 // Sets the number of slots in the `node_hash_set` to the number needed to
354 // accommodate at least `count` total elements without exceeding the current
355 // maximum load factor, and may rehash the container if needed.
358 // node_hash_set::contains()
360 // Determines whether an element comparing equal to the given `key` exists
361 // within the `node_hash_set`, returning `true` if so or `false` otherwise.
362 using Base::contains;
364 // node_hash_set::count(const Key& key) const
366 // Returns the number of elements comparing equal to the given `key` within
367 // the `node_hash_set`. note that this function will return either `1` or `0`
368 // since duplicate elements are not allowed within a `node_hash_set`.
371 // node_hash_set::equal_range()
373 // Returns a closed range [first, last], defined by a `std::pair` of two
374 // iterators, containing all elements with the passed key in the
376 using Base::equal_range;
378 // node_hash_set::find()
380 // Finds an element with the passed `key` within the `node_hash_set`.
383 // node_hash_set::bucket_count()
385 // Returns the number of "buckets" within the `node_hash_set`. Note that
386 // because a flat hash map contains all elements within its internal storage,
387 // this value simply equals the current capacity of the `node_hash_set`.
388 using Base::bucket_count;
390 // node_hash_set::load_factor()
392 // Returns the current load factor of the `node_hash_set` (the average number
393 // of slots occupied with a value within the hash map).
394 using Base::load_factor;
396 // node_hash_set::max_load_factor()
398 // Manages the maximum load factor of the `node_hash_set`. Overloads are
401 // float node_hash_set::max_load_factor()
403 // Returns the current maximum load factor of the `node_hash_set`.
405 // void node_hash_set::max_load_factor(float ml)
407 // Sets the maximum load factor of the `node_hash_set` to the passed value.
409 // NOTE: This overload is provided only for API compatibility with the STL;
410 // `node_hash_set` will ignore any set load factor and manage its rehashing
411 // internally as an implementation detail.
412 using Base::max_load_factor;
414 // node_hash_set::get_allocator()
416 // Returns the allocator function associated with this `node_hash_set`.
417 using Base::get_allocator;
419 // node_hash_set::hash_function()
421 // Returns the hashing function used to hash the keys within this
423 using Base::hash_function;
425 // node_hash_set::key_eq()
427 // Returns the function used for comparing keys equality.
430 ABSL_DEPRECATED("Call `hash_function()` instead.")
431 typename Base::hasher hash_funct() { return this->hash_function(); }
433 ABSL_DEPRECATED("Call `rehash()` instead.")
434 void resize(typename Base::size_type hint) { this->rehash(hint); }
437 namespace container_internal {
440 struct NodeHashSetPolicy
441 : absl::container_internal::node_hash_policy<T&, NodeHashSetPolicy<T>> {
444 using constant_iterators = std::true_type;
446 template <class Allocator, class... Args>
447 static T* new_element(Allocator* alloc, Args&&... args) {
449 typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
450 ValueAlloc value_alloc(*alloc);
451 T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
452 absl::allocator_traits<ValueAlloc>::construct(value_alloc, res,
453 std::forward<Args>(args)...);
457 template <class Allocator>
458 static void delete_element(Allocator* alloc, T* elem) {
460 typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
461 ValueAlloc value_alloc(*alloc);
462 absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
463 absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
466 template <class F, class... Args>
467 static decltype(absl::container_internal::DecomposeValue(
468 std::declval<F>(), std::declval<Args>()...))
469 apply(F&& f, Args&&... args) {
470 return absl::container_internal::DecomposeValue(
471 std::forward<F>(f), std::forward<Args>(args)...);
474 static size_t element_space_used(const T*) { return sizeof(T); }
476 } // namespace container_internal
478 namespace container_algorithm_internal {
480 // Specialization of trait in absl/algorithm/container.h
481 template <class Key, class Hash, class KeyEqual, class Allocator>
482 struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
485 } // namespace container_algorithm_internal
488 #endif // ABSL_CONTAINER_NODE_HASH_SET_H_