00001 // Copyright 2018 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 // 00015 // ----------------------------------------------------------------------------- 00016 // File: node_hash_map.h 00017 // ----------------------------------------------------------------------------- 00018 // 00019 // An `absl::node_hash_map<K, V>` is an unordered associative container of 00020 // unique keys and associated values designed to be a more efficient replacement 00021 // for `std::unordered_map`. Like `unordered_map`, search, insertion, and 00022 // deletion of map elements can be done as an `O(1)` operation. However, 00023 // `node_hash_map` (and other unordered associative containers known as the 00024 // collection of Abseil "Swiss tables") contain other optimizations that result 00025 // in both memory and computation advantages. 00026 // 00027 // In most cases, your default choice for a hash map should be a map of type 00028 // `flat_hash_map`. However, if you need pointer stability and cannot store 00029 // a `flat_hash_map` with `unique_ptr` elements, a `node_hash_map` may be a 00030 // valid alternative. As well, if you are migrating your code from using 00031 // `std::unordered_map`, a `node_hash_map` provides a more straightforward 00032 // migration, because it guarantees pointer stability. Consider migrating to 00033 // `node_hash_map` and perhaps converting to a more efficient `flat_hash_map` 00034 // upon further review. 00035 00036 #ifndef ABSL_CONTAINER_NODE_HASH_MAP_H_ 00037 #define ABSL_CONTAINER_NODE_HASH_MAP_H_ 00038 00039 #include <tuple> 00040 #include <type_traits> 00041 #include <utility> 00042 00043 #include "absl/algorithm/container.h" 00044 #include "absl/container/internal/container_memory.h" 00045 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export 00046 #include "absl/container/internal/node_hash_policy.h" 00047 #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export 00048 #include "absl/memory/memory.h" 00049 00050 namespace absl { 00051 namespace container_internal { 00052 template <class Key, class Value> 00053 class NodeHashMapPolicy; 00054 } // namespace container_internal 00055 00056 // ----------------------------------------------------------------------------- 00057 // absl::node_hash_map 00058 // ----------------------------------------------------------------------------- 00059 // 00060 // An `absl::node_hash_map<K, V>` is an unordered associative container which 00061 // has been optimized for both speed and memory footprint in most common use 00062 // cases. Its interface is similar to that of `std::unordered_map<K, V>` with 00063 // the following notable differences: 00064 // 00065 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and 00066 // `insert()`, provided that the map is provided a compatible heterogeneous 00067 // hashing function and equality operator. 00068 // * Contains a `capacity()` member function indicating the number of element 00069 // slots (open, deleted, and empty) within the hash map. 00070 // * Returns `void` from the `erase(iterator)` overload. 00071 // 00072 // By default, `node_hash_map` uses the `absl::Hash` hashing framework. 00073 // All fundamental and Abseil types that support the `absl::Hash` framework have 00074 // a compatible equality operator for comparing insertions into `node_hash_map`. 00075 // If your type is not yet supported by the `absl::Hash` framework, see 00076 // absl/hash/hash.h for information on extending Abseil hashing to user-defined 00077 // types. 00078 // 00079 // Example: 00080 // 00081 // // Create a node hash map of three strings (that map to strings) 00082 // absl::node_hash_map<std::string, std::string> ducks = 00083 // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}}; 00084 // 00085 // // Insert a new element into the node hash map 00086 // ducks.insert({"d", "donald"}}; 00087 // 00088 // // Force a rehash of the node hash map 00089 // ducks.rehash(0); 00090 // 00091 // // Find the element with the key "b" 00092 // std::string search_key = "b"; 00093 // auto result = ducks.find(search_key); 00094 // if (result != ducks.end()) { 00095 // std::cout << "Result: " << result->second << std::endl; 00096 // } 00097 template <class Key, class Value, 00098 class Hash = absl::container_internal::hash_default_hash<Key>, 00099 class Eq = absl::container_internal::hash_default_eq<Key>, 00100 class Alloc = std::allocator<std::pair<const Key, Value>>> 00101 class node_hash_map 00102 : public absl::container_internal::raw_hash_map< 00103 absl::container_internal::NodeHashMapPolicy<Key, Value>, Hash, Eq, 00104 Alloc> { 00105 using Base = typename node_hash_map::raw_hash_map; 00106 00107 public: 00108 // Constructors and Assignment Operators 00109 // 00110 // A node_hash_map supports the same overload set as `std::unordered_map` 00111 // for construction and assignment: 00112 // 00113 // * Default constructor 00114 // 00115 // // No allocation for the table's elements is made. 00116 // absl::node_hash_map<int, std::string> map1; 00117 // 00118 // * Initializer List constructor 00119 // 00120 // absl::node_hash_map<int, std::string> map2 = 00121 // {{1, "huey"}, {2, "dewey"}, {3, "louie"},}; 00122 // 00123 // * Copy constructor 00124 // 00125 // absl::node_hash_map<int, std::string> map3(map2); 00126 // 00127 // * Copy assignment operator 00128 // 00129 // // Hash functor and Comparator are copied as well 00130 // absl::node_hash_map<int, std::string> map4; 00131 // map4 = map3; 00132 // 00133 // * Move constructor 00134 // 00135 // // Move is guaranteed efficient 00136 // absl::node_hash_map<int, std::string> map5(std::move(map4)); 00137 // 00138 // * Move assignment operator 00139 // 00140 // // May be efficient if allocators are compatible 00141 // absl::node_hash_map<int, std::string> map6; 00142 // map6 = std::move(map5); 00143 // 00144 // * Range constructor 00145 // 00146 // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}}; 00147 // absl::node_hash_map<int, std::string> map7(v.begin(), v.end()); 00148 node_hash_map() {} 00149 using Base::Base; 00150 00151 // node_hash_map::begin() 00152 // 00153 // Returns an iterator to the beginning of the `node_hash_map`. 00154 using Base::begin; 00155 00156 // node_hash_map::cbegin() 00157 // 00158 // Returns a const iterator to the beginning of the `node_hash_map`. 00159 using Base::cbegin; 00160 00161 // node_hash_map::cend() 00162 // 00163 // Returns a const iterator to the end of the `node_hash_map`. 00164 using Base::cend; 00165 00166 // node_hash_map::end() 00167 // 00168 // Returns an iterator to the end of the `node_hash_map`. 00169 using Base::end; 00170 00171 // node_hash_map::capacity() 00172 // 00173 // Returns the number of element slots (assigned, deleted, and empty) 00174 // available within the `node_hash_map`. 00175 // 00176 // NOTE: this member function is particular to `absl::node_hash_map` and is 00177 // not provided in the `std::unordered_map` API. 00178 using Base::capacity; 00179 00180 // node_hash_map::empty() 00181 // 00182 // Returns whether or not the `node_hash_map` is empty. 00183 using Base::empty; 00184 00185 // node_hash_map::max_size() 00186 // 00187 // Returns the largest theoretical possible number of elements within a 00188 // `node_hash_map` under current memory constraints. This value can be thought 00189 // of as the largest value of `std::distance(begin(), end())` for a 00190 // `node_hash_map<K, V>`. 00191 using Base::max_size; 00192 00193 // node_hash_map::size() 00194 // 00195 // Returns the number of elements currently within the `node_hash_map`. 00196 using Base::size; 00197 00198 // node_hash_map::clear() 00199 // 00200 // Removes all elements from the `node_hash_map`. Invalidates any references, 00201 // pointers, or iterators referring to contained elements. 00202 // 00203 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking 00204 // the underlying buffer call `erase(begin(), end())`. 00205 using Base::clear; 00206 00207 // node_hash_map::erase() 00208 // 00209 // Erases elements within the `node_hash_map`. Erasing does not trigger a 00210 // rehash. Overloads are listed below. 00211 // 00212 // void erase(const_iterator pos): 00213 // 00214 // Erases the element at `position` of the `node_hash_map`, returning 00215 // `void`. 00216 // 00217 // NOTE: this return behavior is different than that of STL containers in 00218 // general and `std::unordered_map` in particular. 00219 // 00220 // iterator erase(const_iterator first, const_iterator last): 00221 // 00222 // Erases the elements in the open interval [`first`, `last`), returning an 00223 // iterator pointing to `last`. 00224 // 00225 // size_type erase(const key_type& key): 00226 // 00227 // Erases the element with the matching key, if it exists. 00228 using Base::erase; 00229 00230 // node_hash_map::insert() 00231 // 00232 // Inserts an element of the specified value into the `node_hash_map`, 00233 // returning an iterator pointing to the newly inserted element, provided that 00234 // an element with the given key does not already exist. If rehashing occurs 00235 // due to the insertion, all iterators are invalidated. Overloads are listed 00236 // below. 00237 // 00238 // std::pair<iterator,bool> insert(const init_type& value): 00239 // 00240 // Inserts a value into the `node_hash_map`. Returns a pair consisting of an 00241 // iterator to the inserted element (or to the element that prevented the 00242 // insertion) and a `bool` denoting whether the insertion took place. 00243 // 00244 // std::pair<iterator,bool> insert(T&& value): 00245 // std::pair<iterator,bool> insert(init_type&& value): 00246 // 00247 // Inserts a moveable value into the `node_hash_map`. Returns a `std::pair` 00248 // consisting of an iterator to the inserted element (or to the element that 00249 // prevented the insertion) and a `bool` denoting whether the insertion took 00250 // place. 00251 // 00252 // iterator insert(const_iterator hint, const init_type& value): 00253 // iterator insert(const_iterator hint, T&& value): 00254 // iterator insert(const_iterator hint, init_type&& value); 00255 // 00256 // Inserts a value, using the position of `hint` as a non-binding suggestion 00257 // for where to begin the insertion search. Returns an iterator to the 00258 // inserted element, or to the existing element that prevented the 00259 // insertion. 00260 // 00261 // void insert(InputIterator first, InputIterator last): 00262 // 00263 // Inserts a range of values [`first`, `last`). 00264 // 00265 // NOTE: Although the STL does not specify which element may be inserted if 00266 // multiple keys compare equivalently, for `node_hash_map` we guarantee the 00267 // first match is inserted. 00268 // 00269 // void insert(std::initializer_list<init_type> ilist): 00270 // 00271 // Inserts the elements within the initializer list `ilist`. 00272 // 00273 // NOTE: Although the STL does not specify which element may be inserted if 00274 // multiple keys compare equivalently within the initializer list, for 00275 // `node_hash_map` we guarantee the first match is inserted. 00276 using Base::insert; 00277 00278 // node_hash_map::insert_or_assign() 00279 // 00280 // Inserts an element of the specified value into the `node_hash_map` provided 00281 // that a value with the given key does not already exist, or replaces it with 00282 // the element value if a key for that value already exists, returning an 00283 // iterator pointing to the newly inserted element. If rehashing occurs due to 00284 // the insertion, all iterators are invalidated. Overloads are listed 00285 // below. 00286 // 00287 // std::pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj): 00288 // std::pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj): 00289 // 00290 // Inserts/Assigns (or moves) the element of the specified key into the 00291 // `node_hash_map`. 00292 // 00293 // iterator insert_or_assign(const_iterator hint, 00294 // const init_type& k, T&& obj): 00295 // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj): 00296 // 00297 // Inserts/Assigns (or moves) the element of the specified key into the 00298 // `node_hash_map` using the position of `hint` as a non-binding suggestion 00299 // for where to begin the insertion search. 00300 using Base::insert_or_assign; 00301 00302 // node_hash_map::emplace() 00303 // 00304 // Inserts an element of the specified value by constructing it in-place 00305 // within the `node_hash_map`, provided that no element with the given key 00306 // already exists. 00307 // 00308 // The element may be constructed even if there already is an element with the 00309 // key in the container, in which case the newly constructed element will be 00310 // destroyed immediately. Prefer `try_emplace()` unless your key is not 00311 // copyable or moveable. 00312 // 00313 // If rehashing occurs due to the insertion, all iterators are invalidated. 00314 using Base::emplace; 00315 00316 // node_hash_map::emplace_hint() 00317 // 00318 // Inserts an element of the specified value by constructing it in-place 00319 // within the `node_hash_map`, using the position of `hint` as a non-binding 00320 // suggestion for where to begin the insertion search, and only inserts 00321 // provided that no element with the given key already exists. 00322 // 00323 // The element may be constructed even if there already is an element with the 00324 // key in the container, in which case the newly constructed element will be 00325 // destroyed immediately. Prefer `try_emplace()` unless your key is not 00326 // copyable or moveable. 00327 // 00328 // If rehashing occurs due to the insertion, all iterators are invalidated. 00329 using Base::emplace_hint; 00330 00331 // node_hash_map::try_emplace() 00332 // 00333 // Inserts an element of the specified value by constructing it in-place 00334 // within the `node_hash_map`, provided that no element with the given key 00335 // already exists. Unlike `emplace()`, if an element with the given key 00336 // already exists, we guarantee that no element is constructed. 00337 // 00338 // If rehashing occurs due to the insertion, all iterators are invalidated. 00339 // Overloads are listed below. 00340 // 00341 // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args): 00342 // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args): 00343 // 00344 // Inserts (via copy or move) the element of the specified key into the 00345 // `node_hash_map`. 00346 // 00347 // iterator try_emplace(const_iterator hint, 00348 // const init_type& k, Args&&... args): 00349 // iterator try_emplace(const_iterator hint, init_type&& k, Args&&... args): 00350 // 00351 // Inserts (via copy or move) the element of the specified key into the 00352 // `node_hash_map` using the position of `hint` as a non-binding suggestion 00353 // for where to begin the insertion search. 00354 using Base::try_emplace; 00355 00356 // node_hash_map::extract() 00357 // 00358 // Extracts the indicated element, erasing it in the process, and returns it 00359 // as a C++17-compatible node handle. Overloads are listed below. 00360 // 00361 // node_type extract(const_iterator position): 00362 // 00363 // Extracts the key,value pair of the element at the indicated position and 00364 // returns a node handle owning that extracted data. 00365 // 00366 // node_type extract(const key_type& x): 00367 // 00368 // Extracts the key,value pair of the element with a key matching the passed 00369 // key value and returns a node handle owning that extracted data. If the 00370 // `node_hash_map` does not contain an element with a matching key, this 00371 // function returns an empty node handle. 00372 using Base::extract; 00373 00374 // node_hash_map::merge() 00375 // 00376 // Extracts elements from a given `source` node hash map into this 00377 // `node_hash_map`. If the destination `node_hash_map` already contains an 00378 // element with an equivalent key, that element is not extracted. 00379 using Base::merge; 00380 00381 // node_hash_map::swap(node_hash_map& other) 00382 // 00383 // Exchanges the contents of this `node_hash_map` with those of the `other` 00384 // node hash map, avoiding invocation of any move, copy, or swap operations on 00385 // individual elements. 00386 // 00387 // All iterators and references on the `node_hash_map` remain valid, excepting 00388 // for the past-the-end iterator, which is invalidated. 00389 // 00390 // `swap()` requires that the node hash map's hashing and key equivalence 00391 // functions be Swappable, and are exchaged using unqualified calls to 00392 // non-member `swap()`. If the map's allocator has 00393 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value` 00394 // set to `true`, the allocators are also exchanged using an unqualified call 00395 // to non-member `swap()`; otherwise, the allocators are not swapped. 00396 using Base::swap; 00397 00398 // node_hash_map::rehash(count) 00399 // 00400 // Rehashes the `node_hash_map`, setting the number of slots to be at least 00401 // the passed value. If the new number of slots increases the load factor more 00402 // than the current maximum load factor 00403 // (`count` < `size()` / `max_load_factor()`), then the new number of slots 00404 // will be at least `size()` / `max_load_factor()`. 00405 // 00406 // To force a rehash, pass rehash(0). 00407 using Base::rehash; 00408 00409 // node_hash_map::reserve(count) 00410 // 00411 // Sets the number of slots in the `node_hash_map` to the number needed to 00412 // accommodate at least `count` total elements without exceeding the current 00413 // maximum load factor, and may rehash the container if needed. 00414 using Base::reserve; 00415 00416 // node_hash_map::at() 00417 // 00418 // Returns a reference to the mapped value of the element with key equivalent 00419 // to the passed key. 00420 using Base::at; 00421 00422 // node_hash_map::contains() 00423 // 00424 // Determines whether an element with a key comparing equal to the given `key` 00425 // exists within the `node_hash_map`, returning `true` if so or `false` 00426 // otherwise. 00427 using Base::contains; 00428 00429 // node_hash_map::count(const Key& key) const 00430 // 00431 // Returns the number of elements with a key comparing equal to the given 00432 // `key` within the `node_hash_map`. note that this function will return 00433 // either `1` or `0` since duplicate keys are not allowed within a 00434 // `node_hash_map`. 00435 using Base::count; 00436 00437 // node_hash_map::equal_range() 00438 // 00439 // Returns a closed range [first, last], defined by a `std::pair` of two 00440 // iterators, containing all elements with the passed key in the 00441 // `node_hash_map`. 00442 using Base::equal_range; 00443 00444 // node_hash_map::find() 00445 // 00446 // Finds an element with the passed `key` within the `node_hash_map`. 00447 using Base::find; 00448 00449 // node_hash_map::operator[]() 00450 // 00451 // Returns a reference to the value mapped to the passed key within the 00452 // `node_hash_map`, performing an `insert()` if the key does not already 00453 // exist. If an insertion occurs and results in a rehashing of the container, 00454 // all iterators are invalidated. Otherwise iterators are not affected and 00455 // references are not invalidated. Overloads are listed below. 00456 // 00457 // T& operator[](const Key& key): 00458 // 00459 // Inserts an init_type object constructed in-place if the element with the 00460 // given key does not exist. 00461 // 00462 // T& operator[](Key&& key): 00463 // 00464 // Inserts an init_type object constructed in-place provided that an element 00465 // with the given key does not exist. 00466 using Base::operator[]; 00467 00468 // node_hash_map::bucket_count() 00469 // 00470 // Returns the number of "buckets" within the `node_hash_map`. 00471 using Base::bucket_count; 00472 00473 // node_hash_map::load_factor() 00474 // 00475 // Returns the current load factor of the `node_hash_map` (the average number 00476 // of slots occupied with a value within the hash map). 00477 using Base::load_factor; 00478 00479 // node_hash_map::max_load_factor() 00480 // 00481 // Manages the maximum load factor of the `node_hash_map`. Overloads are 00482 // listed below. 00483 // 00484 // float node_hash_map::max_load_factor() 00485 // 00486 // Returns the current maximum load factor of the `node_hash_map`. 00487 // 00488 // void node_hash_map::max_load_factor(float ml) 00489 // 00490 // Sets the maximum load factor of the `node_hash_map` to the passed value. 00491 // 00492 // NOTE: This overload is provided only for API compatibility with the STL; 00493 // `node_hash_map` will ignore any set load factor and manage its rehashing 00494 // internally as an implementation detail. 00495 using Base::max_load_factor; 00496 00497 // node_hash_map::get_allocator() 00498 // 00499 // Returns the allocator function associated with this `node_hash_map`. 00500 using Base::get_allocator; 00501 00502 // node_hash_map::hash_function() 00503 // 00504 // Returns the hashing function used to hash the keys within this 00505 // `node_hash_map`. 00506 using Base::hash_function; 00507 00508 // node_hash_map::key_eq() 00509 // 00510 // Returns the function used for comparing keys equality. 00511 using Base::key_eq; 00512 00513 ABSL_DEPRECATED("Call `hash_function()` instead.") 00514 typename Base::hasher hash_funct() { return this->hash_function(); } 00515 00516 ABSL_DEPRECATED("Call `rehash()` instead.") 00517 void resize(typename Base::size_type hint) { this->rehash(hint); } 00518 }; 00519 00520 namespace container_internal { 00521 00522 template <class Key, class Value> 00523 class NodeHashMapPolicy 00524 : public absl::container_internal::node_hash_policy< 00525 std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> { 00526 using value_type = std::pair<const Key, Value>; 00527 00528 public: 00529 using key_type = Key; 00530 using mapped_type = Value; 00531 using init_type = std::pair</*non const*/ key_type, mapped_type>; 00532 00533 template <class Allocator, class... Args> 00534 static value_type* new_element(Allocator* alloc, Args&&... args) { 00535 using PairAlloc = typename absl::allocator_traits< 00536 Allocator>::template rebind_alloc<value_type>; 00537 PairAlloc pair_alloc(*alloc); 00538 value_type* res = 00539 absl::allocator_traits<PairAlloc>::allocate(pair_alloc, 1); 00540 absl::allocator_traits<PairAlloc>::construct(pair_alloc, res, 00541 std::forward<Args>(args)...); 00542 return res; 00543 } 00544 00545 template <class Allocator> 00546 static void delete_element(Allocator* alloc, value_type* pair) { 00547 using PairAlloc = typename absl::allocator_traits< 00548 Allocator>::template rebind_alloc<value_type>; 00549 PairAlloc pair_alloc(*alloc); 00550 absl::allocator_traits<PairAlloc>::destroy(pair_alloc, pair); 00551 absl::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1); 00552 } 00553 00554 template <class F, class... Args> 00555 static decltype(absl::container_internal::DecomposePair( 00556 std::declval<F>(), std::declval<Args>()...)) 00557 apply(F&& f, Args&&... args) { 00558 return absl::container_internal::DecomposePair(std::forward<F>(f), 00559 std::forward<Args>(args)...); 00560 } 00561 00562 static size_t element_space_used(const value_type*) { 00563 return sizeof(value_type); 00564 } 00565 00566 static Value& value(value_type* elem) { return elem->second; } 00567 static const Value& value(const value_type* elem) { return elem->second; } 00568 }; 00569 } // namespace container_internal 00570 00571 namespace container_algorithm_internal { 00572 00573 // Specialization of trait in absl/algorithm/container.h 00574 template <class Key, class T, class Hash, class KeyEqual, class Allocator> 00575 struct IsUnorderedContainer< 00576 absl::node_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; 00577 00578 } // namespace container_algorithm_internal 00579 00580 } // namespace absl 00581 00582 #endif // ABSL_CONTAINER_NODE_HASH_MAP_H_