1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use self::VacantEntryState::*;
17 use fmt::{self, Debug};
19 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
20 use iter::{FromIterator, FusedIterator};
21 use mem::{self, replace};
22 use ops::{Deref, Index, InPlace, Place, Placer};
23 use rand::{self, Rng};
26 use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash};
27 use super::table::BucketState::{Empty, Full};
29 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
31 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
33 struct DefaultResizePolicy;
35 impl DefaultResizePolicy {
36 fn new() -> DefaultResizePolicy {
40 /// A hash map's "capacity" is the number of elements it can hold without
41 /// being resized. Its "raw capacity" is the number of slots required to
42 /// provide that capacity, accounting for maximum loading. The raw capacity
43 /// is always zero or a power of two.
45 fn raw_capacity(&self, len: usize) -> usize {
49 // 1. Account for loading: `raw_capacity >= len * 1.1`.
50 // 2. Ensure it is a power of two.
51 // 3. Ensure it is at least the minimum size.
52 let mut raw_cap = len * 11 / 10;
53 assert!(raw_cap >= len, "raw_cap overflow");
54 raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow");
55 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
60 /// The capacity of the given raw capacity.
62 fn capacity(&self, raw_cap: usize) -> usize {
63 // This doesn't have to be checked for overflow since allocation size
64 // in bytes will overflow earlier than multiplication by 10.
66 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
67 // to be: (raw_cap * den + den - 1) / num
68 (raw_cap * 10 + 10 - 1) / 11
72 // The main performance trick in this hashmap is called Robin Hood Hashing.
73 // It gains its excellent performance from one essential operation:
75 // If an insertion collides with an existing element, and that element's
76 // "probe distance" (how far away the element is from its ideal location)
77 // is higher than how far we've already probed, swap the elements.
79 // This massively lowers variance in probe distance, and allows us to get very
80 // high load factors with good performance. The 90% load factor I use is rather
83 // > Why a load factor of approximately 90%?
85 // In general, all the distances to initial buckets will converge on the mean.
86 // At a load factor of α, the odds of finding the target bucket after k
87 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
88 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
89 // this down to make the math easier on the CPU and avoid its FPU.
90 // Since on average we start the probing in the middle of a cache line, this
91 // strategy pulls in two cache lines of hashes on every lookup. I think that's
92 // pretty good, but if you want to trade off some space, it could go down to one
93 // cache line on average with an α of 0.84.
95 // > Wait, what? Where did you get 1-α^k from?
97 // On the first probe, your odds of a collision with an existing element is α.
98 // The odds of doing this twice in a row is approximately α^2. For three times,
99 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
100 // colliding after k tries is 1-α^k.
102 // The paper from 1986 cited below mentions an implementation which keeps track
103 // of the distance-to-initial-bucket histogram. This approach is not suitable
104 // for modern architectures because it requires maintaining an internal data
105 // structure. This allows very good first guesses, but we are most concerned
106 // with guessing entire cache lines, not individual indexes. Furthermore, array
107 // accesses are no longer linear and in one direction, as we have now. There
108 // is also memory and cache pressure that this would entail that would be very
109 // difficult to properly see in a microbenchmark.
111 // ## Future Improvements (FIXME!)
113 // Allow the load factor to be changed dynamically and/or at initialization.
115 // Also, would it be possible for us to reuse storage when growing the
116 // underlying table? This is exactly the use case for 'realloc', and may
117 // be worth exploring.
119 // ## Future Optimizations (FIXME!)
121 // Another possible design choice that I made without any real reason is
122 // parameterizing the raw table over keys and values. Technically, all we need
123 // is the size and alignment of keys and values, and the code should be just as
124 // efficient (well, we might need one for power-of-two size and one for not...).
125 // This has the potential to reduce code bloat in rust executables, without
126 // really losing anything except 4 words (key size, key alignment, val size,
127 // val alignment) which can be passed in to every call of a `RawTable` function.
128 // This would definitely be an avenue worth exploring if people start complaining
129 // about the size of rust executables.
131 // Annotate exceedingly likely branches in `table::make_hash`
132 // and `search_hashed` to reduce instruction cache pressure
133 // and mispredictions once it becomes possible (blocked on issue #11092).
135 // Shrinking the table could simply reallocate in place after moving buckets
136 // to the first half.
138 // The growth algorithm (fragment of the Proof of Correctness)
139 // --------------------
141 // The growth algorithm is basically a fast path of the naive reinsertion-
142 // during-resize algorithm. Other paths should never be taken.
144 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
145 // by allocating a new table of capacity `2n`, and then individually reinsert
146 // each element in the old table into the new one. This guarantees that the
147 // new table is a valid robin hood hashtable with all the desired statistical
148 // properties. Remark that the order we reinsert the elements in should not
149 // matter. For simplicity and efficiency, we will consider only linear
150 // reinsertions, which consist of reinserting all elements in the old table
151 // into the new one by increasing order of index. However we will not be
152 // starting our reinsertions from index 0 in general. If we start from index
153 // i, for the purpose of reinsertion we will consider all elements with real
154 // index j < i to have virtual index n + j.
156 // Our hash generation scheme consists of generating a 64-bit hash and
157 // truncating the most significant bits. When moving to the new table, we
158 // simply introduce a new bit to the front of the hash. Therefore, if an
159 // elements has ideal index i in the old table, it can have one of two ideal
160 // locations in the new table. If the new bit is 0, then the new ideal index
161 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
162 // we are producing two independent tables of size n, and for each element we
163 // independently choose which table to insert it into with equal probability.
164 // However the rather than wrapping around themselves on overflowing their
165 // indexes, the first table overflows into the first, and the first into the
166 // second. Visually, our new table will look something like:
168 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
170 // Where x's are elements inserted into the first table, y's are elements
171 // inserted into the second, and _'s are empty sections. We now define a few
172 // key concepts that we will use later. Note that this is a very abstract
173 // perspective of the table. A real resized table would be at least half
176 // Theorem: A linear robin hood reinsertion from the first ideal element
177 // produces identical results to a linear naive reinsertion from the same
180 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
182 // Adaptive early resizing
183 // ----------------------
184 // To protect against degenerate performance scenarios (including DOS attacks),
185 // the implementation includes an adaptive behavior that can resize the map
186 // early (before its capacity is exceeded) when suspiciously long probe sequences
189 // With this algorithm in place it would be possible to turn a CPU attack into
190 // a memory attack due to the aggressive resizing. To prevent that the
191 // adaptive behavior only triggers when the map is at least half full.
192 // This reduces the effectiveness of the algorithm but also makes it completely safe.
194 // The previous safety measure also prevents degenerate interactions with
195 // really bad quality hash algorithms that can make normal inputs look like a
198 const DISPLACEMENT_THRESHOLD: usize = 128;
200 // The threshold of 128 is chosen to minimize the chance of exceeding it.
201 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
202 // For displacement, the smallest constant that fits our needs is 90,
203 // so we round that up to 128.
205 // At a load factor of α, the odds of finding the target bucket after exactly n
206 // unsuccesful probes[1] are
208 // Pr_α{displacement = n} =
209 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
211 // We use this formula to find the probability of triggering the adaptive behavior
213 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
215 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
216 // hashing with buckets.
218 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
220 /// By default, `HashMap` uses a hashing algorithm selected to provide
221 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
222 /// reasonable best-effort is made to generate this seed from a high quality,
223 /// secure source of randomness provided by the host without blocking the
224 /// program. Because of this, the randomness of the seed depends on the output
225 /// quality of the system's random number generator when the seed is created.
226 /// In particular, seeds generated when the system's entropy pool is abnormally
227 /// low such as during system boot may be of a lower quality.
229 /// The default hashing algorithm is currently SipHash 1-3, though this is
230 /// subject to change at any point in the future. While its performance is very
231 /// competitive for medium sized keys, other hashing algorithms will outperform
232 /// it for small keys such as integers as well as large keys such as long
233 /// strings, though those algorithms will typically *not* protect against
234 /// attacks such as HashDoS.
236 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
237 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
238 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
240 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
241 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
242 /// If you implement these yourself, it is important that the following
246 /// k1 == k2 -> hash(k1) == hash(k2)
249 /// In other words, if two keys are equal, their hashes must be equal.
251 /// It is a logic error for a key to be modified in such a way that the key's
252 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
253 /// the [`Eq`] trait, changes while it is in the map. This is normally only
254 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
256 /// Relevant papers/articles:
258 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
259 /// 2. Emmanuel Goossaert. ["Robin Hood
260 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
261 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
262 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
267 /// use std::collections::HashMap;
269 /// // type inference lets us omit an explicit type signature (which
270 /// // would be `HashMap<&str, &str>` in this example).
271 /// let mut book_reviews = HashMap::new();
273 /// // review some books.
274 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
275 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
276 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
277 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
279 /// // check for a specific one.
280 /// if !book_reviews.contains_key("Les Misérables") {
281 /// println!("We've got {} reviews, but Les Misérables ain't one.",
282 /// book_reviews.len());
285 /// // oops, this review has a lot of spelling mistakes, let's delete it.
286 /// book_reviews.remove("The Adventures of Sherlock Holmes");
288 /// // look up the values associated with some keys.
289 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
290 /// for book in &to_find {
291 /// match book_reviews.get(book) {
292 /// Some(review) => println!("{}: {}", book, review),
293 /// None => println!("{} is unreviewed.", book)
297 /// // iterate over everything.
298 /// for (book, review) in &book_reviews {
299 /// println!("{}: \"{}\"", book, review);
303 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
304 /// for more complex methods of getting, setting, updating and removing keys and
308 /// use std::collections::HashMap;
310 /// // type inference lets us omit an explicit type signature (which
311 /// // would be `HashMap<&str, u8>` in this example).
312 /// let mut player_stats = HashMap::new();
314 /// fn random_stat_buff() -> u8 {
315 /// // could actually return some random value here - let's just return
316 /// // some fixed value for now
320 /// // insert a key only if it doesn't already exist
321 /// player_stats.entry("health").or_insert(100);
323 /// // insert a key using a function that provides a new value only if it
324 /// // doesn't already exist
325 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
327 /// // update a key, guarding against the key possibly not being set
328 /// let stat = player_stats.entry("attack").or_insert(100);
329 /// *stat += random_stat_buff();
332 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
333 /// We must also derive [`PartialEq`].
335 /// [`Eq`]: ../../std/cmp/trait.Eq.html
336 /// [`Hash`]: ../../std/hash/trait.Hash.html
337 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
338 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
339 /// [`Cell`]: ../../std/cell/struct.Cell.html
340 /// [`default`]: #method.default
341 /// [`with_hasher`]: #method.with_hasher
342 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
343 /// [`fnv`]: https://crates.io/crates/fnv
346 /// use std::collections::HashMap;
348 /// #[derive(Hash, Eq, PartialEq, Debug)]
355 /// /// Create a new Viking.
356 /// fn new(name: &str, country: &str) -> Viking {
357 /// Viking { name: name.to_string(), country: country.to_string() }
361 /// // Use a HashMap to store the vikings' health points.
362 /// let mut vikings = HashMap::new();
364 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
365 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
366 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
368 /// // Use derived implementation to print the status of the vikings.
369 /// for (viking, health) in &vikings {
370 /// println!("{:?} has {} hp", viking, health);
374 /// A `HashMap` with fixed list of elements can be initialized from an array:
377 /// use std::collections::HashMap;
380 /// let timber_resources: HashMap<&str, i32> =
381 /// [("Norway", 100),
384 /// .iter().cloned().collect();
385 /// // use the values stored in map
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub struct HashMap<K, V, S = RandomState> {
392 // All hashes are keyed on these values, to prevent hash collision attacks.
395 table: RawTable<K, V>,
397 resize_policy: DefaultResizePolicy,
400 /// Search for a pre-hashed key.
402 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
403 where M: Deref<Target = RawTable<K, V>>,
406 // This is the only function where capacity can be zero. To avoid
407 // undefined behavior when Bucket::new gets the raw bucket in this
408 // case, immediately return the appropriate search result.
409 if table.capacity() == 0 {
410 return InternalEntry::TableIsEmpty;
413 let size = table.size();
414 let mut probe = Bucket::new(table, hash);
415 let mut displacement = 0;
418 let full = match probe.peek() {
421 return InternalEntry::Vacant {
423 elem: NoElem(bucket, displacement),
426 Full(bucket) => bucket,
429 let probe_displacement = full.displacement();
431 if probe_displacement < displacement {
432 // Found a luckier bucket than me.
433 // We can finish the search early if we hit any bucket
434 // with a lower distance to initial bucket than we've probed.
435 return InternalEntry::Vacant {
437 elem: NeqElem(full, probe_displacement),
441 // If the hash doesn't match, it can't be this one..
442 if hash == full.hash() {
443 // If the key doesn't match, it can't be this one..
444 if is_match(full.read().0) {
445 return InternalEntry::Occupied { elem: full };
450 debug_assert!(displacement <= size);
454 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
455 -> (K, V, &mut RawTable<K, V>)
457 let (empty, retkey, retval) = starting_bucket.take();
458 let mut gap = match empty.gap_peek() {
460 Err(b) => return (retkey, retval, b.into_table()),
463 while gap.full().displacement() != 0 {
464 gap = match gap.shift() {
467 return (retkey, retval, b.into_table());
472 // Now we've done all our shifting. Return the value we grabbed earlier.
473 (retkey, retval, gap.into_table())
476 /// Perform robin hood bucket stealing at the given `bucket`. You must
477 /// also pass that bucket's displacement so we don't have to recalculate it.
479 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
480 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
481 mut displacement: usize,
485 -> FullBucketMut<'a, K, V> {
486 let size = bucket.table().size();
487 let raw_capacity = bucket.table().capacity();
488 // There can be at most `size - dib` buckets to displace, because
489 // in the worst case, there are `size` elements and we already are
490 // `displacement` buckets away from the initial one.
491 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
492 // Save the *starting point*.
493 let mut bucket = bucket.stash();
496 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
503 let probe = bucket.next();
504 debug_assert!(probe.index() != idx_end);
506 let full_bucket = match probe.peek() {
509 let bucket = bucket.put(hash, key, val);
510 // Now that it's stolen, just read the value's pointer
511 // right out of the table! Go back to the *starting point*.
513 // This use of `into_table` is misleading. It turns the
514 // bucket, which is a FullBucket on top of a
515 // FullBucketMut, into just one FullBucketMut. The "table"
516 // refers to the inner FullBucketMut in this context.
517 return bucket.into_table();
519 Full(bucket) => bucket,
522 let probe_displacement = full_bucket.displacement();
524 bucket = full_bucket;
526 // Robin hood! Steal the spot.
527 if probe_displacement < displacement {
528 displacement = probe_displacement;
535 impl<K, V, S> HashMap<K, V, S>
539 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
542 table::make_hash(&self.hash_builder, x)
545 /// Search for a key, yielding the index if it's found in the hashtable.
546 /// If you already have the hash for the key lying around, use
549 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
553 let hash = self.make_hash(q);
554 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
558 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
562 let hash = self.make_hash(q);
563 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
566 // The caller should ensure that invariants by Robin Hood Hashing hold
567 // and that there's space in the underlying table.
568 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
569 let mut buckets = Bucket::new(&mut self.table, hash);
570 let start_index = buckets.index();
573 // We don't need to compare hashes for value swap.
574 // Not even DIBs for Robin Hood.
575 buckets = match buckets.peek() {
577 empty.put(hash, k, v);
580 Full(b) => b.into_bucket(),
583 debug_assert!(buckets.index() != start_index);
588 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
589 /// Creates an empty `HashMap`.
594 /// use std::collections::HashMap;
595 /// let mut map: HashMap<&str, isize> = HashMap::new();
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn new() -> HashMap<K, V, RandomState> {
603 /// Creates an empty `HashMap` with the specified capacity.
605 /// The hash map will be able to hold at least `capacity` elements without
606 /// reallocating. If `capacity` is 0, the hash map will not allocate.
611 /// use std::collections::HashMap;
612 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
617 HashMap::with_capacity_and_hasher(capacity, Default::default())
621 impl<K, V, S> HashMap<K, V, S>
625 /// Creates an empty `HashMap` which will use the given hash builder to hash
628 /// The created map has the default initial capacity.
630 /// Warning: `hash_builder` is normally randomly generated, and
631 /// is designed to allow HashMaps to be resistant to attacks that
632 /// cause many collisions and very poor performance. Setting it
633 /// manually using this function can expose a DoS attack vector.
638 /// use std::collections::HashMap;
639 /// use std::collections::hash_map::RandomState;
641 /// let s = RandomState::new();
642 /// let mut map = HashMap::with_hasher(s);
643 /// map.insert(1, 2);
646 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
647 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
649 hash_builder: hash_builder,
650 resize_policy: DefaultResizePolicy::new(),
651 table: RawTable::new(0),
655 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
656 /// to hash the keys.
658 /// The hash map will be able to hold at least `capacity` elements without
659 /// reallocating. If `capacity` is 0, the hash map will not allocate.
661 /// Warning: `hash_builder` is normally randomly generated, and
662 /// is designed to allow HashMaps to be resistant to attacks that
663 /// cause many collisions and very poor performance. Setting it
664 /// manually using this function can expose a DoS attack vector.
669 /// use std::collections::HashMap;
670 /// use std::collections::hash_map::RandomState;
672 /// let s = RandomState::new();
673 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
674 /// map.insert(1, 2);
677 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
678 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
679 let resize_policy = DefaultResizePolicy::new();
680 let raw_cap = resize_policy.raw_capacity(capacity);
682 hash_builder: hash_builder,
683 resize_policy: resize_policy,
684 table: RawTable::new(raw_cap),
688 /// Returns a reference to the map's [`BuildHasher`].
690 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
691 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
692 pub fn hasher(&self) -> &S {
696 /// Returns the number of elements the map can hold without reallocating.
698 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
699 /// more, but is guaranteed to be able to hold at least this many.
704 /// use std::collections::HashMap;
705 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
706 /// assert!(map.capacity() >= 100);
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn capacity(&self) -> usize {
711 self.resize_policy.capacity(self.raw_capacity())
714 /// Returns the hash map's raw capacity.
716 fn raw_capacity(&self) -> usize {
717 self.table.capacity()
720 /// Reserves capacity for at least `additional` more elements to be inserted
721 /// in the `HashMap`. The collection may reserve more space to avoid
722 /// frequent reallocations.
726 /// Panics if the new allocation size overflows [`usize`].
728 /// [`usize`]: ../../std/primitive.usize.html
733 /// use std::collections::HashMap;
734 /// let mut map: HashMap<&str, isize> = HashMap::new();
737 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn reserve(&mut self, additional: usize) {
739 let remaining = self.capacity() - self.len(); // this can't overflow
740 if remaining < additional {
741 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
742 let raw_cap = self.resize_policy.raw_capacity(min_cap);
743 self.resize(raw_cap);
744 } else if self.table.tag() && remaining <= self.len() {
745 // Probe sequence is too long and table is half full,
746 // resize early to reduce probing length.
747 let new_capacity = self.table.capacity() * 2;
748 self.resize(new_capacity);
752 /// Resizes the internal vectors to a new capacity. It's your
753 /// responsibility to:
754 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
755 /// for the load factor.
756 /// 2) Ensure `new_raw_cap` is a power of two or zero.
757 fn resize(&mut self, new_raw_cap: usize) {
758 assert!(self.table.size() <= new_raw_cap);
759 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
761 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
762 let old_size = old_table.size();
764 if old_table.size() == 0 {
768 let mut bucket = Bucket::head_bucket(&mut old_table);
770 // This is how the buckets might be laid out in memory:
771 // ($ marks an initialized bucket)
773 // |$$$_$$$$$$_$$$$$|
775 // But we've skipped the entire initial cluster of buckets
776 // and will continue iteration in this order:
779 // ^ wrap around once end is reached
782 // ^ exit once table.size == 0
784 bucket = match bucket.peek() {
786 let h = bucket.hash();
787 let (b, k, v) = bucket.take();
788 self.insert_hashed_ordered(h, k, v);
789 if b.table().size() == 0 {
794 Empty(b) => b.into_bucket(),
799 assert_eq!(self.table.size(), old_size);
802 /// Shrinks the capacity of the map as much as possible. It will drop
803 /// down as much as possible while maintaining the internal rules
804 /// and possibly leaving some space in accordance with the resize policy.
809 /// use std::collections::HashMap;
811 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
812 /// map.insert(1, 2);
813 /// map.insert(3, 4);
814 /// assert!(map.capacity() >= 100);
815 /// map.shrink_to_fit();
816 /// assert!(map.capacity() >= 2);
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn shrink_to_fit(&mut self) {
820 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
821 if self.raw_capacity() != new_raw_cap {
822 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
823 let old_size = old_table.size();
825 // Shrink the table. Naive algorithm for resizing:
826 for (h, k, v) in old_table.into_iter() {
827 self.insert_hashed_nocheck(h, k, v);
830 debug_assert_eq!(self.table.size(), old_size);
834 /// Insert a pre-hashed key-value pair, without first checking
835 /// that there's enough room in the buckets. Returns a reference to the
836 /// newly insert value.
838 /// If the key already exists, the hashtable will be returned untouched
839 /// and a reference to the existing element will be returned.
840 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
841 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
843 Some(Occupied(mut elem)) => Some(elem.insert(v)),
844 Some(Vacant(elem)) => {
848 None => unreachable!(),
852 /// An iterator visiting all keys in arbitrary order.
853 /// The iterator element type is `&'a K`.
858 /// use std::collections::HashMap;
860 /// let mut map = HashMap::new();
861 /// map.insert("a", 1);
862 /// map.insert("b", 2);
863 /// map.insert("c", 3);
865 /// for key in map.keys() {
866 /// println!("{}", key);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn keys(&self) -> Keys<K, V> {
871 Keys { inner: self.iter() }
874 /// An iterator visiting all values in arbitrary order.
875 /// The iterator element type is `&'a V`.
880 /// use std::collections::HashMap;
882 /// let mut map = HashMap::new();
883 /// map.insert("a", 1);
884 /// map.insert("b", 2);
885 /// map.insert("c", 3);
887 /// for val in map.values() {
888 /// println!("{}", val);
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn values(&self) -> Values<K, V> {
893 Values { inner: self.iter() }
896 /// An iterator visiting all values mutably in arbitrary order.
897 /// The iterator element type is `&'a mut V`.
902 /// use std::collections::HashMap;
904 /// let mut map = HashMap::new();
906 /// map.insert("a", 1);
907 /// map.insert("b", 2);
908 /// map.insert("c", 3);
910 /// for val in map.values_mut() {
911 /// *val = *val + 10;
914 /// for val in map.values() {
915 /// println!("{}", val);
918 #[stable(feature = "map_values_mut", since = "1.10.0")]
919 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
920 ValuesMut { inner: self.iter_mut() }
923 /// An iterator visiting all key-value pairs in arbitrary order.
924 /// The iterator element type is `(&'a K, &'a V)`.
929 /// use std::collections::HashMap;
931 /// let mut map = HashMap::new();
932 /// map.insert("a", 1);
933 /// map.insert("b", 2);
934 /// map.insert("c", 3);
936 /// for (key, val) in map.iter() {
937 /// println!("key: {} val: {}", key, val);
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn iter(&self) -> Iter<K, V> {
942 Iter { inner: self.table.iter() }
945 /// An iterator visiting all key-value pairs in arbitrary order,
946 /// with mutable references to the values.
947 /// The iterator element type is `(&'a K, &'a mut V)`.
952 /// use std::collections::HashMap;
954 /// let mut map = HashMap::new();
955 /// map.insert("a", 1);
956 /// map.insert("b", 2);
957 /// map.insert("c", 3);
959 /// // Update all values
960 /// for (_, val) in map.iter_mut() {
964 /// for (key, val) in &map {
965 /// println!("key: {} val: {}", key, val);
968 #[stable(feature = "rust1", since = "1.0.0")]
969 pub fn iter_mut(&mut self) -> IterMut<K, V> {
970 IterMut { inner: self.table.iter_mut() }
973 /// Gets the given key's corresponding entry in the map for in-place manipulation.
978 /// use std::collections::HashMap;
980 /// let mut letters = HashMap::new();
982 /// for ch in "a short treatise on fungi".chars() {
983 /// let counter = letters.entry(ch).or_insert(0);
987 /// assert_eq!(letters[&'s'], 2);
988 /// assert_eq!(letters[&'t'], 3);
989 /// assert_eq!(letters[&'u'], 1);
990 /// assert_eq!(letters.get(&'y'), None);
992 #[stable(feature = "rust1", since = "1.0.0")]
993 pub fn entry(&mut self, key: K) -> Entry<K, V> {
996 let hash = self.make_hash(&key);
997 search_hashed(&mut self.table, hash, |q| q.eq(&key))
998 .into_entry(key).expect("unreachable")
1001 /// Returns the number of elements in the map.
1006 /// use std::collections::HashMap;
1008 /// let mut a = HashMap::new();
1009 /// assert_eq!(a.len(), 0);
1010 /// a.insert(1, "a");
1011 /// assert_eq!(a.len(), 1);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn len(&self) -> usize {
1018 /// Returns true if the map contains no elements.
1023 /// use std::collections::HashMap;
1025 /// let mut a = HashMap::new();
1026 /// assert!(a.is_empty());
1027 /// a.insert(1, "a");
1028 /// assert!(!a.is_empty());
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn is_empty(&self) -> bool {
1036 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1037 /// allocated memory for reuse.
1042 /// use std::collections::HashMap;
1044 /// let mut a = HashMap::new();
1045 /// a.insert(1, "a");
1046 /// a.insert(2, "b");
1048 /// for (k, v) in a.drain().take(1) {
1049 /// assert!(k == 1 || k == 2);
1050 /// assert!(v == "a" || v == "b");
1053 /// assert!(a.is_empty());
1056 #[stable(feature = "drain", since = "1.6.0")]
1057 pub fn drain(&mut self) -> Drain<K, V> {
1058 Drain { inner: self.table.drain() }
1061 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1067 /// use std::collections::HashMap;
1069 /// let mut a = HashMap::new();
1070 /// a.insert(1, "a");
1072 /// assert!(a.is_empty());
1074 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn clear(&mut self) {
1080 /// Returns a reference to the value corresponding to the key.
1082 /// The key may be any borrowed form of the map's key type, but
1083 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1086 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1087 /// [`Hash`]: ../../std/hash/trait.Hash.html
1092 /// use std::collections::HashMap;
1094 /// let mut map = HashMap::new();
1095 /// map.insert(1, "a");
1096 /// assert_eq!(map.get(&1), Some(&"a"));
1097 /// assert_eq!(map.get(&2), None);
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1104 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1107 /// Returns true if the map contains a value for the specified key.
1109 /// The key may be any borrowed form of the map's key type, but
1110 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1113 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1114 /// [`Hash`]: ../../std/hash/trait.Hash.html
1119 /// use std::collections::HashMap;
1121 /// let mut map = HashMap::new();
1122 /// map.insert(1, "a");
1123 /// assert_eq!(map.contains_key(&1), true);
1124 /// assert_eq!(map.contains_key(&2), false);
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1131 self.search(k).into_occupied_bucket().is_some()
1134 /// Returns a mutable reference to the value corresponding to the key.
1136 /// The key may be any borrowed form of the map's key type, but
1137 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1140 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1141 /// [`Hash`]: ../../std/hash/trait.Hash.html
1146 /// use std::collections::HashMap;
1148 /// let mut map = HashMap::new();
1149 /// map.insert(1, "a");
1150 /// if let Some(x) = map.get_mut(&1) {
1153 /// assert_eq!(map[&1], "b");
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1160 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1163 /// Inserts a key-value pair into the map.
1165 /// If the map did not have this key present, [`None`] is returned.
1167 /// If the map did have this key present, the value is updated, and the old
1168 /// value is returned. The key is not updated, though; this matters for
1169 /// types that can be `==` without being identical. See the [module-level
1170 /// documentation] for more.
1172 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1173 /// [module-level documentation]: index.html#insert-and-complex-keys
1178 /// use std::collections::HashMap;
1180 /// let mut map = HashMap::new();
1181 /// assert_eq!(map.insert(37, "a"), None);
1182 /// assert_eq!(map.is_empty(), false);
1184 /// map.insert(37, "b");
1185 /// assert_eq!(map.insert(37, "c"), Some("b"));
1186 /// assert_eq!(map[&37], "c");
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1190 let hash = self.make_hash(&k);
1192 self.insert_hashed_nocheck(hash, k, v)
1195 /// Removes a key from the map, returning the value at the key if the key
1196 /// was previously in the map.
1198 /// The key may be any borrowed form of the map's key type, but
1199 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1202 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1203 /// [`Hash`]: ../../std/hash/trait.Hash.html
1208 /// use std::collections::HashMap;
1210 /// let mut map = HashMap::new();
1211 /// map.insert(1, "a");
1212 /// assert_eq!(map.remove(&1), Some("a"));
1213 /// assert_eq!(map.remove(&1), None);
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1220 if self.table.size() == 0 {
1224 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1227 /// Retains only the elements specified by the predicate.
1229 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1234 /// #![feature(retain_hash_collection)]
1235 /// use std::collections::HashMap;
1237 /// let mut map: HashMap<isize, isize> = (0..8).map(|x|(x, x*10)).collect();
1238 /// map.retain(|&k, _| k % 2 == 0);
1239 /// assert_eq!(map.len(), 4);
1241 #[unstable(feature = "retain_hash_collection", issue = "36648")]
1242 pub fn retain<F>(&mut self, mut f: F)
1243 where F: FnMut(&K, &mut V) -> bool
1245 if self.table.size() == 0 {
1248 let mut elems_left = self.table.size();
1249 let mut bucket = Bucket::head_bucket(&mut self.table);
1251 let start_index = bucket.index();
1252 while elems_left != 0 {
1253 bucket = match bucket.peek() {
1256 let should_remove = {
1257 let (k, v) = full.read_mut();
1261 let prev_raw = full.raw();
1262 let (_, _, t) = pop_internal(full);
1263 Bucket::new_from(prev_raw, t)
1272 bucket.prev(); // reverse iteration
1273 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl<K, V, S> PartialEq for HashMap<K, V, S>
1284 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1285 if self.len() != other.len() {
1289 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<K, V, S> Eq for HashMap<K, V, S>
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<K, V, S> Debug for HashMap<K, V, S>
1303 where K: Eq + Hash + Debug,
1307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1308 f.debug_map().entries(self.iter()).finish()
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<K, V, S> Default for HashMap<K, V, S>
1315 S: BuildHasher + Default
1317 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1318 fn default() -> HashMap<K, V, S> {
1319 HashMap::with_hasher(Default::default())
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1325 where K: Eq + Hash + Borrow<Q>,
1332 fn index(&self, index: &Q) -> &V {
1333 self.get(index).expect("no entry found for key")
1337 /// An iterator over the entries of a `HashMap`.
1339 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1340 /// documentation for more.
1342 /// [`iter`]: struct.HashMap.html#method.iter
1343 /// [`HashMap`]: struct.HashMap.html
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 pub struct Iter<'a, K: 'a, V: 'a> {
1346 inner: table::Iter<'a, K, V>,
1349 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, K, V> Clone for Iter<'a, K, V> {
1352 fn clone(&self) -> Iter<'a, K, V> {
1353 Iter { inner: self.inner.clone() }
1357 #[stable(feature = "std_debug", since = "1.16.0")]
1358 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1361 .entries(self.clone())
1366 /// A mutable iterator over the entries of a `HashMap`.
1368 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1369 /// documentation for more.
1371 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1372 /// [`HashMap`]: struct.HashMap.html
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub struct IterMut<'a, K: 'a, V: 'a> {
1375 inner: table::IterMut<'a, K, V>,
1378 /// An owning iterator over the entries of a `HashMap`.
1380 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1381 /// (provided by the `IntoIterator` trait). See its documentation for more.
1383 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1384 /// [`HashMap`]: struct.HashMap.html
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub struct IntoIter<K, V> {
1387 pub(super) inner: table::IntoIter<K, V>,
1390 /// An iterator over the keys of a `HashMap`.
1392 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1393 /// documentation for more.
1395 /// [`keys`]: struct.HashMap.html#method.keys
1396 /// [`HashMap`]: struct.HashMap.html
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub struct Keys<'a, K: 'a, V: 'a> {
1399 inner: Iter<'a, K, V>,
1402 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<'a, K, V> Clone for Keys<'a, K, V> {
1405 fn clone(&self) -> Keys<'a, K, V> {
1406 Keys { inner: self.inner.clone() }
1410 #[stable(feature = "std_debug", since = "1.16.0")]
1411 impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> {
1412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1414 .entries(self.clone())
1419 /// An iterator over the values of a `HashMap`.
1421 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1422 /// documentation for more.
1424 /// [`values`]: struct.HashMap.html#method.values
1425 /// [`HashMap`]: struct.HashMap.html
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub struct Values<'a, K: 'a, V: 'a> {
1428 inner: Iter<'a, K, V>,
1431 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<'a, K, V> Clone for Values<'a, K, V> {
1434 fn clone(&self) -> Values<'a, K, V> {
1435 Values { inner: self.inner.clone() }
1439 #[stable(feature = "std_debug", since = "1.16.0")]
1440 impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> {
1441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1443 .entries(self.clone())
1448 /// A draining iterator over the entries of a `HashMap`.
1450 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1451 /// documentation for more.
1453 /// [`drain`]: struct.HashMap.html#method.drain
1454 /// [`HashMap`]: struct.HashMap.html
1455 #[stable(feature = "drain", since = "1.6.0")]
1456 pub struct Drain<'a, K: 'a, V: 'a> {
1457 pub(super) inner: table::Drain<'a, K, V>,
1460 /// A mutable iterator over the values of a `HashMap`.
1462 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1463 /// documentation for more.
1465 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1466 /// [`HashMap`]: struct.HashMap.html
1467 #[stable(feature = "map_values_mut", since = "1.10.0")]
1468 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1469 inner: IterMut<'a, K, V>,
1472 enum InternalEntry<K, V, M> {
1473 Occupied { elem: FullBucket<K, V, M> },
1476 elem: VacantEntryState<K, V, M>,
1481 impl<K, V, M> InternalEntry<K, V, M> {
1483 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1485 InternalEntry::Occupied { elem } => Some(elem),
1491 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1493 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1495 InternalEntry::Occupied { elem } => {
1496 Some(Occupied(OccupiedEntry {
1501 InternalEntry::Vacant { hash, elem } => {
1502 Some(Vacant(VacantEntry {
1508 InternalEntry::TableIsEmpty => None,
1513 /// A view into a single entry in a map, which may either be vacant or occupied.
1515 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1517 /// [`HashMap`]: struct.HashMap.html
1518 /// [`entry`]: struct.HashMap.html#method.entry
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub enum Entry<'a, K: 'a, V: 'a> {
1521 /// An occupied entry.
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1524 OccupiedEntry<'a, K, V>),
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1529 VacantEntry<'a, K, V>),
1532 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1533 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1537 f.debug_tuple("Entry")
1541 Occupied(ref o) => {
1542 f.debug_tuple("Entry")
1550 /// A view into an occupied entry in a `HashMap`.
1551 /// It is part of the [`Entry`] enum.
1553 /// [`Entry`]: enum.Entry.html
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1557 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1560 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1561 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1563 f.debug_struct("OccupiedEntry")
1564 .field("key", self.key())
1565 .field("value", self.get())
1570 /// A view into a vacant entry in a `HashMap`.
1571 /// It is part of the [`Entry`] enum.
1573 /// [`Entry`]: enum.Entry.html
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1578 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1581 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1582 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1584 f.debug_tuple("VacantEntry")
1590 /// Possible states of a VacantEntry.
1591 enum VacantEntryState<K, V, M> {
1592 /// The index is occupied, but the key to insert has precedence,
1593 /// and will kick the current one out on insertion.
1594 NeqElem(FullBucket<K, V, M>, usize),
1595 /// The index is genuinely vacant.
1596 NoElem(EmptyBucket<K, V, M>, usize),
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1604 type Item = (&'a K, &'a V);
1605 type IntoIter = Iter<'a, K, V>;
1607 fn into_iter(self) -> Iter<'a, K, V> {
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1617 type Item = (&'a K, &'a mut V);
1618 type IntoIter = IterMut<'a, K, V>;
1620 fn into_iter(mut self) -> IterMut<'a, K, V> {
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1631 type IntoIter = IntoIter<K, V>;
1633 /// Creates a consuming iterator, that is, one that moves each key-value
1634 /// pair out of the map in arbitrary order. The map cannot be used after
1640 /// use std::collections::HashMap;
1642 /// let mut map = HashMap::new();
1643 /// map.insert("a", 1);
1644 /// map.insert("b", 2);
1645 /// map.insert("c", 3);
1647 /// // Not possible with .iter()
1648 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1650 fn into_iter(self) -> IntoIter<K, V> {
1651 IntoIter { inner: self.table.into_iter() }
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1657 type Item = (&'a K, &'a V);
1660 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1664 fn size_hint(&self) -> (usize, Option<usize>) {
1665 self.inner.size_hint()
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1671 fn len(&self) -> usize {
1676 #[unstable(feature = "fused", issue = "35602")]
1677 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1681 type Item = (&'a K, &'a mut V);
1684 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1688 fn size_hint(&self) -> (usize, Option<usize>) {
1689 self.inner.size_hint()
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1695 fn len(&self) -> usize {
1699 #[unstable(feature = "fused", issue = "35602")]
1700 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1702 #[stable(feature = "std_debug", since = "1.16.0")]
1703 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1704 where K: fmt::Debug,
1707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1709 .entries(self.inner.iter())
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl<K, V> Iterator for IntoIter<K, V> {
1719 fn next(&mut self) -> Option<(K, V)> {
1720 self.inner.next().map(|(_, k, v)| (k, v))
1723 fn size_hint(&self) -> (usize, Option<usize>) {
1724 self.inner.size_hint()
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1730 fn len(&self) -> usize {
1734 #[unstable(feature = "fused", issue = "35602")]
1735 impl<K, V> FusedIterator for IntoIter<K, V> {}
1737 #[stable(feature = "std_debug", since = "1.16.0")]
1738 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741 .entries(self.inner.iter())
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1751 fn next(&mut self) -> Option<(&'a K)> {
1752 self.inner.next().map(|(k, _)| k)
1755 fn size_hint(&self) -> (usize, Option<usize>) {
1756 self.inner.size_hint()
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1762 fn len(&self) -> usize {
1766 #[unstable(feature = "fused", issue = "35602")]
1767 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<'a, K, V> Iterator for Values<'a, K, V> {
1774 fn next(&mut self) -> Option<(&'a V)> {
1775 self.inner.next().map(|(_, v)| v)
1778 fn size_hint(&self) -> (usize, Option<usize>) {
1779 self.inner.size_hint()
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1785 fn len(&self) -> usize {
1789 #[unstable(feature = "fused", issue = "35602")]
1790 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1792 #[stable(feature = "map_values_mut", since = "1.10.0")]
1793 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1794 type Item = &'a mut V;
1797 fn next(&mut self) -> Option<(&'a mut V)> {
1798 self.inner.next().map(|(_, v)| v)
1801 fn size_hint(&self) -> (usize, Option<usize>) {
1802 self.inner.size_hint()
1805 #[stable(feature = "map_values_mut", since = "1.10.0")]
1806 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1808 fn len(&self) -> usize {
1812 #[unstable(feature = "fused", issue = "35602")]
1813 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1815 #[stable(feature = "std_debug", since = "1.16.0")]
1816 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1817 where K: fmt::Debug,
1820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1822 .entries(self.inner.inner.iter())
1827 #[stable(feature = "drain", since = "1.6.0")]
1828 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1832 fn next(&mut self) -> Option<(K, V)> {
1833 self.inner.next().map(|(_, k, v)| (k, v))
1836 fn size_hint(&self) -> (usize, Option<usize>) {
1837 self.inner.size_hint()
1840 #[stable(feature = "drain", since = "1.6.0")]
1841 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1843 fn len(&self) -> usize {
1847 #[unstable(feature = "fused", issue = "35602")]
1848 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1850 #[stable(feature = "std_debug", since = "1.16.0")]
1851 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1852 where K: fmt::Debug,
1855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1857 .entries(self.inner.iter())
1862 /// A place for insertion to a `Entry`.
1864 /// See [`HashMap::entry`](struct.HashMap.html#method.entry) for details.
1865 #[must_use = "places do nothing unless written to with `<-` syntax"]
1866 #[unstable(feature = "collection_placement",
1867 reason = "struct name and placement protocol is subject to change",
1869 pub struct EntryPlace<'a, K: 'a, V: 'a> {
1870 bucket: FullBucketMut<'a, K, V>,
1873 #[unstable(feature = "collection_placement",
1874 reason = "struct name and placement protocol is subject to change",
1876 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for EntryPlace<'a, K, V> {
1877 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1878 f.debug_struct("EntryPlace")
1879 .field("key", self.bucket.read().0)
1880 .field("value", self.bucket.read().1)
1885 #[unstable(feature = "collection_placement",
1886 reason = "struct name and placement protocol is subject to change",
1888 impl<'a, K, V> Drop for EntryPlace<'a, K, V> {
1889 fn drop(&mut self) {
1890 // Inplacement insertion failed. Only key need to drop.
1891 // The value is failed to insert into map.
1892 unsafe { self.bucket.remove_key() };
1896 #[unstable(feature = "collection_placement",
1897 reason = "placement protocol is subject to change",
1899 impl<'a, K, V> Placer<V> for Entry<'a, K, V> {
1900 type Place = EntryPlace<'a, K, V>;
1902 fn make_place(self) -> EntryPlace<'a, K, V> {
1903 let b = match self {
1904 Occupied(mut o) => {
1905 unsafe { ptr::drop_in_place(o.elem.read_mut().1); }
1909 unsafe { v.insert_key() }
1912 EntryPlace { bucket: b }
1916 #[unstable(feature = "collection_placement",
1917 reason = "placement protocol is subject to change",
1919 impl<'a, K, V> Place<V> for EntryPlace<'a, K, V> {
1920 fn pointer(&mut self) -> *mut V {
1921 self.bucket.read_mut().1
1925 #[unstable(feature = "collection_placement",
1926 reason = "placement protocol is subject to change",
1928 impl<'a, K, V> InPlace<V> for EntryPlace<'a, K, V> {
1931 unsafe fn finalize(self) {
1936 impl<'a, K, V> Entry<'a, K, V> {
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 /// Ensures a value is in the entry by inserting the default if empty, and returns
1939 /// a mutable reference to the value in the entry.
1944 /// use std::collections::HashMap;
1946 /// let mut map: HashMap<&str, u32> = HashMap::new();
1947 /// map.entry("poneyland").or_insert(12);
1949 /// assert_eq!(map["poneyland"], 12);
1951 /// *map.entry("poneyland").or_insert(12) += 10;
1952 /// assert_eq!(map["poneyland"], 22);
1954 pub fn or_insert(self, default: V) -> &'a mut V {
1956 Occupied(entry) => entry.into_mut(),
1957 Vacant(entry) => entry.insert(default),
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1963 /// and returns a mutable reference to the value in the entry.
1968 /// use std::collections::HashMap;
1970 /// let mut map: HashMap<&str, String> = HashMap::new();
1971 /// let s = "hoho".to_string();
1973 /// map.entry("poneyland").or_insert_with(|| s);
1975 /// assert_eq!(map["poneyland"], "hoho".to_string());
1977 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1979 Occupied(entry) => entry.into_mut(),
1980 Vacant(entry) => entry.insert(default()),
1984 /// Returns a reference to this entry's key.
1989 /// use std::collections::HashMap;
1991 /// let mut map: HashMap<&str, u32> = HashMap::new();
1992 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1994 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1995 pub fn key(&self) -> &K {
1997 Occupied(ref entry) => entry.key(),
1998 Vacant(ref entry) => entry.key(),
2003 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2004 /// Gets a reference to the key in the entry.
2009 /// use std::collections::HashMap;
2011 /// let mut map: HashMap<&str, u32> = HashMap::new();
2012 /// map.entry("poneyland").or_insert(12);
2013 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2015 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2016 pub fn key(&self) -> &K {
2020 /// Take the ownership of the key and value from the map.
2025 /// use std::collections::HashMap;
2026 /// use std::collections::hash_map::Entry;
2028 /// let mut map: HashMap<&str, u32> = HashMap::new();
2029 /// map.entry("poneyland").or_insert(12);
2031 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2032 /// // We delete the entry from the map.
2033 /// o.remove_entry();
2036 /// assert_eq!(map.contains_key("poneyland"), false);
2038 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2039 pub fn remove_entry(self) -> (K, V) {
2040 let (k, v, _) = pop_internal(self.elem);
2044 /// Gets a reference to the value in the entry.
2049 /// use std::collections::HashMap;
2050 /// use std::collections::hash_map::Entry;
2052 /// let mut map: HashMap<&str, u32> = HashMap::new();
2053 /// map.entry("poneyland").or_insert(12);
2055 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2056 /// assert_eq!(o.get(), &12);
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub fn get(&self) -> &V {
2064 /// Gets a mutable reference to the value in the entry.
2069 /// use std::collections::HashMap;
2070 /// use std::collections::hash_map::Entry;
2072 /// let mut map: HashMap<&str, u32> = HashMap::new();
2073 /// map.entry("poneyland").or_insert(12);
2075 /// assert_eq!(map["poneyland"], 12);
2076 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2077 /// *o.get_mut() += 10;
2080 /// assert_eq!(map["poneyland"], 22);
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 pub fn get_mut(&mut self) -> &mut V {
2084 self.elem.read_mut().1
2087 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2088 /// with a lifetime bound to the map itself.
2093 /// use std::collections::HashMap;
2094 /// use std::collections::hash_map::Entry;
2096 /// let mut map: HashMap<&str, u32> = HashMap::new();
2097 /// map.entry("poneyland").or_insert(12);
2099 /// assert_eq!(map["poneyland"], 12);
2100 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2101 /// *o.into_mut() += 10;
2104 /// assert_eq!(map["poneyland"], 22);
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 pub fn into_mut(self) -> &'a mut V {
2108 self.elem.into_mut_refs().1
2111 /// Sets the value of the entry, and returns the entry's old value.
2116 /// use std::collections::HashMap;
2117 /// use std::collections::hash_map::Entry;
2119 /// let mut map: HashMap<&str, u32> = HashMap::new();
2120 /// map.entry("poneyland").or_insert(12);
2122 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2123 /// assert_eq!(o.insert(15), 12);
2126 /// assert_eq!(map["poneyland"], 15);
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 pub fn insert(&mut self, mut value: V) -> V {
2130 let old_value = self.get_mut();
2131 mem::swap(&mut value, old_value);
2135 /// Takes the value out of the entry, and returns it.
2140 /// use std::collections::HashMap;
2141 /// use std::collections::hash_map::Entry;
2143 /// let mut map: HashMap<&str, u32> = HashMap::new();
2144 /// map.entry("poneyland").or_insert(12);
2146 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2147 /// assert_eq!(o.remove(), 12);
2150 /// assert_eq!(map.contains_key("poneyland"), false);
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 pub fn remove(self) -> V {
2154 pop_internal(self.elem).1
2157 /// Returns a key that was used for search.
2159 /// The key was retained for further use.
2160 fn take_key(&mut self) -> Option<K> {
2165 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2166 /// Gets a reference to the key that would be used when inserting a value
2167 /// through the `VacantEntry`.
2172 /// use std::collections::HashMap;
2174 /// let mut map: HashMap<&str, u32> = HashMap::new();
2175 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2177 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2178 pub fn key(&self) -> &K {
2182 /// Take ownership of the key.
2187 /// use std::collections::HashMap;
2188 /// use std::collections::hash_map::Entry;
2190 /// let mut map: HashMap<&str, u32> = HashMap::new();
2192 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2196 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2197 pub fn into_key(self) -> K {
2201 /// Sets the value of the entry with the VacantEntry's key,
2202 /// and returns a mutable reference to it.
2207 /// use std::collections::HashMap;
2208 /// use std::collections::hash_map::Entry;
2210 /// let mut map: HashMap<&str, u32> = HashMap::new();
2212 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2215 /// assert_eq!(map["poneyland"], 37);
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 pub fn insert(self, value: V) -> &'a mut V {
2219 let b = match self.elem {
2220 NeqElem(mut bucket, disp) => {
2221 if disp >= DISPLACEMENT_THRESHOLD {
2222 bucket.table_mut().set_tag(true);
2224 robin_hood(bucket, disp, self.hash, self.key, value)
2226 NoElem(mut bucket, disp) => {
2227 if disp >= DISPLACEMENT_THRESHOLD {
2228 bucket.table_mut().set_tag(true);
2230 bucket.put(self.hash, self.key, value)
2236 // Only used for InPlacement insert. Avoid unnecessary value copy.
2237 // The value remains uninitialized.
2238 unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2240 NeqElem(mut bucket, disp) => {
2241 if disp >= DISPLACEMENT_THRESHOLD {
2242 bucket.table_mut().set_tag(true);
2244 let uninit = mem::uninitialized();
2245 robin_hood(bucket, disp, self.hash, self.key, uninit)
2247 NoElem(mut bucket, disp) => {
2248 if disp >= DISPLACEMENT_THRESHOLD {
2249 bucket.table_mut().set_tag(true);
2251 bucket.put_key(self.hash, self.key)
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2260 S: BuildHasher + Default
2262 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2263 let mut map = HashMap::with_hasher(Default::default());
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2274 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2275 // Keys may be already present or show multiple times in the iterator.
2276 // Reserve the entire hint lower bound if the map is empty.
2277 // Otherwise reserve half the hint (rounded up), so the map
2278 // will only resize twice in the worst case.
2279 let iter = iter.into_iter();
2280 let reserve = if self.is_empty() {
2283 (iter.size_hint().0 + 1) / 2
2285 self.reserve(reserve);
2286 for (k, v) in iter {
2292 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2293 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2294 where K: Eq + Hash + Copy,
2298 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2299 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2303 /// `RandomState` is the default state for [`HashMap`] types.
2305 /// A particular instance `RandomState` will create the same instances of
2306 /// [`Hasher`], but the hashers created by two different `RandomState`
2307 /// instances are unlikely to produce the same result for the same values.
2309 /// [`HashMap`]: struct.HashMap.html
2310 /// [`Hasher`]: ../../hash/trait.Hasher.html
2315 /// use std::collections::HashMap;
2316 /// use std::collections::hash_map::RandomState;
2318 /// let s = RandomState::new();
2319 /// let mut map = HashMap::with_hasher(s);
2320 /// map.insert(1, 2);
2323 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2324 pub struct RandomState {
2330 /// Constructs a new `RandomState` that is initialized with random keys.
2335 /// use std::collections::hash_map::RandomState;
2337 /// let s = RandomState::new();
2340 #[allow(deprecated)]
2342 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2343 pub fn new() -> RandomState {
2344 // Historically this function did not cache keys from the OS and instead
2345 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2346 // was discovered, however, that because we re-seed the thread-local RNG
2347 // from the OS periodically that this can cause excessive slowdown when
2348 // many hash maps are created on a thread. To solve this performance
2349 // trap we cache the first set of randomly generated keys per-thread.
2351 // Later in #36481 it was discovered that exposing a deterministic
2352 // iteration order allows a form of DOS attack. To counter that we
2353 // increment one of the seeds on every RandomState creation, giving
2354 // every corresponding HashMap a different iteration order.
2355 thread_local!(static KEYS: Cell<(u64, u64)> = {
2356 let r = rand::OsRng::new();
2357 let mut r = r.expect("failed to create an OS RNG");
2358 Cell::new((r.gen(), r.gen()))
2362 let (k0, k1) = keys.get();
2363 keys.set((k0.wrapping_add(1), k1));
2364 RandomState { k0: k0, k1: k1 }
2369 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2370 impl BuildHasher for RandomState {
2371 type Hasher = DefaultHasher;
2373 #[allow(deprecated)]
2374 fn build_hasher(&self) -> DefaultHasher {
2375 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2379 /// The default [`Hasher`] used by [`RandomState`].
2381 /// The internal algorithm is not specified, and so it and its hashes should
2382 /// not be relied upon over releases.
2384 /// [`RandomState`]: struct.RandomState.html
2385 /// [`Hasher`]: ../../hash/trait.Hasher.html
2386 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2387 #[allow(deprecated)]
2389 pub struct DefaultHasher(SipHasher13);
2391 impl DefaultHasher {
2392 /// Creates a new `DefaultHasher`.
2394 /// This hasher is not guaranteed to be the same as all other
2395 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2396 /// instances created through `new` or `default`.
2397 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2398 #[allow(deprecated)]
2399 pub fn new() -> DefaultHasher {
2400 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2404 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2405 impl Default for DefaultHasher {
2406 /// Creates a new `DefaultHasher` using [`new`]. See its documentation for more.
2408 /// [`new`]: #method.new
2409 fn default() -> DefaultHasher {
2410 DefaultHasher::new()
2414 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2415 impl Hasher for DefaultHasher {
2417 fn write(&mut self, msg: &[u8]) {
2422 fn finish(&self) -> u64 {
2427 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2428 impl Default for RandomState {
2429 /// Constructs a new `RandomState`.
2431 fn default() -> RandomState {
2436 #[stable(feature = "std_debug", since = "1.16.0")]
2437 impl fmt::Debug for RandomState {
2438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2439 f.pad("RandomState { .. }")
2443 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2444 where K: Eq + Hash + Borrow<Q>,
2450 fn get(&self, key: &Q) -> Option<&K> {
2451 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2454 fn take(&mut self, key: &Q) -> Option<K> {
2455 if self.table.size() == 0 {
2459 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2462 fn replace(&mut self, key: K) -> Option<K> {
2465 match self.entry(key) {
2466 Occupied(mut occupied) => {
2467 let key = occupied.take_key().unwrap();
2468 Some(mem::replace(occupied.elem.read_mut().0, key))
2479 fn assert_covariance() {
2480 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2483 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2486 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2489 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2492 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2495 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2498 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2501 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2504 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2507 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2510 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2511 -> Drain<'new, &'new str, &'new str> {
2519 use super::Entry::{Occupied, Vacant};
2520 use super::RandomState;
2522 use rand::{thread_rng, Rng};
2526 fn test_zero_capacities() {
2527 type HM = HashMap<i32, i32>;
2530 assert_eq!(m.capacity(), 0);
2532 let m = HM::default();
2533 assert_eq!(m.capacity(), 0);
2535 let m = HM::with_hasher(RandomState::new());
2536 assert_eq!(m.capacity(), 0);
2538 let m = HM::with_capacity(0);
2539 assert_eq!(m.capacity(), 0);
2541 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2542 assert_eq!(m.capacity(), 0);
2544 let mut m = HM::new();
2550 assert_eq!(m.capacity(), 0);
2552 let mut m = HM::new();
2554 assert_eq!(m.capacity(), 0);
2558 fn test_create_capacity_zero() {
2559 let mut m = HashMap::with_capacity(0);
2561 assert!(m.insert(1, 1).is_none());
2563 assert!(m.contains_key(&1));
2564 assert!(!m.contains_key(&0));
2569 let mut m = HashMap::new();
2570 assert_eq!(m.len(), 0);
2571 assert!(m.insert(1, 2).is_none());
2572 assert_eq!(m.len(), 1);
2573 assert!(m.insert(2, 4).is_none());
2574 assert_eq!(m.len(), 2);
2575 assert_eq!(*m.get(&1).unwrap(), 2);
2576 assert_eq!(*m.get(&2).unwrap(), 4);
2581 let mut m = HashMap::new();
2582 assert_eq!(m.len(), 0);
2583 assert!(m.insert(1, 2).is_none());
2584 assert_eq!(m.len(), 1);
2585 assert!(m.insert(2, 4).is_none());
2586 assert_eq!(m.len(), 2);
2588 assert_eq!(*m2.get(&1).unwrap(), 2);
2589 assert_eq!(*m2.get(&2).unwrap(), 4);
2590 assert_eq!(m2.len(), 2);
2593 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2595 #[derive(Hash, PartialEq, Eq)]
2601 fn new(k: usize) -> Dropable {
2602 DROP_VECTOR.with(|slot| {
2603 slot.borrow_mut()[k] += 1;
2610 impl Drop for Dropable {
2611 fn drop(&mut self) {
2612 DROP_VECTOR.with(|slot| {
2613 slot.borrow_mut()[self.k] -= 1;
2618 impl Clone for Dropable {
2619 fn clone(&self) -> Dropable {
2620 Dropable::new(self.k)
2626 DROP_VECTOR.with(|slot| {
2627 *slot.borrow_mut() = vec![0; 200];
2631 let mut m = HashMap::new();
2633 DROP_VECTOR.with(|v| {
2635 assert_eq!(v.borrow()[i], 0);
2640 let d1 = Dropable::new(i);
2641 let d2 = Dropable::new(i + 100);
2645 DROP_VECTOR.with(|v| {
2647 assert_eq!(v.borrow()[i], 1);
2652 let k = Dropable::new(i);
2653 let v = m.remove(&k);
2655 assert!(v.is_some());
2657 DROP_VECTOR.with(|v| {
2658 assert_eq!(v.borrow()[i], 1);
2659 assert_eq!(v.borrow()[i+100], 1);
2663 DROP_VECTOR.with(|v| {
2665 assert_eq!(v.borrow()[i], 0);
2666 assert_eq!(v.borrow()[i+100], 0);
2670 assert_eq!(v.borrow()[i], 1);
2671 assert_eq!(v.borrow()[i+100], 1);
2676 DROP_VECTOR.with(|v| {
2678 assert_eq!(v.borrow()[i], 0);
2684 fn test_into_iter_drops() {
2685 DROP_VECTOR.with(|v| {
2686 *v.borrow_mut() = vec![0; 200];
2690 let mut hm = HashMap::new();
2692 DROP_VECTOR.with(|v| {
2694 assert_eq!(v.borrow()[i], 0);
2699 let d1 = Dropable::new(i);
2700 let d2 = Dropable::new(i + 100);
2704 DROP_VECTOR.with(|v| {
2706 assert_eq!(v.borrow()[i], 1);
2713 // By the way, ensure that cloning doesn't screw up the dropping.
2717 let mut half = hm.into_iter().take(50);
2719 DROP_VECTOR.with(|v| {
2721 assert_eq!(v.borrow()[i], 1);
2725 for _ in half.by_ref() {}
2727 DROP_VECTOR.with(|v| {
2729 .filter(|&i| v.borrow()[i] == 1)
2733 .filter(|&i| v.borrow()[i + 100] == 1)
2741 DROP_VECTOR.with(|v| {
2743 assert_eq!(v.borrow()[i], 0);
2749 fn test_empty_remove() {
2750 let mut m: HashMap<isize, bool> = HashMap::new();
2751 assert_eq!(m.remove(&0), None);
2755 fn test_empty_entry() {
2756 let mut m: HashMap<isize, bool> = HashMap::new();
2758 Occupied(_) => panic!(),
2761 assert!(*m.entry(0).or_insert(true));
2762 assert_eq!(m.len(), 1);
2766 fn test_empty_iter() {
2767 let mut m: HashMap<isize, bool> = HashMap::new();
2768 assert_eq!(m.drain().next(), None);
2769 assert_eq!(m.keys().next(), None);
2770 assert_eq!(m.values().next(), None);
2771 assert_eq!(m.values_mut().next(), None);
2772 assert_eq!(m.iter().next(), None);
2773 assert_eq!(m.iter_mut().next(), None);
2774 assert_eq!(m.len(), 0);
2775 assert!(m.is_empty());
2776 assert_eq!(m.into_iter().next(), None);
2780 fn test_lots_of_insertions() {
2781 let mut m = HashMap::new();
2783 // Try this a few times to make sure we never screw up the hashmap's
2786 assert!(m.is_empty());
2789 assert!(m.insert(i, i).is_none());
2793 assert_eq!(r, Some(&j));
2796 for j in i + 1..1001 {
2798 assert_eq!(r, None);
2802 for i in 1001..2001 {
2803 assert!(!m.contains_key(&i));
2808 assert!(m.remove(&i).is_some());
2811 assert!(!m.contains_key(&j));
2814 for j in i + 1..1001 {
2815 assert!(m.contains_key(&j));
2820 assert!(!m.contains_key(&i));
2824 assert!(m.insert(i, i).is_none());
2828 for i in (1..1001).rev() {
2829 assert!(m.remove(&i).is_some());
2832 assert!(!m.contains_key(&j));
2836 assert!(m.contains_key(&j));
2843 fn test_find_mut() {
2844 let mut m = HashMap::new();
2845 assert!(m.insert(1, 12).is_none());
2846 assert!(m.insert(2, 8).is_none());
2847 assert!(m.insert(5, 14).is_none());
2849 match m.get_mut(&5) {
2851 Some(x) => *x = new,
2853 assert_eq!(m.get(&5), Some(&new));
2857 fn test_insert_overwrite() {
2858 let mut m = HashMap::new();
2859 assert!(m.insert(1, 2).is_none());
2860 assert_eq!(*m.get(&1).unwrap(), 2);
2861 assert!(!m.insert(1, 3).is_none());
2862 assert_eq!(*m.get(&1).unwrap(), 3);
2866 fn test_insert_conflicts() {
2867 let mut m = HashMap::with_capacity(4);
2868 assert!(m.insert(1, 2).is_none());
2869 assert!(m.insert(5, 3).is_none());
2870 assert!(m.insert(9, 4).is_none());
2871 assert_eq!(*m.get(&9).unwrap(), 4);
2872 assert_eq!(*m.get(&5).unwrap(), 3);
2873 assert_eq!(*m.get(&1).unwrap(), 2);
2877 fn test_conflict_remove() {
2878 let mut m = HashMap::with_capacity(4);
2879 assert!(m.insert(1, 2).is_none());
2880 assert_eq!(*m.get(&1).unwrap(), 2);
2881 assert!(m.insert(5, 3).is_none());
2882 assert_eq!(*m.get(&1).unwrap(), 2);
2883 assert_eq!(*m.get(&5).unwrap(), 3);
2884 assert!(m.insert(9, 4).is_none());
2885 assert_eq!(*m.get(&1).unwrap(), 2);
2886 assert_eq!(*m.get(&5).unwrap(), 3);
2887 assert_eq!(*m.get(&9).unwrap(), 4);
2888 assert!(m.remove(&1).is_some());
2889 assert_eq!(*m.get(&9).unwrap(), 4);
2890 assert_eq!(*m.get(&5).unwrap(), 3);
2894 fn test_is_empty() {
2895 let mut m = HashMap::with_capacity(4);
2896 assert!(m.insert(1, 2).is_none());
2897 assert!(!m.is_empty());
2898 assert!(m.remove(&1).is_some());
2899 assert!(m.is_empty());
2904 let mut m = HashMap::new();
2906 assert_eq!(m.remove(&1), Some(2));
2907 assert_eq!(m.remove(&1), None);
2912 let mut m = HashMap::with_capacity(4);
2914 assert!(m.insert(i, i*2).is_none());
2916 assert_eq!(m.len(), 32);
2918 let mut observed: u32 = 0;
2921 assert_eq!(*v, *k * 2);
2922 observed |= 1 << *k;
2924 assert_eq!(observed, 0xFFFF_FFFF);
2929 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2930 let map: HashMap<_, _> = vec.into_iter().collect();
2931 let keys: Vec<_> = map.keys().cloned().collect();
2932 assert_eq!(keys.len(), 3);
2933 assert!(keys.contains(&1));
2934 assert!(keys.contains(&2));
2935 assert!(keys.contains(&3));
2940 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2941 let map: HashMap<_, _> = vec.into_iter().collect();
2942 let values: Vec<_> = map.values().cloned().collect();
2943 assert_eq!(values.len(), 3);
2944 assert!(values.contains(&'a'));
2945 assert!(values.contains(&'b'));
2946 assert!(values.contains(&'c'));
2950 fn test_values_mut() {
2951 let vec = vec![(1, 1), (2, 2), (3, 3)];
2952 let mut map: HashMap<_, _> = vec.into_iter().collect();
2953 for value in map.values_mut() {
2954 *value = (*value) * 2
2956 let values: Vec<_> = map.values().cloned().collect();
2957 assert_eq!(values.len(), 3);
2958 assert!(values.contains(&2));
2959 assert!(values.contains(&4));
2960 assert!(values.contains(&6));
2965 let mut m = HashMap::new();
2966 assert!(m.get(&1).is_none());
2970 Some(v) => assert_eq!(*v, 2),
2976 let mut m1 = HashMap::new();
2981 let mut m2 = HashMap::new();
2994 let mut map = HashMap::new();
2995 let empty: HashMap<i32, i32> = HashMap::new();
3000 let map_str = format!("{:?}", map);
3002 assert!(map_str == "{1: 2, 3: 4}" ||
3003 map_str == "{3: 4, 1: 2}");
3004 assert_eq!(format!("{:?}", empty), "{}");
3009 let mut m = HashMap::new();
3011 assert_eq!(m.len(), 0);
3012 assert!(m.is_empty());
3015 let old_raw_cap = m.raw_capacity();
3016 while old_raw_cap == m.raw_capacity() {
3021 assert_eq!(m.len(), i);
3022 assert!(!m.is_empty());
3026 fn test_behavior_resize_policy() {
3027 let mut m = HashMap::new();
3029 assert_eq!(m.len(), 0);
3030 assert_eq!(m.raw_capacity(), 0);
3031 assert!(m.is_empty());
3035 assert!(m.is_empty());
3036 let initial_raw_cap = m.raw_capacity();
3037 m.reserve(initial_raw_cap);
3038 let raw_cap = m.raw_capacity();
3040 assert_eq!(raw_cap, initial_raw_cap * 2);
3043 for _ in 0..raw_cap * 3 / 4 {
3047 // three quarters full
3049 assert_eq!(m.len(), i);
3050 assert_eq!(m.raw_capacity(), raw_cap);
3052 for _ in 0..raw_cap / 4 {
3058 let new_raw_cap = m.raw_capacity();
3059 assert_eq!(new_raw_cap, raw_cap * 2);
3061 for _ in 0..raw_cap / 2 - 1 {
3064 assert_eq!(m.raw_capacity(), new_raw_cap);
3066 // A little more than one quarter full.
3068 assert_eq!(m.raw_capacity(), raw_cap);
3069 // again, a little more than half full
3070 for _ in 0..raw_cap / 2 - 1 {
3076 assert_eq!(m.len(), i);
3077 assert!(!m.is_empty());
3078 assert_eq!(m.raw_capacity(), initial_raw_cap);
3082 fn test_reserve_shrink_to_fit() {
3083 let mut m = HashMap::new();
3086 assert!(m.capacity() >= m.len());
3092 let usable_cap = m.capacity();
3093 for i in 128..(128 + 256) {
3095 assert_eq!(m.capacity(), usable_cap);
3098 for i in 100..(128 + 256) {
3099 assert_eq!(m.remove(&i), Some(i));
3103 assert_eq!(m.len(), 100);
3104 assert!(!m.is_empty());
3105 assert!(m.capacity() >= m.len());
3108 assert_eq!(m.remove(&i), Some(i));
3113 assert_eq!(m.len(), 1);
3114 assert!(m.capacity() >= m.len());
3115 assert_eq!(m.remove(&0), Some(0));
3119 fn test_from_iter() {
3120 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3122 let map: HashMap<_, _> = xs.iter().cloned().collect();
3124 for &(k, v) in &xs {
3125 assert_eq!(map.get(&k), Some(&v));
3130 fn test_size_hint() {
3131 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3133 let map: HashMap<_, _> = xs.iter().cloned().collect();
3135 let mut iter = map.iter();
3137 for _ in iter.by_ref().take(3) {}
3139 assert_eq!(iter.size_hint(), (3, Some(3)));
3143 fn test_iter_len() {
3144 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3146 let map: HashMap<_, _> = xs.iter().cloned().collect();
3148 let mut iter = map.iter();
3150 for _ in iter.by_ref().take(3) {}
3152 assert_eq!(iter.len(), 3);
3156 fn test_mut_size_hint() {
3157 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3159 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3161 let mut iter = map.iter_mut();
3163 for _ in iter.by_ref().take(3) {}
3165 assert_eq!(iter.size_hint(), (3, Some(3)));
3169 fn test_iter_mut_len() {
3170 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3172 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3174 let mut iter = map.iter_mut();
3176 for _ in iter.by_ref().take(3) {}
3178 assert_eq!(iter.len(), 3);
3183 let mut map = HashMap::new();
3189 assert_eq!(map[&2], 1);
3194 fn test_index_nonexistent() {
3195 let mut map = HashMap::new();
3206 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3208 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3210 // Existing key (insert)
3211 match map.entry(1) {
3212 Vacant(_) => unreachable!(),
3213 Occupied(mut view) => {
3214 assert_eq!(view.get(), &10);
3215 assert_eq!(view.insert(100), 10);
3218 assert_eq!(map.get(&1).unwrap(), &100);
3219 assert_eq!(map.len(), 6);
3222 // Existing key (update)
3223 match map.entry(2) {
3224 Vacant(_) => unreachable!(),
3225 Occupied(mut view) => {
3226 let v = view.get_mut();
3227 let new_v = (*v) * 10;
3231 assert_eq!(map.get(&2).unwrap(), &200);
3232 assert_eq!(map.len(), 6);
3234 // Existing key (take)
3235 match map.entry(3) {
3236 Vacant(_) => unreachable!(),
3238 assert_eq!(view.remove(), 30);
3241 assert_eq!(map.get(&3), None);
3242 assert_eq!(map.len(), 5);
3245 // Inexistent key (insert)
3246 match map.entry(10) {
3247 Occupied(_) => unreachable!(),
3249 assert_eq!(*view.insert(1000), 1000);
3252 assert_eq!(map.get(&10).unwrap(), &1000);
3253 assert_eq!(map.len(), 6);
3257 fn test_entry_take_doesnt_corrupt() {
3258 #![allow(deprecated)] //rand
3260 fn check(m: &HashMap<isize, ()>) {
3262 assert!(m.contains_key(k),
3263 "{} is in keys() but not in the map?", k);
3267 let mut m = HashMap::new();
3268 let mut rng = thread_rng();
3270 // Populate the map with some items.
3272 let x = rng.gen_range(-10, 10);
3277 let x = rng.gen_range(-10, 10);
3281 println!("{}: remove {}", i, x);
3291 fn test_extend_ref() {
3292 let mut a = HashMap::new();
3294 let mut b = HashMap::new();
3296 b.insert(3, "three");
3300 assert_eq!(a.len(), 3);
3301 assert_eq!(a[&1], "one");
3302 assert_eq!(a[&2], "two");
3303 assert_eq!(a[&3], "three");
3307 fn test_capacity_not_less_than_len() {
3308 let mut a = HashMap::new();
3316 assert!(a.capacity() > a.len());
3318 let free = a.capacity() - a.len();
3324 assert_eq!(a.len(), a.capacity());
3326 // Insert at capacity should cause allocation.
3328 assert!(a.capacity() > a.len());
3332 fn test_occupied_entry_key() {
3333 let mut a = HashMap::new();
3334 let key = "hello there";
3335 let value = "value goes here";
3336 assert!(a.is_empty());
3337 a.insert(key.clone(), value.clone());
3338 assert_eq!(a.len(), 1);
3339 assert_eq!(a[key], value);
3341 match a.entry(key.clone()) {
3342 Vacant(_) => panic!(),
3343 Occupied(e) => assert_eq!(key, *e.key()),
3345 assert_eq!(a.len(), 1);
3346 assert_eq!(a[key], value);
3350 fn test_vacant_entry_key() {
3351 let mut a = HashMap::new();
3352 let key = "hello there";
3353 let value = "value goes here";
3355 assert!(a.is_empty());
3356 match a.entry(key.clone()) {
3357 Occupied(_) => panic!(),
3359 assert_eq!(key, *e.key());
3360 e.insert(value.clone());
3363 assert_eq!(a.len(), 1);
3364 assert_eq!(a[key], value);
3369 let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3371 map.retain(|&k, _| k % 2 == 0);
3372 assert_eq!(map.len(), 50);
3373 assert_eq!(map[&2], 20);
3374 assert_eq!(map[&4], 40);
3375 assert_eq!(map[&6], 60);
3379 fn test_adaptive() {
3380 const TEST_LEN: usize = 5000;
3381 // by cloning we get maps with the same hasher seed
3382 let mut first = HashMap::new();
3383 let mut second = first.clone();
3384 first.extend((0..TEST_LEN).map(|i| (i, i)));
3385 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3387 for (&k, &v) in &second {
3388 let prev_cap = first.capacity();
3389 let expect_grow = first.len() == prev_cap;
3391 if !expect_grow && first.capacity() != prev_cap {
3395 panic!("Adaptive early resize failed");
3399 fn test_placement_in() {
3400 let mut map = HashMap::new();
3401 map.extend((0..10).map(|i| (i, i)));
3403 map.entry(100) <- 100;
3404 assert_eq!(map[&100], 100);
3407 assert_eq!(map[&0], 10);
3409 assert_eq!(map.len(), 11);
3413 fn test_placement_panic() {
3414 let mut map = HashMap::new();
3415 map.extend((0..10).map(|i| (i, i)));
3417 fn mkpanic() -> usize { panic!() }
3419 // modify existing key
3420 // when panic happens, previous key is removed.
3421 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3422 assert_eq!(map.len(), 9);
3423 assert!(!map.contains_key(&0));
3426 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3427 assert_eq!(map.len(), 9);
3428 assert!(!map.contains_key(&100));
3432 fn test_placement_drop() {
3434 struct TestV<'a>(&'a mut bool);
3435 impl<'a> Drop for TestV<'a> {
3436 fn drop(&mut self) {
3437 if !*self.0 { panic!("value double drop!"); } // no double drop
3442 fn makepanic<'a>() -> TestV<'a> { panic!() }
3444 let mut can_drop = true;
3445 let mut hm = HashMap::new();
3446 hm.insert(0, TestV(&mut can_drop));
3447 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3448 assert_eq!(hm.len(), 0);