node_hash_map.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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_map.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // An `y_absl::node_hash_map<K, V>` is an unordered associative container of
  20. // unique keys and associated values designed to be a more efficient replacement
  21. // for `std::unordered_map`. Like `unordered_map`, search, insertion, and
  22. // deletion of map elements can be done as an `O(1)` operation. However,
  23. // `node_hash_map` (and other unordered associative containers known as the
  24. // collection of Abseil "Swiss tables") contain other optimizations that result
  25. // in both memory and computation advantages.
  26. //
  27. // In most cases, your default choice for a hash map should be a map of type
  28. // `flat_hash_map`. However, if you need pointer stability and cannot store
  29. // a `flat_hash_map` with `unique_ptr` elements, a `node_hash_map` may be a
  30. // valid alternative. As well, if you are migrating your code from using
  31. // `std::unordered_map`, a `node_hash_map` provides a more straightforward
  32. // migration, because it guarantees pointer stability. Consider migrating to
  33. // `node_hash_map` and perhaps converting to a more efficient `flat_hash_map`
  34. // upon further review.
  35. //
  36. // `node_hash_map` is not exception-safe.
  37. #ifndef Y_ABSL_CONTAINER_NODE_HASH_MAP_H_
  38. #define Y_ABSL_CONTAINER_NODE_HASH_MAP_H_
  39. #include <cstddef>
  40. #include <memory>
  41. #include <type_traits>
  42. #include <utility>
  43. #include "y_absl/algorithm/container.h"
  44. #include "y_absl/base/attributes.h"
  45. #include "y_absl/container/hash_container_defaults.h"
  46. #include "y_absl/container/internal/container_memory.h"
  47. #include "y_absl/container/internal/node_slot_policy.h"
  48. #include "y_absl/container/internal/raw_hash_map.h" // IWYU pragma: export
  49. #include "y_absl/memory/memory.h"
  50. #include "y_absl/meta/type_traits.h"
  51. namespace y_absl {
  52. Y_ABSL_NAMESPACE_BEGIN
  53. namespace container_internal {
  54. template <class Key, class Value>
  55. class NodeHashMapPolicy;
  56. } // namespace container_internal
  57. // -----------------------------------------------------------------------------
  58. // y_absl::node_hash_map
  59. // -----------------------------------------------------------------------------
  60. //
  61. // An `y_absl::node_hash_map<K, V>` is an unordered associative container which
  62. // has been optimized for both speed and memory footprint in most common use
  63. // cases. Its interface is similar to that of `std::unordered_map<K, V>` with
  64. // the following notable differences:
  65. //
  66. // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
  67. // `insert()`, provided that the map is provided a compatible heterogeneous
  68. // hashing function and equality operator. See below for details.
  69. // * Contains a `capacity()` member function indicating the number of element
  70. // slots (open, deleted, and empty) within the hash map.
  71. // * Returns `void` from the `erase(iterator)` overload.
  72. //
  73. // By default, `node_hash_map` uses the `y_absl::Hash` hashing framework.
  74. // All fundamental and Abseil types that support the `y_absl::Hash` framework have
  75. // a compatible equality operator for comparing insertions into `node_hash_map`.
  76. // If your type is not yet supported by the `y_absl::Hash` framework, see
  77. // y_absl/hash/hash.h for information on extending Abseil hashing to user-defined
  78. // types.
  79. //
  80. // Using `y_absl::node_hash_map` at interface boundaries in dynamically loaded
  81. // libraries (e.g. .dll, .so) is unsupported due to way `y_absl::Hash` values may
  82. // be randomized across dynamically loaded libraries.
  83. //
  84. // To achieve heterogeneous lookup for custom types either `Hash` and `Eq` type
  85. // parameters can be used or `T` should have public inner types
  86. // `absl_container_hash` and (optionally) `absl_container_eq`. In either case,
  87. // `typename Hash::is_transparent` and `typename Eq::is_transparent` should be
  88. // well-formed. Both types are basically functors:
  89. // * `Hash` should support `size_t operator()(U val) const` that returns a hash
  90. // for the given `val`.
  91. // * `Eq` should support `bool operator()(U lhs, V rhs) const` that returns true
  92. // if `lhs` is equal to `rhs`.
  93. //
  94. // In most cases `T` needs only to provide the `absl_container_hash`. In this
  95. // case `std::equal_to<void>` will be used instead of `eq` part.
  96. //
  97. // Example:
  98. //
  99. // // Create a node hash map of three strings (that map to strings)
  100. // y_absl::node_hash_map<TString, TString> ducks =
  101. // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
  102. //
  103. // // Insert a new element into the node hash map
  104. // ducks.insert({"d", "donald"}};
  105. //
  106. // // Force a rehash of the node hash map
  107. // ducks.rehash(0);
  108. //
  109. // // Find the element with the key "b"
  110. // TString search_key = "b";
  111. // auto result = ducks.find(search_key);
  112. // if (result != ducks.end()) {
  113. // std::cout << "Result: " << result->second << std::endl;
  114. // }
  115. template <class Key, class Value, class Hash = DefaultHashContainerHash<Key>,
  116. class Eq = DefaultHashContainerEq<Key>,
  117. class Alloc = std::allocator<std::pair<const Key, Value>>>
  118. class Y_ABSL_INTERNAL_ATTRIBUTE_OWNER node_hash_map
  119. : public y_absl::container_internal::raw_hash_map<
  120. y_absl::container_internal::NodeHashMapPolicy<Key, Value>, Hash, Eq,
  121. Alloc> {
  122. using Base = typename node_hash_map::raw_hash_map;
  123. public:
  124. // Constructors and Assignment Operators
  125. //
  126. // A node_hash_map supports the same overload set as `std::unordered_map`
  127. // for construction and assignment:
  128. //
  129. // * Default constructor
  130. //
  131. // // No allocation for the table's elements is made.
  132. // y_absl::node_hash_map<int, TString> map1;
  133. //
  134. // * Initializer List constructor
  135. //
  136. // y_absl::node_hash_map<int, TString> map2 =
  137. // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
  138. //
  139. // * Copy constructor
  140. //
  141. // y_absl::node_hash_map<int, TString> map3(map2);
  142. //
  143. // * Copy assignment operator
  144. //
  145. // // Hash functor and Comparator are copied as well
  146. // y_absl::node_hash_map<int, TString> map4;
  147. // map4 = map3;
  148. //
  149. // * Move constructor
  150. //
  151. // // Move is guaranteed efficient
  152. // y_absl::node_hash_map<int, TString> map5(std::move(map4));
  153. //
  154. // * Move assignment operator
  155. //
  156. // // May be efficient if allocators are compatible
  157. // y_absl::node_hash_map<int, TString> map6;
  158. // map6 = std::move(map5);
  159. //
  160. // * Range constructor
  161. //
  162. // std::vector<std::pair<int, TString>> v = {{1, "a"}, {2, "b"}};
  163. // y_absl::node_hash_map<int, TString> map7(v.begin(), v.end());
  164. node_hash_map() {}
  165. using Base::Base;
  166. // node_hash_map::begin()
  167. //
  168. // Returns an iterator to the beginning of the `node_hash_map`.
  169. using Base::begin;
  170. // node_hash_map::cbegin()
  171. //
  172. // Returns a const iterator to the beginning of the `node_hash_map`.
  173. using Base::cbegin;
  174. // node_hash_map::cend()
  175. //
  176. // Returns a const iterator to the end of the `node_hash_map`.
  177. using Base::cend;
  178. // node_hash_map::end()
  179. //
  180. // Returns an iterator to the end of the `node_hash_map`.
  181. using Base::end;
  182. // node_hash_map::capacity()
  183. //
  184. // Returns the number of element slots (assigned, deleted, and empty)
  185. // available within the `node_hash_map`.
  186. //
  187. // NOTE: this member function is particular to `y_absl::node_hash_map` and is
  188. // not provided in the `std::unordered_map` API.
  189. using Base::capacity;
  190. // node_hash_map::empty()
  191. //
  192. // Returns whether or not the `node_hash_map` is empty.
  193. using Base::empty;
  194. // node_hash_map::max_size()
  195. //
  196. // Returns the largest theoretical possible number of elements within a
  197. // `node_hash_map` under current memory constraints. This value can be thought
  198. // of as the largest value of `std::distance(begin(), end())` for a
  199. // `node_hash_map<K, V>`.
  200. using Base::max_size;
  201. // node_hash_map::size()
  202. //
  203. // Returns the number of elements currently within the `node_hash_map`.
  204. using Base::size;
  205. // node_hash_map::clear()
  206. //
  207. // Removes all elements from the `node_hash_map`. Invalidates any references,
  208. // pointers, or iterators referring to contained elements.
  209. //
  210. // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
  211. // the underlying buffer call `erase(begin(), end())`.
  212. using Base::clear;
  213. // node_hash_map::erase()
  214. //
  215. // Erases elements within the `node_hash_map`. Erasing does not trigger a
  216. // rehash. Overloads are listed below.
  217. //
  218. // void erase(const_iterator pos):
  219. //
  220. // Erases the element at `position` of the `node_hash_map`, returning
  221. // `void`.
  222. //
  223. // NOTE: this return behavior is different than that of STL containers in
  224. // general and `std::unordered_map` in particular.
  225. //
  226. // iterator erase(const_iterator first, const_iterator last):
  227. //
  228. // Erases the elements in the open interval [`first`, `last`), returning an
  229. // iterator pointing to `last`. The special case of calling
  230. // `erase(begin(), end())` resets the reserved growth such that if
  231. // `reserve(N)` has previously been called and there has been no intervening
  232. // call to `clear()`, then after calling `erase(begin(), end())`, it is safe
  233. // to assume that inserting N elements will not cause a rehash.
  234. //
  235. // size_type erase(const key_type& key):
  236. //
  237. // Erases the element with the matching key, if it exists, returning the
  238. // number of elements erased (0 or 1).
  239. using Base::erase;
  240. // node_hash_map::insert()
  241. //
  242. // Inserts an element of the specified value into the `node_hash_map`,
  243. // returning an iterator pointing to the newly inserted element, provided that
  244. // an element with the given key does not already exist. If rehashing occurs
  245. // due to the insertion, all iterators are invalidated. Overloads are listed
  246. // below.
  247. //
  248. // std::pair<iterator,bool> insert(const init_type& value):
  249. //
  250. // Inserts a value into the `node_hash_map`. Returns a pair consisting of an
  251. // iterator to the inserted element (or to the element that prevented the
  252. // insertion) and a `bool` denoting whether the insertion took place.
  253. //
  254. // std::pair<iterator,bool> insert(T&& value):
  255. // std::pair<iterator,bool> insert(init_type&& value):
  256. //
  257. // Inserts a moveable value into the `node_hash_map`. Returns a `std::pair`
  258. // consisting of an iterator to the inserted element (or to the element that
  259. // prevented the insertion) and a `bool` denoting whether the insertion took
  260. // place.
  261. //
  262. // iterator insert(const_iterator hint, const init_type& value):
  263. // iterator insert(const_iterator hint, T&& value):
  264. // iterator insert(const_iterator hint, init_type&& value);
  265. //
  266. // Inserts a value, using the position of `hint` as a non-binding suggestion
  267. // for where to begin the insertion search. Returns an iterator to the
  268. // inserted element, or to the existing element that prevented the
  269. // insertion.
  270. //
  271. // void insert(InputIterator first, InputIterator last):
  272. //
  273. // Inserts a range of values [`first`, `last`).
  274. //
  275. // NOTE: Although the STL does not specify which element may be inserted if
  276. // multiple keys compare equivalently, for `node_hash_map` we guarantee the
  277. // first match is inserted.
  278. //
  279. // void insert(std::initializer_list<init_type> ilist):
  280. //
  281. // Inserts the elements within the initializer list `ilist`.
  282. //
  283. // NOTE: Although the STL does not specify which element may be inserted if
  284. // multiple keys compare equivalently within the initializer list, for
  285. // `node_hash_map` we guarantee the first match is inserted.
  286. using Base::insert;
  287. // node_hash_map::insert_or_assign()
  288. //
  289. // Inserts an element of the specified value into the `node_hash_map` provided
  290. // that a value with the given key does not already exist, or replaces it with
  291. // the element value if a key for that value already exists, returning an
  292. // iterator pointing to the newly inserted element. If rehashing occurs due to
  293. // the insertion, all iterators are invalidated. Overloads are listed
  294. // below.
  295. //
  296. // std::pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
  297. // std::pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
  298. //
  299. // Inserts/Assigns (or moves) the element of the specified key into the
  300. // `node_hash_map`.
  301. //
  302. // iterator insert_or_assign(const_iterator hint,
  303. // const init_type& k, T&& obj):
  304. // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
  305. //
  306. // Inserts/Assigns (or moves) the element of the specified key into the
  307. // `node_hash_map` using the position of `hint` as a non-binding suggestion
  308. // for where to begin the insertion search.
  309. using Base::insert_or_assign;
  310. // node_hash_map::emplace()
  311. //
  312. // Inserts an element of the specified value by constructing it in-place
  313. // within the `node_hash_map`, provided that no element with the given key
  314. // already exists.
  315. //
  316. // The element may be constructed even if there already is an element with the
  317. // key in the container, in which case the newly constructed element will be
  318. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  319. // copyable or moveable.
  320. //
  321. // If rehashing occurs due to the insertion, all iterators are invalidated.
  322. using Base::emplace;
  323. // node_hash_map::emplace_hint()
  324. //
  325. // Inserts an element of the specified value by constructing it in-place
  326. // within the `node_hash_map`, using the position of `hint` as a non-binding
  327. // suggestion for where to begin the insertion search, and only inserts
  328. // provided that no element with the given key already exists.
  329. //
  330. // The element may be constructed even if there already is an element with the
  331. // key in the container, in which case the newly constructed element will be
  332. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  333. // copyable or moveable.
  334. //
  335. // If rehashing occurs due to the insertion, all iterators are invalidated.
  336. using Base::emplace_hint;
  337. // node_hash_map::try_emplace()
  338. //
  339. // Inserts an element of the specified value by constructing it in-place
  340. // within the `node_hash_map`, provided that no element with the given key
  341. // already exists. Unlike `emplace()`, if an element with the given key
  342. // already exists, we guarantee that no element is constructed.
  343. //
  344. // If rehashing occurs due to the insertion, all iterators are invalidated.
  345. // Overloads are listed below.
  346. //
  347. // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
  348. // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
  349. //
  350. // Inserts (via copy or move) the element of the specified key into the
  351. // `node_hash_map`.
  352. //
  353. // iterator try_emplace(const_iterator hint,
  354. // const key_type& k, Args&&... args):
  355. // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
  356. //
  357. // Inserts (via copy or move) the element of the specified key into the
  358. // `node_hash_map` using the position of `hint` as a non-binding suggestion
  359. // for where to begin the insertion search.
  360. //
  361. // All `try_emplace()` overloads make the same guarantees regarding rvalue
  362. // arguments as `std::unordered_map::try_emplace()`, namely that these
  363. // functions will not move from rvalue arguments if insertions do not happen.
  364. using Base::try_emplace;
  365. // node_hash_map::extract()
  366. //
  367. // Extracts the indicated element, erasing it in the process, and returns it
  368. // as a C++17-compatible node handle. Overloads are listed below.
  369. //
  370. // node_type extract(const_iterator position):
  371. //
  372. // Extracts the key,value pair of the element at the indicated position and
  373. // returns a node handle owning that extracted data.
  374. //
  375. // node_type extract(const key_type& x):
  376. //
  377. // Extracts the key,value pair of the element with a key matching the passed
  378. // key value and returns a node handle owning that extracted data. If the
  379. // `node_hash_map` does not contain an element with a matching key, this
  380. // function returns an empty node handle.
  381. //
  382. // NOTE: when compiled in an earlier version of C++ than C++17,
  383. // `node_type::key()` returns a const reference to the key instead of a
  384. // mutable reference. We cannot safely return a mutable reference without
  385. // std::launder (which is not available before C++17).
  386. using Base::extract;
  387. // node_hash_map::merge()
  388. //
  389. // Extracts elements from a given `source` node hash map into this
  390. // `node_hash_map`. If the destination `node_hash_map` already contains an
  391. // element with an equivalent key, that element is not extracted.
  392. using Base::merge;
  393. // node_hash_map::swap(node_hash_map& other)
  394. //
  395. // Exchanges the contents of this `node_hash_map` with those of the `other`
  396. // node hash map, avoiding invocation of any move, copy, or swap operations on
  397. // individual elements.
  398. //
  399. // All iterators and references on the `node_hash_map` remain valid, excepting
  400. // for the past-the-end iterator, which is invalidated.
  401. //
  402. // `swap()` requires that the node hash map's hashing and key equivalence
  403. // functions be Swappable, and are exchanged using unqualified calls to
  404. // non-member `swap()`. If the map's allocator has
  405. // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
  406. // set to `true`, the allocators are also exchanged using an unqualified call
  407. // to non-member `swap()`; otherwise, the allocators are not swapped.
  408. using Base::swap;
  409. // node_hash_map::rehash(count)
  410. //
  411. // Rehashes the `node_hash_map`, setting the number of slots to be at least
  412. // the passed value. If the new number of slots increases the load factor more
  413. // than the current maximum load factor
  414. // (`count` < `size()` / `max_load_factor()`), then the new number of slots
  415. // will be at least `size()` / `max_load_factor()`.
  416. //
  417. // To force a rehash, pass rehash(0).
  418. using Base::rehash;
  419. // node_hash_map::reserve(count)
  420. //
  421. // Sets the number of slots in the `node_hash_map` to the number needed to
  422. // accommodate at least `count` total elements without exceeding the current
  423. // maximum load factor, and may rehash the container if needed.
  424. using Base::reserve;
  425. // node_hash_map::at()
  426. //
  427. // Returns a reference to the mapped value of the element with key equivalent
  428. // to the passed key.
  429. using Base::at;
  430. // node_hash_map::contains()
  431. //
  432. // Determines whether an element with a key comparing equal to the given `key`
  433. // exists within the `node_hash_map`, returning `true` if so or `false`
  434. // otherwise.
  435. using Base::contains;
  436. // node_hash_map::count(const Key& key) const
  437. //
  438. // Returns the number of elements with a key comparing equal to the given
  439. // `key` within the `node_hash_map`. note that this function will return
  440. // either `1` or `0` since duplicate keys are not allowed within a
  441. // `node_hash_map`.
  442. using Base::count;
  443. // node_hash_map::equal_range()
  444. //
  445. // Returns a closed range [first, last], defined by a `std::pair` of two
  446. // iterators, containing all elements with the passed key in the
  447. // `node_hash_map`.
  448. using Base::equal_range;
  449. // node_hash_map::find()
  450. //
  451. // Finds an element with the passed `key` within the `node_hash_map`.
  452. using Base::find;
  453. // node_hash_map::operator[]()
  454. //
  455. // Returns a reference to the value mapped to the passed key within the
  456. // `node_hash_map`, performing an `insert()` if the key does not already
  457. // exist. If an insertion occurs and results in a rehashing of the container,
  458. // all iterators are invalidated. Otherwise iterators are not affected and
  459. // references are not invalidated. Overloads are listed below.
  460. //
  461. // T& operator[](const Key& key):
  462. //
  463. // Inserts an init_type object constructed in-place if the element with the
  464. // given key does not exist.
  465. //
  466. // T& operator[](Key&& key):
  467. //
  468. // Inserts an init_type object constructed in-place provided that an element
  469. // with the given key does not exist.
  470. using Base::operator[];
  471. // node_hash_map::bucket_count()
  472. //
  473. // Returns the number of "buckets" within the `node_hash_map`.
  474. using Base::bucket_count;
  475. // node_hash_map::load_factor()
  476. //
  477. // Returns the current load factor of the `node_hash_map` (the average number
  478. // of slots occupied with a value within the hash map).
  479. using Base::load_factor;
  480. // node_hash_map::max_load_factor()
  481. //
  482. // Manages the maximum load factor of the `node_hash_map`. Overloads are
  483. // listed below.
  484. //
  485. // float node_hash_map::max_load_factor()
  486. //
  487. // Returns the current maximum load factor of the `node_hash_map`.
  488. //
  489. // void node_hash_map::max_load_factor(float ml)
  490. //
  491. // Sets the maximum load factor of the `node_hash_map` to the passed value.
  492. //
  493. // NOTE: This overload is provided only for API compatibility with the STL;
  494. // `node_hash_map` will ignore any set load factor and manage its rehashing
  495. // internally as an implementation detail.
  496. using Base::max_load_factor;
  497. // node_hash_map::get_allocator()
  498. //
  499. // Returns the allocator function associated with this `node_hash_map`.
  500. using Base::get_allocator;
  501. // node_hash_map::hash_function()
  502. //
  503. // Returns the hashing function used to hash the keys within this
  504. // `node_hash_map`.
  505. using Base::hash_function;
  506. // node_hash_map::key_eq()
  507. //
  508. // Returns the function used for comparing keys equality.
  509. using Base::key_eq;
  510. };
  511. // erase_if(node_hash_map<>, Pred)
  512. //
  513. // Erases all elements that satisfy the predicate `pred` from the container `c`.
  514. // Returns the number of erased elements.
  515. template <typename K, typename V, typename H, typename E, typename A,
  516. typename Predicate>
  517. typename node_hash_map<K, V, H, E, A>::size_type erase_if(
  518. node_hash_map<K, V, H, E, A>& c, Predicate pred) {
  519. return container_internal::EraseIf(pred, &c);
  520. }
  521. namespace container_internal {
  522. // c_for_each_fast(node_hash_map<>, Function)
  523. //
  524. // Container-based version of the <algorithm> `std::for_each()` function to
  525. // apply a function to a container's elements.
  526. // There is no guarantees on the order of the function calls.
  527. // Erasure and/or insertion of elements in the function is not allowed.
  528. template <typename K, typename V, typename H, typename E, typename A,
  529. typename Function>
  530. decay_t<Function> c_for_each_fast(const node_hash_map<K, V, H, E, A>& c,
  531. Function&& f) {
  532. container_internal::ForEach(f, &c);
  533. return f;
  534. }
  535. template <typename K, typename V, typename H, typename E, typename A,
  536. typename Function>
  537. decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>& c,
  538. Function&& f) {
  539. container_internal::ForEach(f, &c);
  540. return f;
  541. }
  542. template <typename K, typename V, typename H, typename E, typename A,
  543. typename Function>
  544. decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>&& c,
  545. Function&& f) {
  546. container_internal::ForEach(f, &c);
  547. return f;
  548. }
  549. } // namespace container_internal
  550. namespace container_internal {
  551. template <class Key, class Value>
  552. class NodeHashMapPolicy
  553. : public y_absl::container_internal::node_slot_policy<
  554. std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> {
  555. using value_type = std::pair<const Key, Value>;
  556. public:
  557. using key_type = Key;
  558. using mapped_type = Value;
  559. using init_type = std::pair</*non const*/ key_type, mapped_type>;
  560. template <class Allocator, class... Args>
  561. static value_type* new_element(Allocator* alloc, Args&&... args) {
  562. using PairAlloc = typename y_absl::allocator_traits<
  563. Allocator>::template rebind_alloc<value_type>;
  564. PairAlloc pair_alloc(*alloc);
  565. value_type* res =
  566. y_absl::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
  567. y_absl::allocator_traits<PairAlloc>::construct(pair_alloc, res,
  568. std::forward<Args>(args)...);
  569. return res;
  570. }
  571. template <class Allocator>
  572. static void delete_element(Allocator* alloc, value_type* pair) {
  573. using PairAlloc = typename y_absl::allocator_traits<
  574. Allocator>::template rebind_alloc<value_type>;
  575. PairAlloc pair_alloc(*alloc);
  576. y_absl::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
  577. y_absl::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
  578. }
  579. template <class F, class... Args>
  580. static decltype(y_absl::container_internal::DecomposePair(
  581. std::declval<F>(), std::declval<Args>()...))
  582. apply(F&& f, Args&&... args) {
  583. return y_absl::container_internal::DecomposePair(std::forward<F>(f),
  584. std::forward<Args>(args)...);
  585. }
  586. static size_t element_space_used(const value_type*) {
  587. return sizeof(value_type);
  588. }
  589. static Value& value(value_type* elem) { return elem->second; }
  590. static const Value& value(const value_type* elem) { return elem->second; }
  591. template <class Hash>
  592. static constexpr HashSlotFn get_hash_slot_fn() {
  593. return memory_internal::IsLayoutCompatible<Key, Value>::value
  594. ? &TypeErasedDerefAndApplyToSlotFn<Hash, Key>
  595. : nullptr;
  596. }
  597. };
  598. } // namespace container_internal
  599. namespace container_algorithm_internal {
  600. // Specialization of trait in y_absl/algorithm/container.h
  601. template <class Key, class T, class Hash, class KeyEqual, class Allocator>
  602. struct IsUnorderedContainer<
  603. y_absl::node_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
  604. } // namespace container_algorithm_internal
  605. Y_ABSL_NAMESPACE_END
  606. } // namespace y_absl
  607. #endif // Y_ABSL_CONTAINER_NODE_HASH_MAP_H_