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 21 kB

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