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