Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-30 09:31:42

0001 // Copyright 2018 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 //
0015 // -----------------------------------------------------------------------------
0016 // File: node_hash_set.h
0017 // -----------------------------------------------------------------------------
0018 //
0019 // An `absl::node_hash_set<T>` is an unordered associative container designed to
0020 // be a more efficient replacement for `std::unordered_set`. Like
0021 // `unordered_set`, search, insertion, and deletion of set elements can be done
0022 // as an `O(1)` operation. However, `node_hash_set` (and other unordered
0023 // associative containers known as the collection of Abseil "Swiss tables")
0024 // contain other optimizations that result in both memory and computation
0025 // advantages.
0026 //
0027 // In most cases, your default choice for a hash table should be a map of type
0028 // `flat_hash_map` or a set of type `flat_hash_set`. However, if you need
0029 // pointer stability, a `node_hash_set` should be your preferred choice. As
0030 // well, if you are migrating your code from using `std::unordered_set`, a
0031 // `node_hash_set` should be an easy migration. Consider migrating to
0032 // `node_hash_set` and perhaps converting to a more efficient `flat_hash_set`
0033 // upon further review.
0034 //
0035 // `node_hash_set` is not exception-safe.
0036 
0037 #ifndef ABSL_CONTAINER_NODE_HASH_SET_H_
0038 #define ABSL_CONTAINER_NODE_HASH_SET_H_
0039 
0040 #include <cstddef>
0041 #include <memory>
0042 #include <type_traits>
0043 
0044 #include "absl/algorithm/container.h"
0045 #include "absl/base/attributes.h"
0046 #include "absl/container/hash_container_defaults.h"
0047 #include "absl/container/internal/container_memory.h"
0048 #include "absl/container/internal/node_slot_policy.h"
0049 #include "absl/container/internal/raw_hash_set.h"  // IWYU pragma: export
0050 #include "absl/memory/memory.h"
0051 #include "absl/meta/type_traits.h"
0052 
0053 namespace absl {
0054 ABSL_NAMESPACE_BEGIN
0055 namespace container_internal {
0056 template <typename T>
0057 struct NodeHashSetPolicy;
0058 }  // namespace container_internal
0059 
0060 // -----------------------------------------------------------------------------
0061 // absl::node_hash_set
0062 // -----------------------------------------------------------------------------
0063 //
0064 // An `absl::node_hash_set<T>` is an unordered associative container which
0065 // has been optimized for both speed and memory footprint in most common use
0066 // cases. Its interface is similar to that of `std::unordered_set<T>` with the
0067 // following notable differences:
0068 //
0069 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
0070 //   `insert()`, provided that the set is provided a compatible heterogeneous
0071 //   hashing function and equality operator. See below for details.
0072 // * Contains a `capacity()` member function indicating the number of element
0073 //   slots (open, deleted, and empty) within the hash set.
0074 // * Returns `void` from the `erase(iterator)` overload.
0075 //
0076 // By default, `node_hash_set` uses the `absl::Hash` hashing framework.
0077 // All fundamental and Abseil types that support the `absl::Hash` framework have
0078 // a compatible equality operator for comparing insertions into `node_hash_set`.
0079 // If your type is not yet supported by the `absl::Hash` framework, see
0080 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
0081 // types.
0082 //
0083 // Using `absl::node_hash_set` at interface boundaries in dynamically loaded
0084 // libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
0085 // be randomized across dynamically loaded libraries.
0086 //
0087 // To achieve heterogeneous lookup for custom types either `Hash` and `Eq` type
0088 // parameters can be used or `T` should have public inner types
0089 // `absl_container_hash` and (optionally) `absl_container_eq`. In either case,
0090 // `typename Hash::is_transparent` and `typename Eq::is_transparent` should be
0091 // well-formed. Both types are basically functors:
0092 // * `Hash` should support `size_t operator()(U val) const` that returns a hash
0093 // for the given `val`.
0094 // * `Eq` should support `bool operator()(U lhs, V rhs) const` that returns true
0095 // if `lhs` is equal to `rhs`.
0096 //
0097 // In most cases `T` needs only to provide the `absl_container_hash`. In this
0098 // case `std::equal_to<void>` will be used instead of `eq` part.
0099 //
0100 // Example:
0101 //
0102 //   // Create a node hash set of three strings
0103 //   absl::node_hash_set<std::string> ducks =
0104 //     {"huey", "dewey", "louie"};
0105 //
0106 //  // Insert a new element into the node hash set
0107 //  ducks.insert("donald");
0108 //
0109 //  // Force a rehash of the node hash set
0110 //  ducks.rehash(0);
0111 //
0112 //  // See if "dewey" is present
0113 //  if (ducks.contains("dewey")) {
0114 //    std::cout << "We found dewey!" << std::endl;
0115 //  }
0116 template <class T, class Hash = DefaultHashContainerHash<T>,
0117           class Eq = DefaultHashContainerEq<T>, class Alloc = std::allocator<T>>
0118 class ABSL_INTERNAL_ATTRIBUTE_OWNER node_hash_set
0119     : public absl::container_internal::raw_hash_set<
0120           absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> {
0121   using Base = typename node_hash_set::raw_hash_set;
0122 
0123  public:
0124   // Constructors and Assignment Operators
0125   //
0126   // A node_hash_set supports the same overload set as `std::unordered_set`
0127   // for construction and assignment:
0128   //
0129   // *  Default constructor
0130   //
0131   //    // No allocation for the table's elements is made.
0132   //    absl::node_hash_set<std::string> set1;
0133   //
0134   // * Initializer List constructor
0135   //
0136   //   absl::node_hash_set<std::string> set2 =
0137   //       {{"huey"}, {"dewey"}, {"louie"}};
0138   //
0139   // * Copy constructor
0140   //
0141   //   absl::node_hash_set<std::string> set3(set2);
0142   //
0143   // * Copy assignment operator
0144   //
0145   //  // Hash functor and Comparator are copied as well
0146   //  absl::node_hash_set<std::string> set4;
0147   //  set4 = set3;
0148   //
0149   // * Move constructor
0150   //
0151   //   // Move is guaranteed efficient
0152   //   absl::node_hash_set<std::string> set5(std::move(set4));
0153   //
0154   // * Move assignment operator
0155   //
0156   //   // May be efficient if allocators are compatible
0157   //   absl::node_hash_set<std::string> set6;
0158   //   set6 = std::move(set5);
0159   //
0160   // * Range constructor
0161   //
0162   //   std::vector<std::string> v = {"a", "b"};
0163   //   absl::node_hash_set<std::string> set7(v.begin(), v.end());
0164   node_hash_set() {}
0165   using Base::Base;
0166 
0167   // node_hash_set::begin()
0168   //
0169   // Returns an iterator to the beginning of the `node_hash_set`.
0170   using Base::begin;
0171 
0172   // node_hash_set::cbegin()
0173   //
0174   // Returns a const iterator to the beginning of the `node_hash_set`.
0175   using Base::cbegin;
0176 
0177   // node_hash_set::cend()
0178   //
0179   // Returns a const iterator to the end of the `node_hash_set`.
0180   using Base::cend;
0181 
0182   // node_hash_set::end()
0183   //
0184   // Returns an iterator to the end of the `node_hash_set`.
0185   using Base::end;
0186 
0187   // node_hash_set::capacity()
0188   //
0189   // Returns the number of element slots (assigned, deleted, and empty)
0190   // available within the `node_hash_set`.
0191   //
0192   // NOTE: this member function is particular to `absl::node_hash_set` and is
0193   // not provided in the `std::unordered_set` API.
0194   using Base::capacity;
0195 
0196   // node_hash_set::empty()
0197   //
0198   // Returns whether or not the `node_hash_set` is empty.
0199   using Base::empty;
0200 
0201   // node_hash_set::max_size()
0202   //
0203   // Returns the largest theoretical possible number of elements within a
0204   // `node_hash_set` under current memory constraints. This value can be thought
0205   // of the largest value of `std::distance(begin(), end())` for a
0206   // `node_hash_set<T>`.
0207   using Base::max_size;
0208 
0209   // node_hash_set::size()
0210   //
0211   // Returns the number of elements currently within the `node_hash_set`.
0212   using Base::size;
0213 
0214   // node_hash_set::clear()
0215   //
0216   // Removes all elements from the `node_hash_set`. Invalidates any references,
0217   // pointers, or iterators referring to contained elements.
0218   //
0219   // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
0220   // the underlying buffer call `erase(begin(), end())`.
0221   using Base::clear;
0222 
0223   // node_hash_set::erase()
0224   //
0225   // Erases elements within the `node_hash_set`. Erasing does not trigger a
0226   // rehash. Overloads are listed below.
0227   //
0228   // void erase(const_iterator pos):
0229   //
0230   //   Erases the element at `position` of the `node_hash_set`, returning
0231   //   `void`.
0232   //
0233   //   NOTE: this return behavior is different than that of STL containers in
0234   //   general and `std::unordered_set` in particular.
0235   //
0236   // iterator erase(const_iterator first, const_iterator last):
0237   //
0238   //   Erases the elements in the open interval [`first`, `last`), returning an
0239   //   iterator pointing to `last`. The special case of calling
0240   //   `erase(begin(), end())` resets the reserved growth such that if
0241   //   `reserve(N)` has previously been called and there has been no intervening
0242   //   call to `clear()`, then after calling `erase(begin(), end())`, it is safe
0243   //   to assume that inserting N elements will not cause a rehash.
0244   //
0245   // size_type erase(const key_type& key):
0246   //
0247   //   Erases the element with the matching key, if it exists, returning the
0248   //   number of elements erased (0 or 1).
0249   using Base::erase;
0250 
0251   // node_hash_set::insert()
0252   //
0253   // Inserts an element of the specified value into the `node_hash_set`,
0254   // returning an iterator pointing to the newly inserted element, provided that
0255   // an element with the given key does not already exist. If rehashing occurs
0256   // due to the insertion, all iterators are invalidated. Overloads are listed
0257   // below.
0258   //
0259   // std::pair<iterator,bool> insert(const T& value):
0260   //
0261   //   Inserts a value into the `node_hash_set`. Returns a pair consisting of an
0262   //   iterator to the inserted element (or to the element that prevented the
0263   //   insertion) and a bool denoting whether the insertion took place.
0264   //
0265   // std::pair<iterator,bool> insert(T&& value):
0266   //
0267   //   Inserts a moveable value into the `node_hash_set`. Returns a pair
0268   //   consisting of an iterator to the inserted element (or to the element that
0269   //   prevented the insertion) and a bool denoting whether the insertion took
0270   //   place.
0271   //
0272   // iterator insert(const_iterator hint, const T& value):
0273   // iterator insert(const_iterator hint, T&& value):
0274   //
0275   //   Inserts a value, using the position of `hint` as a non-binding suggestion
0276   //   for where to begin the insertion search. Returns an iterator to the
0277   //   inserted element, or to the existing element that prevented the
0278   //   insertion.
0279   //
0280   // void insert(InputIterator first, InputIterator last):
0281   //
0282   //   Inserts a range of values [`first`, `last`).
0283   //
0284   //   NOTE: Although the STL does not specify which element may be inserted if
0285   //   multiple keys compare equivalently, for `node_hash_set` we guarantee the
0286   //   first match is inserted.
0287   //
0288   // void insert(std::initializer_list<T> ilist):
0289   //
0290   //   Inserts the elements within the initializer list `ilist`.
0291   //
0292   //   NOTE: Although the STL does not specify which element may be inserted if
0293   //   multiple keys compare equivalently within the initializer list, for
0294   //   `node_hash_set` we guarantee the first match is inserted.
0295   using Base::insert;
0296 
0297   // node_hash_set::emplace()
0298   //
0299   // Inserts an element of the specified value by constructing it in-place
0300   // within the `node_hash_set`, provided that no element with the given key
0301   // already exists.
0302   //
0303   // The element may be constructed even if there already is an element with the
0304   // key in the container, in which case the newly constructed element will be
0305   // destroyed immediately.
0306   //
0307   // If rehashing occurs due to the insertion, all iterators are invalidated.
0308   using Base::emplace;
0309 
0310   // node_hash_set::emplace_hint()
0311   //
0312   // Inserts an element of the specified value by constructing it in-place
0313   // within the `node_hash_set`, using the position of `hint` as a non-binding
0314   // suggestion for where to begin the insertion search, and only inserts
0315   // provided that no element with the given key already exists.
0316   //
0317   // The element may be constructed even if there already is an element with the
0318   // key in the container, in which case the newly constructed element will be
0319   // destroyed immediately.
0320   //
0321   // If rehashing occurs due to the insertion, all iterators are invalidated.
0322   using Base::emplace_hint;
0323 
0324   // node_hash_set::extract()
0325   //
0326   // Extracts the indicated element, erasing it in the process, and returns it
0327   // as a C++17-compatible node handle. Overloads are listed below.
0328   //
0329   // node_type extract(const_iterator position):
0330   //
0331   //   Extracts the element at the indicated position and returns a node handle
0332   //   owning that extracted data.
0333   //
0334   // node_type extract(const key_type& x):
0335   //
0336   //   Extracts the element with the key matching the passed key value and
0337   //   returns a node handle owning that extracted data. If the `node_hash_set`
0338   //   does not contain an element with a matching key, this function returns an
0339   // empty node handle.
0340   using Base::extract;
0341 
0342   // node_hash_set::merge()
0343   //
0344   // Extracts elements from a given `source` node hash set into this
0345   // `node_hash_set`. If the destination `node_hash_set` already contains an
0346   // element with an equivalent key, that element is not extracted.
0347   using Base::merge;
0348 
0349   // node_hash_set::swap(node_hash_set& other)
0350   //
0351   // Exchanges the contents of this `node_hash_set` with those of the `other`
0352   // node hash set, avoiding invocation of any move, copy, or swap operations on
0353   // individual elements.
0354   //
0355   // All iterators and references on the `node_hash_set` remain valid, excepting
0356   // for the past-the-end iterator, which is invalidated.
0357   //
0358   // `swap()` requires that the node hash set's hashing and key equivalence
0359   // functions be Swappable, and are exchanged using unqualified calls to
0360   // non-member `swap()`. If the set's allocator has
0361   // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
0362   // set to `true`, the allocators are also exchanged using an unqualified call
0363   // to non-member `swap()`; otherwise, the allocators are not swapped.
0364   using Base::swap;
0365 
0366   // node_hash_set::rehash(count)
0367   //
0368   // Rehashes the `node_hash_set`, setting the number of slots to be at least
0369   // the passed value. If the new number of slots increases the load factor more
0370   // than the current maximum load factor
0371   // (`count` < `size()` / `max_load_factor()`), then the new number of slots
0372   // will be at least `size()` / `max_load_factor()`.
0373   //
0374   // To force a rehash, pass rehash(0).
0375   //
0376   // NOTE: unlike behavior in `std::unordered_set`, references are also
0377   // invalidated upon a `rehash()`.
0378   using Base::rehash;
0379 
0380   // node_hash_set::reserve(count)
0381   //
0382   // Sets the number of slots in the `node_hash_set` to the number needed to
0383   // accommodate at least `count` total elements without exceeding the current
0384   // maximum load factor, and may rehash the container if needed.
0385   using Base::reserve;
0386 
0387   // node_hash_set::contains()
0388   //
0389   // Determines whether an element comparing equal to the given `key` exists
0390   // within the `node_hash_set`, returning `true` if so or `false` otherwise.
0391   using Base::contains;
0392 
0393   // node_hash_set::count(const Key& key) const
0394   //
0395   // Returns the number of elements comparing equal to the given `key` within
0396   // the `node_hash_set`. note that this function will return either `1` or `0`
0397   // since duplicate elements are not allowed within a `node_hash_set`.
0398   using Base::count;
0399 
0400   // node_hash_set::equal_range()
0401   //
0402   // Returns a closed range [first, last], defined by a `std::pair` of two
0403   // iterators, containing all elements with the passed key in the
0404   // `node_hash_set`.
0405   using Base::equal_range;
0406 
0407   // node_hash_set::find()
0408   //
0409   // Finds an element with the passed `key` within the `node_hash_set`.
0410   using Base::find;
0411 
0412   // node_hash_set::bucket_count()
0413   //
0414   // Returns the number of "buckets" within the `node_hash_set`. Note that
0415   // because a node hash set contains all elements within its internal storage,
0416   // this value simply equals the current capacity of the `node_hash_set`.
0417   using Base::bucket_count;
0418 
0419   // node_hash_set::load_factor()
0420   //
0421   // Returns the current load factor of the `node_hash_set` (the average number
0422   // of slots occupied with a value within the hash set).
0423   using Base::load_factor;
0424 
0425   // node_hash_set::max_load_factor()
0426   //
0427   // Manages the maximum load factor of the `node_hash_set`. Overloads are
0428   // listed below.
0429   //
0430   // float node_hash_set::max_load_factor()
0431   //
0432   //   Returns the current maximum load factor of the `node_hash_set`.
0433   //
0434   // void node_hash_set::max_load_factor(float ml)
0435   //
0436   //   Sets the maximum load factor of the `node_hash_set` to the passed value.
0437   //
0438   //   NOTE: This overload is provided only for API compatibility with the STL;
0439   //   `node_hash_set` will ignore any set load factor and manage its rehashing
0440   //   internally as an implementation detail.
0441   using Base::max_load_factor;
0442 
0443   // node_hash_set::get_allocator()
0444   //
0445   // Returns the allocator function associated with this `node_hash_set`.
0446   using Base::get_allocator;
0447 
0448   // node_hash_set::hash_function()
0449   //
0450   // Returns the hashing function used to hash the keys within this
0451   // `node_hash_set`.
0452   using Base::hash_function;
0453 
0454   // node_hash_set::key_eq()
0455   //
0456   // Returns the function used for comparing keys equality.
0457   using Base::key_eq;
0458 };
0459 
0460 // erase_if(node_hash_set<>, Pred)
0461 //
0462 // Erases all elements that satisfy the predicate `pred` from the container `c`.
0463 // Returns the number of erased elements.
0464 template <typename T, typename H, typename E, typename A, typename Predicate>
0465 typename node_hash_set<T, H, E, A>::size_type erase_if(
0466     node_hash_set<T, H, E, A>& c, Predicate pred) {
0467   return container_internal::EraseIf(pred, &c);
0468 }
0469 
0470 namespace container_internal {
0471 
0472 // c_for_each_fast(node_hash_set<>, Function)
0473 //
0474 // Container-based version of the <algorithm> `std::for_each()` function to
0475 // apply a function to a container's elements.
0476 // There is no guarantees on the order of the function calls.
0477 // Erasure and/or insertion of elements in the function is not allowed.
0478 template <typename T, typename H, typename E, typename A, typename Function>
0479 decay_t<Function> c_for_each_fast(const node_hash_set<T, H, E, A>& c,
0480                                   Function&& f) {
0481   container_internal::ForEach(f, &c);
0482   return f;
0483 }
0484 template <typename T, typename H, typename E, typename A, typename Function>
0485 decay_t<Function> c_for_each_fast(node_hash_set<T, H, E, A>& c, Function&& f) {
0486   container_internal::ForEach(f, &c);
0487   return f;
0488 }
0489 template <typename T, typename H, typename E, typename A, typename Function>
0490 decay_t<Function> c_for_each_fast(node_hash_set<T, H, E, A>&& c, Function&& f) {
0491   container_internal::ForEach(f, &c);
0492   return f;
0493 }
0494 
0495 }  // namespace container_internal
0496 
0497 namespace container_internal {
0498 
0499 template <class T>
0500 struct NodeHashSetPolicy
0501     : absl::container_internal::node_slot_policy<T&, NodeHashSetPolicy<T>> {
0502   using key_type = T;
0503   using init_type = T;
0504   using constant_iterators = std::true_type;
0505 
0506   template <class Allocator, class... Args>
0507   static T* new_element(Allocator* alloc, Args&&... args) {
0508     using ValueAlloc =
0509         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
0510     ValueAlloc value_alloc(*alloc);
0511     T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
0512     absl::allocator_traits<ValueAlloc>::construct(value_alloc, res,
0513                                                   std::forward<Args>(args)...);
0514     return res;
0515   }
0516 
0517   template <class Allocator>
0518   static void delete_element(Allocator* alloc, T* elem) {
0519     using ValueAlloc =
0520         typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
0521     ValueAlloc value_alloc(*alloc);
0522     absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
0523     absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
0524   }
0525 
0526   template <class F, class... Args>
0527   static decltype(absl::container_internal::DecomposeValue(
0528       std::declval<F>(), std::declval<Args>()...))
0529   apply(F&& f, Args&&... args) {
0530     return absl::container_internal::DecomposeValue(
0531         std::forward<F>(f), std::forward<Args>(args)...);
0532   }
0533 
0534   static size_t element_space_used(const T*) { return sizeof(T); }
0535 
0536   template <class Hash>
0537   static constexpr HashSlotFn get_hash_slot_fn() {
0538     return &TypeErasedDerefAndApplyToSlotFn<Hash, T>;
0539   }
0540 };
0541 }  // namespace container_internal
0542 
0543 namespace container_algorithm_internal {
0544 
0545 // Specialization of trait in absl/algorithm/container.h
0546 template <class Key, class Hash, class KeyEqual, class Allocator>
0547 struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
0548     : std::true_type {};
0549 
0550 }  // namespace container_algorithm_internal
0551 ABSL_NAMESPACE_END
0552 }  // namespace absl
0553 
0554 #endif  // ABSL_CONTAINER_NODE_HASH_SET_H_