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::*;
16 use fmt::{self, Debug};
17 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
18 use iter::{FromIterator, FusedIterator};
19 use mem::{self, replace};
20 use ops::{Deref, Index};
21 use rand::{self, Rng};
32 use super::table::BucketState::{
37 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
39 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
41 struct DefaultResizePolicy;
43 impl DefaultResizePolicy {
44 fn new() -> DefaultResizePolicy {
48 /// A hash map's "capacity" is the number of elements it can hold without
49 /// being resized. Its "raw capacity" is the number of slots required to
50 /// provide that capacity, accounting for maximum loading. The raw capacity
51 /// is always zero or a power of two.
53 fn raw_capacity(&self, len: usize) -> usize {
57 // 1. Account for loading: `raw_capacity >= len * 1.1`.
58 // 2. Ensure it is a power of two.
59 // 3. Ensure it is at least the minimum size.
60 let mut raw_cap = len * 11 / 10;
61 assert!(raw_cap >= len, "raw_cap overflow");
62 raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow");
63 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
68 /// The capacity of the given raw capacity.
70 fn capacity(&self, raw_cap: usize) -> usize {
71 // This doesn't have to be checked for overflow since allocation size
72 // in bytes will overflow earlier than multiplication by 10.
74 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
75 // to be: (raw_cap * den + den - 1) / num
76 (raw_cap * 10 + 10 - 1) / 11
80 // The main performance trick in this hashmap is called Robin Hood Hashing.
81 // It gains its excellent performance from one essential operation:
83 // If an insertion collides with an existing element, and that element's
84 // "probe distance" (how far away the element is from its ideal location)
85 // is higher than how far we've already probed, swap the elements.
87 // This massively lowers variance in probe distance, and allows us to get very
88 // high load factors with good performance. The 90% load factor I use is rather
91 // > Why a load factor of approximately 90%?
93 // In general, all the distances to initial buckets will converge on the mean.
94 // At a load factor of α, the odds of finding the target bucket after k
95 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
96 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
97 // this down to make the math easier on the CPU and avoid its FPU.
98 // Since on average we start the probing in the middle of a cache line, this
99 // strategy pulls in two cache lines of hashes on every lookup. I think that's
100 // pretty good, but if you want to trade off some space, it could go down to one
101 // cache line on average with an α of 0.84.
103 // > Wait, what? Where did you get 1-α^k from?
105 // On the first probe, your odds of a collision with an existing element is α.
106 // The odds of doing this twice in a row is approximately α^2. For three times,
107 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
108 // colliding after k tries is 1-α^k.
110 // The paper from 1986 cited below mentions an implementation which keeps track
111 // of the distance-to-initial-bucket histogram. This approach is not suitable
112 // for modern architectures because it requires maintaining an internal data
113 // structure. This allows very good first guesses, but we are most concerned
114 // with guessing entire cache lines, not individual indexes. Furthermore, array
115 // accesses are no longer linear and in one direction, as we have now. There
116 // is also memory and cache pressure that this would entail that would be very
117 // difficult to properly see in a microbenchmark.
119 // ## Future Improvements (FIXME!)
121 // Allow the load factor to be changed dynamically and/or at initialization.
123 // Also, would it be possible for us to reuse storage when growing the
124 // underlying table? This is exactly the use case for 'realloc', and may
125 // be worth exploring.
127 // ## Future Optimizations (FIXME!)
129 // Another possible design choice that I made without any real reason is
130 // parameterizing the raw table over keys and values. Technically, all we need
131 // is the size and alignment of keys and values, and the code should be just as
132 // efficient (well, we might need one for power-of-two size and one for not...).
133 // This has the potential to reduce code bloat in rust executables, without
134 // really losing anything except 4 words (key size, key alignment, val size,
135 // val alignment) which can be passed in to every call of a `RawTable` function.
136 // This would definitely be an avenue worth exploring if people start complaining
137 // about the size of rust executables.
139 // Annotate exceedingly likely branches in `table::make_hash`
140 // and `search_hashed` to reduce instruction cache pressure
141 // and mispredictions once it becomes possible (blocked on issue #11092).
143 // Shrinking the table could simply reallocate in place after moving buckets
144 // to the first half.
146 // The growth algorithm (fragment of the Proof of Correctness)
147 // --------------------
149 // The growth algorithm is basically a fast path of the naive reinsertion-
150 // during-resize algorithm. Other paths should never be taken.
152 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
153 // by allocating a new table of capacity `2n`, and then individually reinsert
154 // each element in the old table into the new one. This guarantees that the
155 // new table is a valid robin hood hashtable with all the desired statistical
156 // properties. Remark that the order we reinsert the elements in should not
157 // matter. For simplicity and efficiency, we will consider only linear
158 // reinsertions, which consist of reinserting all elements in the old table
159 // into the new one by increasing order of index. However we will not be
160 // starting our reinsertions from index 0 in general. If we start from index
161 // i, for the purpose of reinsertion we will consider all elements with real
162 // index j < i to have virtual index n + j.
164 // Our hash generation scheme consists of generating a 64-bit hash and
165 // truncating the most significant bits. When moving to the new table, we
166 // simply introduce a new bit to the front of the hash. Therefore, if an
167 // elements has ideal index i in the old table, it can have one of two ideal
168 // locations in the new table. If the new bit is 0, then the new ideal index
169 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
170 // we are producing two independent tables of size n, and for each element we
171 // independently choose which table to insert it into with equal probability.
172 // However the rather than wrapping around themselves on overflowing their
173 // indexes, the first table overflows into the first, and the first into the
174 // second. Visually, our new table will look something like:
176 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
178 // Where x's are elements inserted into the first table, y's are elements
179 // inserted into the second, and _'s are empty sections. We now define a few
180 // key concepts that we will use later. Note that this is a very abstract
181 // perspective of the table. A real resized table would be at least half
184 // Theorem: A linear robin hood reinsertion from the first ideal element
185 // produces identical results to a linear naive reinsertion from the same
188 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
190 /// A hash map implementation which uses linear probing with Robin Hood bucket
193 /// By default, `HashMap` uses a hashing algorithm selected to provide
194 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
195 /// reasonable best-effort is made to generate this seed from a high quality,
196 /// secure source of randomness provided by the host without blocking the
197 /// program. Because of this, the randomness of the seed is dependant on the
198 /// quality of the system's random number generator at the time it is created.
199 /// In particular, seeds generated when the system's entropy pool is abnormally
200 /// low such as during system boot may be of a lower quality.
202 /// The default hashing algorithm is currently SipHash 1-3, though this is
203 /// subject to change at any point in the future. While its performance is very
204 /// competitive for medium sized keys, other hashing algorithms will outperform
205 /// it for small keys such as integers as well as large keys such as long
206 /// strings, though those algorithms will typically *not* protect against
207 /// attacks such as HashDoS.
209 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
210 /// `HashMap::default`, `HashMap::with_hasher`, and
211 /// `HashMap::with_capacity_and_hasher` methods. Many alternative algorithms
212 /// are available on crates.io, such as the `fnv` crate.
214 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
215 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
216 /// If you implement these yourself, it is important that the following
220 /// k1 == k2 -> hash(k1) == hash(k2)
223 /// In other words, if two keys are equal, their hashes must be equal.
225 /// It is a logic error for a key to be modified in such a way that the key's
226 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
227 /// the [`Eq`] trait, changes while it is in the map. This is normally only
228 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
230 /// Relevant papers/articles:
232 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
233 /// 2. Emmanuel Goossaert. ["Robin Hood
234 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
235 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
236 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
241 /// use std::collections::HashMap;
243 /// // type inference lets us omit an explicit type signature (which
244 /// // would be `HashMap<&str, &str>` in this example).
245 /// let mut book_reviews = HashMap::new();
247 /// // review some books.
248 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
249 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
250 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
251 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
253 /// // check for a specific one.
254 /// if !book_reviews.contains_key("Les Misérables") {
255 /// println!("We've got {} reviews, but Les Misérables ain't one.",
256 /// book_reviews.len());
259 /// // oops, this review has a lot of spelling mistakes, let's delete it.
260 /// book_reviews.remove("The Adventures of Sherlock Holmes");
262 /// // look up the values associated with some keys.
263 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
264 /// for book in &to_find {
265 /// match book_reviews.get(book) {
266 /// Some(review) => println!("{}: {}", book, review),
267 /// None => println!("{} is unreviewed.", book)
271 /// // iterate over everything.
272 /// for (book, review) in &book_reviews {
273 /// println!("{}: \"{}\"", book, review);
277 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
278 /// for more complex methods of getting, setting, updating and removing keys and
282 /// use std::collections::HashMap;
284 /// // type inference lets us omit an explicit type signature (which
285 /// // would be `HashMap<&str, u8>` in this example).
286 /// let mut player_stats = HashMap::new();
288 /// fn random_stat_buff() -> u8 {
289 /// // could actually return some random value here - let's just return
290 /// // some fixed value for now
294 /// // insert a key only if it doesn't already exist
295 /// player_stats.entry("health").or_insert(100);
297 /// // insert a key using a function that provides a new value only if it
298 /// // doesn't already exist
299 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
301 /// // update a key, guarding against the key possibly not being set
302 /// let stat = player_stats.entry("attack").or_insert(100);
303 /// *stat += random_stat_buff();
306 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
307 /// We must also derive [`PartialEq`].
309 /// [`Eq`]: ../../std/cmp/trait.Eq.html
310 /// [`Hash`]: ../../std/hash/trait.Hash.html
311 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
312 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
313 /// [`Cell`]: ../../std/cell/struct.Cell.html
316 /// use std::collections::HashMap;
318 /// #[derive(Hash, Eq, PartialEq, Debug)]
325 /// /// Create a new Viking.
326 /// fn new(name: &str, country: &str) -> Viking {
327 /// Viking { name: name.to_string(), country: country.to_string() }
331 /// // Use a HashMap to store the vikings' health points.
332 /// let mut vikings = HashMap::new();
334 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
335 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
336 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
338 /// // Use derived implementation to print the status of the vikings.
339 /// for (viking, health) in &vikings {
340 /// println!("{:?} has {} hp", viking, health);
344 /// A HashMap with fixed list of elements can be initialized from an array:
347 /// use std::collections::HashMap;
350 /// let timber_resources: HashMap<&str, i32> =
351 /// [("Norway", 100),
354 /// .iter().cloned().collect();
355 /// // use the values stored in map
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub struct HashMap<K, V, S = RandomState> {
362 // All hashes are keyed on these values, to prevent hash collision attacks.
365 table: RawTable<K, V>,
367 resize_policy: DefaultResizePolicy,
370 /// Search for a pre-hashed key.
372 fn search_hashed<K, V, M, F>(table: M,
375 -> InternalEntry<K, V, M> where
376 M: Deref<Target=RawTable<K, V>>,
377 F: FnMut(&K) -> bool,
379 // This is the only function where capacity can be zero. To avoid
380 // undefined behavior when Bucket::new gets the raw bucket in this
381 // case, immediately return the appropriate search result.
382 if table.capacity() == 0 {
383 return InternalEntry::TableIsEmpty;
386 let size = table.size() as isize;
387 let mut probe = Bucket::new(table, hash);
388 let ib = probe.index() as isize;
391 let full = match probe.peek() {
394 return InternalEntry::Vacant {
396 elem: NoElem(bucket),
399 Full(bucket) => bucket
402 let robin_ib = full.index() as isize - full.displacement() as isize;
405 // Found a luckier bucket than me.
406 // We can finish the search early if we hit any bucket
407 // with a lower distance to initial bucket than we've probed.
408 return InternalEntry::Vacant {
410 elem: NeqElem(full, robin_ib as usize),
414 // If the hash doesn't match, it can't be this one..
415 if hash == full.hash() {
416 // If the key doesn't match, it can't be this one..
417 if is_match(full.read().0) {
418 return InternalEntry::Occupied {
425 debug_assert!(probe.index() as isize != ib + size + 1);
429 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
430 let (empty, retkey, retval) = starting_bucket.take();
431 let mut gap = match empty.gap_peek() {
433 None => return (retkey, retval)
436 while gap.full().displacement() != 0 {
437 gap = match gap.shift() {
443 // Now we've done all our shifting. Return the value we grabbed earlier.
447 /// Perform robin hood bucket stealing at the given `bucket`. You must
448 /// also pass the position of that bucket's initial bucket so we don't have
449 /// to recalculate it.
451 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
452 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
458 let starting_index = bucket.index();
459 let size = bucket.table().size();
460 // Save the *starting point*.
461 let mut bucket = bucket.stash();
462 // There can be at most `size - dib` buckets to displace, because
463 // in the worst case, there are `size` elements and we already are
464 // `displacement` buckets away from the initial one.
465 let idx_end = starting_index + size - bucket.displacement();
468 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
474 let probe = bucket.next();
475 debug_assert!(probe.index() != idx_end);
477 let full_bucket = match probe.peek() {
480 let bucket = bucket.put(hash, key, val);
481 // Now that it's stolen, just read the value's pointer
482 // right out of the table! Go back to the *starting point*.
484 // This use of `into_table` is misleading. It turns the
485 // bucket, which is a FullBucket on top of a
486 // FullBucketMut, into just one FullBucketMut. The "table"
487 // refers to the inner FullBucketMut in this context.
488 return bucket.into_table().into_mut_refs().1;
490 Full(bucket) => bucket
493 let probe_ib = full_bucket.index() - full_bucket.displacement();
495 bucket = full_bucket;
497 // Robin hood! Steal the spot.
506 impl<K, V, S> HashMap<K, V, S>
507 where K: Eq + Hash, S: BuildHasher
509 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
510 table::make_hash(&self.hash_builder, x)
513 /// Search for a key, yielding the index if it's found in the hashtable.
514 /// If you already have the hash for the key lying around, use
517 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
518 where K: Borrow<Q>, Q: Eq + Hash
520 let hash = self.make_hash(q);
521 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
525 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
526 where K: Borrow<Q>, Q: Eq + Hash
528 let hash = self.make_hash(q);
529 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
532 // The caller should ensure that invariants by Robin Hood Hashing hold.
533 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
534 let raw_cap = self.raw_capacity();
535 let mut buckets = Bucket::new(&mut self.table, hash);
536 let ib = buckets.index();
538 while buckets.index() != ib + raw_cap {
539 // We don't need to compare hashes for value swap.
540 // Not even DIBs for Robin Hood.
541 buckets = match buckets.peek() {
543 empty.put(hash, k, v);
546 Full(b) => b.into_bucket()
550 panic!("Internal HashMap error: Out of space.");
554 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
555 /// Creates an empty `HashMap`.
560 /// use std::collections::HashMap;
561 /// let mut map: HashMap<&str, isize> = HashMap::new();
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn new() -> HashMap<K, V, RandomState> {
569 /// Creates an empty `HashMap` with the specified capacity.
571 /// The hash map will be able to hold at least `capacity` elements without
572 /// reallocating. If `capacity` is 0, the hash map will not allocate.
577 /// use std::collections::HashMap;
578 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
581 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
583 HashMap::with_capacity_and_hasher(capacity, Default::default())
587 impl<K, V, S> HashMap<K, V, S>
588 where K: Eq + Hash, S: BuildHasher
590 /// Creates an empty `HashMap` which will use the given hash builder to hash
593 /// The created map has the default initial capacity.
595 /// Warning: `hash_builder` is normally randomly generated, and
596 /// is designed to allow HashMaps to be resistant to attacks that
597 /// cause many collisions and very poor performance. Setting it
598 /// manually using this function can expose a DoS attack vector.
603 /// use std::collections::HashMap;
604 /// use std::collections::hash_map::RandomState;
606 /// let s = RandomState::new();
607 /// let mut map = HashMap::with_hasher(s);
608 /// map.insert(1, 2);
611 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
612 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
614 hash_builder: hash_builder,
615 resize_policy: DefaultResizePolicy::new(),
616 table: RawTable::new(0),
620 /// Creates an empty `HashMap` with the specified capacity, using `hasher`
621 /// to hash the keys.
623 /// The hash map will be able to hold at least `capacity` elements without
624 /// reallocating. If `capacity` is 0, the hash map will not allocate.
625 /// Warning: `hasher` is normally randomly generated, and
626 /// is designed to allow HashMaps to be resistant to attacks that
627 /// cause many collisions and very poor performance. Setting it
628 /// manually using this function can expose a DoS attack vector.
633 /// use std::collections::HashMap;
634 /// use std::collections::hash_map::RandomState;
636 /// let s = RandomState::new();
637 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
638 /// map.insert(1, 2);
641 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
642 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S)
643 -> HashMap<K, V, S> {
644 let resize_policy = DefaultResizePolicy::new();
645 let raw_cap = resize_policy.raw_capacity(capacity);
647 hash_builder: hash_builder,
648 resize_policy: resize_policy,
649 table: RawTable::new(raw_cap),
653 /// Returns a reference to the map's hasher.
654 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
655 pub fn hasher(&self) -> &S {
659 /// Returns the number of elements the map can hold without reallocating.
661 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
662 /// more, but is guaranteed to be able to hold at least this many.
667 /// use std::collections::HashMap;
668 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
669 /// assert!(map.capacity() >= 100);
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn capacity(&self) -> usize {
674 self.resize_policy.capacity(self.raw_capacity())
677 /// Returns the hash map's raw capacity.
679 fn raw_capacity(&self) -> usize {
680 self.table.capacity()
683 /// Reserves capacity for at least `additional` more elements to be inserted
684 /// in the `HashMap`. The collection may reserve more space to avoid
685 /// frequent reallocations.
689 /// Panics if the new allocation size overflows `usize`.
694 /// use std::collections::HashMap;
695 /// let mut map: HashMap<&str, isize> = HashMap::new();
698 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn reserve(&mut self, additional: usize) {
700 let remaining = self.capacity() - self.len(); // this can't overflow
701 if remaining < additional {
702 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
703 let raw_cap = self.resize_policy.raw_capacity(min_cap);
704 self.resize(raw_cap);
708 /// Resizes the internal vectors to a new capacity. It's your
709 /// responsibility to:
710 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
711 /// for the load factor.
712 /// 2) Ensure `new_raw_cap` is a power of two or zero.
713 fn resize(&mut self, new_raw_cap: usize) {
714 assert!(self.table.size() <= new_raw_cap);
715 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
717 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
718 let old_size = old_table.size();
720 if old_table.capacity() == 0 || old_table.size() == 0 {
725 // Specialization of the other branch.
726 let mut bucket = Bucket::first(&mut old_table);
728 // "So a few of the first shall be last: for many be called,
731 // We'll most likely encounter a few buckets at the beginning that
732 // have their initial buckets near the end of the table. They were
733 // placed at the beginning as the probe wrapped around the table
734 // during insertion. We must skip forward to a bucket that won't
735 // get reinserted too early and won't unfairly steal others spot.
736 // This eliminates the need for robin hood.
738 bucket = match bucket.peek() {
740 if full.displacement() == 0 {
741 // This bucket occupies its ideal spot.
742 // It indicates the start of another "cluster".
743 bucket = full.into_bucket();
746 // Leaving this bucket in the last cluster for later.
750 // Encountered a hole between clusters.
757 // This is how the buckets might be laid out in memory:
758 // ($ marks an initialized bucket)
760 // |$$$_$$$$$$_$$$$$|
762 // But we've skipped the entire initial cluster of buckets
763 // and will continue iteration in this order:
766 // ^ wrap around once end is reached
769 // ^ exit once table.size == 0
771 bucket = match bucket.peek() {
773 let h = bucket.hash();
774 let (b, k, v) = bucket.take();
775 self.insert_hashed_ordered(h, k, v);
776 if b.table().size() == 0 {
781 Empty(b) => b.into_bucket()
786 assert_eq!(self.table.size(), old_size);
789 /// Shrinks the capacity of the map as much as possible. It will drop
790 /// down as much as possible while maintaining the internal rules
791 /// and possibly leaving some space in accordance with the resize policy.
796 /// use std::collections::HashMap;
798 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
799 /// map.insert(1, 2);
800 /// map.insert(3, 4);
801 /// assert!(map.capacity() >= 100);
802 /// map.shrink_to_fit();
803 /// assert!(map.capacity() >= 2);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn shrink_to_fit(&mut self) {
807 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
808 if self.raw_capacity() != new_raw_cap {
809 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
810 let old_size = old_table.size();
812 // Shrink the table. Naive algorithm for resizing:
813 for (h, k, v) in old_table.into_iter() {
814 self.insert_hashed_nocheck(h, k, v);
817 debug_assert_eq!(self.table.size(), old_size);
821 /// Insert a pre-hashed key-value pair, without first checking
822 /// that there's enough room in the buckets. Returns a reference to the
823 /// newly insert value.
825 /// If the key already exists, the hashtable will be returned untouched
826 /// and a reference to the existing element will be returned.
827 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
828 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
830 Some(Occupied(mut elem)) => {
833 Some(Vacant(elem)) => {
843 /// An iterator visiting all keys in arbitrary order.
844 /// Iterator element type is `&'a K`.
849 /// use std::collections::HashMap;
851 /// let mut map = HashMap::new();
852 /// map.insert("a", 1);
853 /// map.insert("b", 2);
854 /// map.insert("c", 3);
856 /// for key in map.keys() {
857 /// println!("{}", key);
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn keys(&self) -> Keys<K, V> {
862 Keys { inner: self.iter() }
865 /// An iterator visiting all values in arbitrary order.
866 /// Iterator element type is `&'a V`.
871 /// use std::collections::HashMap;
873 /// let mut map = HashMap::new();
874 /// map.insert("a", 1);
875 /// map.insert("b", 2);
876 /// map.insert("c", 3);
878 /// for val in map.values() {
879 /// println!("{}", val);
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn values(&self) -> Values<K, V> {
884 Values { inner: self.iter() }
887 /// An iterator visiting all values mutably in arbitrary order.
888 /// Iterator element type is `&'a mut V`.
893 /// use std::collections::HashMap;
895 /// let mut map = HashMap::new();
897 /// map.insert("a", 1);
898 /// map.insert("b", 2);
899 /// map.insert("c", 3);
901 /// for val in map.values_mut() {
902 /// *val = *val + 10;
905 /// for val in map.values() {
906 /// println!("{}", val);
909 #[stable(feature = "map_values_mut", since = "1.10.0")]
910 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
911 ValuesMut { inner: self.iter_mut() }
914 /// An iterator visiting all key-value pairs in arbitrary order.
915 /// Iterator element type is `(&'a K, &'a V)`.
920 /// use std::collections::HashMap;
922 /// let mut map = HashMap::new();
923 /// map.insert("a", 1);
924 /// map.insert("b", 2);
925 /// map.insert("c", 3);
927 /// for (key, val) in map.iter() {
928 /// println!("key: {} val: {}", key, val);
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn iter(&self) -> Iter<K, V> {
933 Iter { inner: self.table.iter() }
936 /// An iterator visiting all key-value pairs in arbitrary order,
937 /// with mutable references to the values.
938 /// Iterator element type is `(&'a K, &'a mut V)`.
943 /// use std::collections::HashMap;
945 /// let mut map = HashMap::new();
946 /// map.insert("a", 1);
947 /// map.insert("b", 2);
948 /// map.insert("c", 3);
950 /// // Update all values
951 /// for (_, val) in map.iter_mut() {
955 /// for (key, val) in &map {
956 /// println!("key: {} val: {}", key, val);
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn iter_mut(&mut self) -> IterMut<K, V> {
961 IterMut { inner: self.table.iter_mut() }
964 /// Gets the given key's corresponding entry in the map for in-place manipulation.
969 /// use std::collections::HashMap;
971 /// let mut letters = HashMap::new();
973 /// for ch in "a short treatise on fungi".chars() {
974 /// let counter = letters.entry(ch).or_insert(0);
978 /// assert_eq!(letters[&'s'], 2);
979 /// assert_eq!(letters[&'t'], 3);
980 /// assert_eq!(letters[&'u'], 1);
981 /// assert_eq!(letters.get(&'y'), None);
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn entry(&mut self, key: K) -> Entry<K, V> {
987 self.search_mut(&key).into_entry(key).expect("unreachable")
990 /// Returns the number of elements in the map.
995 /// use std::collections::HashMap;
997 /// let mut a = HashMap::new();
998 /// assert_eq!(a.len(), 0);
999 /// a.insert(1, "a");
1000 /// assert_eq!(a.len(), 1);
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn len(&self) -> usize { self.table.size() }
1005 /// Returns true if the map contains no elements.
1010 /// use std::collections::HashMap;
1012 /// let mut a = HashMap::new();
1013 /// assert!(a.is_empty());
1014 /// a.insert(1, "a");
1015 /// assert!(!a.is_empty());
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 pub fn is_empty(&self) -> bool { self.len() == 0 }
1021 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1022 /// allocated memory for reuse.
1027 /// use std::collections::HashMap;
1029 /// let mut a = HashMap::new();
1030 /// a.insert(1, "a");
1031 /// a.insert(2, "b");
1033 /// for (k, v) in a.drain().take(1) {
1034 /// assert!(k == 1 || k == 2);
1035 /// assert!(v == "a" || v == "b");
1038 /// assert!(a.is_empty());
1041 #[stable(feature = "drain", since = "1.6.0")]
1042 pub fn drain(&mut self) -> Drain<K, V> {
1044 inner: self.table.drain(),
1048 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1054 /// use std::collections::HashMap;
1056 /// let mut a = HashMap::new();
1057 /// a.insert(1, "a");
1059 /// assert!(a.is_empty());
1061 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub fn clear(&mut self) {
1067 /// Returns a reference to the value corresponding to the key.
1069 /// The key may be any borrowed form of the map's key type, but
1070 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1073 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1074 /// [`Hash`]: ../../std/hash/trait.Hash.html
1079 /// use std::collections::HashMap;
1081 /// let mut map = HashMap::new();
1082 /// map.insert(1, "a");
1083 /// assert_eq!(map.get(&1), Some(&"a"));
1084 /// assert_eq!(map.get(&2), None);
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1088 where K: Borrow<Q>, Q: Hash + Eq
1090 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1093 /// Returns true if the map contains a value for the specified key.
1095 /// The key may be any borrowed form of the map's key type, but
1096 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1099 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1100 /// [`Hash`]: ../../std/hash/trait.Hash.html
1105 /// use std::collections::HashMap;
1107 /// let mut map = HashMap::new();
1108 /// map.insert(1, "a");
1109 /// assert_eq!(map.contains_key(&1), true);
1110 /// assert_eq!(map.contains_key(&2), false);
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1114 where K: Borrow<Q>, Q: Hash + Eq
1116 self.search(k).into_occupied_bucket().is_some()
1119 /// Returns a mutable reference to the value corresponding to the key.
1121 /// The key may be any borrowed form of the map's key type, but
1122 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1125 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1126 /// [`Hash`]: ../../std/hash/trait.Hash.html
1131 /// use std::collections::HashMap;
1133 /// let mut map = HashMap::new();
1134 /// map.insert(1, "a");
1135 /// if let Some(x) = map.get_mut(&1) {
1138 /// assert_eq!(map[&1], "b");
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1142 where K: Borrow<Q>, Q: Hash + Eq
1144 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1147 /// Inserts a key-value pair into the map.
1149 /// If the map did not have this key present, `None` is returned.
1151 /// If the map did have this key present, the value is updated, and the old
1152 /// value is returned. The key is not updated, though; this matters for
1153 /// types that can be `==` without being identical. See the [module-level
1154 /// documentation] for more.
1156 /// [module-level documentation]: index.html#insert-and-complex-keys
1161 /// use std::collections::HashMap;
1163 /// let mut map = HashMap::new();
1164 /// assert_eq!(map.insert(37, "a"), None);
1165 /// assert_eq!(map.is_empty(), false);
1167 /// map.insert(37, "b");
1168 /// assert_eq!(map.insert(37, "c"), Some("b"));
1169 /// assert_eq!(map[&37], "c");
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1173 let hash = self.make_hash(&k);
1175 self.insert_hashed_nocheck(hash, k, v)
1178 /// Removes a key from the map, returning the value at the key if the key
1179 /// was previously in the map.
1181 /// The key may be any borrowed form of the map's key type, but
1182 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1185 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1186 /// [`Hash`]: ../../std/hash/trait.Hash.html
1191 /// use std::collections::HashMap;
1193 /// let mut map = HashMap::new();
1194 /// map.insert(1, "a");
1195 /// assert_eq!(map.remove(&1), Some("a"));
1196 /// assert_eq!(map.remove(&1), None);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1200 where K: Borrow<Q>, Q: Hash + Eq
1202 if self.table.size() == 0 {
1206 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<K, V, S> PartialEq for HashMap<K, V, S>
1212 where K: Eq + Hash, V: PartialEq, S: BuildHasher
1214 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1215 if self.len() != other.len() { return false; }
1217 self.iter().all(|(key, value)|
1218 other.get(key).map_or(false, |v| *value == *v)
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<K, V, S> Eq for HashMap<K, V, S>
1225 where K: Eq + Hash, V: Eq, S: BuildHasher
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<K, V, S> Debug for HashMap<K, V, S>
1230 where K: Eq + Hash + Debug, V: Debug, S: BuildHasher
1232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1233 f.debug_map().entries(self.iter()).finish()
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<K, V, S> Default for HashMap<K, V, S>
1240 S: BuildHasher + Default,
1242 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1243 fn default() -> HashMap<K, V, S> {
1244 HashMap::with_hasher(Default::default())
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1250 where K: Eq + Hash + Borrow<Q>,
1257 fn index(&self, index: &Q) -> &V {
1258 self.get(index).expect("no entry found for key")
1262 /// HashMap iterator.
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 pub struct Iter<'a, K: 'a, V: 'a> {
1265 inner: table::Iter<'a, K, V>
1268 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<'a, K, V> Clone for Iter<'a, K, V> {
1271 fn clone(&self) -> Iter<'a, K, V> {
1273 inner: self.inner.clone()
1278 /// HashMap mutable values iterator.
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub struct IterMut<'a, K: 'a, V: 'a> {
1281 inner: table::IterMut<'a, K, V>
1284 /// HashMap move iterator.
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub struct IntoIter<K, V> {
1287 inner: table::IntoIter<K, V>
1290 /// HashMap keys iterator.
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub struct Keys<'a, K: 'a, V: 'a> {
1293 inner: Iter<'a, K, V>
1296 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<'a, K, V> Clone for Keys<'a, K, V> {
1299 fn clone(&self) -> Keys<'a, K, V> {
1301 inner: self.inner.clone()
1306 /// HashMap values iterator.
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub struct Values<'a, K: 'a, V: 'a> {
1309 inner: Iter<'a, K, V>
1312 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<'a, K, V> Clone for Values<'a, K, V> {
1315 fn clone(&self) -> Values<'a, K, V> {
1317 inner: self.inner.clone()
1322 /// HashMap drain iterator.
1323 #[stable(feature = "drain", since = "1.6.0")]
1324 pub struct Drain<'a, K: 'a, V: 'a> {
1325 inner: table::Drain<'a, K, V>
1328 /// Mutable HashMap values iterator.
1329 #[stable(feature = "map_values_mut", since = "1.10.0")]
1330 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1331 inner: IterMut<'a, K, V>
1334 enum InternalEntry<K, V, M> {
1336 elem: FullBucket<K, V, M>,
1340 elem: VacantEntryState<K, V, M>,
1345 impl<K, V, M> InternalEntry<K, V, M> {
1347 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1349 InternalEntry::Occupied { elem } => Some(elem),
1355 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1357 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1359 InternalEntry::Occupied { elem } => {
1360 Some(Occupied(OccupiedEntry {
1365 InternalEntry::Vacant { hash, elem } => {
1366 Some(Vacant(VacantEntry {
1372 InternalEntry::TableIsEmpty => None
1377 /// A view into a single location in a map, which may be vacant or occupied.
1378 /// This enum is constructed from the [`entry`] method on [`HashMap`].
1380 /// [`HashMap`]: struct.HashMap.html
1381 /// [`entry`]: struct.HashMap.html#method.entry
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub enum Entry<'a, K: 'a, V: 'a> {
1384 /// An occupied Entry.
1385 #[stable(feature = "rust1", since = "1.0.0")]
1387 #[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>
1391 #[stable(feature = "rust1", since = "1.0.0")]
1393 #[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>
1397 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1398 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1401 Vacant(ref v) => f.debug_tuple("Entry")
1404 Occupied(ref o) => f.debug_tuple("Entry")
1411 /// A view into a single occupied location in a HashMap.
1412 /// It is part of the [`Entry`] enum.
1414 /// [`Entry`]: enum.Entry.html
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1418 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1421 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1422 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1424 f.debug_struct("OccupiedEntry")
1425 .field("key", self.key())
1426 .field("value", self.get())
1431 /// A view into a single empty location in a HashMap.
1432 /// It is part of the [`Entry`] enum.
1434 /// [`Entry`]: enum.Entry.html
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1439 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1442 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1443 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1444 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1445 f.debug_tuple("VacantEntry")
1451 /// Possible states of a VacantEntry.
1452 enum VacantEntryState<K, V, M> {
1453 /// The index is occupied, but the key to insert has precedence,
1454 /// and will kick the current one out on insertion.
1455 NeqElem(FullBucket<K, V, M>, usize),
1456 /// The index is genuinely vacant.
1457 NoElem(EmptyBucket<K, V, M>),
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1462 where K: Eq + Hash, S: BuildHasher
1464 type Item = (&'a K, &'a V);
1465 type IntoIter = Iter<'a, K, V>;
1467 fn into_iter(self) -> Iter<'a, K, V> {
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1474 where K: Eq + Hash, S: BuildHasher
1476 type Item = (&'a K, &'a mut V);
1477 type IntoIter = IterMut<'a, K, V>;
1479 fn into_iter(mut self) -> IterMut<'a, K, V> {
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1486 where K: Eq + Hash, S: BuildHasher
1489 type IntoIter = IntoIter<K, V>;
1491 /// Creates a consuming iterator, that is, one that moves each key-value
1492 /// pair out of the map in arbitrary order. The map cannot be used after
1498 /// use std::collections::HashMap;
1500 /// let mut map = HashMap::new();
1501 /// map.insert("a", 1);
1502 /// map.insert("b", 2);
1503 /// map.insert("c", 3);
1505 /// // Not possible with .iter()
1506 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1508 fn into_iter(self) -> IntoIter<K, V> {
1510 inner: self.table.into_iter()
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1517 type Item = (&'a K, &'a V);
1519 #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1520 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1524 #[inline] fn len(&self) -> usize { self.inner.len() }
1527 #[unstable(feature = "fused", issue = "35602")]
1528 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1532 type Item = (&'a K, &'a mut V);
1534 #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1535 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1539 #[inline] fn len(&self) -> usize { self.inner.len() }
1541 #[unstable(feature = "fused", issue = "35602")]
1542 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<K, V> Iterator for IntoIter<K, V> {
1548 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next().map(|(_, k, v)| (k, v)) }
1549 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1553 #[inline] fn len(&self) -> usize { self.inner.len() }
1555 #[unstable(feature = "fused", issue = "35602")]
1556 impl<K, V> FusedIterator for IntoIter<K, V> {}
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1562 #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next().map(|(k, _)| k) }
1563 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1567 #[inline] fn len(&self) -> usize { self.inner.len() }
1569 #[unstable(feature = "fused", issue = "35602")]
1570 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<'a, K, V> Iterator for Values<'a, K, V> {
1576 #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next().map(|(_, v)| v) }
1577 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1581 #[inline] fn len(&self) -> usize { self.inner.len() }
1583 #[unstable(feature = "fused", issue = "35602")]
1584 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1586 #[stable(feature = "map_values_mut", since = "1.10.0")]
1587 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1588 type Item = &'a mut V;
1590 #[inline] fn next(&mut self) -> Option<(&'a mut V)> { self.inner.next().map(|(_, v)| v) }
1591 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1593 #[stable(feature = "map_values_mut", since = "1.10.0")]
1594 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1595 #[inline] fn len(&self) -> usize { self.inner.len() }
1597 #[unstable(feature = "fused", issue = "35602")]
1598 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1604 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next().map(|(_, k, v)| (k, v)) }
1605 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1609 #[inline] fn len(&self) -> usize { self.inner.len() }
1611 #[unstable(feature = "fused", issue = "35602")]
1612 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1614 impl<'a, K, V> Entry<'a, K, V> {
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 /// Ensures a value is in the entry by inserting the default if empty, and returns
1617 /// a mutable reference to the value in the entry.
1622 /// use std::collections::HashMap;
1624 /// let mut map: HashMap<&str, u32> = HashMap::new();
1625 /// map.entry("poneyland").or_insert(12);
1627 /// assert_eq!(map["poneyland"], 12);
1629 /// *map.entry("poneyland").or_insert(12) += 10;
1630 /// assert_eq!(map["poneyland"], 22);
1632 pub fn or_insert(self, default: V) -> &'a mut V {
1634 Occupied(entry) => entry.into_mut(),
1635 Vacant(entry) => entry.insert(default),
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1641 /// and returns a mutable reference to the value in the entry.
1646 /// use std::collections::HashMap;
1648 /// let mut map: HashMap<&str, String> = HashMap::new();
1649 /// let s = "hoho".to_owned();
1651 /// map.entry("poneyland").or_insert_with(|| s);
1653 /// assert_eq!(map["poneyland"], "hoho".to_owned());
1655 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1657 Occupied(entry) => entry.into_mut(),
1658 Vacant(entry) => entry.insert(default()),
1662 /// Returns a reference to this entry's key.
1667 /// use std::collections::HashMap;
1669 /// let mut map: HashMap<&str, u32> = HashMap::new();
1670 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1672 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1673 pub fn key(&self) -> &K {
1675 Occupied(ref entry) => entry.key(),
1676 Vacant(ref entry) => entry.key(),
1681 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1682 /// Gets a reference to the key in the entry.
1687 /// use std::collections::HashMap;
1689 /// let mut map: HashMap<&str, u32> = HashMap::new();
1690 /// map.entry("poneyland").or_insert(12);
1691 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1693 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1694 pub fn key(&self) -> &K {
1698 /// Deprecated, renamed to `remove_entry`
1699 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1700 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
1701 pub fn remove_pair(self) -> (K, V) {
1705 /// Take the ownership of the key and value from the map.
1710 /// use std::collections::HashMap;
1711 /// use std::collections::hash_map::Entry;
1713 /// let mut map: HashMap<&str, u32> = HashMap::new();
1714 /// map.entry("poneyland").or_insert(12);
1716 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1717 /// // We delete the entry from the map.
1718 /// o.remove_entry();
1721 /// assert_eq!(map.contains_key("poneyland"), false);
1723 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
1724 pub fn remove_entry(self) -> (K, V) {
1725 pop_internal(self.elem)
1728 /// Gets a reference to the value in the entry.
1733 /// use std::collections::HashMap;
1734 /// use std::collections::hash_map::Entry;
1736 /// let mut map: HashMap<&str, u32> = HashMap::new();
1737 /// map.entry("poneyland").or_insert(12);
1739 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1740 /// assert_eq!(o.get(), &12);
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 pub fn get(&self) -> &V {
1748 /// Gets a mutable reference to the value in the entry.
1753 /// use std::collections::HashMap;
1754 /// use std::collections::hash_map::Entry;
1756 /// let mut map: HashMap<&str, u32> = HashMap::new();
1757 /// map.entry("poneyland").or_insert(12);
1759 /// assert_eq!(map["poneyland"], 12);
1760 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
1761 /// *o.get_mut() += 10;
1764 /// assert_eq!(map["poneyland"], 22);
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub fn get_mut(&mut self) -> &mut V {
1768 self.elem.read_mut().1
1771 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1772 /// with a lifetime bound to the map itself.
1777 /// use std::collections::HashMap;
1778 /// use std::collections::hash_map::Entry;
1780 /// let mut map: HashMap<&str, u32> = HashMap::new();
1781 /// map.entry("poneyland").or_insert(12);
1783 /// assert_eq!(map["poneyland"], 12);
1784 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1785 /// *o.into_mut() += 10;
1788 /// assert_eq!(map["poneyland"], 22);
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub fn into_mut(self) -> &'a mut V {
1792 self.elem.into_mut_refs().1
1795 /// Sets the value of the entry, and returns the entry's old value.
1800 /// use std::collections::HashMap;
1801 /// use std::collections::hash_map::Entry;
1803 /// let mut map: HashMap<&str, u32> = HashMap::new();
1804 /// map.entry("poneyland").or_insert(12);
1806 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
1807 /// assert_eq!(o.insert(15), 12);
1810 /// assert_eq!(map["poneyland"], 15);
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 pub fn insert(&mut self, mut value: V) -> V {
1814 let old_value = self.get_mut();
1815 mem::swap(&mut value, old_value);
1819 /// Takes the value out of the entry, and returns it.
1824 /// use std::collections::HashMap;
1825 /// use std::collections::hash_map::Entry;
1827 /// let mut map: HashMap<&str, u32> = HashMap::new();
1828 /// map.entry("poneyland").or_insert(12);
1830 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1831 /// assert_eq!(o.remove(), 12);
1834 /// assert_eq!(map.contains_key("poneyland"), false);
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 pub fn remove(self) -> V {
1838 pop_internal(self.elem).1
1841 /// Returns a key that was used for search.
1843 /// The key was retained for further use.
1844 fn take_key(&mut self) -> Option<K> {
1849 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1850 /// Gets a reference to the key that would be used when inserting a value
1851 /// through the `VacantEntry`.
1856 /// use std::collections::HashMap;
1858 /// let mut map: HashMap<&str, u32> = HashMap::new();
1859 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1861 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1862 pub fn key(&self) -> &K {
1866 /// Take ownership of the key.
1871 /// use std::collections::HashMap;
1872 /// use std::collections::hash_map::Entry;
1874 /// let mut map: HashMap<&str, u32> = HashMap::new();
1876 /// if let Entry::Vacant(v) = map.entry("poneyland") {
1880 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
1881 pub fn into_key(self) -> K {
1885 /// Sets the value of the entry with the VacantEntry's key,
1886 /// and returns a mutable reference to it.
1891 /// use std::collections::HashMap;
1892 /// use std::collections::hash_map::Entry;
1894 /// let mut map: HashMap<&str, u32> = HashMap::new();
1896 /// if let Entry::Vacant(o) = map.entry("poneyland") {
1899 /// assert_eq!(map["poneyland"], 37);
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 pub fn insert(self, value: V) -> &'a mut V {
1904 NeqElem(bucket, ib) => {
1905 robin_hood(bucket, ib, self.hash, self.key, value)
1908 bucket.put(self.hash, self.key, value).into_mut_refs().1
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1916 where K: Eq + Hash, S: BuildHasher + Default
1918 fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, S> {
1919 let iterator = iter.into_iter();
1920 let lower = iterator.size_hint().0;
1921 let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
1922 map.extend(iterator);
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1929 where K: Eq + Hash, S: BuildHasher
1931 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1932 for (k, v) in iter {
1938 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1939 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
1940 where K: Eq + Hash + Copy, V: Copy, S: BuildHasher
1942 fn extend<T: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: T) {
1943 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1947 /// `RandomState` is the default state for [`HashMap`] types.
1949 /// A particular instance `RandomState` will create the same instances of
1950 /// [`Hasher`], but the hashers created by two different `RandomState`
1951 /// instances are unlikely to produce the same result for the same values.
1953 /// [`HashMap`]: struct.HashMap.html
1954 /// [`Hasher`]: ../../hash/trait.Hasher.html
1959 /// use std::collections::HashMap;
1960 /// use std::collections::hash_map::RandomState;
1962 /// let s = RandomState::new();
1963 /// let mut map = HashMap::with_hasher(s);
1964 /// map.insert(1, 2);
1967 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1968 pub struct RandomState {
1974 /// Constructs a new `RandomState` that is initialized with random keys.
1979 /// use std::collections::hash_map::RandomState;
1981 /// let s = RandomState::new();
1984 #[allow(deprecated)] // rand
1985 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1986 pub fn new() -> RandomState {
1987 // Historically this function did not cache keys from the OS and instead
1988 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
1989 // was discovered, however, that because we re-seed the thread-local RNG
1990 // from the OS periodically that this can cause excessive slowdown when
1991 // many hash maps are created on a thread. To solve this performance
1992 // trap we cache the first set of randomly generated keys per-thread.
1994 // In doing this, however, we lose the property that all hash maps have
1995 // nondeterministic iteration order as all of those created on the same
1996 // thread would have the same hash keys. This property has been nice in
1997 // the past as it allows for maximal flexibility in the implementation
1998 // of `HashMap` itself.
2000 // The constraint here (if there even is one) is just that maps created
2001 // on the same thread have the same iteration order, and that *may* be
2002 // relied upon even though it is not a documented guarantee at all of
2003 // the `HashMap` type. In any case we've decided that this is reasonable
2004 // for now, so caching keys thread-locally seems fine.
2005 thread_local!(static KEYS: (u64, u64) = {
2006 let r = rand::OsRng::new();
2007 let mut r = r.expect("failed to create an OS RNG");
2011 KEYS.with(|&(k0, k1)| {
2012 RandomState { k0: k0, k1: k1 }
2017 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2018 impl BuildHasher for RandomState {
2019 type Hasher = DefaultHasher;
2021 fn build_hasher(&self) -> DefaultHasher {
2022 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2026 /// The default [`Hasher`] used by [`RandomState`].
2028 /// The internal algorithm is not specified, and so it and its hashes should
2029 /// not be relied upon over releases.
2031 /// [`RandomState`]: struct.RandomState.html
2032 /// [`Hasher`]: ../../hash/trait.Hasher.html
2033 #[unstable(feature = "hashmap_default_hasher", issue = "0")]
2034 pub struct DefaultHasher(SipHasher13);
2036 #[unstable(feature = "hashmap_default_hasher", issue = "0")]
2037 impl Hasher for DefaultHasher {
2039 fn write(&mut self, msg: &[u8]) {
2044 fn finish(&self) -> u64 {
2049 #[stable(feature = "rust1", since = "1.0.0")]
2050 impl Default for RandomState {
2051 /// Constructs a new `RandomState`.
2053 fn default() -> RandomState {
2058 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2059 where K: Eq + Hash + Borrow<Q>, S: BuildHasher, Q: Eq + Hash
2063 fn get(&self, key: &Q) -> Option<&K> {
2064 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2067 fn take(&mut self, key: &Q) -> Option<K> {
2068 if self.table.size() == 0 {
2072 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2075 fn replace(&mut self, key: K) -> Option<K> {
2078 match self.entry(key) {
2079 Occupied(mut occupied) => {
2080 let key = occupied.take_key().unwrap();
2081 Some(mem::replace(occupied.elem.read_mut().0, key))
2092 fn assert_covariance() {
2093 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { v }
2094 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> { v }
2095 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> { v }
2096 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> { v }
2097 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> { v }
2098 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> { v }
2099 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> { v }
2100 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> { v }
2101 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> { v }
2102 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { v }
2103 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2104 -> Drain<'new, &'new str, &'new str> { d }
2110 use super::Entry::{Occupied, Vacant};
2111 use super::RandomState;
2113 use rand::{thread_rng, Rng};
2116 fn test_zero_capacities() {
2117 type HM = HashMap<i32, i32>;
2120 assert_eq!(m.capacity(), 0);
2122 let m = HM::default();
2123 assert_eq!(m.capacity(), 0);
2125 let m = HM::with_hasher(RandomState::new());
2126 assert_eq!(m.capacity(), 0);
2128 let m = HM::with_capacity(0);
2129 assert_eq!(m.capacity(), 0);
2131 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2132 assert_eq!(m.capacity(), 0);
2134 let mut m = HM::new();
2140 assert_eq!(m.capacity(), 0);
2142 let mut m = HM::new();
2144 assert_eq!(m.capacity(), 0);
2148 fn test_create_capacity_zero() {
2149 let mut m = HashMap::with_capacity(0);
2151 assert!(m.insert(1, 1).is_none());
2153 assert!(m.contains_key(&1));
2154 assert!(!m.contains_key(&0));
2159 let mut m = HashMap::new();
2160 assert_eq!(m.len(), 0);
2161 assert!(m.insert(1, 2).is_none());
2162 assert_eq!(m.len(), 1);
2163 assert!(m.insert(2, 4).is_none());
2164 assert_eq!(m.len(), 2);
2165 assert_eq!(*m.get(&1).unwrap(), 2);
2166 assert_eq!(*m.get(&2).unwrap(), 4);
2171 let mut m = HashMap::new();
2172 assert_eq!(m.len(), 0);
2173 assert!(m.insert(1, 2).is_none());
2174 assert_eq!(m.len(), 1);
2175 assert!(m.insert(2, 4).is_none());
2176 assert_eq!(m.len(), 2);
2178 assert_eq!(*m2.get(&1).unwrap(), 2);
2179 assert_eq!(*m2.get(&2).unwrap(), 4);
2180 assert_eq!(m2.len(), 2);
2183 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2185 #[derive(Hash, PartialEq, Eq)]
2191 fn new(k: usize) -> Dropable {
2192 DROP_VECTOR.with(|slot| {
2193 slot.borrow_mut()[k] += 1;
2200 impl Drop for Dropable {
2201 fn drop(&mut self) {
2202 DROP_VECTOR.with(|slot| {
2203 slot.borrow_mut()[self.k] -= 1;
2208 impl Clone for Dropable {
2209 fn clone(&self) -> Dropable {
2210 Dropable::new(self.k)
2216 DROP_VECTOR.with(|slot| {
2217 *slot.borrow_mut() = vec![0; 200];
2221 let mut m = HashMap::new();
2223 DROP_VECTOR.with(|v| {
2225 assert_eq!(v.borrow()[i], 0);
2230 let d1 = Dropable::new(i);
2231 let d2 = Dropable::new(i+100);
2235 DROP_VECTOR.with(|v| {
2237 assert_eq!(v.borrow()[i], 1);
2242 let k = Dropable::new(i);
2243 let v = m.remove(&k);
2245 assert!(v.is_some());
2247 DROP_VECTOR.with(|v| {
2248 assert_eq!(v.borrow()[i], 1);
2249 assert_eq!(v.borrow()[i+100], 1);
2253 DROP_VECTOR.with(|v| {
2255 assert_eq!(v.borrow()[i], 0);
2256 assert_eq!(v.borrow()[i+100], 0);
2260 assert_eq!(v.borrow()[i], 1);
2261 assert_eq!(v.borrow()[i+100], 1);
2266 DROP_VECTOR.with(|v| {
2268 assert_eq!(v.borrow()[i], 0);
2274 fn test_into_iter_drops() {
2275 DROP_VECTOR.with(|v| {
2276 *v.borrow_mut() = vec![0; 200];
2280 let mut hm = HashMap::new();
2282 DROP_VECTOR.with(|v| {
2284 assert_eq!(v.borrow()[i], 0);
2289 let d1 = Dropable::new(i);
2290 let d2 = Dropable::new(i+100);
2294 DROP_VECTOR.with(|v| {
2296 assert_eq!(v.borrow()[i], 1);
2303 // By the way, ensure that cloning doesn't screw up the dropping.
2307 let mut half = hm.into_iter().take(50);
2309 DROP_VECTOR.with(|v| {
2311 assert_eq!(v.borrow()[i], 1);
2315 for _ in half.by_ref() {}
2317 DROP_VECTOR.with(|v| {
2318 let nk = (0..100).filter(|&i| {
2322 let nv = (0..100).filter(|&i| {
2323 v.borrow()[i+100] == 1
2331 DROP_VECTOR.with(|v| {
2333 assert_eq!(v.borrow()[i], 0);
2339 fn test_empty_remove() {
2340 let mut m: HashMap<isize, bool> = HashMap::new();
2341 assert_eq!(m.remove(&0), None);
2345 fn test_empty_entry() {
2346 let mut m: HashMap<isize, bool> = HashMap::new();
2348 Occupied(_) => panic!(),
2351 assert!(*m.entry(0).or_insert(true));
2352 assert_eq!(m.len(), 1);
2356 fn test_empty_iter() {
2357 let mut m: HashMap<isize, bool> = HashMap::new();
2358 assert_eq!(m.drain().next(), None);
2359 assert_eq!(m.keys().next(), None);
2360 assert_eq!(m.values().next(), None);
2361 assert_eq!(m.values_mut().next(), None);
2362 assert_eq!(m.iter().next(), None);
2363 assert_eq!(m.iter_mut().next(), None);
2364 assert_eq!(m.len(), 0);
2365 assert!(m.is_empty());
2366 assert_eq!(m.into_iter().next(), None);
2370 fn test_lots_of_insertions() {
2371 let mut m = HashMap::new();
2373 // Try this a few times to make sure we never screw up the hashmap's
2376 assert!(m.is_empty());
2379 assert!(m.insert(i, i).is_none());
2383 assert_eq!(r, Some(&j));
2386 for j in i+1..1001 {
2388 assert_eq!(r, None);
2392 for i in 1001..2001 {
2393 assert!(!m.contains_key(&i));
2398 assert!(m.remove(&i).is_some());
2401 assert!(!m.contains_key(&j));
2404 for j in i+1..1001 {
2405 assert!(m.contains_key(&j));
2410 assert!(!m.contains_key(&i));
2414 assert!(m.insert(i, i).is_none());
2418 for i in (1..1001).rev() {
2419 assert!(m.remove(&i).is_some());
2422 assert!(!m.contains_key(&j));
2426 assert!(m.contains_key(&j));
2433 fn test_find_mut() {
2434 let mut m = HashMap::new();
2435 assert!(m.insert(1, 12).is_none());
2436 assert!(m.insert(2, 8).is_none());
2437 assert!(m.insert(5, 14).is_none());
2439 match m.get_mut(&5) {
2440 None => panic!(), Some(x) => *x = new
2442 assert_eq!(m.get(&5), Some(&new));
2446 fn test_insert_overwrite() {
2447 let mut m = HashMap::new();
2448 assert!(m.insert(1, 2).is_none());
2449 assert_eq!(*m.get(&1).unwrap(), 2);
2450 assert!(!m.insert(1, 3).is_none());
2451 assert_eq!(*m.get(&1).unwrap(), 3);
2455 fn test_insert_conflicts() {
2456 let mut m = HashMap::with_capacity(4);
2457 assert!(m.insert(1, 2).is_none());
2458 assert!(m.insert(5, 3).is_none());
2459 assert!(m.insert(9, 4).is_none());
2460 assert_eq!(*m.get(&9).unwrap(), 4);
2461 assert_eq!(*m.get(&5).unwrap(), 3);
2462 assert_eq!(*m.get(&1).unwrap(), 2);
2466 fn test_conflict_remove() {
2467 let mut m = HashMap::with_capacity(4);
2468 assert!(m.insert(1, 2).is_none());
2469 assert_eq!(*m.get(&1).unwrap(), 2);
2470 assert!(m.insert(5, 3).is_none());
2471 assert_eq!(*m.get(&1).unwrap(), 2);
2472 assert_eq!(*m.get(&5).unwrap(), 3);
2473 assert!(m.insert(9, 4).is_none());
2474 assert_eq!(*m.get(&1).unwrap(), 2);
2475 assert_eq!(*m.get(&5).unwrap(), 3);
2476 assert_eq!(*m.get(&9).unwrap(), 4);
2477 assert!(m.remove(&1).is_some());
2478 assert_eq!(*m.get(&9).unwrap(), 4);
2479 assert_eq!(*m.get(&5).unwrap(), 3);
2483 fn test_is_empty() {
2484 let mut m = HashMap::with_capacity(4);
2485 assert!(m.insert(1, 2).is_none());
2486 assert!(!m.is_empty());
2487 assert!(m.remove(&1).is_some());
2488 assert!(m.is_empty());
2493 let mut m = HashMap::new();
2495 assert_eq!(m.remove(&1), Some(2));
2496 assert_eq!(m.remove(&1), None);
2501 let mut m = HashMap::with_capacity(4);
2503 assert!(m.insert(i, i*2).is_none());
2505 assert_eq!(m.len(), 32);
2507 let mut observed: u32 = 0;
2510 assert_eq!(*v, *k * 2);
2511 observed |= 1 << *k;
2513 assert_eq!(observed, 0xFFFF_FFFF);
2518 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2519 let map: HashMap<_, _> = vec.into_iter().collect();
2520 let keys: Vec<_> = map.keys().cloned().collect();
2521 assert_eq!(keys.len(), 3);
2522 assert!(keys.contains(&1));
2523 assert!(keys.contains(&2));
2524 assert!(keys.contains(&3));
2529 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2530 let map: HashMap<_, _> = vec.into_iter().collect();
2531 let values: Vec<_> = map.values().cloned().collect();
2532 assert_eq!(values.len(), 3);
2533 assert!(values.contains(&'a'));
2534 assert!(values.contains(&'b'));
2535 assert!(values.contains(&'c'));
2539 fn test_values_mut() {
2540 let vec = vec![(1, 1), (2, 2), (3, 3)];
2541 let mut map: HashMap<_, _> = vec.into_iter().collect();
2542 for value in map.values_mut() {
2543 *value = (*value) * 2
2545 let values: Vec<_> = map.values().cloned().collect();
2546 assert_eq!(values.len(), 3);
2547 assert!(values.contains(&2));
2548 assert!(values.contains(&4));
2549 assert!(values.contains(&6));
2554 let mut m = HashMap::new();
2555 assert!(m.get(&1).is_none());
2559 Some(v) => assert_eq!(*v, 2)
2565 let mut m1 = HashMap::new();
2570 let mut m2 = HashMap::new();
2583 let mut map = HashMap::new();
2584 let empty: HashMap<i32, i32> = HashMap::new();
2589 let map_str = format!("{:?}", map);
2591 assert!(map_str == "{1: 2, 3: 4}" ||
2592 map_str == "{3: 4, 1: 2}");
2593 assert_eq!(format!("{:?}", empty), "{}");
2598 let mut m = HashMap::new();
2600 assert_eq!(m.len(), 0);
2601 assert!(m.is_empty());
2604 let old_raw_cap = m.raw_capacity();
2605 while old_raw_cap == m.raw_capacity() {
2610 assert_eq!(m.len(), i);
2611 assert!(!m.is_empty());
2615 fn test_behavior_resize_policy() {
2616 let mut m = HashMap::new();
2618 assert_eq!(m.len(), 0);
2619 assert_eq!(m.raw_capacity(), 0);
2620 assert!(m.is_empty());
2624 assert!(m.is_empty());
2625 let initial_raw_cap = m.raw_capacity();
2626 m.reserve(initial_raw_cap);
2627 let raw_cap = m.raw_capacity();
2629 assert_eq!(raw_cap, initial_raw_cap * 2);
2632 for _ in 0..raw_cap * 3 / 4 {
2636 // three quarters full
2638 assert_eq!(m.len(), i);
2639 assert_eq!(m.raw_capacity(), raw_cap);
2641 for _ in 0..raw_cap / 4 {
2647 let new_raw_cap = m.raw_capacity();
2648 assert_eq!(new_raw_cap, raw_cap * 2);
2650 for _ in 0..raw_cap / 2 - 1 {
2653 assert_eq!(m.raw_capacity(), new_raw_cap);
2655 // A little more than one quarter full.
2657 assert_eq!(m.raw_capacity(), raw_cap);
2658 // again, a little more than half full
2659 for _ in 0..raw_cap / 2 - 1 {
2665 assert_eq!(m.len(), i);
2666 assert!(!m.is_empty());
2667 assert_eq!(m.raw_capacity(), initial_raw_cap);
2671 fn test_reserve_shrink_to_fit() {
2672 let mut m = HashMap::new();
2675 assert!(m.capacity() >= m.len());
2681 let usable_cap = m.capacity();
2682 for i in 128..(128 + 256) {
2684 assert_eq!(m.capacity(), usable_cap);
2687 for i in 100..(128 + 256) {
2688 assert_eq!(m.remove(&i), Some(i));
2692 assert_eq!(m.len(), 100);
2693 assert!(!m.is_empty());
2694 assert!(m.capacity() >= m.len());
2697 assert_eq!(m.remove(&i), Some(i));
2702 assert_eq!(m.len(), 1);
2703 assert!(m.capacity() >= m.len());
2704 assert_eq!(m.remove(&0), Some(0));
2708 fn test_from_iter() {
2709 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2711 let map: HashMap<_, _> = xs.iter().cloned().collect();
2713 for &(k, v) in &xs {
2714 assert_eq!(map.get(&k), Some(&v));
2719 fn test_size_hint() {
2720 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2722 let map: HashMap<_, _> = xs.iter().cloned().collect();
2724 let mut iter = map.iter();
2726 for _ in iter.by_ref().take(3) {}
2728 assert_eq!(iter.size_hint(), (3, Some(3)));
2732 fn test_iter_len() {
2733 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2735 let map: HashMap<_, _> = xs.iter().cloned().collect();
2737 let mut iter = map.iter();
2739 for _ in iter.by_ref().take(3) {}
2741 assert_eq!(iter.len(), 3);
2745 fn test_mut_size_hint() {
2746 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2748 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2750 let mut iter = map.iter_mut();
2752 for _ in iter.by_ref().take(3) {}
2754 assert_eq!(iter.size_hint(), (3, Some(3)));
2758 fn test_iter_mut_len() {
2759 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2761 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2763 let mut iter = map.iter_mut();
2765 for _ in iter.by_ref().take(3) {}
2767 assert_eq!(iter.len(), 3);
2772 let mut map = HashMap::new();
2778 assert_eq!(map[&2], 1);
2783 fn test_index_nonexistent() {
2784 let mut map = HashMap::new();
2795 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2797 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2799 // Existing key (insert)
2800 match map.entry(1) {
2801 Vacant(_) => unreachable!(),
2802 Occupied(mut view) => {
2803 assert_eq!(view.get(), &10);
2804 assert_eq!(view.insert(100), 10);
2807 assert_eq!(map.get(&1).unwrap(), &100);
2808 assert_eq!(map.len(), 6);
2811 // Existing key (update)
2812 match map.entry(2) {
2813 Vacant(_) => unreachable!(),
2814 Occupied(mut view) => {
2815 let v = view.get_mut();
2816 let new_v = (*v) * 10;
2820 assert_eq!(map.get(&2).unwrap(), &200);
2821 assert_eq!(map.len(), 6);
2823 // Existing key (take)
2824 match map.entry(3) {
2825 Vacant(_) => unreachable!(),
2827 assert_eq!(view.remove(), 30);
2830 assert_eq!(map.get(&3), None);
2831 assert_eq!(map.len(), 5);
2834 // Inexistent key (insert)
2835 match map.entry(10) {
2836 Occupied(_) => unreachable!(),
2838 assert_eq!(*view.insert(1000), 1000);
2841 assert_eq!(map.get(&10).unwrap(), &1000);
2842 assert_eq!(map.len(), 6);
2846 fn test_entry_take_doesnt_corrupt() {
2847 #![allow(deprecated)] //rand
2849 fn check(m: &HashMap<isize, ()>) {
2851 assert!(m.contains_key(k),
2852 "{} is in keys() but not in the map?", k);
2856 let mut m = HashMap::new();
2857 let mut rng = thread_rng();
2859 // Populate the map with some items.
2861 let x = rng.gen_range(-10, 10);
2866 let x = rng.gen_range(-10, 10);
2870 println!("{}: remove {}", i, x);
2880 fn test_extend_ref() {
2881 let mut a = HashMap::new();
2883 let mut b = HashMap::new();
2885 b.insert(3, "three");
2889 assert_eq!(a.len(), 3);
2890 assert_eq!(a[&1], "one");
2891 assert_eq!(a[&2], "two");
2892 assert_eq!(a[&3], "three");
2896 fn test_capacity_not_less_than_len() {
2897 let mut a = HashMap::new();
2905 assert!(a.capacity() > a.len());
2907 let free = a.capacity() - a.len();
2913 assert_eq!(a.len(), a.capacity());
2915 // Insert at capacity should cause allocation.
2917 assert!(a.capacity() > a.len());
2921 fn test_occupied_entry_key() {
2922 let mut a = HashMap::new();
2923 let key = "hello there";
2924 let value = "value goes here";
2925 assert!(a.is_empty());
2926 a.insert(key.clone(), value.clone());
2927 assert_eq!(a.len(), 1);
2928 assert_eq!(a[key], value);
2930 match a.entry(key.clone()) {
2931 Vacant(_) => panic!(),
2932 Occupied(e) => assert_eq!(key, *e.key()),
2934 assert_eq!(a.len(), 1);
2935 assert_eq!(a[key], value);
2939 fn test_vacant_entry_key() {
2940 let mut a = HashMap::new();
2941 let key = "hello there";
2942 let value = "value goes here";
2944 assert!(a.is_empty());
2945 match a.entry(key.clone()) {
2946 Occupied(_) => panic!(),
2948 assert_eq!(key, *e.key());
2949 e.insert(value.clone());
2952 assert_eq!(a.len(), 1);
2953 assert_eq!(a[key], value);