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;
19 use mem::{self, replace};
20 use ops::{Deref, Index};
21 use rand::{self, Rng};
32 use super::table::BucketState::{
37 const INITIAL_LOG2_CAP: usize = 5;
38 const INITIAL_CAPACITY: usize = 1 << INITIAL_LOG2_CAP; // 2^5
40 /// The default behavior of HashMap implements a load factor of 90.9%.
41 /// This behavior is characterized by the following condition:
43 /// - if size > 0.909 * capacity: grow the map
45 struct DefaultResizePolicy;
47 impl DefaultResizePolicy {
48 fn new() -> DefaultResizePolicy {
53 fn min_capacity(&self, usable_size: usize) -> usize {
54 // Here, we are rephrasing the logic by specifying the lower limit
57 // - if `cap < size * 1.1`: grow the map
61 /// An inverse of `min_capacity`, approximately.
63 fn usable_capacity(&self, cap: usize) -> usize {
64 // As the number of entries approaches usable capacity,
65 // min_capacity(size) must be smaller than the internal capacity,
66 // so that the map is not resized:
67 // `min_capacity(usable_capacity(x)) <= x`.
68 // The left-hand side can only be smaller due to flooring by integer
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: (cap * den + den - 1) / num
76 (cap * 10 + 10 - 1) / 11
81 fn test_resize_policy() {
82 let rp = DefaultResizePolicy;
84 assert!(rp.min_capacity(rp.usable_capacity(n)) <= n);
85 assert!(rp.usable_capacity(rp.min_capacity(n)) <= n);
89 // The main performance trick in this hashmap is called Robin Hood Hashing.
90 // It gains its excellent performance from one essential operation:
92 // If an insertion collides with an existing element, and that element's
93 // "probe distance" (how far away the element is from its ideal location)
94 // is higher than how far we've already probed, swap the elements.
96 // This massively lowers variance in probe distance, and allows us to get very
97 // high load factors with good performance. The 90% load factor I use is rather
100 // > Why a load factor of approximately 90%?
102 // In general, all the distances to initial buckets will converge on the mean.
103 // At a load factor of α, the odds of finding the target bucket after k
104 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
105 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
106 // this down to make the math easier on the CPU and avoid its FPU.
107 // Since on average we start the probing in the middle of a cache line, this
108 // strategy pulls in two cache lines of hashes on every lookup. I think that's
109 // pretty good, but if you want to trade off some space, it could go down to one
110 // cache line on average with an α of 0.84.
112 // > Wait, what? Where did you get 1-α^k from?
114 // On the first probe, your odds of a collision with an existing element is α.
115 // The odds of doing this twice in a row is approximately α^2. For three times,
116 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
117 // colliding after k tries is 1-α^k.
119 // The paper from 1986 cited below mentions an implementation which keeps track
120 // of the distance-to-initial-bucket histogram. This approach is not suitable
121 // for modern architectures because it requires maintaining an internal data
122 // structure. This allows very good first guesses, but we are most concerned
123 // with guessing entire cache lines, not individual indexes. Furthermore, array
124 // accesses are no longer linear and in one direction, as we have now. There
125 // is also memory and cache pressure that this would entail that would be very
126 // difficult to properly see in a microbenchmark.
128 // ## Future Improvements (FIXME!)
130 // Allow the load factor to be changed dynamically and/or at initialization.
132 // Also, would it be possible for us to reuse storage when growing the
133 // underlying table? This is exactly the use case for 'realloc', and may
134 // be worth exploring.
136 // ## Future Optimizations (FIXME!)
138 // Another possible design choice that I made without any real reason is
139 // parameterizing the raw table over keys and values. Technically, all we need
140 // is the size and alignment of keys and values, and the code should be just as
141 // efficient (well, we might need one for power-of-two size and one for not...).
142 // This has the potential to reduce code bloat in rust executables, without
143 // really losing anything except 4 words (key size, key alignment, val size,
144 // val alignment) which can be passed in to every call of a `RawTable` function.
145 // This would definitely be an avenue worth exploring if people start complaining
146 // about the size of rust executables.
148 // Annotate exceedingly likely branches in `table::make_hash`
149 // and `search_hashed` to reduce instruction cache pressure
150 // and mispredictions once it becomes possible (blocked on issue #11092).
152 // Shrinking the table could simply reallocate in place after moving buckets
153 // to the first half.
155 // The growth algorithm (fragment of the Proof of Correctness)
156 // --------------------
158 // The growth algorithm is basically a fast path of the naive reinsertion-
159 // during-resize algorithm. Other paths should never be taken.
161 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
162 // by allocating a new table of capacity `2n`, and then individually reinsert
163 // each element in the old table into the new one. This guarantees that the
164 // new table is a valid robin hood hashtable with all the desired statistical
165 // properties. Remark that the order we reinsert the elements in should not
166 // matter. For simplicity and efficiency, we will consider only linear
167 // reinsertions, which consist of reinserting all elements in the old table
168 // into the new one by increasing order of index. However we will not be
169 // starting our reinsertions from index 0 in general. If we start from index
170 // i, for the purpose of reinsertion we will consider all elements with real
171 // index j < i to have virtual index n + j.
173 // Our hash generation scheme consists of generating a 64-bit hash and
174 // truncating the most significant bits. When moving to the new table, we
175 // simply introduce a new bit to the front of the hash. Therefore, if an
176 // elements has ideal index i in the old table, it can have one of two ideal
177 // locations in the new table. If the new bit is 0, then the new ideal index
178 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
179 // we are producing two independent tables of size n, and for each element we
180 // independently choose which table to insert it into with equal probability.
181 // However the rather than wrapping around themselves on overflowing their
182 // indexes, the first table overflows into the first, and the first into the
183 // second. Visually, our new table will look something like:
185 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
187 // Where x's are elements inserted into the first table, y's are elements
188 // inserted into the second, and _'s are empty sections. We now define a few
189 // key concepts that we will use later. Note that this is a very abstract
190 // perspective of the table. A real resized table would be at least half
193 // Theorem: A linear robin hood reinsertion from the first ideal element
194 // produces identical results to a linear naive reinsertion from the same
197 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
199 /// A hash map implementation which uses linear probing with Robin
200 /// Hood bucket stealing.
202 /// The hashes are all keyed by the thread-local random number generator
203 /// on creation by default. This means that the ordering of the keys is
204 /// randomized, but makes the tables more resistant to
205 /// denial-of-service attacks (Hash DoS). No guarantees are made to the
206 /// quality of the random data. The implementation uses the best available
207 /// random data from your platform at the time of creation. This behavior
208 /// can be overridden with one of the constructors.
210 /// It is required that the keys implement the `Eq` and `Hash` traits, although
211 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
212 /// If you implement these yourself, it is important that the following
216 /// k1 == k2 -> hash(k1) == hash(k2)
219 /// In other words, if two keys are equal, their hashes must be equal.
221 /// It is a logic error for a key to be modified in such a way that the key's
222 /// hash, as determined by the `Hash` trait, or its equality, as determined by
223 /// the `Eq` trait, changes while it is in the map. This is normally only
224 /// possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
226 /// Relevant papers/articles:
228 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
229 /// 2. Emmanuel Goossaert. ["Robin Hood
230 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
231 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
232 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
237 /// use std::collections::HashMap;
239 /// // type inference lets us omit an explicit type signature (which
240 /// // would be `HashMap<&str, &str>` in this example).
241 /// let mut book_reviews = HashMap::new();
243 /// // review some books.
244 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
245 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
246 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
247 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
249 /// // check for a specific one.
250 /// if !book_reviews.contains_key("Les Misérables") {
251 /// println!("We've got {} reviews, but Les Misérables ain't one.",
252 /// book_reviews.len());
255 /// // oops, this review has a lot of spelling mistakes, let's delete it.
256 /// book_reviews.remove("The Adventures of Sherlock Holmes");
258 /// // look up the values associated with some keys.
259 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
260 /// for book in &to_find {
261 /// match book_reviews.get(book) {
262 /// Some(review) => println!("{}: {}", book, review),
263 /// None => println!("{} is unreviewed.", book)
267 /// // iterate over everything.
268 /// for (book, review) in &book_reviews {
269 /// println!("{}: \"{}\"", book, review);
273 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
274 /// for more complex methods of getting, setting, updating and removing keys and
278 /// use std::collections::HashMap;
280 /// // type inference lets us omit an explicit type signature (which
281 /// // would be `HashMap<&str, u8>` in this example).
282 /// let mut player_stats = HashMap::new();
284 /// fn random_stat_buff() -> u8 {
285 /// // could actually return some random value here - let's just return
286 /// // some fixed value for now
290 /// // insert a key only if it doesn't already exist
291 /// player_stats.entry("health").or_insert(100);
293 /// // insert a key using a function that provides a new value only if it
294 /// // doesn't already exist
295 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
297 /// // update a key, guarding against the key possibly not being set
298 /// let stat = player_stats.entry("attack").or_insert(100);
299 /// *stat += random_stat_buff();
302 /// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
303 /// We must also derive `PartialEq`.
306 /// use std::collections::HashMap;
308 /// #[derive(Hash, Eq, PartialEq, Debug)]
315 /// /// Create a new Viking.
316 /// fn new(name: &str, country: &str) -> Viking {
317 /// Viking { name: name.to_string(), country: country.to_string() }
321 /// // Use a HashMap to store the vikings' health points.
322 /// let mut vikings = HashMap::new();
324 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
325 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
326 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
328 /// // Use derived implementation to print the status of the vikings.
329 /// for (viking, health) in &vikings {
330 /// println!("{:?} has {} hp", viking, health);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub struct HashMap<K, V, S = RandomState> {
336 // All hashes are keyed on these values, to prevent hash collision attacks.
339 table: RawTable<K, V>,
341 resize_policy: DefaultResizePolicy,
344 /// Search for a pre-hashed key.
346 fn search_hashed<K, V, M, F>(table: M,
349 -> InternalEntry<K, V, M> where
350 M: Deref<Target=RawTable<K, V>>,
351 F: FnMut(&K) -> bool,
353 // This is the only function where capacity can be zero. To avoid
354 // undefined behavior when Bucket::new gets the raw bucket in this
355 // case, immediately return the appropriate search result.
356 if table.capacity() == 0 {
357 return InternalEntry::TableIsEmpty;
360 let size = table.size() as isize;
361 let mut probe = Bucket::new(table, hash);
362 let ib = probe.index() as isize;
365 let full = match probe.peek() {
368 return InternalEntry::Vacant {
370 elem: NoElem(bucket),
373 Full(bucket) => bucket
376 let robin_ib = full.index() as isize - full.displacement() as isize;
379 // Found a luckier bucket than me.
380 // We can finish the search early if we hit any bucket
381 // with a lower distance to initial bucket than we've probed.
382 return InternalEntry::Vacant {
384 elem: NeqElem(full, robin_ib as usize),
388 // If the hash doesn't match, it can't be this one..
389 if hash == full.hash() {
390 // If the key doesn't match, it can't be this one..
391 if is_match(full.read().0) {
392 return InternalEntry::Occupied {
399 debug_assert!(probe.index() as isize != ib + size + 1);
403 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
404 let (empty, retkey, retval) = starting_bucket.take();
405 let mut gap = match empty.gap_peek() {
407 None => return (retkey, retval)
410 while gap.full().displacement() != 0 {
411 gap = match gap.shift() {
417 // Now we've done all our shifting. Return the value we grabbed earlier.
421 /// Perform robin hood bucket stealing at the given `bucket`. You must
422 /// also pass the position of that bucket's initial bucket so we don't have
423 /// to recalculate it.
425 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
426 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
432 let starting_index = bucket.index();
433 let size = bucket.table().size();
434 // Save the *starting point*.
435 let mut bucket = bucket.stash();
436 // There can be at most `size - dib` buckets to displace, because
437 // in the worst case, there are `size` elements and we already are
438 // `displacement` buckets away from the initial one.
439 let idx_end = starting_index + size - bucket.displacement();
442 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
448 let probe = bucket.next();
449 debug_assert!(probe.index() != idx_end);
451 let full_bucket = match probe.peek() {
454 let bucket = bucket.put(hash, key, val);
455 // Now that it's stolen, just read the value's pointer
456 // right out of the table! Go back to the *starting point*.
458 // This use of `into_table` is misleading. It turns the
459 // bucket, which is a FullBucket on top of a
460 // FullBucketMut, into just one FullBucketMut. The "table"
461 // refers to the inner FullBucketMut in this context.
462 return bucket.into_table().into_mut_refs().1;
464 Full(bucket) => bucket
467 let probe_ib = full_bucket.index() - full_bucket.displacement();
469 bucket = full_bucket;
471 // Robin hood! Steal the spot.
480 impl<K, V, S> HashMap<K, V, S>
481 where K: Eq + Hash, S: BuildHasher
483 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
484 table::make_hash(&self.hash_builder, x)
487 /// Search for a key, yielding the index if it's found in the hashtable.
488 /// If you already have the hash for the key lying around, use
491 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
492 where K: Borrow<Q>, Q: Eq + Hash
494 let hash = self.make_hash(q);
495 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
499 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
500 where K: Borrow<Q>, Q: Eq + Hash
502 let hash = self.make_hash(q);
503 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
506 // The caller should ensure that invariants by Robin Hood Hashing hold.
507 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
508 let cap = self.table.capacity();
509 let mut buckets = Bucket::new(&mut self.table, hash);
510 let ib = buckets.index();
512 while buckets.index() != ib + cap {
513 // We don't need to compare hashes for value swap.
514 // Not even DIBs for Robin Hood.
515 buckets = match buckets.peek() {
517 empty.put(hash, k, v);
520 Full(b) => b.into_bucket()
524 panic!("Internal HashMap error: Out of space.");
528 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
529 /// Creates an empty HashMap.
534 /// use std::collections::HashMap;
535 /// let mut map: HashMap<&str, isize> = HashMap::new();
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn new() -> HashMap<K, V, RandomState> {
543 /// Creates an empty hash map with the given initial capacity.
548 /// use std::collections::HashMap;
549 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
554 HashMap::with_capacity_and_hasher(capacity, Default::default())
558 impl<K, V, S> HashMap<K, V, S>
559 where K: Eq + Hash, S: BuildHasher
561 /// Creates an empty hashmap which will use the given hash builder to hash
564 /// The created map has the default initial capacity.
566 /// Warning: `hash_builder` is normally randomly generated, and
567 /// is designed to allow HashMaps to be resistant to attacks that
568 /// cause many collisions and very poor performance. Setting it
569 /// manually using this function can expose a DoS attack vector.
574 /// use std::collections::HashMap;
575 /// use std::collections::hash_map::RandomState;
577 /// let s = RandomState::new();
578 /// let mut map = HashMap::with_hasher(s);
579 /// map.insert(1, 2);
582 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
583 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
585 hash_builder: hash_builder,
586 resize_policy: DefaultResizePolicy::new(),
587 table: RawTable::new(0),
591 /// Creates an empty HashMap with space for at least `capacity`
592 /// elements, using `hasher` to hash the keys.
594 /// Warning: `hasher` is normally randomly generated, and
595 /// is designed to allow HashMaps to be resistant to attacks that
596 /// cause many collisions and very poor performance. Setting it
597 /// manually using this function can expose a DoS attack vector.
602 /// use std::collections::HashMap;
603 /// use std::collections::hash_map::RandomState;
605 /// let s = RandomState::new();
606 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
607 /// map.insert(1, 2);
610 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
611 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S)
612 -> HashMap<K, V, S> {
613 let resize_policy = DefaultResizePolicy::new();
614 let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
615 let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
616 assert!(internal_cap >= capacity, "capacity overflow");
618 hash_builder: hash_builder,
619 resize_policy: resize_policy,
620 table: RawTable::new(internal_cap),
624 /// Returns a reference to the map's hasher.
625 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
626 pub fn hasher(&self) -> &S {
630 /// Returns the number of elements the map can hold without reallocating.
632 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
633 /// more, but is guaranteed to be able to hold at least this many.
638 /// use std::collections::HashMap;
639 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
640 /// assert!(map.capacity() >= 100);
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn capacity(&self) -> usize {
645 self.resize_policy.usable_capacity(self.table.capacity())
648 /// Reserves capacity for at least `additional` more elements to be inserted
649 /// in the `HashMap`. The collection may reserve more space to avoid
650 /// frequent reallocations.
654 /// Panics if the new allocation size overflows `usize`.
659 /// use std::collections::HashMap;
660 /// let mut map: HashMap<&str, isize> = HashMap::new();
663 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn reserve(&mut self, additional: usize) {
665 let new_size = self.len().checked_add(additional).expect("capacity overflow");
666 let min_cap = self.resize_policy.min_capacity(new_size);
668 // An invalid value shouldn't make us run out of space. This includes
669 // an overflow check.
670 assert!(new_size <= min_cap);
672 if self.table.capacity() < min_cap {
673 let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
674 self.resize(new_capacity);
678 /// Resizes the internal vectors to a new capacity. It's your responsibility to:
679 /// 1) Make sure the new capacity is enough for all the elements, accounting
680 /// for the load factor.
681 /// 2) Ensure new_capacity is a power of two or zero.
682 fn resize(&mut self, new_capacity: usize) {
683 assert!(self.table.size() <= new_capacity);
684 assert!(new_capacity.is_power_of_two() || new_capacity == 0);
686 let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
687 let old_size = old_table.size();
689 if old_table.capacity() == 0 || old_table.size() == 0 {
694 // Specialization of the other branch.
695 let mut bucket = Bucket::first(&mut old_table);
697 // "So a few of the first shall be last: for many be called,
700 // We'll most likely encounter a few buckets at the beginning that
701 // have their initial buckets near the end of the table. They were
702 // placed at the beginning as the probe wrapped around the table
703 // during insertion. We must skip forward to a bucket that won't
704 // get reinserted too early and won't unfairly steal others spot.
705 // This eliminates the need for robin hood.
707 bucket = match bucket.peek() {
709 if full.displacement() == 0 {
710 // This bucket occupies its ideal spot.
711 // It indicates the start of another "cluster".
712 bucket = full.into_bucket();
715 // Leaving this bucket in the last cluster for later.
719 // Encountered a hole between clusters.
726 // This is how the buckets might be laid out in memory:
727 // ($ marks an initialized bucket)
729 // |$$$_$$$$$$_$$$$$|
731 // But we've skipped the entire initial cluster of buckets
732 // and will continue iteration in this order:
735 // ^ wrap around once end is reached
738 // ^ exit once table.size == 0
740 bucket = match bucket.peek() {
742 let h = bucket.hash();
743 let (b, k, v) = bucket.take();
744 self.insert_hashed_ordered(h, k, v);
745 if b.table().size() == 0 {
750 Empty(b) => b.into_bucket()
755 assert_eq!(self.table.size(), old_size);
758 /// Shrinks the capacity of the map as much as possible. It will drop
759 /// down as much as possible while maintaining the internal rules
760 /// and possibly leaving some space in accordance with the resize policy.
765 /// use std::collections::HashMap;
767 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
768 /// map.insert(1, 2);
769 /// map.insert(3, 4);
770 /// assert!(map.capacity() >= 100);
771 /// map.shrink_to_fit();
772 /// assert!(map.capacity() >= 2);
774 #[stable(feature = "rust1", since = "1.0.0")]
775 pub fn shrink_to_fit(&mut self) {
776 let min_capacity = self.resize_policy.min_capacity(self.len());
777 let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
779 // An invalid value shouldn't make us run out of space.
780 debug_assert!(self.len() <= min_capacity);
782 if self.table.capacity() != min_capacity {
783 let old_table = replace(&mut self.table, RawTable::new(min_capacity));
784 let old_size = old_table.size();
786 // Shrink the table. Naive algorithm for resizing:
787 for (h, k, v) in old_table.into_iter() {
788 self.insert_hashed_nocheck(h, k, v);
791 debug_assert_eq!(self.table.size(), old_size);
795 /// Insert a pre-hashed key-value pair, without first checking
796 /// that there's enough room in the buckets. Returns a reference to the
797 /// newly insert value.
799 /// If the key already exists, the hashtable will be returned untouched
800 /// and a reference to the existing element will be returned.
801 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
802 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
804 Some(Occupied(mut elem)) => {
807 Some(Vacant(elem)) => {
817 /// An iterator visiting all keys in arbitrary order.
818 /// Iterator element type is `&'a K`.
823 /// use std::collections::HashMap;
825 /// let mut map = HashMap::new();
826 /// map.insert("a", 1);
827 /// map.insert("b", 2);
828 /// map.insert("c", 3);
830 /// for key in map.keys() {
831 /// println!("{}", key);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn keys(&self) -> Keys<K, V> {
836 Keys { inner: self.iter() }
839 /// An iterator visiting all values in arbitrary order.
840 /// Iterator element type is `&'a V`.
845 /// use std::collections::HashMap;
847 /// let mut map = HashMap::new();
848 /// map.insert("a", 1);
849 /// map.insert("b", 2);
850 /// map.insert("c", 3);
852 /// for val in map.values() {
853 /// println!("{}", val);
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn values(&self) -> Values<K, V> {
858 Values { inner: self.iter() }
861 /// An iterator visiting all values mutably in arbitrary order.
862 /// Iterator element type is `&'a mut V`.
867 /// use std::collections::HashMap;
869 /// let mut map = HashMap::new();
871 /// map.insert("a", 1);
872 /// map.insert("b", 2);
873 /// map.insert("c", 3);
875 /// for val in map.values_mut() {
876 /// *val = *val + 10;
879 /// for val in map.values() {
880 /// print!("{}", val);
883 #[stable(feature = "map_values_mut", since = "1.10.0")]
884 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
885 ValuesMut { inner: self.iter_mut() }
888 /// An iterator visiting all key-value pairs in arbitrary order.
889 /// Iterator element type is `(&'a K, &'a V)`.
894 /// use std::collections::HashMap;
896 /// let mut map = HashMap::new();
897 /// map.insert("a", 1);
898 /// map.insert("b", 2);
899 /// map.insert("c", 3);
901 /// for (key, val) in map.iter() {
902 /// println!("key: {} val: {}", key, val);
905 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn iter(&self) -> Iter<K, V> {
907 Iter { inner: self.table.iter() }
910 /// An iterator visiting all key-value pairs in arbitrary order,
911 /// with mutable references to the values.
912 /// Iterator element type is `(&'a K, &'a mut V)`.
917 /// use std::collections::HashMap;
919 /// let mut map = HashMap::new();
920 /// map.insert("a", 1);
921 /// map.insert("b", 2);
922 /// map.insert("c", 3);
924 /// // Update all values
925 /// for (_, val) in map.iter_mut() {
929 /// for (key, val) in &map {
930 /// println!("key: {} val: {}", key, val);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn iter_mut(&mut self) -> IterMut<K, V> {
935 IterMut { inner: self.table.iter_mut() }
938 /// Gets the given key's corresponding entry in the map for in-place manipulation.
943 /// use std::collections::HashMap;
945 /// let mut letters = HashMap::new();
947 /// for ch in "a short treatise on fungi".chars() {
948 /// let counter = letters.entry(ch).or_insert(0);
952 /// assert_eq!(letters[&'s'], 2);
953 /// assert_eq!(letters[&'t'], 3);
954 /// assert_eq!(letters[&'u'], 1);
955 /// assert_eq!(letters.get(&'y'), None);
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn entry(&mut self, key: K) -> Entry<K, V> {
961 self.search_mut(&key).into_entry(key).expect("unreachable")
964 /// Returns the number of elements in the map.
969 /// use std::collections::HashMap;
971 /// let mut a = HashMap::new();
972 /// assert_eq!(a.len(), 0);
973 /// a.insert(1, "a");
974 /// assert_eq!(a.len(), 1);
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn len(&self) -> usize { self.table.size() }
979 /// Returns true if the map contains no elements.
984 /// use std::collections::HashMap;
986 /// let mut a = HashMap::new();
987 /// assert!(a.is_empty());
988 /// a.insert(1, "a");
989 /// assert!(!a.is_empty());
992 #[stable(feature = "rust1", since = "1.0.0")]
993 pub fn is_empty(&self) -> bool { self.len() == 0 }
995 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
996 /// allocated memory for reuse.
1001 /// use std::collections::HashMap;
1003 /// let mut a = HashMap::new();
1004 /// a.insert(1, "a");
1005 /// a.insert(2, "b");
1007 /// for (k, v) in a.drain().take(1) {
1008 /// assert!(k == 1 || k == 2);
1009 /// assert!(v == "a" || v == "b");
1012 /// assert!(a.is_empty());
1015 #[stable(feature = "drain", since = "1.6.0")]
1016 pub fn drain(&mut self) -> Drain<K, V> {
1018 inner: self.table.drain(),
1022 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1028 /// use std::collections::HashMap;
1030 /// let mut a = HashMap::new();
1031 /// a.insert(1, "a");
1033 /// assert!(a.is_empty());
1035 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn clear(&mut self) {
1041 /// Returns a reference to the value corresponding to the key.
1043 /// The key may be any borrowed form of the map's key type, but
1044 /// `Hash` and `Eq` on the borrowed form *must* match those for
1050 /// use std::collections::HashMap;
1052 /// let mut map = HashMap::new();
1053 /// map.insert(1, "a");
1054 /// assert_eq!(map.get(&1), Some(&"a"));
1055 /// assert_eq!(map.get(&2), None);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1059 where K: Borrow<Q>, Q: Hash + Eq
1061 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1064 /// Returns true if the map contains a value for the specified key.
1066 /// The key may be any borrowed form of the map's key type, but
1067 /// `Hash` and `Eq` on the borrowed form *must* match those for
1073 /// use std::collections::HashMap;
1075 /// let mut map = HashMap::new();
1076 /// map.insert(1, "a");
1077 /// assert_eq!(map.contains_key(&1), true);
1078 /// assert_eq!(map.contains_key(&2), false);
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1082 where K: Borrow<Q>, Q: Hash + Eq
1084 self.search(k).into_occupied_bucket().is_some()
1087 /// Returns a mutable reference to the value corresponding to the key.
1089 /// The key may be any borrowed form of the map's key type, but
1090 /// `Hash` and `Eq` on the borrowed form *must* match those for
1096 /// use std::collections::HashMap;
1098 /// let mut map = HashMap::new();
1099 /// map.insert(1, "a");
1100 /// if let Some(x) = map.get_mut(&1) {
1103 /// assert_eq!(map[&1], "b");
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1107 where K: Borrow<Q>, Q: Hash + Eq
1109 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1112 /// Inserts a key-value pair into the map.
1114 /// If the map did not have this key present, `None` is returned.
1116 /// If the map did have this key present, the value is updated, and the old
1117 /// value is returned. The key is not updated, though; this matters for
1118 /// types that can be `==` without being identical. See the [module-level
1119 /// documentation] for more.
1121 /// [module-level documentation]: index.html#insert-and-complex-keys
1126 /// use std::collections::HashMap;
1128 /// let mut map = HashMap::new();
1129 /// assert_eq!(map.insert(37, "a"), None);
1130 /// assert_eq!(map.is_empty(), false);
1132 /// map.insert(37, "b");
1133 /// assert_eq!(map.insert(37, "c"), Some("b"));
1134 /// assert_eq!(map[&37], "c");
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1138 let hash = self.make_hash(&k);
1140 self.insert_hashed_nocheck(hash, k, v)
1143 /// Removes a key from the map, returning the value at the key if the key
1144 /// was previously in the map.
1146 /// The key may be any borrowed form of the map's key type, but
1147 /// `Hash` and `Eq` on the borrowed form *must* match those for
1153 /// use std::collections::HashMap;
1155 /// let mut map = HashMap::new();
1156 /// map.insert(1, "a");
1157 /// assert_eq!(map.remove(&1), Some("a"));
1158 /// assert_eq!(map.remove(&1), None);
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1162 where K: Borrow<Q>, Q: Hash + Eq
1164 if self.table.size() == 0 {
1168 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 impl<K, V, S> PartialEq for HashMap<K, V, S>
1174 where K: Eq + Hash, V: PartialEq, S: BuildHasher
1176 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1177 if self.len() != other.len() { return false; }
1179 self.iter().all(|(key, value)|
1180 other.get(key).map_or(false, |v| *value == *v)
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<K, V, S> Eq for HashMap<K, V, S>
1187 where K: Eq + Hash, V: Eq, S: BuildHasher
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<K, V, S> Debug for HashMap<K, V, S>
1192 where K: Eq + Hash + Debug, V: Debug, S: BuildHasher
1194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1195 f.debug_map().entries(self.iter()).finish()
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<K, V, S> Default for HashMap<K, V, S>
1202 S: BuildHasher + Default,
1204 fn default() -> HashMap<K, V, S> {
1205 HashMap::with_hasher(Default::default())
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1211 where K: Eq + Hash + Borrow<Q>,
1218 fn index(&self, index: &Q) -> &V {
1219 self.get(index).expect("no entry found for key")
1223 /// HashMap iterator.
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub struct Iter<'a, K: 'a, V: 'a> {
1226 inner: table::Iter<'a, K, V>
1229 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<'a, K, V> Clone for Iter<'a, K, V> {
1232 fn clone(&self) -> Iter<'a, K, V> {
1234 inner: self.inner.clone()
1239 /// HashMap mutable values iterator.
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 pub struct IterMut<'a, K: 'a, V: 'a> {
1242 inner: table::IterMut<'a, K, V>
1245 /// HashMap move iterator.
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub struct IntoIter<K, V> {
1248 inner: table::IntoIter<K, V>
1251 /// HashMap keys iterator.
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 pub struct Keys<'a, K: 'a, V: 'a> {
1254 inner: Iter<'a, K, V>
1257 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<'a, K, V> Clone for Keys<'a, K, V> {
1260 fn clone(&self) -> Keys<'a, K, V> {
1262 inner: self.inner.clone()
1267 /// HashMap values iterator.
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 pub struct Values<'a, K: 'a, V: 'a> {
1270 inner: Iter<'a, K, V>
1273 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<'a, K, V> Clone for Values<'a, K, V> {
1276 fn clone(&self) -> Values<'a, K, V> {
1278 inner: self.inner.clone()
1283 /// HashMap drain iterator.
1284 #[stable(feature = "drain", since = "1.6.0")]
1285 pub struct Drain<'a, K: 'a, V: 'a> {
1286 inner: table::Drain<'a, K, V>
1289 /// Mutable HashMap values iterator.
1290 #[stable(feature = "map_values_mut", since = "1.10.0")]
1291 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1292 inner: IterMut<'a, K, V>
1295 enum InternalEntry<K, V, M> {
1297 elem: FullBucket<K, V, M>,
1301 elem: VacantEntryState<K, V, M>,
1306 impl<K, V, M> InternalEntry<K, V, M> {
1308 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1310 InternalEntry::Occupied { elem } => Some(elem),
1316 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1318 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1320 InternalEntry::Occupied { elem } => {
1321 Some(Occupied(OccupiedEntry {
1326 InternalEntry::Vacant { hash, elem } => {
1327 Some(Vacant(VacantEntry {
1333 InternalEntry::TableIsEmpty => None
1338 /// A view into a single location in a map, which may be vacant or occupied.
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 pub enum Entry<'a, K: 'a, V: 'a> {
1341 /// An occupied Entry.
1342 #[stable(feature = "rust1", since = "1.0.0")]
1344 #[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>
1348 #[stable(feature = "rust1", since = "1.0.0")]
1350 #[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>
1354 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1355 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1358 Vacant(ref v) => f.debug_tuple("Entry")
1361 Occupied(ref o) => f.debug_tuple("Entry")
1368 /// A view into a single occupied location in a HashMap.
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1372 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1375 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1376 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1378 f.debug_struct("OccupiedEntry")
1379 .field("key", self.key())
1380 .field("value", self.get())
1385 /// A view into a single empty location in a HashMap.
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1390 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1393 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1394 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1396 f.debug_tuple("VacantEntry")
1402 /// Possible states of a VacantEntry.
1403 enum VacantEntryState<K, V, M> {
1404 /// The index is occupied, but the key to insert has precedence,
1405 /// and will kick the current one out on insertion.
1406 NeqElem(FullBucket<K, V, M>, usize),
1407 /// The index is genuinely vacant.
1408 NoElem(EmptyBucket<K, V, M>),
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1413 where K: Eq + Hash, S: BuildHasher
1415 type Item = (&'a K, &'a V);
1416 type IntoIter = Iter<'a, K, V>;
1418 fn into_iter(self) -> Iter<'a, K, V> {
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1425 where K: Eq + Hash, S: BuildHasher
1427 type Item = (&'a K, &'a mut V);
1428 type IntoIter = IterMut<'a, K, V>;
1430 fn into_iter(mut self) -> IterMut<'a, K, V> {
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1437 where K: Eq + Hash, S: BuildHasher
1440 type IntoIter = IntoIter<K, V>;
1442 /// Creates a consuming iterator, that is, one that moves each key-value
1443 /// pair out of the map in arbitrary order. The map cannot be used after
1449 /// use std::collections::HashMap;
1451 /// let mut map = HashMap::new();
1452 /// map.insert("a", 1);
1453 /// map.insert("b", 2);
1454 /// map.insert("c", 3);
1456 /// // Not possible with .iter()
1457 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1459 fn into_iter(self) -> IntoIter<K, V> {
1461 inner: self.table.into_iter()
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1468 type Item = (&'a K, &'a V);
1470 #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1471 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1475 #[inline] fn len(&self) -> usize { self.inner.len() }
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1480 type Item = (&'a K, &'a mut V);
1482 #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1483 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1487 #[inline] fn len(&self) -> usize { self.inner.len() }
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<K, V> Iterator for IntoIter<K, V> {
1494 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next().map(|(_, k, v)| (k, v)) }
1495 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1499 #[inline] fn len(&self) -> usize { self.inner.len() }
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1506 #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next().map(|(k, _)| k) }
1507 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1511 #[inline] fn len(&self) -> usize { self.inner.len() }
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<'a, K, V> Iterator for Values<'a, K, V> {
1518 #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next().map(|(_, v)| v) }
1519 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1523 #[inline] fn len(&self) -> usize { self.inner.len() }
1526 #[stable(feature = "map_values_mut", since = "1.10.0")]
1527 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1528 type Item = &'a mut V;
1530 #[inline] fn next(&mut self) -> Option<(&'a mut V)> { self.inner.next().map(|(_, v)| v) }
1531 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1533 #[stable(feature = "map_values_mut", since = "1.10.0")]
1534 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1535 #[inline] fn len(&self) -> usize { self.inner.len() }
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1542 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next().map(|(_, k, v)| (k, v)) }
1543 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1547 #[inline] fn len(&self) -> usize { self.inner.len() }
1550 impl<'a, K, V> Entry<'a, K, V> {
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 /// Ensures a value is in the entry by inserting the default if empty, and returns
1553 /// a mutable reference to the value in the entry.
1554 pub fn or_insert(self, default: V) -> &'a mut V {
1556 Occupied(entry) => entry.into_mut(),
1557 Vacant(entry) => entry.insert(default),
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1563 /// and returns a mutable reference to the value in the entry.
1564 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1566 Occupied(entry) => entry.into_mut(),
1567 Vacant(entry) => entry.insert(default()),
1571 /// Returns a reference to this entry's key.
1572 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1573 pub fn key(&self) -> &K {
1575 Occupied(ref entry) => entry.key(),
1576 Vacant(ref entry) => entry.key(),
1581 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1582 /// Gets a reference to the key in the entry.
1583 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1584 pub fn key(&self) -> &K {
1588 /// Take the ownership of the key and value from the map.
1589 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1590 pub fn remove_pair(self) -> (K, V) {
1591 pop_internal(self.elem)
1594 /// Gets a reference to the value in the entry.
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 pub fn get(&self) -> &V {
1600 /// Gets a mutable reference to the value in the entry.
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 pub fn get_mut(&mut self) -> &mut V {
1603 self.elem.read_mut().1
1606 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1607 /// with a lifetime bound to the map itself
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 pub fn into_mut(self) -> &'a mut V {
1610 self.elem.into_mut_refs().1
1613 /// Sets the value of the entry, and returns the entry's old value
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 pub fn insert(&mut self, mut value: V) -> V {
1616 let old_value = self.get_mut();
1617 mem::swap(&mut value, old_value);
1621 /// Takes the value out of the entry, and returns it
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub fn remove(self) -> V {
1624 pop_internal(self.elem).1
1627 /// Returns a key that was used for search.
1629 /// The key was retained for further use.
1630 fn take_key(&mut self) -> Option<K> {
1635 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1636 /// Gets a reference to the key that would be used when inserting a value
1637 /// through the VacantEntry.
1638 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1639 pub fn key(&self) -> &K {
1643 /// Take ownership of the key.
1644 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1645 pub fn into_key(self) -> K {
1649 /// Sets the value of the entry with the VacantEntry's key,
1650 /// and returns a mutable reference to it
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 pub fn insert(self, value: V) -> &'a mut V {
1654 NeqElem(bucket, ib) => {
1655 robin_hood(bucket, ib, self.hash, self.key, value)
1658 bucket.put(self.hash, self.key, value).into_mut_refs().1
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1666 where K: Eq + Hash, S: BuildHasher + Default
1668 fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, S> {
1669 let iterator = iter.into_iter();
1670 let lower = iterator.size_hint().0;
1671 let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
1672 map.extend(iterator);
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1679 where K: Eq + Hash, S: BuildHasher
1681 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1682 for (k, v) in iter {
1688 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1689 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
1690 where K: Eq + Hash + Copy, V: Copy, S: BuildHasher
1692 fn extend<T: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: T) {
1693 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1697 /// `RandomState` is the default state for `HashMap` types.
1699 /// A particular instance `RandomState` will create the same instances of
1700 /// `Hasher`, but the hashers created by two different `RandomState`
1701 /// instances are unlikely to produce the same result for the same values.
1706 /// use std::collections::HashMap;
1707 /// use std::collections::hash_map::RandomState;
1709 /// let s = RandomState::new();
1710 /// let mut map = HashMap::with_hasher(s);
1711 /// map.insert(1, 2);
1714 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1715 pub struct RandomState {
1721 /// Constructs a new `RandomState` that is initialized with random keys.
1726 /// use std::collections::hash_map::RandomState;
1728 /// let s = RandomState::new();
1731 #[allow(deprecated)] // rand
1732 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1733 pub fn new() -> RandomState {
1734 // Historically this function did not cache keys from the OS and instead
1735 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
1736 // was discovered, however, that because we re-seed the thread-local RNG
1737 // from the OS periodically that this can cause excessive slowdown when
1738 // many hash maps are created on a thread. To solve this performance
1739 // trap we cache the first set of randomly generated keys per-thread.
1741 // In doing this, however, we lose the property that all hash maps have
1742 // nondeterministic iteration order as all of those created on the same
1743 // thread would have the same hash keys. This property has been nice in
1744 // the past as it allows for maximal flexibility in the implementation
1745 // of `HashMap` itself.
1747 // The constraint here (if there even is one) is just that maps created
1748 // on the same thread have the same iteration order, and that *may* be
1749 // relied upon even though it is not a documented guarantee at all of
1750 // the `HashMap` type. In any case we've decided that this is reasonable
1751 // for now, so caching keys thread-locally seems fine.
1752 thread_local!(static KEYS: (u64, u64) = {
1753 let r = rand::OsRng::new();
1754 let mut r = r.expect("failed to create an OS RNG");
1758 KEYS.with(|&(k0, k1)| {
1759 RandomState { k0: k0, k1: k1 }
1764 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1765 impl BuildHasher for RandomState {
1766 type Hasher = DefaultHasher;
1768 fn build_hasher(&self) -> DefaultHasher {
1769 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
1773 /// The default `Hasher` used by `RandomState`.
1775 /// The internal algorithm is not specified, and so it and its hashes should
1776 /// not be relied upon over releases.
1777 #[unstable(feature = "hashmap_default_hasher", issue = "0")]
1778 pub struct DefaultHasher(SipHasher13);
1780 #[unstable(feature = "hashmap_default_hasher", issue = "0")]
1781 impl Hasher for DefaultHasher {
1783 fn write(&mut self, msg: &[u8]) {
1788 fn finish(&self) -> u64 {
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl Default for RandomState {
1796 fn default() -> RandomState {
1801 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
1802 where K: Eq + Hash + Borrow<Q>, S: BuildHasher, Q: Eq + Hash
1806 fn get(&self, key: &Q) -> Option<&K> {
1807 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
1810 fn take(&mut self, key: &Q) -> Option<K> {
1811 if self.table.size() == 0 {
1815 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
1818 fn replace(&mut self, key: K) -> Option<K> {
1821 match self.entry(key) {
1822 Occupied(mut occupied) => {
1823 let key = occupied.take_key().unwrap();
1824 Some(mem::replace(occupied.elem.read_mut().0, key))
1835 fn assert_covariance() {
1836 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { v }
1837 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> { v }
1838 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> { v }
1839 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> { v }
1840 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> { v }
1841 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> { v }
1842 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> { v }
1843 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> { v }
1844 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> { v }
1845 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { v }
1853 use super::Entry::{Occupied, Vacant};
1855 use rand::{thread_rng, Rng};
1858 fn test_create_capacity_zero() {
1859 let mut m = HashMap::with_capacity(0);
1861 assert!(m.insert(1, 1).is_none());
1863 assert!(m.contains_key(&1));
1864 assert!(!m.contains_key(&0));
1869 let mut m = HashMap::new();
1870 assert_eq!(m.len(), 0);
1871 assert!(m.insert(1, 2).is_none());
1872 assert_eq!(m.len(), 1);
1873 assert!(m.insert(2, 4).is_none());
1874 assert_eq!(m.len(), 2);
1875 assert_eq!(*m.get(&1).unwrap(), 2);
1876 assert_eq!(*m.get(&2).unwrap(), 4);
1881 let mut m = HashMap::new();
1882 assert_eq!(m.len(), 0);
1883 assert!(m.insert(1, 2).is_none());
1884 assert_eq!(m.len(), 1);
1885 assert!(m.insert(2, 4).is_none());
1886 assert_eq!(m.len(), 2);
1888 assert_eq!(*m2.get(&1).unwrap(), 2);
1889 assert_eq!(*m2.get(&2).unwrap(), 4);
1890 assert_eq!(m2.len(), 2);
1893 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
1895 #[derive(Hash, PartialEq, Eq)]
1901 fn new(k: usize) -> Dropable {
1902 DROP_VECTOR.with(|slot| {
1903 slot.borrow_mut()[k] += 1;
1910 impl Drop for Dropable {
1911 fn drop(&mut self) {
1912 DROP_VECTOR.with(|slot| {
1913 slot.borrow_mut()[self.k] -= 1;
1918 impl Clone for Dropable {
1919 fn clone(&self) -> Dropable {
1920 Dropable::new(self.k)
1926 DROP_VECTOR.with(|slot| {
1927 *slot.borrow_mut() = vec![0; 200];
1931 let mut m = HashMap::new();
1933 DROP_VECTOR.with(|v| {
1935 assert_eq!(v.borrow()[i], 0);
1940 let d1 = Dropable::new(i);
1941 let d2 = Dropable::new(i+100);
1945 DROP_VECTOR.with(|v| {
1947 assert_eq!(v.borrow()[i], 1);
1952 let k = Dropable::new(i);
1953 let v = m.remove(&k);
1955 assert!(v.is_some());
1957 DROP_VECTOR.with(|v| {
1958 assert_eq!(v.borrow()[i], 1);
1959 assert_eq!(v.borrow()[i+100], 1);
1963 DROP_VECTOR.with(|v| {
1965 assert_eq!(v.borrow()[i], 0);
1966 assert_eq!(v.borrow()[i+100], 0);
1970 assert_eq!(v.borrow()[i], 1);
1971 assert_eq!(v.borrow()[i+100], 1);
1976 DROP_VECTOR.with(|v| {
1978 assert_eq!(v.borrow()[i], 0);
1984 fn test_into_iter_drops() {
1985 DROP_VECTOR.with(|v| {
1986 *v.borrow_mut() = vec![0; 200];
1990 let mut hm = HashMap::new();
1992 DROP_VECTOR.with(|v| {
1994 assert_eq!(v.borrow()[i], 0);
1999 let d1 = Dropable::new(i);
2000 let d2 = Dropable::new(i+100);
2004 DROP_VECTOR.with(|v| {
2006 assert_eq!(v.borrow()[i], 1);
2013 // By the way, ensure that cloning doesn't screw up the dropping.
2017 let mut half = hm.into_iter().take(50);
2019 DROP_VECTOR.with(|v| {
2021 assert_eq!(v.borrow()[i], 1);
2025 for _ in half.by_ref() {}
2027 DROP_VECTOR.with(|v| {
2028 let nk = (0..100).filter(|&i| {
2032 let nv = (0..100).filter(|&i| {
2033 v.borrow()[i+100] == 1
2041 DROP_VECTOR.with(|v| {
2043 assert_eq!(v.borrow()[i], 0);
2049 fn test_empty_remove() {
2050 let mut m: HashMap<isize, bool> = HashMap::new();
2051 assert_eq!(m.remove(&0), None);
2055 fn test_empty_entry() {
2056 let mut m: HashMap<isize, bool> = HashMap::new();
2058 Occupied(_) => panic!(),
2061 assert!(*m.entry(0).or_insert(true));
2062 assert_eq!(m.len(), 1);
2066 fn test_empty_iter() {
2067 let mut m: HashMap<isize, bool> = HashMap::new();
2068 assert_eq!(m.drain().next(), None);
2069 assert_eq!(m.keys().next(), None);
2070 assert_eq!(m.values().next(), None);
2071 assert_eq!(m.values_mut().next(), None);
2072 assert_eq!(m.iter().next(), None);
2073 assert_eq!(m.iter_mut().next(), None);
2074 assert_eq!(m.len(), 0);
2075 assert!(m.is_empty());
2076 assert_eq!(m.into_iter().next(), None);
2080 fn test_lots_of_insertions() {
2081 let mut m = HashMap::new();
2083 // Try this a few times to make sure we never screw up the hashmap's
2086 assert!(m.is_empty());
2089 assert!(m.insert(i, i).is_none());
2093 assert_eq!(r, Some(&j));
2096 for j in i+1..1001 {
2098 assert_eq!(r, None);
2102 for i in 1001..2001 {
2103 assert!(!m.contains_key(&i));
2108 assert!(m.remove(&i).is_some());
2111 assert!(!m.contains_key(&j));
2114 for j in i+1..1001 {
2115 assert!(m.contains_key(&j));
2120 assert!(!m.contains_key(&i));
2124 assert!(m.insert(i, i).is_none());
2128 for i in (1..1001).rev() {
2129 assert!(m.remove(&i).is_some());
2132 assert!(!m.contains_key(&j));
2136 assert!(m.contains_key(&j));
2143 fn test_find_mut() {
2144 let mut m = HashMap::new();
2145 assert!(m.insert(1, 12).is_none());
2146 assert!(m.insert(2, 8).is_none());
2147 assert!(m.insert(5, 14).is_none());
2149 match m.get_mut(&5) {
2150 None => panic!(), Some(x) => *x = new
2152 assert_eq!(m.get(&5), Some(&new));
2156 fn test_insert_overwrite() {
2157 let mut m = HashMap::new();
2158 assert!(m.insert(1, 2).is_none());
2159 assert_eq!(*m.get(&1).unwrap(), 2);
2160 assert!(!m.insert(1, 3).is_none());
2161 assert_eq!(*m.get(&1).unwrap(), 3);
2165 fn test_insert_conflicts() {
2166 let mut m = HashMap::with_capacity(4);
2167 assert!(m.insert(1, 2).is_none());
2168 assert!(m.insert(5, 3).is_none());
2169 assert!(m.insert(9, 4).is_none());
2170 assert_eq!(*m.get(&9).unwrap(), 4);
2171 assert_eq!(*m.get(&5).unwrap(), 3);
2172 assert_eq!(*m.get(&1).unwrap(), 2);
2176 fn test_conflict_remove() {
2177 let mut m = HashMap::with_capacity(4);
2178 assert!(m.insert(1, 2).is_none());
2179 assert_eq!(*m.get(&1).unwrap(), 2);
2180 assert!(m.insert(5, 3).is_none());
2181 assert_eq!(*m.get(&1).unwrap(), 2);
2182 assert_eq!(*m.get(&5).unwrap(), 3);
2183 assert!(m.insert(9, 4).is_none());
2184 assert_eq!(*m.get(&1).unwrap(), 2);
2185 assert_eq!(*m.get(&5).unwrap(), 3);
2186 assert_eq!(*m.get(&9).unwrap(), 4);
2187 assert!(m.remove(&1).is_some());
2188 assert_eq!(*m.get(&9).unwrap(), 4);
2189 assert_eq!(*m.get(&5).unwrap(), 3);
2193 fn test_is_empty() {
2194 let mut m = HashMap::with_capacity(4);
2195 assert!(m.insert(1, 2).is_none());
2196 assert!(!m.is_empty());
2197 assert!(m.remove(&1).is_some());
2198 assert!(m.is_empty());
2203 let mut m = HashMap::new();
2205 assert_eq!(m.remove(&1), Some(2));
2206 assert_eq!(m.remove(&1), None);
2211 let mut m = HashMap::with_capacity(4);
2213 assert!(m.insert(i, i*2).is_none());
2215 assert_eq!(m.len(), 32);
2217 let mut observed: u32 = 0;
2220 assert_eq!(*v, *k * 2);
2221 observed |= 1 << *k;
2223 assert_eq!(observed, 0xFFFF_FFFF);
2228 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2229 let map: HashMap<_, _> = vec.into_iter().collect();
2230 let keys: Vec<_> = map.keys().cloned().collect();
2231 assert_eq!(keys.len(), 3);
2232 assert!(keys.contains(&1));
2233 assert!(keys.contains(&2));
2234 assert!(keys.contains(&3));
2239 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2240 let map: HashMap<_, _> = vec.into_iter().collect();
2241 let values: Vec<_> = map.values().cloned().collect();
2242 assert_eq!(values.len(), 3);
2243 assert!(values.contains(&'a'));
2244 assert!(values.contains(&'b'));
2245 assert!(values.contains(&'c'));
2249 fn test_values_mut() {
2250 let vec = vec![(1, 1), (2, 2), (3, 3)];
2251 let mut map: HashMap<_, _> = vec.into_iter().collect();
2252 for value in map.values_mut() {
2253 *value = (*value) * 2
2255 let values: Vec<_> = map.values().cloned().collect();
2256 assert_eq!(values.len(), 3);
2257 assert!(values.contains(&2));
2258 assert!(values.contains(&4));
2259 assert!(values.contains(&6));
2264 let mut m = HashMap::new();
2265 assert!(m.get(&1).is_none());
2269 Some(v) => assert_eq!(*v, 2)
2275 let mut m1 = HashMap::new();
2280 let mut m2 = HashMap::new();
2293 let mut map = HashMap::new();
2294 let empty: HashMap<i32, i32> = HashMap::new();
2299 let map_str = format!("{:?}", map);
2301 assert!(map_str == "{1: 2, 3: 4}" ||
2302 map_str == "{3: 4, 1: 2}");
2303 assert_eq!(format!("{:?}", empty), "{}");
2308 let mut m = HashMap::new();
2310 assert_eq!(m.len(), 0);
2311 assert!(m.is_empty());
2314 let old_cap = m.table.capacity();
2315 while old_cap == m.table.capacity() {
2320 assert_eq!(m.len(), i);
2321 assert!(!m.is_empty());
2325 fn test_behavior_resize_policy() {
2326 let mut m = HashMap::new();
2328 assert_eq!(m.len(), 0);
2329 assert_eq!(m.table.capacity(), 0);
2330 assert!(m.is_empty());
2334 assert!(m.is_empty());
2335 let initial_cap = m.table.capacity();
2336 m.reserve(initial_cap);
2337 let cap = m.table.capacity();
2339 assert_eq!(cap, initial_cap * 2);
2342 for _ in 0..cap * 3 / 4 {
2346 // three quarters full
2348 assert_eq!(m.len(), i);
2349 assert_eq!(m.table.capacity(), cap);
2351 for _ in 0..cap / 4 {
2357 let new_cap = m.table.capacity();
2358 assert_eq!(new_cap, cap * 2);
2360 for _ in 0..cap / 2 - 1 {
2363 assert_eq!(m.table.capacity(), new_cap);
2365 // A little more than one quarter full.
2367 assert_eq!(m.table.capacity(), cap);
2368 // again, a little more than half full
2369 for _ in 0..cap / 2 - 1 {
2375 assert_eq!(m.len(), i);
2376 assert!(!m.is_empty());
2377 assert_eq!(m.table.capacity(), initial_cap);
2381 fn test_reserve_shrink_to_fit() {
2382 let mut m = HashMap::new();
2385 assert!(m.capacity() >= m.len());
2391 let usable_cap = m.capacity();
2392 for i in 128..(128 + 256) {
2394 assert_eq!(m.capacity(), usable_cap);
2397 for i in 100..(128 + 256) {
2398 assert_eq!(m.remove(&i), Some(i));
2402 assert_eq!(m.len(), 100);
2403 assert!(!m.is_empty());
2404 assert!(m.capacity() >= m.len());
2407 assert_eq!(m.remove(&i), Some(i));
2412 assert_eq!(m.len(), 1);
2413 assert!(m.capacity() >= m.len());
2414 assert_eq!(m.remove(&0), Some(0));
2418 fn test_from_iter() {
2419 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2421 let map: HashMap<_, _> = xs.iter().cloned().collect();
2423 for &(k, v) in &xs {
2424 assert_eq!(map.get(&k), Some(&v));
2429 fn test_size_hint() {
2430 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2432 let map: HashMap<_, _> = xs.iter().cloned().collect();
2434 let mut iter = map.iter();
2436 for _ in iter.by_ref().take(3) {}
2438 assert_eq!(iter.size_hint(), (3, Some(3)));
2442 fn test_iter_len() {
2443 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2445 let map: HashMap<_, _> = xs.iter().cloned().collect();
2447 let mut iter = map.iter();
2449 for _ in iter.by_ref().take(3) {}
2451 assert_eq!(iter.len(), 3);
2455 fn test_mut_size_hint() {
2456 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2458 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2460 let mut iter = map.iter_mut();
2462 for _ in iter.by_ref().take(3) {}
2464 assert_eq!(iter.size_hint(), (3, Some(3)));
2468 fn test_iter_mut_len() {
2469 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2471 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2473 let mut iter = map.iter_mut();
2475 for _ in iter.by_ref().take(3) {}
2477 assert_eq!(iter.len(), 3);
2482 let mut map = HashMap::new();
2488 assert_eq!(map[&2], 1);
2493 fn test_index_nonexistent() {
2494 let mut map = HashMap::new();
2505 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2507 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2509 // Existing key (insert)
2510 match map.entry(1) {
2511 Vacant(_) => unreachable!(),
2512 Occupied(mut view) => {
2513 assert_eq!(view.get(), &10);
2514 assert_eq!(view.insert(100), 10);
2517 assert_eq!(map.get(&1).unwrap(), &100);
2518 assert_eq!(map.len(), 6);
2521 // Existing key (update)
2522 match map.entry(2) {
2523 Vacant(_) => unreachable!(),
2524 Occupied(mut view) => {
2525 let v = view.get_mut();
2526 let new_v = (*v) * 10;
2530 assert_eq!(map.get(&2).unwrap(), &200);
2531 assert_eq!(map.len(), 6);
2533 // Existing key (take)
2534 match map.entry(3) {
2535 Vacant(_) => unreachable!(),
2537 assert_eq!(view.remove(), 30);
2540 assert_eq!(map.get(&3), None);
2541 assert_eq!(map.len(), 5);
2544 // Inexistent key (insert)
2545 match map.entry(10) {
2546 Occupied(_) => unreachable!(),
2548 assert_eq!(*view.insert(1000), 1000);
2551 assert_eq!(map.get(&10).unwrap(), &1000);
2552 assert_eq!(map.len(), 6);
2556 fn test_entry_take_doesnt_corrupt() {
2557 #![allow(deprecated)] //rand
2559 fn check(m: &HashMap<isize, ()>) {
2561 assert!(m.contains_key(k),
2562 "{} is in keys() but not in the map?", k);
2566 let mut m = HashMap::new();
2567 let mut rng = thread_rng();
2569 // Populate the map with some items.
2571 let x = rng.gen_range(-10, 10);
2576 let x = rng.gen_range(-10, 10);
2580 println!("{}: remove {}", i, x);
2590 fn test_extend_ref() {
2591 let mut a = HashMap::new();
2593 let mut b = HashMap::new();
2595 b.insert(3, "three");
2599 assert_eq!(a.len(), 3);
2600 assert_eq!(a[&1], "one");
2601 assert_eq!(a[&2], "two");
2602 assert_eq!(a[&3], "three");
2606 fn test_capacity_not_less_than_len() {
2607 let mut a = HashMap::new();
2615 assert!(a.capacity() > a.len());
2617 let free = a.capacity() - a.len();
2623 assert_eq!(a.len(), a.capacity());
2625 // Insert at capacity should cause allocation.
2627 assert!(a.capacity() > a.len());
2631 fn test_occupied_entry_key() {
2632 let mut a = HashMap::new();
2633 let key = "hello there";
2634 let value = "value goes here";
2635 assert!(a.is_empty());
2636 a.insert(key.clone(), value.clone());
2637 assert_eq!(a.len(), 1);
2638 assert_eq!(a[key], value);
2640 match a.entry(key.clone()) {
2641 Vacant(_) => panic!(),
2642 Occupied(e) => assert_eq!(key, *e.key()),
2644 assert_eq!(a.len(), 1);
2645 assert_eq!(a[key], value);
2649 fn test_vacant_entry_key() {
2650 let mut a = HashMap::new();
2651 let key = "hello there";
2652 let value = "value goes here";
2654 assert!(a.is_empty());
2655 match a.entry(key.clone()) {
2656 Occupied(_) => panic!(),
2658 assert_eq!(key, *e.key());
2659 e.insert(value.clone());
2662 assert_eq!(a.len(), 1);
2663 assert_eq!(a[key], value);