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