node_hash_map.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 `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 ABSL_CONTAINER_NODE_HASH_MAP_H_
  38. #define ABSL_CONTAINER_NODE_HASH_MAP_H_
  39. #include <cstddef>
  40. #include <memory>
  41. #include <type_traits>
  42. #include <utility>
  43. #include "absl/algorithm/container.h"
  44. #include "absl/base/attributes.h"
  45. #include "absl/container/hash_container_defaults.h"
  46. #include "absl/container/internal/container_memory.h"
  47. #include "absl/container/internal/node_slot_policy.h"
  48. #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
  49. #include "absl/memory/memory.h"
  50. #include "absl/meta/type_traits.h"
  51. namespace absl {
  52. ABSL_NAMESPACE_BEGIN
  53. namespace container_internal {
  54. template <class Key, class Value>
  55. class NodeHashMapPolicy;
  56. } // namespace container_internal
  57. // -----------------------------------------------------------------------------
  58. // absl::node_hash_map
  59. // -----------------------------------------------------------------------------
  60. //
  61. // An `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 `absl::Hash` hashing framework.
  74. // All fundamental and Abseil types that support the `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 `absl::Hash` framework, see
  77. // absl/hash/hash.h for information on extending Abseil hashing to user-defined
  78. // types.
  79. //
  80. // Using `absl::node_hash_map` at interface boundaries in dynamically loaded
  81. // libraries (e.g. .dll, .so) is unsupported due to way `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. // absl::node_hash_map<std::string, std::string> 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. // std::string 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 ABSL_ATTRIBUTE_OWNER node_hash_map
  119. : public absl::container_internal::raw_hash_map<
  120. 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. // absl::node_hash_map<int, std::string> map1;
  133. //
  134. // * Initializer List constructor
  135. //
  136. // absl::node_hash_map<int, std::string> map2 =
  137. // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
  138. //
  139. // * Copy constructor
  140. //
  141. // absl::node_hash_map<int, std::string> map3(map2);
  142. //
  143. // * Copy assignment operator
  144. //
  145. // // Hash functor and Comparator are copied as well
  146. // absl::node_hash_map<int, std::string> map4;
  147. // map4 = map3;
  148. //
  149. // * Move constructor
  150. //
  151. // // Move is guaranteed efficient
  152. // absl::node_hash_map<int, std::string> map5(std::move(map4));
  153. //
  154. // * Move assignment operator
  155. //
  156. // // May be efficient if allocators are compatible
  157. // absl::node_hash_map<int, std::string> map6;
  158. // map6 = std::move(map5);
  159. //
  160. // * Range constructor
  161. //
  162. // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
  163. // absl::node_hash_map<int, std::string> 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 `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: Returning `void` in this case is different than that of STL
  224. // containers in general and `std::unordered_map` in particular (which
  225. // return an iterator to the element following the erased element). If that
  226. // iterator is needed, simply post increment the iterator:
  227. //
  228. // map.erase(it++);
  229. //
  230. //
  231. // iterator erase(const_iterator first, const_iterator last):
  232. //
  233. // Erases the elements in the open interval [`first`, `last`), returning an
  234. // iterator pointing to `last`. The special case of calling
  235. // `erase(begin(), end())` resets the reserved growth such that if
  236. // `reserve(N)` has previously been called and there has been no intervening
  237. // call to `clear()`, then after calling `erase(begin(), end())`, it is safe
  238. // to assume that inserting N elements will not cause a rehash.
  239. //
  240. // size_type erase(const key_type& key):
  241. //
  242. // Erases the element with the matching key, if it exists, returning the
  243. // number of elements erased (0 or 1).
  244. using Base::erase;
  245. // node_hash_map::insert()
  246. //
  247. // Inserts an element of the specified value into the `node_hash_map`,
  248. // returning an iterator pointing to the newly inserted element, provided that
  249. // an element with the given key does not already exist. If rehashing occurs
  250. // due to the insertion, all iterators are invalidated. Overloads are listed
  251. // below.
  252. //
  253. // std::pair<iterator,bool> insert(const init_type& value):
  254. //
  255. // Inserts a value into the `node_hash_map`. Returns a pair consisting of an
  256. // iterator to the inserted element (or to the element that prevented the
  257. // insertion) and a `bool` denoting whether the insertion took place.
  258. //
  259. // std::pair<iterator,bool> insert(T&& value):
  260. // std::pair<iterator,bool> insert(init_type&& value):
  261. //
  262. // Inserts a moveable value into the `node_hash_map`. Returns a `std::pair`
  263. // consisting of an iterator to the inserted element (or to the element that
  264. // prevented the insertion) and a `bool` denoting whether the insertion took
  265. // place.
  266. //
  267. // iterator insert(const_iterator hint, const init_type& value):
  268. // iterator insert(const_iterator hint, T&& value):
  269. // iterator insert(const_iterator hint, init_type&& value);
  270. //
  271. // Inserts a value, using the position of `hint` as a non-binding suggestion
  272. // for where to begin the insertion search. Returns an iterator to the
  273. // inserted element, or to the existing element that prevented the
  274. // insertion.
  275. //
  276. // void insert(InputIterator first, InputIterator last):
  277. //
  278. // Inserts a range of values [`first`, `last`).
  279. //
  280. // NOTE: Although the STL does not specify which element may be inserted if
  281. // multiple keys compare equivalently, for `node_hash_map` we guarantee the
  282. // first match is inserted.
  283. //
  284. // void insert(std::initializer_list<init_type> ilist):
  285. //
  286. // Inserts the elements within the initializer list `ilist`.
  287. //
  288. // NOTE: Although the STL does not specify which element may be inserted if
  289. // multiple keys compare equivalently within the initializer list, for
  290. // `node_hash_map` we guarantee the first match is inserted.
  291. using Base::insert;
  292. // node_hash_map::insert_or_assign()
  293. //
  294. // Inserts an element of the specified value into the `node_hash_map` provided
  295. // that a value with the given key does not already exist, or replaces it with
  296. // the element value if a key for that value already exists, returning an
  297. // iterator pointing to the newly inserted element. If rehashing occurs due to
  298. // the insertion, all iterators are invalidated. Overloads are listed
  299. // below.
  300. //
  301. // std::pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
  302. // std::pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
  303. //
  304. // Inserts/Assigns (or moves) the element of the specified key into the
  305. // `node_hash_map`.
  306. //
  307. // iterator insert_or_assign(const_iterator hint,
  308. // const init_type& k, T&& obj):
  309. // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
  310. //
  311. // Inserts/Assigns (or moves) the element of the specified key into the
  312. // `node_hash_map` using the position of `hint` as a non-binding suggestion
  313. // for where to begin the insertion search.
  314. using Base::insert_or_assign;
  315. // node_hash_map::emplace()
  316. //
  317. // Inserts an element of the specified value by constructing it in-place
  318. // within the `node_hash_map`, provided that no element with the given key
  319. // already exists.
  320. //
  321. // The element may be constructed even if there already is an element with the
  322. // key in the container, in which case the newly constructed element will be
  323. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  324. // copyable or moveable.
  325. //
  326. // If rehashing occurs due to the insertion, all iterators are invalidated.
  327. using Base::emplace;
  328. // node_hash_map::emplace_hint()
  329. //
  330. // Inserts an element of the specified value by constructing it in-place
  331. // within the `node_hash_map`, using the position of `hint` as a non-binding
  332. // suggestion for where to begin the insertion search, and only inserts
  333. // provided that no element with the given key already exists.
  334. //
  335. // The element may be constructed even if there already is an element with the
  336. // key in the container, in which case the newly constructed element will be
  337. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  338. // copyable or moveable.
  339. //
  340. // If rehashing occurs due to the insertion, all iterators are invalidated.
  341. using Base::emplace_hint;
  342. // node_hash_map::try_emplace()
  343. //
  344. // Inserts an element of the specified value by constructing it in-place
  345. // within the `node_hash_map`, provided that no element with the given key
  346. // already exists. Unlike `emplace()`, if an element with the given key
  347. // already exists, we guarantee that no element is constructed.
  348. //
  349. // If rehashing occurs due to the insertion, all iterators are invalidated.
  350. // Overloads are listed below.
  351. //
  352. // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
  353. // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
  354. //
  355. // Inserts (via copy or move) the element of the specified key into the
  356. // `node_hash_map`.
  357. //
  358. // iterator try_emplace(const_iterator hint,
  359. // const key_type& k, Args&&... args):
  360. // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
  361. //
  362. // Inserts (via copy or move) the element of the specified key into the
  363. // `node_hash_map` using the position of `hint` as a non-binding suggestion
  364. // for where to begin the insertion search.
  365. //
  366. // All `try_emplace()` overloads make the same guarantees regarding rvalue
  367. // arguments as `std::unordered_map::try_emplace()`, namely that these
  368. // functions will not move from rvalue arguments if insertions do not happen.
  369. using Base::try_emplace;
  370. // node_hash_map::extract()
  371. //
  372. // Extracts the indicated element, erasing it in the process, and returns it
  373. // as a C++17-compatible node handle. Overloads are listed below.
  374. //
  375. // node_type extract(const_iterator position):
  376. //
  377. // Extracts the key,value pair of the element at the indicated position and
  378. // returns a node handle owning that extracted data.
  379. //
  380. // node_type extract(const key_type& x):
  381. //
  382. // Extracts the key,value pair of the element with a key matching the passed
  383. // key value and returns a node handle owning that extracted data. If the
  384. // `node_hash_map` does not contain an element with a matching key, this
  385. // function returns an empty node handle.
  386. //
  387. // NOTE: when compiled in an earlier version of C++ than C++17,
  388. // `node_type::key()` returns a const reference to the key instead of a
  389. // mutable reference. We cannot safely return a mutable reference without
  390. // std::launder (which is not available before C++17).
  391. using Base::extract;
  392. // node_hash_map::merge()
  393. //
  394. // Extracts elements from a given `source` node hash map into this
  395. // `node_hash_map`. If the destination `node_hash_map` already contains an
  396. // element with an equivalent key, that element is not extracted.
  397. using Base::merge;
  398. // node_hash_map::swap(node_hash_map& other)
  399. //
  400. // Exchanges the contents of this `node_hash_map` with those of the `other`
  401. // node hash map.
  402. //
  403. // All iterators and references on the `node_hash_map` remain valid, excepting
  404. // for the past-the-end iterator, which is invalidated.
  405. //
  406. // `swap()` requires that the node hash map's hashing and key equivalence
  407. // functions be Swappable, and are exchanged using unqualified calls to
  408. // non-member `swap()`. If the map's allocator has
  409. // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
  410. // set to `true`, the allocators are also exchanged using an unqualified call
  411. // to non-member `swap()`; otherwise, the allocators are not swapped.
  412. using Base::swap;
  413. // node_hash_map::rehash(count)
  414. //
  415. // Rehashes the `node_hash_map`, setting the number of slots to be at least
  416. // the passed value. If the new number of slots increases the load factor more
  417. // than the current maximum load factor
  418. // (`count` < `size()` / `max_load_factor()`), then the new number of slots
  419. // will be at least `size()` / `max_load_factor()`.
  420. //
  421. // To force a rehash, pass rehash(0).
  422. using Base::rehash;
  423. // node_hash_map::reserve(count)
  424. //
  425. // Sets the number of slots in the `node_hash_map` to the number needed to
  426. // accommodate at least `count` total elements without exceeding the current
  427. // maximum load factor, and may rehash the container if needed.
  428. using Base::reserve;
  429. // node_hash_map::at()
  430. //
  431. // Returns a reference to the mapped value of the element with key equivalent
  432. // to the passed key.
  433. using Base::at;
  434. // node_hash_map::contains()
  435. //
  436. // Determines whether an element with a key comparing equal to the given `key`
  437. // exists within the `node_hash_map`, returning `true` if so or `false`
  438. // otherwise.
  439. using Base::contains;
  440. // node_hash_map::count(const Key& key) const
  441. //
  442. // Returns the number of elements with a key comparing equal to the given
  443. // `key` within the `node_hash_map`. note that this function will return
  444. // either `1` or `0` since duplicate keys are not allowed within a
  445. // `node_hash_map`.
  446. using Base::count;
  447. // node_hash_map::equal_range()
  448. //
  449. // Returns a closed range [first, last], defined by a `std::pair` of two
  450. // iterators, containing all elements with the passed key in the
  451. // `node_hash_map`.
  452. using Base::equal_range;
  453. // node_hash_map::find()
  454. //
  455. // Finds an element with the passed `key` within the `node_hash_map`.
  456. using Base::find;
  457. // node_hash_map::operator[]()
  458. //
  459. // Returns a reference to the value mapped to the passed key within the
  460. // `node_hash_map`, performing an `insert()` if the key does not already
  461. // exist. If an insertion occurs and results in a rehashing of the container,
  462. // all iterators are invalidated. Otherwise iterators are not affected and
  463. // references are not invalidated. Overloads are listed below.
  464. //
  465. // T& operator[](const Key& key):
  466. //
  467. // Inserts an init_type object constructed in-place if the element with the
  468. // given key does not exist.
  469. //
  470. // T& operator[](Key&& key):
  471. //
  472. // Inserts an init_type object constructed in-place provided that an element
  473. // with the given key does not exist.
  474. using Base::operator[];
  475. // node_hash_map::bucket_count()
  476. //
  477. // Returns the number of "buckets" within the `node_hash_map`.
  478. using Base::bucket_count;
  479. // node_hash_map::load_factor()
  480. //
  481. // Returns the current load factor of the `node_hash_map` (the average number
  482. // of slots occupied with a value within the hash map).
  483. using Base::load_factor;
  484. // node_hash_map::max_load_factor()
  485. //
  486. // Manages the maximum load factor of the `node_hash_map`. Overloads are
  487. // listed below.
  488. //
  489. // float node_hash_map::max_load_factor()
  490. //
  491. // Returns the current maximum load factor of the `node_hash_map`.
  492. //
  493. // void node_hash_map::max_load_factor(float ml)
  494. //
  495. // Sets the maximum load factor of the `node_hash_map` to the passed value.
  496. //
  497. // NOTE: This overload is provided only for API compatibility with the STL;
  498. // `node_hash_map` will ignore any set load factor and manage its rehashing
  499. // internally as an implementation detail.
  500. using Base::max_load_factor;
  501. // node_hash_map::get_allocator()
  502. //
  503. // Returns the allocator function associated with this `node_hash_map`.
  504. using Base::get_allocator;
  505. // node_hash_map::hash_function()
  506. //
  507. // Returns the hashing function used to hash the keys within this
  508. // `node_hash_map`.
  509. using Base::hash_function;
  510. // node_hash_map::key_eq()
  511. //
  512. // Returns the function used for comparing keys equality.
  513. using Base::key_eq;
  514. };
  515. // erase_if(node_hash_map<>, Pred)
  516. //
  517. // Erases all elements that satisfy the predicate `pred` from the container `c`.
  518. // Returns the number of erased elements.
  519. template <typename K, typename V, typename H, typename E, typename A,
  520. typename Predicate>
  521. typename node_hash_map<K, V, H, E, A>::size_type erase_if(
  522. node_hash_map<K, V, H, E, A>& c, Predicate pred) {
  523. return container_internal::EraseIf(pred, &c);
  524. }
  525. // swap(node_hash_map<>, node_hash_map<>)
  526. //
  527. // Swaps the contents of two `node_hash_map` containers.
  528. //
  529. // NOTE: we need to define this function template in order for
  530. // `flat_hash_set::swap` to be called instead of `std::swap`. Even though we
  531. // have `swap(raw_hash_set&, raw_hash_set&)` defined, that function requires a
  532. // derived-to-base conversion, whereas `std::swap` is a function template so
  533. // `std::swap` will be preferred by compiler.
  534. template <typename K, typename V, typename H, typename E, typename A>
  535. void swap(node_hash_map<K, V, H, E, A>& x,
  536. node_hash_map<K, V, H, E, A>& y) noexcept(noexcept(x.swap(y))) {
  537. return x.swap(y);
  538. }
  539. namespace container_internal {
  540. // c_for_each_fast(node_hash_map<>, Function)
  541. //
  542. // Container-based version of the <algorithm> `std::for_each()` function to
  543. // apply a function to a container's elements.
  544. // There is no guarantees on the order of the function calls.
  545. // Erasure and/or insertion of elements in the function is not allowed.
  546. template <typename K, typename V, typename H, typename E, typename A,
  547. typename Function>
  548. decay_t<Function> c_for_each_fast(const node_hash_map<K, V, H, E, A>& c,
  549. Function&& f) {
  550. container_internal::ForEach(f, &c);
  551. return f;
  552. }
  553. template <typename K, typename V, typename H, typename E, typename A,
  554. typename Function>
  555. decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>& c,
  556. Function&& f) {
  557. container_internal::ForEach(f, &c);
  558. return f;
  559. }
  560. template <typename K, typename V, typename H, typename E, typename A,
  561. typename Function>
  562. decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>&& c,
  563. Function&& f) {
  564. container_internal::ForEach(f, &c);
  565. return f;
  566. }
  567. } // namespace container_internal
  568. namespace container_internal {
  569. template <class Key, class Value>
  570. class NodeHashMapPolicy
  571. : public absl::container_internal::node_slot_policy<
  572. std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> {
  573. using value_type = std::pair<const Key, Value>;
  574. public:
  575. using key_type = Key;
  576. using mapped_type = Value;
  577. using init_type = std::pair</*non const*/ key_type, mapped_type>;
  578. template <class Allocator, class... Args>
  579. static value_type* new_element(Allocator* alloc, Args&&... args) {
  580. using PairAlloc = typename absl::allocator_traits<
  581. Allocator>::template rebind_alloc<value_type>;
  582. PairAlloc pair_alloc(*alloc);
  583. value_type* res =
  584. absl::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
  585. absl::allocator_traits<PairAlloc>::construct(pair_alloc, res,
  586. std::forward<Args>(args)...);
  587. return res;
  588. }
  589. template <class Allocator>
  590. static void delete_element(Allocator* alloc, value_type* pair) {
  591. using PairAlloc = typename absl::allocator_traits<
  592. Allocator>::template rebind_alloc<value_type>;
  593. PairAlloc pair_alloc(*alloc);
  594. absl::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
  595. absl::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
  596. }
  597. template <class F, class... Args>
  598. static decltype(absl::container_internal::DecomposePair(
  599. std::declval<F>(), std::declval<Args>()...))
  600. apply(F&& f, Args&&... args) {
  601. return absl::container_internal::DecomposePair(std::forward<F>(f),
  602. std::forward<Args>(args)...);
  603. }
  604. static size_t element_space_used(const value_type*) {
  605. return sizeof(value_type);
  606. }
  607. static Value& value(value_type* elem) { return elem->second; }
  608. static const Value& value(const value_type* elem) { return elem->second; }
  609. template <class Hash>
  610. static constexpr HashSlotFn get_hash_slot_fn() {
  611. return memory_internal::IsLayoutCompatible<Key, Value>::value
  612. ? &TypeErasedDerefAndApplyToSlotFn<Hash, Key>
  613. : nullptr;
  614. }
  615. };
  616. } // namespace container_internal
  617. namespace container_algorithm_internal {
  618. // Specialization of trait in absl/algorithm/container.h
  619. template <class Key, class T, class Hash, class KeyEqual, class Allocator>
  620. struct IsUnorderedContainer<
  621. absl::node_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
  622. } // namespace container_algorithm_internal
  623. ABSL_NAMESPACE_END
  624. } // namespace absl
  625. #endif // ABSL_CONTAINER_NODE_HASH_MAP_H_