You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

node_hash_set.h 19 kB

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