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 implementation which uses linear probing with Robin Hood bucket
221 /// By default, `HashMap` uses a hashing algorithm selected to provide
222 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
223 /// reasonable best-effort is made to generate this seed from a high quality,
224 /// secure source of randomness provided by the host without blocking the
225 /// program. Because of this, the randomness of the seed depends on the output
226 /// quality of the system's random number generator when the seed is created.
227 /// In particular, seeds generated when the system's entropy pool is abnormally
228 /// low such as during system boot may be of a lower quality.
230 /// The default hashing algorithm is currently SipHash 1-3, though this is
231 /// subject to change at any point in the future. While its performance is very
232 /// competitive for medium sized keys, other hashing algorithms will outperform
233 /// it for small keys such as integers as well as large keys such as long
234 /// strings, though those algorithms will typically *not* protect against
235 /// attacks such as HashDoS.
237 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
238 /// [`HashMap::default`], [`HashMap::with_hasher`], and
239 /// [`HashMap::with_capacity_and_hasher`] methods. Many alternative algorithms
240 /// are available on crates.io, such as the [`fnv`] crate.
242 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
243 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
244 /// If you implement these yourself, it is important that the following
248 /// k1 == k2 -> hash(k1) == hash(k2)
251 /// In other words, if two keys are equal, their hashes must be equal.
253 /// It is a logic error for a key to be modified in such a way that the key's
254 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
255 /// the [`Eq`] trait, changes while it is in the map. This is normally only
256 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
258 /// Relevant papers/articles:
260 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
261 /// 2. Emmanuel Goossaert. ["Robin Hood
262 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
263 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
264 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
269 /// use std::collections::HashMap;
271 /// // type inference lets us omit an explicit type signature (which
272 /// // would be `HashMap<&str, &str>` in this example).
273 /// let mut book_reviews = HashMap::new();
275 /// // review some books.
276 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
277 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
278 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
279 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
281 /// // check for a specific one.
282 /// if !book_reviews.contains_key("Les Misérables") {
283 /// println!("We've got {} reviews, but Les Misérables ain't one.",
284 /// book_reviews.len());
287 /// // oops, this review has a lot of spelling mistakes, let's delete it.
288 /// book_reviews.remove("The Adventures of Sherlock Holmes");
290 /// // look up the values associated with some keys.
291 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
292 /// for book in &to_find {
293 /// match book_reviews.get(book) {
294 /// Some(review) => println!("{}: {}", book, review),
295 /// None => println!("{} is unreviewed.", book)
299 /// // iterate over everything.
300 /// for (book, review) in &book_reviews {
301 /// println!("{}: \"{}\"", book, review);
305 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
306 /// for more complex methods of getting, setting, updating and removing keys and
310 /// use std::collections::HashMap;
312 /// // type inference lets us omit an explicit type signature (which
313 /// // would be `HashMap<&str, u8>` in this example).
314 /// let mut player_stats = HashMap::new();
316 /// fn random_stat_buff() -> u8 {
317 /// // could actually return some random value here - let's just return
318 /// // some fixed value for now
322 /// // insert a key only if it doesn't already exist
323 /// player_stats.entry("health").or_insert(100);
325 /// // insert a key using a function that provides a new value only if it
326 /// // doesn't already exist
327 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
329 /// // update a key, guarding against the key possibly not being set
330 /// let stat = player_stats.entry("attack").or_insert(100);
331 /// *stat += random_stat_buff();
334 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
335 /// We must also derive [`PartialEq`].
337 /// [`Eq`]: ../../std/cmp/trait.Eq.html
338 /// [`Hash`]: ../../std/hash/trait.Hash.html
339 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
340 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
341 /// [`Cell`]: ../../std/cell/struct.Cell.html
342 /// [`HashMap::default`]: #method.default
343 /// [`HashMap::with_hasher`]: #method.with_hasher
344 /// [`HashMap::with_capacity_and_hasher`]: #method.with_capacity_and_hasher
345 /// [`fnv`]: https://crates.io/crates/fnv
348 /// use std::collections::HashMap;
350 /// #[derive(Hash, Eq, PartialEq, Debug)]
357 /// /// Create a new Viking.
358 /// fn new(name: &str, country: &str) -> Viking {
359 /// Viking { name: name.to_string(), country: country.to_string() }
363 /// // Use a HashMap to store the vikings' health points.
364 /// let mut vikings = HashMap::new();
366 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
367 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
368 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
370 /// // Use derived implementation to print the status of the vikings.
371 /// for (viking, health) in &vikings {
372 /// println!("{:?} has {} hp", viking, health);
376 /// A HashMap with fixed list of elements can be initialized from an array:
379 /// use std::collections::HashMap;
382 /// let timber_resources: HashMap<&str, i32> =
383 /// [("Norway", 100),
386 /// .iter().cloned().collect();
387 /// // use the values stored in map
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub struct HashMap<K, V, S = RandomState> {
394 // All hashes are keyed on these values, to prevent hash collision attacks.
397 table: RawTable<K, V>,
399 resize_policy: DefaultResizePolicy,
402 /// Search for a pre-hashed key.
404 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
405 where M: Deref<Target = RawTable<K, V>>,
408 // This is the only function where capacity can be zero. To avoid
409 // undefined behavior when Bucket::new gets the raw bucket in this
410 // case, immediately return the appropriate search result.
411 if table.capacity() == 0 {
412 return InternalEntry::TableIsEmpty;
415 let size = table.size();
416 let mut probe = Bucket::new(table, hash);
417 let mut displacement = 0;
420 let full = match probe.peek() {
423 return InternalEntry::Vacant {
425 elem: NoElem(bucket, displacement),
428 Full(bucket) => bucket,
431 let probe_displacement = full.displacement();
433 if probe_displacement < displacement {
434 // Found a luckier bucket than me.
435 // We can finish the search early if we hit any bucket
436 // with a lower distance to initial bucket than we've probed.
437 return InternalEntry::Vacant {
439 elem: NeqElem(full, probe_displacement),
443 // If the hash doesn't match, it can't be this one..
444 if hash == full.hash() {
445 // If the key doesn't match, it can't be this one..
446 if is_match(full.read().0) {
447 return InternalEntry::Occupied { elem: full };
452 debug_assert!(displacement <= size);
456 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
457 -> (K, V, &mut RawTable<K, V>)
459 let (empty, retkey, retval) = starting_bucket.take();
460 let mut gap = match empty.gap_peek() {
462 Err(b) => return (retkey, retval, b.into_table()),
465 while gap.full().displacement() != 0 {
466 gap = match gap.shift() {
469 return (retkey, retval, b.into_table());
474 // Now we've done all our shifting. Return the value we grabbed earlier.
475 (retkey, retval, gap.into_bucket().into_table())
478 /// Perform robin hood bucket stealing at the given `bucket`. You must
479 /// also pass that bucket's displacement so we don't have to recalculate it.
481 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
482 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
483 mut displacement: usize,
487 -> FullBucketMut<'a, K, V> {
488 let start_index = bucket.index();
489 let size = bucket.table().size();
490 // Save the *starting point*.
491 let mut bucket = bucket.stash();
492 // There can be at most `size - dib` buckets to displace, because
493 // in the worst case, there are `size` elements and we already are
494 // `displacement` buckets away from the initial one.
495 let idx_end = start_index + size - bucket.displacement();
498 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
505 let probe = bucket.next();
506 debug_assert!(probe.index() != idx_end);
508 let full_bucket = match probe.peek() {
511 let bucket = bucket.put(hash, key, val);
512 // Now that it's stolen, just read the value's pointer
513 // right out of the table! Go back to the *starting point*.
515 // This use of `into_table` is misleading. It turns the
516 // bucket, which is a FullBucket on top of a
517 // FullBucketMut, into just one FullBucketMut. The "table"
518 // refers to the inner FullBucketMut in this context.
519 return bucket.into_table();
521 Full(bucket) => bucket,
524 let probe_displacement = full_bucket.displacement();
526 bucket = full_bucket;
528 // Robin hood! Steal the spot.
529 if probe_displacement < displacement {
530 displacement = probe_displacement;
537 impl<K, V, S> HashMap<K, V, S>
541 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
544 table::make_hash(&self.hash_builder, x)
547 /// Search for a key, yielding the index if it's found in the hashtable.
548 /// If you already have the hash for the key lying around, use
551 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
555 let hash = self.make_hash(q);
556 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
560 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
564 let hash = self.make_hash(q);
565 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
568 // The caller should ensure that invariants by Robin Hood Hashing hold
569 // and that there's space in the underlying table.
570 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
571 let raw_cap = self.raw_capacity();
572 let mut buckets = Bucket::new(&mut self.table, hash);
573 // note that buckets.index() keeps increasing
574 // even if the pointer wraps back to the first bucket.
575 let limit_bucket = buckets.index() + raw_cap;
578 // We don't need to compare hashes for value swap.
579 // Not even DIBs for Robin Hood.
580 buckets = match buckets.peek() {
582 empty.put(hash, k, v);
585 Full(b) => b.into_bucket(),
588 debug_assert!(buckets.index() < limit_bucket);
593 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
594 /// Creates an empty `HashMap`.
599 /// use std::collections::HashMap;
600 /// let mut map: HashMap<&str, isize> = HashMap::new();
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn new() -> HashMap<K, V, RandomState> {
608 /// Creates an empty `HashMap` with the specified capacity.
610 /// The hash map will be able to hold at least `capacity` elements without
611 /// reallocating. If `capacity` is 0, the hash map will not allocate.
616 /// use std::collections::HashMap;
617 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
620 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
622 HashMap::with_capacity_and_hasher(capacity, Default::default())
626 impl<K, V, S> HashMap<K, V, S>
630 /// Creates an empty `HashMap` which will use the given hash builder to hash
633 /// The created map has the default initial capacity.
635 /// Warning: `hash_builder` is normally randomly generated, and
636 /// is designed to allow HashMaps to be resistant to attacks that
637 /// cause many collisions and very poor performance. Setting it
638 /// manually using this function can expose a DoS attack vector.
643 /// use std::collections::HashMap;
644 /// use std::collections::hash_map::RandomState;
646 /// let s = RandomState::new();
647 /// let mut map = HashMap::with_hasher(s);
648 /// map.insert(1, 2);
651 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
652 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
654 hash_builder: hash_builder,
655 resize_policy: DefaultResizePolicy::new(),
656 table: RawTable::new(0),
660 /// Creates an empty `HashMap` with the specified capacity, using `hasher`
661 /// to hash the keys.
663 /// The hash map will be able to hold at least `capacity` elements without
664 /// reallocating. If `capacity` is 0, the hash map will not allocate.
665 /// Warning: `hasher` is normally randomly generated, and
666 /// is designed to allow HashMaps to be resistant to attacks that
667 /// cause many collisions and very poor performance. Setting it
668 /// manually using this function can expose a DoS attack vector.
673 /// use std::collections::HashMap;
674 /// use std::collections::hash_map::RandomState;
676 /// let s = RandomState::new();
677 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
678 /// map.insert(1, 2);
681 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
682 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
683 let resize_policy = DefaultResizePolicy::new();
684 let raw_cap = resize_policy.raw_capacity(capacity);
686 hash_builder: hash_builder,
687 resize_policy: resize_policy,
688 table: RawTable::new(raw_cap),
692 /// Returns a reference to the map's hasher.
693 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
694 pub fn hasher(&self) -> &S {
698 /// Returns the number of elements the map can hold without reallocating.
700 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
701 /// more, but is guaranteed to be able to hold at least this many.
706 /// use std::collections::HashMap;
707 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
708 /// assert!(map.capacity() >= 100);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn capacity(&self) -> usize {
713 self.resize_policy.capacity(self.raw_capacity())
716 /// Returns the hash map's raw capacity.
718 fn raw_capacity(&self) -> usize {
719 self.table.capacity()
722 /// Reserves capacity for at least `additional` more elements to be inserted
723 /// in the `HashMap`. The collection may reserve more space to avoid
724 /// frequent reallocations.
728 /// Panics if the new allocation size overflows [`usize`].
730 /// [`usize`]: ../../std/primitive.usize.html
735 /// use std::collections::HashMap;
736 /// let mut map: HashMap<&str, isize> = HashMap::new();
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn reserve(&mut self, additional: usize) {
741 let remaining = self.capacity() - self.len(); // this can't overflow
742 if remaining < additional {
743 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
744 let raw_cap = self.resize_policy.raw_capacity(min_cap);
745 self.resize(raw_cap);
746 } else if self.table.tag() && remaining <= self.len() {
747 // Probe sequence is too long and table is half full,
748 // resize early to reduce probing length.
749 let new_capacity = self.table.capacity() * 2;
750 self.resize(new_capacity);
754 /// Resizes the internal vectors to a new capacity. It's your
755 /// responsibility to:
756 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
757 /// for the load factor.
758 /// 2) Ensure `new_raw_cap` is a power of two or zero.
759 fn resize(&mut self, new_raw_cap: usize) {
760 assert!(self.table.size() <= new_raw_cap);
761 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
763 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
764 let old_size = old_table.size();
766 if old_table.size() == 0 {
770 let mut bucket = Bucket::head_bucket(&mut old_table);
772 // This is how the buckets might be laid out in memory:
773 // ($ marks an initialized bucket)
775 // |$$$_$$$$$$_$$$$$|
777 // But we've skipped the entire initial cluster of buckets
778 // and will continue iteration in this order:
781 // ^ wrap around once end is reached
784 // ^ exit once table.size == 0
786 bucket = match bucket.peek() {
788 let h = bucket.hash();
789 let (b, k, v) = bucket.take();
790 self.insert_hashed_ordered(h, k, v);
791 if b.table().size() == 0 {
796 Empty(b) => b.into_bucket(),
801 assert_eq!(self.table.size(), old_size);
804 /// Shrinks the capacity of the map as much as possible. It will drop
805 /// down as much as possible while maintaining the internal rules
806 /// and possibly leaving some space in accordance with the resize policy.
811 /// use std::collections::HashMap;
813 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
814 /// map.insert(1, 2);
815 /// map.insert(3, 4);
816 /// assert!(map.capacity() >= 100);
817 /// map.shrink_to_fit();
818 /// assert!(map.capacity() >= 2);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub fn shrink_to_fit(&mut self) {
822 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
823 if self.raw_capacity() != new_raw_cap {
824 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
825 let old_size = old_table.size();
827 // Shrink the table. Naive algorithm for resizing:
828 for (h, k, v) in old_table.into_iter() {
829 self.insert_hashed_nocheck(h, k, v);
832 debug_assert_eq!(self.table.size(), old_size);
836 /// Insert a pre-hashed key-value pair, without first checking
837 /// that there's enough room in the buckets. Returns a reference to the
838 /// newly insert value.
840 /// If the key already exists, the hashtable will be returned untouched
841 /// and a reference to the existing element will be returned.
842 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
843 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
845 Some(Occupied(mut elem)) => Some(elem.insert(v)),
846 Some(Vacant(elem)) => {
850 None => unreachable!(),
854 /// An iterator visiting all keys in arbitrary order.
855 /// Iterator element type is `&'a K`.
860 /// use std::collections::HashMap;
862 /// let mut map = HashMap::new();
863 /// map.insert("a", 1);
864 /// map.insert("b", 2);
865 /// map.insert("c", 3);
867 /// for key in map.keys() {
868 /// println!("{}", key);
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn keys(&self) -> Keys<K, V> {
873 Keys { inner: self.iter() }
876 /// An iterator visiting all values in arbitrary order.
877 /// Iterator element type is `&'a V`.
882 /// use std::collections::HashMap;
884 /// let mut map = HashMap::new();
885 /// map.insert("a", 1);
886 /// map.insert("b", 2);
887 /// map.insert("c", 3);
889 /// for val in map.values() {
890 /// println!("{}", val);
893 #[stable(feature = "rust1", since = "1.0.0")]
894 pub fn values(&self) -> Values<K, V> {
895 Values { inner: self.iter() }
898 /// An iterator visiting all values mutably in arbitrary order.
899 /// Iterator element type is `&'a mut V`.
904 /// use std::collections::HashMap;
906 /// let mut map = HashMap::new();
908 /// map.insert("a", 1);
909 /// map.insert("b", 2);
910 /// map.insert("c", 3);
912 /// for val in map.values_mut() {
913 /// *val = *val + 10;
916 /// for val in map.values() {
917 /// println!("{}", val);
920 #[stable(feature = "map_values_mut", since = "1.10.0")]
921 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
922 ValuesMut { inner: self.iter_mut() }
925 /// An iterator visiting all key-value pairs in arbitrary order.
926 /// Iterator element type is `(&'a K, &'a V)`.
931 /// use std::collections::HashMap;
933 /// let mut map = HashMap::new();
934 /// map.insert("a", 1);
935 /// map.insert("b", 2);
936 /// map.insert("c", 3);
938 /// for (key, val) in map.iter() {
939 /// println!("key: {} val: {}", key, val);
942 #[stable(feature = "rust1", since = "1.0.0")]
943 pub fn iter(&self) -> Iter<K, V> {
944 Iter { inner: self.table.iter() }
947 /// An iterator visiting all key-value pairs in arbitrary order,
948 /// with mutable references to the values.
949 /// Iterator element type is `(&'a K, &'a mut V)`.
954 /// use std::collections::HashMap;
956 /// let mut map = HashMap::new();
957 /// map.insert("a", 1);
958 /// map.insert("b", 2);
959 /// map.insert("c", 3);
961 /// // Update all values
962 /// for (_, val) in map.iter_mut() {
966 /// for (key, val) in &map {
967 /// println!("key: {} val: {}", key, val);
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn iter_mut(&mut self) -> IterMut<K, V> {
972 IterMut { inner: self.table.iter_mut() }
975 /// Gets the given key's corresponding entry in the map for in-place manipulation.
980 /// use std::collections::HashMap;
982 /// let mut letters = HashMap::new();
984 /// for ch in "a short treatise on fungi".chars() {
985 /// let counter = letters.entry(ch).or_insert(0);
989 /// assert_eq!(letters[&'s'], 2);
990 /// assert_eq!(letters[&'t'], 3);
991 /// assert_eq!(letters[&'u'], 1);
992 /// assert_eq!(letters.get(&'y'), None);
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn entry(&mut self, key: K) -> Entry<K, V> {
998 let hash = self.make_hash(&key);
999 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1000 .into_entry(key).expect("unreachable")
1003 /// Returns the number of elements in the map.
1008 /// use std::collections::HashMap;
1010 /// let mut a = HashMap::new();
1011 /// assert_eq!(a.len(), 0);
1012 /// a.insert(1, "a");
1013 /// assert_eq!(a.len(), 1);
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 pub fn len(&self) -> usize {
1020 /// Returns true if the map contains no elements.
1025 /// use std::collections::HashMap;
1027 /// let mut a = HashMap::new();
1028 /// assert!(a.is_empty());
1029 /// a.insert(1, "a");
1030 /// assert!(!a.is_empty());
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn is_empty(&self) -> bool {
1038 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1039 /// allocated memory for reuse.
1044 /// use std::collections::HashMap;
1046 /// let mut a = HashMap::new();
1047 /// a.insert(1, "a");
1048 /// a.insert(2, "b");
1050 /// for (k, v) in a.drain().take(1) {
1051 /// assert!(k == 1 || k == 2);
1052 /// assert!(v == "a" || v == "b");
1055 /// assert!(a.is_empty());
1058 #[stable(feature = "drain", since = "1.6.0")]
1059 pub fn drain(&mut self) -> Drain<K, V> {
1060 Drain { inner: self.table.drain() }
1063 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1069 /// use std::collections::HashMap;
1071 /// let mut a = HashMap::new();
1072 /// a.insert(1, "a");
1074 /// assert!(a.is_empty());
1076 #[stable(feature = "rust1", since = "1.0.0")]
1078 pub fn clear(&mut self) {
1082 /// Returns a reference to the value corresponding to the key.
1084 /// The key may be any borrowed form of the map's key type, but
1085 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1088 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1089 /// [`Hash`]: ../../std/hash/trait.Hash.html
1094 /// use std::collections::HashMap;
1096 /// let mut map = HashMap::new();
1097 /// map.insert(1, "a");
1098 /// assert_eq!(map.get(&1), Some(&"a"));
1099 /// assert_eq!(map.get(&2), None);
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1106 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1109 /// Returns true if the map contains a value for the specified key.
1111 /// The key may be any borrowed form of the map's key type, but
1112 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1115 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1116 /// [`Hash`]: ../../std/hash/trait.Hash.html
1121 /// use std::collections::HashMap;
1123 /// let mut map = HashMap::new();
1124 /// map.insert(1, "a");
1125 /// assert_eq!(map.contains_key(&1), true);
1126 /// assert_eq!(map.contains_key(&2), false);
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1133 self.search(k).into_occupied_bucket().is_some()
1136 /// Returns a mutable reference to the value corresponding to the key.
1138 /// The key may be any borrowed form of the map's key type, but
1139 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1142 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1143 /// [`Hash`]: ../../std/hash/trait.Hash.html
1148 /// use std::collections::HashMap;
1150 /// let mut map = HashMap::new();
1151 /// map.insert(1, "a");
1152 /// if let Some(x) = map.get_mut(&1) {
1155 /// assert_eq!(map[&1], "b");
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1162 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1165 /// Inserts a key-value pair into the map.
1167 /// If the map did not have this key present, [`None`] is returned.
1169 /// If the map did have this key present, the value is updated, and the old
1170 /// value is returned. The key is not updated, though; this matters for
1171 /// types that can be `==` without being identical. See the [module-level
1172 /// documentation] for more.
1174 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1175 /// [module-level documentation]: index.html#insert-and-complex-keys
1180 /// use std::collections::HashMap;
1182 /// let mut map = HashMap::new();
1183 /// assert_eq!(map.insert(37, "a"), None);
1184 /// assert_eq!(map.is_empty(), false);
1186 /// map.insert(37, "b");
1187 /// assert_eq!(map.insert(37, "c"), Some("b"));
1188 /// assert_eq!(map[&37], "c");
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1192 let hash = self.make_hash(&k);
1194 self.insert_hashed_nocheck(hash, k, v)
1197 /// Removes a key from the map, returning the value at the key if the key
1198 /// was previously in the map.
1200 /// The key may be any borrowed form of the map's key type, but
1201 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1204 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1205 /// [`Hash`]: ../../std/hash/trait.Hash.html
1210 /// use std::collections::HashMap;
1212 /// let mut map = HashMap::new();
1213 /// map.insert(1, "a");
1214 /// assert_eq!(map.remove(&1), Some("a"));
1215 /// assert_eq!(map.remove(&1), None);
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1222 if self.table.size() == 0 {
1226 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1229 /// Retains only the elements specified by the predicate.
1231 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1236 /// #![feature(retain_hash_collection)]
1237 /// use std::collections::HashMap;
1239 /// let mut map: HashMap<isize, isize> = (0..8).map(|x|(x, x*10)).collect();
1240 /// map.retain(|&k, _| k % 2 == 0);
1241 /// assert_eq!(map.len(), 4);
1243 #[unstable(feature = "retain_hash_collection", issue = "36648")]
1244 pub fn retain<F>(&mut self, mut f: F)
1245 where F: FnMut(&K, &mut V) -> bool
1247 if self.table.capacity() == 0 || self.table.size() == 0 {
1250 let mut bucket = Bucket::head_bucket(&mut self.table);
1252 let tail = bucket.index();
1254 bucket = match bucket.peek() {
1256 let should_remove = {
1257 let (k, v) = full.read_mut();
1261 let prev_idx = full.index();
1262 let prev_raw = full.raw();
1263 let (_, _, t) = pop_internal(full);
1264 Bucket::new_from(prev_raw, prev_idx, t)
1273 bucket.prev(); // reverse iteration
1274 if bucket.index() == tail {
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<K, V, S> PartialEq for HashMap<K, V, S>
1287 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1288 if self.len() != other.len() {
1292 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<K, V, S> Eq for HashMap<K, V, S>
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<K, V, S> Debug for HashMap<K, V, S>
1306 where K: Eq + Hash + Debug,
1310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1311 f.debug_map().entries(self.iter()).finish()
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<K, V, S> Default for HashMap<K, V, S>
1318 S: BuildHasher + Default
1320 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1321 fn default() -> HashMap<K, V, S> {
1322 HashMap::with_hasher(Default::default())
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1328 where K: Eq + Hash + Borrow<Q>,
1335 fn index(&self, index: &Q) -> &V {
1336 self.get(index).expect("no entry found for key")
1340 /// HashMap iterator.
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub struct Iter<'a, K: 'a, V: 'a> {
1343 inner: table::Iter<'a, K, V>,
1346 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<'a, K, V> Clone for Iter<'a, K, V> {
1349 fn clone(&self) -> Iter<'a, K, V> {
1350 Iter { inner: self.inner.clone() }
1354 #[stable(feature = "std_debug", since = "1.16.0")]
1355 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1358 .entries(self.clone())
1363 /// HashMap mutable values iterator.
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub struct IterMut<'a, K: 'a, V: 'a> {
1366 inner: table::IterMut<'a, K, V>,
1369 /// HashMap move iterator.
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub struct IntoIter<K, V> {
1372 pub(super) inner: table::IntoIter<K, V>,
1375 /// HashMap keys iterator.
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 pub struct Keys<'a, K: 'a, V: 'a> {
1378 inner: Iter<'a, K, V>,
1381 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<'a, K, V> Clone for Keys<'a, K, V> {
1384 fn clone(&self) -> Keys<'a, K, V> {
1385 Keys { inner: self.inner.clone() }
1389 #[stable(feature = "std_debug", since = "1.16.0")]
1390 impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> {
1391 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1393 .entries(self.clone())
1398 /// HashMap values iterator.
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 pub struct Values<'a, K: 'a, V: 'a> {
1401 inner: Iter<'a, K, V>,
1404 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<'a, K, V> Clone for Values<'a, K, V> {
1407 fn clone(&self) -> Values<'a, K, V> {
1408 Values { inner: self.inner.clone() }
1412 #[stable(feature = "std_debug", since = "1.16.0")]
1413 impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> {
1414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1416 .entries(self.clone())
1421 /// HashMap drain iterator.
1422 #[stable(feature = "drain", since = "1.6.0")]
1423 pub struct Drain<'a, K: 'a, V: 'a> {
1424 pub(super) inner: table::Drain<'a, K, V>,
1427 /// Mutable HashMap values iterator.
1428 #[stable(feature = "map_values_mut", since = "1.10.0")]
1429 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1430 inner: IterMut<'a, K, V>,
1433 enum InternalEntry<K, V, M> {
1434 Occupied { elem: FullBucket<K, V, M> },
1437 elem: VacantEntryState<K, V, M>,
1442 impl<K, V, M> InternalEntry<K, V, M> {
1444 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1446 InternalEntry::Occupied { elem } => Some(elem),
1452 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1454 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1456 InternalEntry::Occupied { elem } => {
1457 Some(Occupied(OccupiedEntry {
1462 InternalEntry::Vacant { hash, elem } => {
1463 Some(Vacant(VacantEntry {
1469 InternalEntry::TableIsEmpty => None,
1474 /// A view into a single location in a map, which may be vacant or occupied.
1475 /// This enum is constructed from the [`entry`] method on [`HashMap`].
1477 /// [`HashMap`]: struct.HashMap.html
1478 /// [`entry`]: struct.HashMap.html#method.entry
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 pub enum Entry<'a, K: 'a, V: 'a> {
1481 /// An occupied Entry.
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1484 OccupiedEntry<'a, K, V>),
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1489 VacantEntry<'a, K, V>),
1492 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1493 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 f.debug_tuple("Entry")
1501 Occupied(ref o) => {
1502 f.debug_tuple("Entry")
1510 /// A view into a single occupied location in a HashMap.
1511 /// It is part of the [`Entry`] enum.
1513 /// [`Entry`]: enum.Entry.html
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1517 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1520 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1521 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1523 f.debug_struct("OccupiedEntry")
1524 .field("key", self.key())
1525 .field("value", self.get())
1530 /// A view into a single empty location in a HashMap.
1531 /// It is part of the [`Entry`] enum.
1533 /// [`Entry`]: enum.Entry.html
1534 #[stable(feature = "rust1", since = "1.0.0")]
1535 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1538 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1541 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1542 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1544 f.debug_tuple("VacantEntry")
1550 /// Possible states of a VacantEntry.
1551 enum VacantEntryState<K, V, M> {
1552 /// The index is occupied, but the key to insert has precedence,
1553 /// and will kick the current one out on insertion.
1554 NeqElem(FullBucket<K, V, M>, usize),
1555 /// The index is genuinely vacant.
1556 NoElem(EmptyBucket<K, V, M>, usize),
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1564 type Item = (&'a K, &'a V);
1565 type IntoIter = Iter<'a, K, V>;
1567 fn into_iter(self) -> Iter<'a, K, V> {
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1577 type Item = (&'a K, &'a mut V);
1578 type IntoIter = IterMut<'a, K, V>;
1580 fn into_iter(mut self) -> IterMut<'a, K, V> {
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1591 type IntoIter = IntoIter<K, V>;
1593 /// Creates a consuming iterator, that is, one that moves each key-value
1594 /// pair out of the map in arbitrary order. The map cannot be used after
1600 /// use std::collections::HashMap;
1602 /// let mut map = HashMap::new();
1603 /// map.insert("a", 1);
1604 /// map.insert("b", 2);
1605 /// map.insert("c", 3);
1607 /// // Not possible with .iter()
1608 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1610 fn into_iter(self) -> IntoIter<K, V> {
1611 IntoIter { inner: self.table.into_iter() }
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1617 type Item = (&'a K, &'a V);
1620 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1624 fn size_hint(&self) -> (usize, Option<usize>) {
1625 self.inner.size_hint()
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1631 fn len(&self) -> usize {
1636 #[unstable(feature = "fused", issue = "35602")]
1637 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1641 type Item = (&'a K, &'a mut V);
1644 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1648 fn size_hint(&self) -> (usize, Option<usize>) {
1649 self.inner.size_hint()
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1655 fn len(&self) -> usize {
1659 #[unstable(feature = "fused", issue = "35602")]
1660 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1662 #[stable(feature = "std_debug", since = "1.16.0")]
1663 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1664 where K: fmt::Debug,
1667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1669 .entries(self.inner.iter())
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<K, V> Iterator for IntoIter<K, V> {
1679 fn next(&mut self) -> Option<(K, V)> {
1680 self.inner.next().map(|(_, k, v)| (k, v))
1683 fn size_hint(&self) -> (usize, Option<usize>) {
1684 self.inner.size_hint()
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1690 fn len(&self) -> usize {
1694 #[unstable(feature = "fused", issue = "35602")]
1695 impl<K, V> FusedIterator for IntoIter<K, V> {}
1697 #[stable(feature = "std_debug", since = "1.16.0")]
1698 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1699 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1701 .entries(self.inner.iter())
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1711 fn next(&mut self) -> Option<(&'a K)> {
1712 self.inner.next().map(|(k, _)| k)
1715 fn size_hint(&self) -> (usize, Option<usize>) {
1716 self.inner.size_hint()
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1722 fn len(&self) -> usize {
1726 #[unstable(feature = "fused", issue = "35602")]
1727 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<'a, K, V> Iterator for Values<'a, K, V> {
1734 fn next(&mut self) -> Option<(&'a V)> {
1735 self.inner.next().map(|(_, v)| v)
1738 fn size_hint(&self) -> (usize, Option<usize>) {
1739 self.inner.size_hint()
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1745 fn len(&self) -> usize {
1749 #[unstable(feature = "fused", issue = "35602")]
1750 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1752 #[stable(feature = "map_values_mut", since = "1.10.0")]
1753 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1754 type Item = &'a mut V;
1757 fn next(&mut self) -> Option<(&'a mut V)> {
1758 self.inner.next().map(|(_, v)| v)
1761 fn size_hint(&self) -> (usize, Option<usize>) {
1762 self.inner.size_hint()
1765 #[stable(feature = "map_values_mut", since = "1.10.0")]
1766 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1768 fn len(&self) -> usize {
1772 #[unstable(feature = "fused", issue = "35602")]
1773 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1775 #[stable(feature = "std_debug", since = "1.16.0")]
1776 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1777 where K: fmt::Debug,
1780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1782 .entries(self.inner.inner.iter())
1787 #[stable(feature = "drain", since = "1.6.0")]
1788 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1792 fn next(&mut self) -> Option<(K, V)> {
1793 self.inner.next().map(|(_, k, v)| (k, v))
1796 fn size_hint(&self) -> (usize, Option<usize>) {
1797 self.inner.size_hint()
1800 #[stable(feature = "drain", since = "1.6.0")]
1801 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1803 fn len(&self) -> usize {
1807 #[unstable(feature = "fused", issue = "35602")]
1808 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1810 #[stable(feature = "std_debug", since = "1.16.0")]
1811 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1812 where K: fmt::Debug,
1815 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1817 .entries(self.inner.iter())
1822 /// A place for insertion to a `Entry`.
1824 /// See [`HashMap::entry`](struct.HashMap.html#method.entry) for details.
1825 #[must_use = "places do nothing unless written to with `<-` syntax"]
1826 #[unstable(feature = "collection_placement",
1827 reason = "struct name and placement protocol is subject to change",
1829 pub struct EntryPlace<'a, K: 'a, V: 'a> {
1830 bucket: FullBucketMut<'a, K, V>,
1833 #[unstable(feature = "collection_placement",
1834 reason = "struct name and placement protocol is subject to change",
1836 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for EntryPlace<'a, K, V> {
1837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1838 f.debug_struct("EntryPlace")
1839 .field("key", self.bucket.read().0)
1840 .field("value", self.bucket.read().1)
1845 #[unstable(feature = "collection_placement",
1846 reason = "struct name and placement protocol is subject to change",
1848 impl<'a, K, V> Drop for EntryPlace<'a, K, V> {
1849 fn drop(&mut self) {
1850 // Inplacement insertion failed. Only key need to drop.
1851 // The value is failed to insert into map.
1852 unsafe { self.bucket.remove_key() };
1856 #[unstable(feature = "collection_placement",
1857 reason = "placement protocol is subject to change",
1859 impl<'a, K, V> Placer<V> for Entry<'a, K, V> {
1860 type Place = EntryPlace<'a, K, V>;
1862 fn make_place(self) -> EntryPlace<'a, K, V> {
1863 let b = match self {
1864 Occupied(mut o) => {
1865 unsafe { ptr::drop_in_place(o.elem.read_mut().1); }
1869 unsafe { v.insert_key() }
1872 EntryPlace { bucket: b }
1876 #[unstable(feature = "collection_placement",
1877 reason = "placement protocol is subject to change",
1879 impl<'a, K, V> Place<V> for EntryPlace<'a, K, V> {
1880 fn pointer(&mut self) -> *mut V {
1881 self.bucket.read_mut().1
1885 #[unstable(feature = "collection_placement",
1886 reason = "placement protocol is subject to change",
1888 impl<'a, K, V> InPlace<V> for EntryPlace<'a, K, V> {
1891 unsafe fn finalize(self) {
1896 impl<'a, K, V> Entry<'a, K, V> {
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 /// Ensures a value is in the entry by inserting the default if empty, and returns
1899 /// a mutable reference to the value in the entry.
1904 /// use std::collections::HashMap;
1906 /// let mut map: HashMap<&str, u32> = HashMap::new();
1907 /// map.entry("poneyland").or_insert(12);
1909 /// assert_eq!(map["poneyland"], 12);
1911 /// *map.entry("poneyland").or_insert(12) += 10;
1912 /// assert_eq!(map["poneyland"], 22);
1914 pub fn or_insert(self, default: V) -> &'a mut V {
1916 Occupied(entry) => entry.into_mut(),
1917 Vacant(entry) => entry.insert(default),
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1923 /// and returns a mutable reference to the value in the entry.
1928 /// use std::collections::HashMap;
1930 /// let mut map: HashMap<&str, String> = HashMap::new();
1931 /// let s = "hoho".to_string();
1933 /// map.entry("poneyland").or_insert_with(|| s);
1935 /// assert_eq!(map["poneyland"], "hoho".to_string());
1937 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1939 Occupied(entry) => entry.into_mut(),
1940 Vacant(entry) => entry.insert(default()),
1944 /// Returns a reference to this entry's key.
1949 /// use std::collections::HashMap;
1951 /// let mut map: HashMap<&str, u32> = HashMap::new();
1952 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1954 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1955 pub fn key(&self) -> &K {
1957 Occupied(ref entry) => entry.key(),
1958 Vacant(ref entry) => entry.key(),
1963 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1964 /// Gets a reference to the key in the entry.
1969 /// use std::collections::HashMap;
1971 /// let mut map: HashMap<&str, u32> = HashMap::new();
1972 /// map.entry("poneyland").or_insert(12);
1973 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1975 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1976 pub fn key(&self) -> &K {
1980 /// Deprecated, renamed to `remove_entry`
1981 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1982 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
1983 pub fn remove_pair(self) -> (K, V) {
1987 /// Take the ownership of the key and value from the map.
1992 /// use std::collections::HashMap;
1993 /// use std::collections::hash_map::Entry;
1995 /// let mut map: HashMap<&str, u32> = HashMap::new();
1996 /// map.entry("poneyland").or_insert(12);
1998 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1999 /// // We delete the entry from the map.
2000 /// o.remove_entry();
2003 /// assert_eq!(map.contains_key("poneyland"), false);
2005 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2006 pub fn remove_entry(self) -> (K, V) {
2007 let (k, v, _) = pop_internal(self.elem);
2011 /// Gets a reference to the value in the entry.
2016 /// use std::collections::HashMap;
2017 /// use std::collections::hash_map::Entry;
2019 /// let mut map: HashMap<&str, u32> = HashMap::new();
2020 /// map.entry("poneyland").or_insert(12);
2022 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2023 /// assert_eq!(o.get(), &12);
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 pub fn get(&self) -> &V {
2031 /// Gets a mutable reference to the value in the entry.
2036 /// use std::collections::HashMap;
2037 /// use std::collections::hash_map::Entry;
2039 /// let mut map: HashMap<&str, u32> = HashMap::new();
2040 /// map.entry("poneyland").or_insert(12);
2042 /// assert_eq!(map["poneyland"], 12);
2043 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2044 /// *o.get_mut() += 10;
2047 /// assert_eq!(map["poneyland"], 22);
2049 #[stable(feature = "rust1", since = "1.0.0")]
2050 pub fn get_mut(&mut self) -> &mut V {
2051 self.elem.read_mut().1
2054 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2055 /// with a lifetime bound to the map itself.
2060 /// use std::collections::HashMap;
2061 /// use std::collections::hash_map::Entry;
2063 /// let mut map: HashMap<&str, u32> = HashMap::new();
2064 /// map.entry("poneyland").or_insert(12);
2066 /// assert_eq!(map["poneyland"], 12);
2067 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2068 /// *o.into_mut() += 10;
2071 /// assert_eq!(map["poneyland"], 22);
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 pub fn into_mut(self) -> &'a mut V {
2075 self.elem.into_mut_refs().1
2078 /// Sets the value of the entry, and returns the entry's old value.
2083 /// use std::collections::HashMap;
2084 /// use std::collections::hash_map::Entry;
2086 /// let mut map: HashMap<&str, u32> = HashMap::new();
2087 /// map.entry("poneyland").or_insert(12);
2089 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2090 /// assert_eq!(o.insert(15), 12);
2093 /// assert_eq!(map["poneyland"], 15);
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 pub fn insert(&mut self, mut value: V) -> V {
2097 let old_value = self.get_mut();
2098 mem::swap(&mut value, old_value);
2102 /// Takes the value out of the entry, and returns it.
2107 /// use std::collections::HashMap;
2108 /// use std::collections::hash_map::Entry;
2110 /// let mut map: HashMap<&str, u32> = HashMap::new();
2111 /// map.entry("poneyland").or_insert(12);
2113 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2114 /// assert_eq!(o.remove(), 12);
2117 /// assert_eq!(map.contains_key("poneyland"), false);
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 pub fn remove(self) -> V {
2121 pop_internal(self.elem).1
2124 /// Returns a key that was used for search.
2126 /// The key was retained for further use.
2127 fn take_key(&mut self) -> Option<K> {
2132 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2133 /// Gets a reference to the key that would be used when inserting a value
2134 /// through the `VacantEntry`.
2139 /// use std::collections::HashMap;
2141 /// let mut map: HashMap<&str, u32> = HashMap::new();
2142 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2144 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2145 pub fn key(&self) -> &K {
2149 /// Take ownership of the key.
2154 /// use std::collections::HashMap;
2155 /// use std::collections::hash_map::Entry;
2157 /// let mut map: HashMap<&str, u32> = HashMap::new();
2159 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2163 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2164 pub fn into_key(self) -> K {
2168 /// Sets the value of the entry with the VacantEntry's key,
2169 /// and returns a mutable reference to it.
2174 /// use std::collections::HashMap;
2175 /// use std::collections::hash_map::Entry;
2177 /// let mut map: HashMap<&str, u32> = HashMap::new();
2179 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2182 /// assert_eq!(map["poneyland"], 37);
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 pub fn insert(self, value: V) -> &'a mut V {
2186 let b = match self.elem {
2187 NeqElem(mut bucket, disp) => {
2188 if disp >= DISPLACEMENT_THRESHOLD {
2189 bucket.table_mut().set_tag(true);
2191 robin_hood(bucket, disp, self.hash, self.key, value)
2193 NoElem(mut bucket, disp) => {
2194 if disp >= DISPLACEMENT_THRESHOLD {
2195 bucket.table_mut().set_tag(true);
2197 bucket.put(self.hash, self.key, value)
2203 // Only used for InPlacement insert. Avoid unnecessary value copy.
2204 // The value remains uninitialized.
2205 unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2207 NeqElem(mut bucket, disp) => {
2208 if disp >= DISPLACEMENT_THRESHOLD {
2209 bucket.table_mut().set_tag(true);
2211 let uninit = mem::uninitialized();
2212 robin_hood(bucket, disp, self.hash, self.key, uninit)
2214 NoElem(mut bucket, disp) => {
2215 if disp >= DISPLACEMENT_THRESHOLD {
2216 bucket.table_mut().set_tag(true);
2218 bucket.put_key(self.hash, self.key)
2224 #[stable(feature = "rust1", since = "1.0.0")]
2225 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2227 S: BuildHasher + Default
2229 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2230 let mut map = HashMap::with_hasher(Default::default());
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2241 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2242 // Keys may be already present or show multiple times in the iterator.
2243 // Reserve the entire hint lower bound if the map is empty.
2244 // Otherwise reserve half the hint (rounded up), so the map
2245 // will only resize twice in the worst case.
2246 let iter = iter.into_iter();
2247 let reserve = if self.is_empty() {
2250 (iter.size_hint().0 + 1) / 2
2252 self.reserve(reserve);
2253 for (k, v) in iter {
2259 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2260 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2261 where K: Eq + Hash + Copy,
2265 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2266 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2270 /// `RandomState` is the default state for [`HashMap`] types.
2272 /// A particular instance `RandomState` will create the same instances of
2273 /// [`Hasher`], but the hashers created by two different `RandomState`
2274 /// instances are unlikely to produce the same result for the same values.
2276 /// [`HashMap`]: struct.HashMap.html
2277 /// [`Hasher`]: ../../hash/trait.Hasher.html
2282 /// use std::collections::HashMap;
2283 /// use std::collections::hash_map::RandomState;
2285 /// let s = RandomState::new();
2286 /// let mut map = HashMap::with_hasher(s);
2287 /// map.insert(1, 2);
2290 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2291 pub struct RandomState {
2297 /// Constructs a new `RandomState` that is initialized with random keys.
2302 /// use std::collections::hash_map::RandomState;
2304 /// let s = RandomState::new();
2307 #[allow(deprecated)]
2309 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2310 pub fn new() -> RandomState {
2311 // Historically this function did not cache keys from the OS and instead
2312 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2313 // was discovered, however, that because we re-seed the thread-local RNG
2314 // from the OS periodically that this can cause excessive slowdown when
2315 // many hash maps are created on a thread. To solve this performance
2316 // trap we cache the first set of randomly generated keys per-thread.
2318 // Later in #36481 it was discovered that exposing a deterministic
2319 // iteration order allows a form of DOS attack. To counter that we
2320 // increment one of the seeds on every RandomState creation, giving
2321 // every corresponding HashMap a different iteration order.
2322 thread_local!(static KEYS: Cell<(u64, u64)> = {
2323 let r = rand::OsRng::new();
2324 let mut r = r.expect("failed to create an OS RNG");
2325 Cell::new((r.gen(), r.gen()))
2329 let (k0, k1) = keys.get();
2330 keys.set((k0.wrapping_add(1), k1));
2331 RandomState { k0: k0, k1: k1 }
2336 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2337 impl BuildHasher for RandomState {
2338 type Hasher = DefaultHasher;
2340 #[allow(deprecated)]
2341 fn build_hasher(&self) -> DefaultHasher {
2342 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2346 /// The default [`Hasher`] used by [`RandomState`].
2348 /// The internal algorithm is not specified, and so it and its hashes should
2349 /// not be relied upon over releases.
2351 /// [`RandomState`]: struct.RandomState.html
2352 /// [`Hasher`]: ../../hash/trait.Hasher.html
2353 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2354 #[allow(deprecated)]
2356 pub struct DefaultHasher(SipHasher13);
2358 impl DefaultHasher {
2359 /// Creates a new `DefaultHasher`.
2361 /// This hasher is not guaranteed to be the same as all other
2362 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2363 /// instances created through `new` or `default`.
2364 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2365 #[allow(deprecated)]
2366 pub fn new() -> DefaultHasher {
2367 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2371 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2372 impl Default for DefaultHasher {
2373 /// Creates a new `DefaultHasher` using [`DefaultHasher::new`]. See
2374 /// [`DefaultHasher::new`] documentation for more information.
2376 /// [`DefaultHasher::new`]: #method.new
2377 fn default() -> DefaultHasher {
2378 DefaultHasher::new()
2382 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2383 impl Hasher for DefaultHasher {
2385 fn write(&mut self, msg: &[u8]) {
2390 fn finish(&self) -> u64 {
2395 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2396 impl Default for RandomState {
2397 /// Constructs a new `RandomState`.
2399 fn default() -> RandomState {
2404 #[stable(feature = "std_debug", since = "1.16.0")]
2405 impl fmt::Debug for RandomState {
2406 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2407 f.pad("RandomState { .. }")
2411 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2412 where K: Eq + Hash + Borrow<Q>,
2418 fn get(&self, key: &Q) -> Option<&K> {
2419 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2422 fn take(&mut self, key: &Q) -> Option<K> {
2423 if self.table.size() == 0 {
2427 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2430 fn replace(&mut self, key: K) -> Option<K> {
2433 match self.entry(key) {
2434 Occupied(mut occupied) => {
2435 let key = occupied.take_key().unwrap();
2436 Some(mem::replace(occupied.elem.read_mut().0, key))
2447 fn assert_covariance() {
2448 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2451 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2454 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2457 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2460 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2463 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2466 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2469 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2472 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2475 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2478 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2479 -> Drain<'new, &'new str, &'new str> {
2487 use super::Entry::{Occupied, Vacant};
2488 use super::RandomState;
2490 use rand::{thread_rng, Rng};
2494 fn test_zero_capacities() {
2495 type HM = HashMap<i32, i32>;
2498 assert_eq!(m.capacity(), 0);
2500 let m = HM::default();
2501 assert_eq!(m.capacity(), 0);
2503 let m = HM::with_hasher(RandomState::new());
2504 assert_eq!(m.capacity(), 0);
2506 let m = HM::with_capacity(0);
2507 assert_eq!(m.capacity(), 0);
2509 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2510 assert_eq!(m.capacity(), 0);
2512 let mut m = HM::new();
2518 assert_eq!(m.capacity(), 0);
2520 let mut m = HM::new();
2522 assert_eq!(m.capacity(), 0);
2526 fn test_create_capacity_zero() {
2527 let mut m = HashMap::with_capacity(0);
2529 assert!(m.insert(1, 1).is_none());
2531 assert!(m.contains_key(&1));
2532 assert!(!m.contains_key(&0));
2537 let mut m = HashMap::new();
2538 assert_eq!(m.len(), 0);
2539 assert!(m.insert(1, 2).is_none());
2540 assert_eq!(m.len(), 1);
2541 assert!(m.insert(2, 4).is_none());
2542 assert_eq!(m.len(), 2);
2543 assert_eq!(*m.get(&1).unwrap(), 2);
2544 assert_eq!(*m.get(&2).unwrap(), 4);
2549 let mut m = HashMap::new();
2550 assert_eq!(m.len(), 0);
2551 assert!(m.insert(1, 2).is_none());
2552 assert_eq!(m.len(), 1);
2553 assert!(m.insert(2, 4).is_none());
2554 assert_eq!(m.len(), 2);
2556 assert_eq!(*m2.get(&1).unwrap(), 2);
2557 assert_eq!(*m2.get(&2).unwrap(), 4);
2558 assert_eq!(m2.len(), 2);
2561 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2563 #[derive(Hash, PartialEq, Eq)]
2569 fn new(k: usize) -> Dropable {
2570 DROP_VECTOR.with(|slot| {
2571 slot.borrow_mut()[k] += 1;
2578 impl Drop for Dropable {
2579 fn drop(&mut self) {
2580 DROP_VECTOR.with(|slot| {
2581 slot.borrow_mut()[self.k] -= 1;
2586 impl Clone for Dropable {
2587 fn clone(&self) -> Dropable {
2588 Dropable::new(self.k)
2594 DROP_VECTOR.with(|slot| {
2595 *slot.borrow_mut() = vec![0; 200];
2599 let mut m = HashMap::new();
2601 DROP_VECTOR.with(|v| {
2603 assert_eq!(v.borrow()[i], 0);
2608 let d1 = Dropable::new(i);
2609 let d2 = Dropable::new(i + 100);
2613 DROP_VECTOR.with(|v| {
2615 assert_eq!(v.borrow()[i], 1);
2620 let k = Dropable::new(i);
2621 let v = m.remove(&k);
2623 assert!(v.is_some());
2625 DROP_VECTOR.with(|v| {
2626 assert_eq!(v.borrow()[i], 1);
2627 assert_eq!(v.borrow()[i+100], 1);
2631 DROP_VECTOR.with(|v| {
2633 assert_eq!(v.borrow()[i], 0);
2634 assert_eq!(v.borrow()[i+100], 0);
2638 assert_eq!(v.borrow()[i], 1);
2639 assert_eq!(v.borrow()[i+100], 1);
2644 DROP_VECTOR.with(|v| {
2646 assert_eq!(v.borrow()[i], 0);
2652 fn test_into_iter_drops() {
2653 DROP_VECTOR.with(|v| {
2654 *v.borrow_mut() = vec![0; 200];
2658 let mut hm = HashMap::new();
2660 DROP_VECTOR.with(|v| {
2662 assert_eq!(v.borrow()[i], 0);
2667 let d1 = Dropable::new(i);
2668 let d2 = Dropable::new(i + 100);
2672 DROP_VECTOR.with(|v| {
2674 assert_eq!(v.borrow()[i], 1);
2681 // By the way, ensure that cloning doesn't screw up the dropping.
2685 let mut half = hm.into_iter().take(50);
2687 DROP_VECTOR.with(|v| {
2689 assert_eq!(v.borrow()[i], 1);
2693 for _ in half.by_ref() {}
2695 DROP_VECTOR.with(|v| {
2697 .filter(|&i| v.borrow()[i] == 1)
2701 .filter(|&i| v.borrow()[i + 100] == 1)
2709 DROP_VECTOR.with(|v| {
2711 assert_eq!(v.borrow()[i], 0);
2717 fn test_empty_remove() {
2718 let mut m: HashMap<isize, bool> = HashMap::new();
2719 assert_eq!(m.remove(&0), None);
2723 fn test_empty_entry() {
2724 let mut m: HashMap<isize, bool> = HashMap::new();
2726 Occupied(_) => panic!(),
2729 assert!(*m.entry(0).or_insert(true));
2730 assert_eq!(m.len(), 1);
2734 fn test_empty_iter() {
2735 let mut m: HashMap<isize, bool> = HashMap::new();
2736 assert_eq!(m.drain().next(), None);
2737 assert_eq!(m.keys().next(), None);
2738 assert_eq!(m.values().next(), None);
2739 assert_eq!(m.values_mut().next(), None);
2740 assert_eq!(m.iter().next(), None);
2741 assert_eq!(m.iter_mut().next(), None);
2742 assert_eq!(m.len(), 0);
2743 assert!(m.is_empty());
2744 assert_eq!(m.into_iter().next(), None);
2748 fn test_lots_of_insertions() {
2749 let mut m = HashMap::new();
2751 // Try this a few times to make sure we never screw up the hashmap's
2754 assert!(m.is_empty());
2757 assert!(m.insert(i, i).is_none());
2761 assert_eq!(r, Some(&j));
2764 for j in i + 1..1001 {
2766 assert_eq!(r, None);
2770 for i in 1001..2001 {
2771 assert!(!m.contains_key(&i));
2776 assert!(m.remove(&i).is_some());
2779 assert!(!m.contains_key(&j));
2782 for j in i + 1..1001 {
2783 assert!(m.contains_key(&j));
2788 assert!(!m.contains_key(&i));
2792 assert!(m.insert(i, i).is_none());
2796 for i in (1..1001).rev() {
2797 assert!(m.remove(&i).is_some());
2800 assert!(!m.contains_key(&j));
2804 assert!(m.contains_key(&j));
2811 fn test_find_mut() {
2812 let mut m = HashMap::new();
2813 assert!(m.insert(1, 12).is_none());
2814 assert!(m.insert(2, 8).is_none());
2815 assert!(m.insert(5, 14).is_none());
2817 match m.get_mut(&5) {
2819 Some(x) => *x = new,
2821 assert_eq!(m.get(&5), Some(&new));
2825 fn test_insert_overwrite() {
2826 let mut m = HashMap::new();
2827 assert!(m.insert(1, 2).is_none());
2828 assert_eq!(*m.get(&1).unwrap(), 2);
2829 assert!(!m.insert(1, 3).is_none());
2830 assert_eq!(*m.get(&1).unwrap(), 3);
2834 fn test_insert_conflicts() {
2835 let mut m = HashMap::with_capacity(4);
2836 assert!(m.insert(1, 2).is_none());
2837 assert!(m.insert(5, 3).is_none());
2838 assert!(m.insert(9, 4).is_none());
2839 assert_eq!(*m.get(&9).unwrap(), 4);
2840 assert_eq!(*m.get(&5).unwrap(), 3);
2841 assert_eq!(*m.get(&1).unwrap(), 2);
2845 fn test_conflict_remove() {
2846 let mut m = HashMap::with_capacity(4);
2847 assert!(m.insert(1, 2).is_none());
2848 assert_eq!(*m.get(&1).unwrap(), 2);
2849 assert!(m.insert(5, 3).is_none());
2850 assert_eq!(*m.get(&1).unwrap(), 2);
2851 assert_eq!(*m.get(&5).unwrap(), 3);
2852 assert!(m.insert(9, 4).is_none());
2853 assert_eq!(*m.get(&1).unwrap(), 2);
2854 assert_eq!(*m.get(&5).unwrap(), 3);
2855 assert_eq!(*m.get(&9).unwrap(), 4);
2856 assert!(m.remove(&1).is_some());
2857 assert_eq!(*m.get(&9).unwrap(), 4);
2858 assert_eq!(*m.get(&5).unwrap(), 3);
2862 fn test_is_empty() {
2863 let mut m = HashMap::with_capacity(4);
2864 assert!(m.insert(1, 2).is_none());
2865 assert!(!m.is_empty());
2866 assert!(m.remove(&1).is_some());
2867 assert!(m.is_empty());
2872 let mut m = HashMap::new();
2874 assert_eq!(m.remove(&1), Some(2));
2875 assert_eq!(m.remove(&1), None);
2880 let mut m = HashMap::with_capacity(4);
2882 assert!(m.insert(i, i*2).is_none());
2884 assert_eq!(m.len(), 32);
2886 let mut observed: u32 = 0;
2889 assert_eq!(*v, *k * 2);
2890 observed |= 1 << *k;
2892 assert_eq!(observed, 0xFFFF_FFFF);
2897 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2898 let map: HashMap<_, _> = vec.into_iter().collect();
2899 let keys: Vec<_> = map.keys().cloned().collect();
2900 assert_eq!(keys.len(), 3);
2901 assert!(keys.contains(&1));
2902 assert!(keys.contains(&2));
2903 assert!(keys.contains(&3));
2908 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2909 let map: HashMap<_, _> = vec.into_iter().collect();
2910 let values: Vec<_> = map.values().cloned().collect();
2911 assert_eq!(values.len(), 3);
2912 assert!(values.contains(&'a'));
2913 assert!(values.contains(&'b'));
2914 assert!(values.contains(&'c'));
2918 fn test_values_mut() {
2919 let vec = vec![(1, 1), (2, 2), (3, 3)];
2920 let mut map: HashMap<_, _> = vec.into_iter().collect();
2921 for value in map.values_mut() {
2922 *value = (*value) * 2
2924 let values: Vec<_> = map.values().cloned().collect();
2925 assert_eq!(values.len(), 3);
2926 assert!(values.contains(&2));
2927 assert!(values.contains(&4));
2928 assert!(values.contains(&6));
2933 let mut m = HashMap::new();
2934 assert!(m.get(&1).is_none());
2938 Some(v) => assert_eq!(*v, 2),
2944 let mut m1 = HashMap::new();
2949 let mut m2 = HashMap::new();
2962 let mut map = HashMap::new();
2963 let empty: HashMap<i32, i32> = HashMap::new();
2968 let map_str = format!("{:?}", map);
2970 assert!(map_str == "{1: 2, 3: 4}" ||
2971 map_str == "{3: 4, 1: 2}");
2972 assert_eq!(format!("{:?}", empty), "{}");
2977 let mut m = HashMap::new();
2979 assert_eq!(m.len(), 0);
2980 assert!(m.is_empty());
2983 let old_raw_cap = m.raw_capacity();
2984 while old_raw_cap == m.raw_capacity() {
2989 assert_eq!(m.len(), i);
2990 assert!(!m.is_empty());
2994 fn test_behavior_resize_policy() {
2995 let mut m = HashMap::new();
2997 assert_eq!(m.len(), 0);
2998 assert_eq!(m.raw_capacity(), 0);
2999 assert!(m.is_empty());
3003 assert!(m.is_empty());
3004 let initial_raw_cap = m.raw_capacity();
3005 m.reserve(initial_raw_cap);
3006 let raw_cap = m.raw_capacity();
3008 assert_eq!(raw_cap, initial_raw_cap * 2);
3011 for _ in 0..raw_cap * 3 / 4 {
3015 // three quarters full
3017 assert_eq!(m.len(), i);
3018 assert_eq!(m.raw_capacity(), raw_cap);
3020 for _ in 0..raw_cap / 4 {
3026 let new_raw_cap = m.raw_capacity();
3027 assert_eq!(new_raw_cap, raw_cap * 2);
3029 for _ in 0..raw_cap / 2 - 1 {
3032 assert_eq!(m.raw_capacity(), new_raw_cap);
3034 // A little more than one quarter full.
3036 assert_eq!(m.raw_capacity(), raw_cap);
3037 // again, a little more than half full
3038 for _ in 0..raw_cap / 2 - 1 {
3044 assert_eq!(m.len(), i);
3045 assert!(!m.is_empty());
3046 assert_eq!(m.raw_capacity(), initial_raw_cap);
3050 fn test_reserve_shrink_to_fit() {
3051 let mut m = HashMap::new();
3054 assert!(m.capacity() >= m.len());
3060 let usable_cap = m.capacity();
3061 for i in 128..(128 + 256) {
3063 assert_eq!(m.capacity(), usable_cap);
3066 for i in 100..(128 + 256) {
3067 assert_eq!(m.remove(&i), Some(i));
3071 assert_eq!(m.len(), 100);
3072 assert!(!m.is_empty());
3073 assert!(m.capacity() >= m.len());
3076 assert_eq!(m.remove(&i), Some(i));
3081 assert_eq!(m.len(), 1);
3082 assert!(m.capacity() >= m.len());
3083 assert_eq!(m.remove(&0), Some(0));
3087 fn test_from_iter() {
3088 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3090 let map: HashMap<_, _> = xs.iter().cloned().collect();
3092 for &(k, v) in &xs {
3093 assert_eq!(map.get(&k), Some(&v));
3098 fn test_size_hint() {
3099 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3101 let map: HashMap<_, _> = xs.iter().cloned().collect();
3103 let mut iter = map.iter();
3105 for _ in iter.by_ref().take(3) {}
3107 assert_eq!(iter.size_hint(), (3, Some(3)));
3111 fn test_iter_len() {
3112 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3114 let map: HashMap<_, _> = xs.iter().cloned().collect();
3116 let mut iter = map.iter();
3118 for _ in iter.by_ref().take(3) {}
3120 assert_eq!(iter.len(), 3);
3124 fn test_mut_size_hint() {
3125 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3127 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3129 let mut iter = map.iter_mut();
3131 for _ in iter.by_ref().take(3) {}
3133 assert_eq!(iter.size_hint(), (3, Some(3)));
3137 fn test_iter_mut_len() {
3138 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3140 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3142 let mut iter = map.iter_mut();
3144 for _ in iter.by_ref().take(3) {}
3146 assert_eq!(iter.len(), 3);
3151 let mut map = HashMap::new();
3157 assert_eq!(map[&2], 1);
3162 fn test_index_nonexistent() {
3163 let mut map = HashMap::new();
3174 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3176 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3178 // Existing key (insert)
3179 match map.entry(1) {
3180 Vacant(_) => unreachable!(),
3181 Occupied(mut view) => {
3182 assert_eq!(view.get(), &10);
3183 assert_eq!(view.insert(100), 10);
3186 assert_eq!(map.get(&1).unwrap(), &100);
3187 assert_eq!(map.len(), 6);
3190 // Existing key (update)
3191 match map.entry(2) {
3192 Vacant(_) => unreachable!(),
3193 Occupied(mut view) => {
3194 let v = view.get_mut();
3195 let new_v = (*v) * 10;
3199 assert_eq!(map.get(&2).unwrap(), &200);
3200 assert_eq!(map.len(), 6);
3202 // Existing key (take)
3203 match map.entry(3) {
3204 Vacant(_) => unreachable!(),
3206 assert_eq!(view.remove(), 30);
3209 assert_eq!(map.get(&3), None);
3210 assert_eq!(map.len(), 5);
3213 // Inexistent key (insert)
3214 match map.entry(10) {
3215 Occupied(_) => unreachable!(),
3217 assert_eq!(*view.insert(1000), 1000);
3220 assert_eq!(map.get(&10).unwrap(), &1000);
3221 assert_eq!(map.len(), 6);
3225 fn test_entry_take_doesnt_corrupt() {
3226 #![allow(deprecated)] //rand
3228 fn check(m: &HashMap<isize, ()>) {
3230 assert!(m.contains_key(k),
3231 "{} is in keys() but not in the map?", k);
3235 let mut m = HashMap::new();
3236 let mut rng = thread_rng();
3238 // Populate the map with some items.
3240 let x = rng.gen_range(-10, 10);
3245 let x = rng.gen_range(-10, 10);
3249 println!("{}: remove {}", i, x);
3259 fn test_extend_ref() {
3260 let mut a = HashMap::new();
3262 let mut b = HashMap::new();
3264 b.insert(3, "three");
3268 assert_eq!(a.len(), 3);
3269 assert_eq!(a[&1], "one");
3270 assert_eq!(a[&2], "two");
3271 assert_eq!(a[&3], "three");
3275 fn test_capacity_not_less_than_len() {
3276 let mut a = HashMap::new();
3284 assert!(a.capacity() > a.len());
3286 let free = a.capacity() - a.len();
3292 assert_eq!(a.len(), a.capacity());
3294 // Insert at capacity should cause allocation.
3296 assert!(a.capacity() > a.len());
3300 fn test_occupied_entry_key() {
3301 let mut a = HashMap::new();
3302 let key = "hello there";
3303 let value = "value goes here";
3304 assert!(a.is_empty());
3305 a.insert(key.clone(), value.clone());
3306 assert_eq!(a.len(), 1);
3307 assert_eq!(a[key], value);
3309 match a.entry(key.clone()) {
3310 Vacant(_) => panic!(),
3311 Occupied(e) => assert_eq!(key, *e.key()),
3313 assert_eq!(a.len(), 1);
3314 assert_eq!(a[key], value);
3318 fn test_vacant_entry_key() {
3319 let mut a = HashMap::new();
3320 let key = "hello there";
3321 let value = "value goes here";
3323 assert!(a.is_empty());
3324 match a.entry(key.clone()) {
3325 Occupied(_) => panic!(),
3327 assert_eq!(key, *e.key());
3328 e.insert(value.clone());
3331 assert_eq!(a.len(), 1);
3332 assert_eq!(a[key], value);
3337 let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3339 map.retain(|&k, _| k % 2 == 0);
3340 assert_eq!(map.len(), 50);
3341 assert_eq!(map[&2], 20);
3342 assert_eq!(map[&4], 40);
3343 assert_eq!(map[&6], 60);
3347 fn test_adaptive() {
3348 const TEST_LEN: usize = 5000;
3349 // by cloning we get maps with the same hasher seed
3350 let mut first = HashMap::new();
3351 let mut second = first.clone();
3352 first.extend((0..TEST_LEN).map(|i| (i, i)));
3353 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3355 for (&k, &v) in &second {
3356 let prev_cap = first.capacity();
3357 let expect_grow = first.len() == prev_cap;
3359 if !expect_grow && first.capacity() != prev_cap {
3363 panic!("Adaptive early resize failed");
3367 fn test_placement_in() {
3368 let mut map = HashMap::new();
3369 map.extend((0..10).map(|i| (i, i)));
3371 map.entry(100) <- 100;
3372 assert_eq!(map[&100], 100);
3375 assert_eq!(map[&0], 10);
3377 assert_eq!(map.len(), 11);
3381 fn test_placement_panic() {
3382 let mut map = HashMap::new();
3383 map.extend((0..10).map(|i| (i, i)));
3385 fn mkpanic() -> usize { panic!() }
3387 // modify existing key
3388 // when panic happens, previous key is removed.
3389 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3390 assert_eq!(map.len(), 9);
3391 assert!(!map.contains_key(&0));
3394 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3395 assert_eq!(map.len(), 9);
3396 assert!(!map.contains_key(&100));
3400 fn test_placement_drop() {
3402 struct TestV<'a>(&'a mut bool);
3403 impl<'a> Drop for TestV<'a> {
3404 fn drop(&mut self) {
3405 if !*self.0 { panic!("value double drop!"); } // no double drop
3410 fn makepanic<'a>() -> TestV<'a> { panic!() }
3412 let mut can_drop = true;
3413 let mut hm = HashMap::new();
3414 hm.insert(0, TestV(&mut can_drop));
3415 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3416 assert_eq!(hm.len(), 0);