1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use self::VacantEntryState::*;
17 use fmt::{self, Debug};
19 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
20 use iter::{FromIterator, FusedIterator};
21 use mem::{self, replace};
22 use ops::{Deref, Index};
23 use rand::{self, Rng};
25 use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash};
26 use super::table::BucketState::{Empty, Full};
28 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
30 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
32 struct DefaultResizePolicy;
34 impl DefaultResizePolicy {
35 fn new() -> DefaultResizePolicy {
39 /// A hash map's "capacity" is the number of elements it can hold without
40 /// being resized. Its "raw capacity" is the number of slots required to
41 /// provide that capacity, accounting for maximum loading. The raw capacity
42 /// is always zero or a power of two.
44 fn raw_capacity(&self, len: usize) -> usize {
48 // 1. Account for loading: `raw_capacity >= len * 1.1`.
49 // 2. Ensure it is a power of two.
50 // 3. Ensure it is at least the minimum size.
51 let mut raw_cap = len * 11 / 10;
52 assert!(raw_cap >= len, "raw_cap overflow");
53 raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow");
54 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
59 /// The capacity of the given raw capacity.
61 fn capacity(&self, raw_cap: usize) -> usize {
62 // This doesn't have to be checked for overflow since allocation size
63 // in bytes will overflow earlier than multiplication by 10.
65 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
66 // to be: (raw_cap * den + den - 1) / num
67 (raw_cap * 10 + 10 - 1) / 11
71 // The main performance trick in this hashmap is called Robin Hood Hashing.
72 // It gains its excellent performance from one essential operation:
74 // If an insertion collides with an existing element, and that element's
75 // "probe distance" (how far away the element is from its ideal location)
76 // is higher than how far we've already probed, swap the elements.
78 // This massively lowers variance in probe distance, and allows us to get very
79 // high load factors with good performance. The 90% load factor I use is rather
82 // > Why a load factor of approximately 90%?
84 // In general, all the distances to initial buckets will converge on the mean.
85 // At a load factor of α, the odds of finding the target bucket after k
86 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
87 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
88 // this down to make the math easier on the CPU and avoid its FPU.
89 // Since on average we start the probing in the middle of a cache line, this
90 // strategy pulls in two cache lines of hashes on every lookup. I think that's
91 // pretty good, but if you want to trade off some space, it could go down to one
92 // cache line on average with an α of 0.84.
94 // > Wait, what? Where did you get 1-α^k from?
96 // On the first probe, your odds of a collision with an existing element is α.
97 // The odds of doing this twice in a row is approximately α^2. For three times,
98 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
99 // colliding after k tries is 1-α^k.
101 // The paper from 1986 cited below mentions an implementation which keeps track
102 // of the distance-to-initial-bucket histogram. This approach is not suitable
103 // for modern architectures because it requires maintaining an internal data
104 // structure. This allows very good first guesses, but we are most concerned
105 // with guessing entire cache lines, not individual indexes. Furthermore, array
106 // accesses are no longer linear and in one direction, as we have now. There
107 // is also memory and cache pressure that this would entail that would be very
108 // difficult to properly see in a microbenchmark.
110 // ## Future Improvements (FIXME!)
112 // Allow the load factor to be changed dynamically and/or at initialization.
114 // Also, would it be possible for us to reuse storage when growing the
115 // underlying table? This is exactly the use case for 'realloc', and may
116 // be worth exploring.
118 // ## Future Optimizations (FIXME!)
120 // Another possible design choice that I made without any real reason is
121 // parameterizing the raw table over keys and values. Technically, all we need
122 // is the size and alignment of keys and values, and the code should be just as
123 // efficient (well, we might need one for power-of-two size and one for not...).
124 // This has the potential to reduce code bloat in rust executables, without
125 // really losing anything except 4 words (key size, key alignment, val size,
126 // val alignment) which can be passed in to every call of a `RawTable` function.
127 // This would definitely be an avenue worth exploring if people start complaining
128 // about the size of rust executables.
130 // Annotate exceedingly likely branches in `table::make_hash`
131 // and `search_hashed` to reduce instruction cache pressure
132 // and mispredictions once it becomes possible (blocked on issue #11092).
134 // Shrinking the table could simply reallocate in place after moving buckets
135 // to the first half.
137 // The growth algorithm (fragment of the Proof of Correctness)
138 // --------------------
140 // The growth algorithm is basically a fast path of the naive reinsertion-
141 // during-resize algorithm. Other paths should never be taken.
143 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
144 // by allocating a new table of capacity `2n`, and then individually reinsert
145 // each element in the old table into the new one. This guarantees that the
146 // new table is a valid robin hood hashtable with all the desired statistical
147 // properties. Remark that the order we reinsert the elements in should not
148 // matter. For simplicity and efficiency, we will consider only linear
149 // reinsertions, which consist of reinserting all elements in the old table
150 // into the new one by increasing order of index. However we will not be
151 // starting our reinsertions from index 0 in general. If we start from index
152 // i, for the purpose of reinsertion we will consider all elements with real
153 // index j < i to have virtual index n + j.
155 // Our hash generation scheme consists of generating a 64-bit hash and
156 // truncating the most significant bits. When moving to the new table, we
157 // simply introduce a new bit to the front of the hash. Therefore, if an
158 // elements has ideal index i in the old table, it can have one of two ideal
159 // locations in the new table. If the new bit is 0, then the new ideal index
160 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
161 // we are producing two independent tables of size n, and for each element we
162 // independently choose which table to insert it into with equal probability.
163 // However the rather than wrapping around themselves on overflowing their
164 // indexes, the first table overflows into the first, and the first into the
165 // second. Visually, our new table will look something like:
167 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
169 // Where x's are elements inserted into the first table, y's are elements
170 // inserted into the second, and _'s are empty sections. We now define a few
171 // key concepts that we will use later. Note that this is a very abstract
172 // perspective of the table. A real resized table would be at least half
175 // Theorem: A linear robin hood reinsertion from the first ideal element
176 // produces identical results to a linear naive reinsertion from the same
179 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
181 /// A hash map implementation which uses linear probing with Robin Hood bucket
184 /// By default, `HashMap` uses a hashing algorithm selected to provide
185 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
186 /// reasonable best-effort is made to generate this seed from a high quality,
187 /// secure source of randomness provided by the host without blocking the
188 /// program. Because of this, the randomness of the seed is dependant on the
189 /// quality of the system's random number generator at the time it is created.
190 /// In particular, seeds generated when the system's entropy pool is abnormally
191 /// low such as during system boot may be of a lower quality.
193 /// The default hashing algorithm is currently SipHash 1-3, though this is
194 /// subject to change at any point in the future. While its performance is very
195 /// competitive for medium sized keys, other hashing algorithms will outperform
196 /// it for small keys such as integers as well as large keys such as long
197 /// strings, though those algorithms will typically *not* protect against
198 /// attacks such as HashDoS.
200 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
201 /// `HashMap::default`, `HashMap::with_hasher`, and
202 /// `HashMap::with_capacity_and_hasher` methods. Many alternative algorithms
203 /// are available on crates.io, such as the `fnv` crate.
205 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
206 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
207 /// If you implement these yourself, it is important that the following
211 /// k1 == k2 -> hash(k1) == hash(k2)
214 /// In other words, if two keys are equal, their hashes must be equal.
216 /// It is a logic error for a key to be modified in such a way that the key's
217 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
218 /// the [`Eq`] trait, changes while it is in the map. This is normally only
219 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
221 /// Relevant papers/articles:
223 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
224 /// 2. Emmanuel Goossaert. ["Robin Hood
225 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
226 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
227 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
232 /// use std::collections::HashMap;
234 /// // type inference lets us omit an explicit type signature (which
235 /// // would be `HashMap<&str, &str>` in this example).
236 /// let mut book_reviews = HashMap::new();
238 /// // review some books.
239 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
240 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
241 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
242 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
244 /// // check for a specific one.
245 /// if !book_reviews.contains_key("Les Misérables") {
246 /// println!("We've got {} reviews, but Les Misérables ain't one.",
247 /// book_reviews.len());
250 /// // oops, this review has a lot of spelling mistakes, let's delete it.
251 /// book_reviews.remove("The Adventures of Sherlock Holmes");
253 /// // look up the values associated with some keys.
254 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
255 /// for book in &to_find {
256 /// match book_reviews.get(book) {
257 /// Some(review) => println!("{}: {}", book, review),
258 /// None => println!("{} is unreviewed.", book)
262 /// // iterate over everything.
263 /// for (book, review) in &book_reviews {
264 /// println!("{}: \"{}\"", book, review);
268 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
269 /// for more complex methods of getting, setting, updating and removing keys and
273 /// use std::collections::HashMap;
275 /// // type inference lets us omit an explicit type signature (which
276 /// // would be `HashMap<&str, u8>` in this example).
277 /// let mut player_stats = HashMap::new();
279 /// fn random_stat_buff() -> u8 {
280 /// // could actually return some random value here - let's just return
281 /// // some fixed value for now
285 /// // insert a key only if it doesn't already exist
286 /// player_stats.entry("health").or_insert(100);
288 /// // insert a key using a function that provides a new value only if it
289 /// // doesn't already exist
290 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
292 /// // update a key, guarding against the key possibly not being set
293 /// let stat = player_stats.entry("attack").or_insert(100);
294 /// *stat += random_stat_buff();
297 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
298 /// We must also derive [`PartialEq`].
300 /// [`Eq`]: ../../std/cmp/trait.Eq.html
301 /// [`Hash`]: ../../std/hash/trait.Hash.html
302 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
303 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
304 /// [`Cell`]: ../../std/cell/struct.Cell.html
307 /// use std::collections::HashMap;
309 /// #[derive(Hash, Eq, PartialEq, Debug)]
316 /// /// Create a new Viking.
317 /// fn new(name: &str, country: &str) -> Viking {
318 /// Viking { name: name.to_string(), country: country.to_string() }
322 /// // Use a HashMap to store the vikings' health points.
323 /// let mut vikings = HashMap::new();
325 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
326 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
327 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
329 /// // Use derived implementation to print the status of the vikings.
330 /// for (viking, health) in &vikings {
331 /// println!("{:?} has {} hp", viking, health);
335 /// A HashMap with fixed list of elements can be initialized from an array:
338 /// use std::collections::HashMap;
341 /// let timber_resources: HashMap<&str, i32> =
342 /// [("Norway", 100),
345 /// .iter().cloned().collect();
346 /// // use the values stored in map
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub struct HashMap<K, V, S = RandomState> {
353 // All hashes are keyed on these values, to prevent hash collision attacks.
356 table: RawTable<K, V>,
358 resize_policy: DefaultResizePolicy,
361 /// Search for a pre-hashed key.
363 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
364 where M: Deref<Target = RawTable<K, V>>,
367 // This is the only function where capacity can be zero. To avoid
368 // undefined behavior when Bucket::new gets the raw bucket in this
369 // case, immediately return the appropriate search result.
370 if table.capacity() == 0 {
371 return InternalEntry::TableIsEmpty;
374 let size = table.size();
375 let mut probe = Bucket::new(table, hash);
376 let mut displacement = 0;
379 let full = match probe.peek() {
382 return InternalEntry::Vacant {
384 elem: NoElem(bucket),
387 Full(bucket) => bucket,
390 let probe_displacement = full.displacement();
392 if probe_displacement < displacement {
393 // Found a luckier bucket than me.
394 // We can finish the search early if we hit any bucket
395 // with a lower distance to initial bucket than we've probed.
396 return InternalEntry::Vacant {
398 elem: NeqElem(full, probe_displacement),
402 // If the hash doesn't match, it can't be this one..
403 if hash == full.hash() {
404 // If the key doesn't match, it can't be this one..
405 if is_match(full.read().0) {
406 return InternalEntry::Occupied { elem: full };
411 debug_assert!(displacement <= size);
415 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
416 let (empty, retkey, retval) = starting_bucket.take();
417 let mut gap = match empty.gap_peek() {
419 None => return (retkey, retval),
422 while gap.full().displacement() != 0 {
423 gap = match gap.shift() {
429 // Now we've done all our shifting. Return the value we grabbed earlier.
433 /// Perform robin hood bucket stealing at the given `bucket`. You must
434 /// also pass that bucket's displacement so we don't have to recalculate it.
436 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
437 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
438 mut displacement: usize,
443 let starting_index = bucket.index();
444 let size = bucket.table().size();
445 // Save the *starting point*.
446 let mut bucket = bucket.stash();
447 // There can be at most `size - dib` buckets to displace, because
448 // in the worst case, there are `size` elements and we already are
449 // `displacement` buckets away from the initial one.
450 let idx_end = starting_index + size - bucket.displacement();
453 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
460 let probe = bucket.next();
461 debug_assert!(probe.index() != idx_end);
463 let full_bucket = match probe.peek() {
466 let bucket = bucket.put(hash, key, val);
467 // Now that it's stolen, just read the value's pointer
468 // right out of the table! Go back to the *starting point*.
470 // This use of `into_table` is misleading. It turns the
471 // bucket, which is a FullBucket on top of a
472 // FullBucketMut, into just one FullBucketMut. The "table"
473 // refers to the inner FullBucketMut in this context.
474 return bucket.into_table().into_mut_refs().1;
476 Full(bucket) => bucket,
479 let probe_displacement = full_bucket.displacement();
481 bucket = full_bucket;
483 // Robin hood! Steal the spot.
484 if probe_displacement < displacement {
485 displacement = probe_displacement;
492 impl<K, V, S> HashMap<K, V, S>
496 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
499 table::make_hash(&self.hash_builder, x)
502 /// Search for a key, yielding the index if it's found in the hashtable.
503 /// If you already have the hash for the key lying around, use
506 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
510 let hash = self.make_hash(q);
511 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
515 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
519 let hash = self.make_hash(q);
520 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
523 // The caller should ensure that invariants by Robin Hood Hashing hold
524 // and that there's space in the underlying table.
525 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
526 let raw_cap = self.raw_capacity();
527 let mut buckets = Bucket::new(&mut self.table, hash);
528 // note that buckets.index() keeps increasing
529 // even if the pointer wraps back to the first bucket.
530 let limit_bucket = buckets.index() + raw_cap;
533 // We don't need to compare hashes for value swap.
534 // Not even DIBs for Robin Hood.
535 buckets = match buckets.peek() {
537 empty.put(hash, k, v);
540 Full(b) => b.into_bucket(),
543 debug_assert!(buckets.index() < limit_bucket);
548 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
549 /// Creates an empty `HashMap`.
554 /// use std::collections::HashMap;
555 /// let mut map: HashMap<&str, isize> = HashMap::new();
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn new() -> HashMap<K, V, RandomState> {
563 /// Creates an empty `HashMap` with the specified capacity.
565 /// The hash map will be able to hold at least `capacity` elements without
566 /// reallocating. If `capacity` is 0, the hash map will not allocate.
571 /// use std::collections::HashMap;
572 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
577 HashMap::with_capacity_and_hasher(capacity, Default::default())
581 impl<K, V, S> HashMap<K, V, S>
585 /// Creates an empty `HashMap` which will use the given hash builder to hash
588 /// The created map has the default initial capacity.
590 /// Warning: `hash_builder` is normally randomly generated, and
591 /// is designed to allow HashMaps to be resistant to attacks that
592 /// cause many collisions and very poor performance. Setting it
593 /// manually using this function can expose a DoS attack vector.
598 /// use std::collections::HashMap;
599 /// use std::collections::hash_map::RandomState;
601 /// let s = RandomState::new();
602 /// let mut map = HashMap::with_hasher(s);
603 /// map.insert(1, 2);
606 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
607 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
609 hash_builder: hash_builder,
610 resize_policy: DefaultResizePolicy::new(),
611 table: RawTable::new(0),
615 /// Creates an empty `HashMap` with the specified capacity, using `hasher`
616 /// to hash the keys.
618 /// The hash map will be able to hold at least `capacity` elements without
619 /// reallocating. If `capacity` is 0, the hash map will not allocate.
620 /// Warning: `hasher` is normally randomly generated, and
621 /// is designed to allow HashMaps to be resistant to attacks that
622 /// cause many collisions and very poor performance. Setting it
623 /// manually using this function can expose a DoS attack vector.
628 /// use std::collections::HashMap;
629 /// use std::collections::hash_map::RandomState;
631 /// let s = RandomState::new();
632 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
633 /// map.insert(1, 2);
636 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
637 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
638 let resize_policy = DefaultResizePolicy::new();
639 let raw_cap = resize_policy.raw_capacity(capacity);
641 hash_builder: hash_builder,
642 resize_policy: resize_policy,
643 table: RawTable::new(raw_cap),
647 /// Returns a reference to the map's hasher.
648 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
649 pub fn hasher(&self) -> &S {
653 /// Returns the number of elements the map can hold without reallocating.
655 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
656 /// more, but is guaranteed to be able to hold at least this many.
661 /// use std::collections::HashMap;
662 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
663 /// assert!(map.capacity() >= 100);
666 #[stable(feature = "rust1", since = "1.0.0")]
667 pub fn capacity(&self) -> usize {
668 self.resize_policy.capacity(self.raw_capacity())
671 /// Returns the hash map's raw capacity.
673 fn raw_capacity(&self) -> usize {
674 self.table.capacity()
677 /// Reserves capacity for at least `additional` more elements to be inserted
678 /// in the `HashMap`. The collection may reserve more space to avoid
679 /// frequent reallocations.
683 /// Panics if the new allocation size overflows `usize`.
688 /// use std::collections::HashMap;
689 /// let mut map: HashMap<&str, isize> = HashMap::new();
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn reserve(&mut self, additional: usize) {
694 let remaining = self.capacity() - self.len(); // this can't overflow
695 if remaining < additional {
696 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
697 let raw_cap = self.resize_policy.raw_capacity(min_cap);
698 self.resize(raw_cap);
702 /// Resizes the internal vectors to a new capacity. It's your
703 /// responsibility to:
704 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
705 /// for the load factor.
706 /// 2) Ensure `new_raw_cap` is a power of two or zero.
707 fn resize(&mut self, new_raw_cap: usize) {
708 assert!(self.table.size() <= new_raw_cap);
709 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
711 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
712 let old_size = old_table.size();
714 if old_table.capacity() == 0 || old_table.size() == 0 {
719 // Specialization of the other branch.
720 let mut bucket = Bucket::first(&mut old_table);
722 // "So a few of the first shall be last: for many be called,
725 // We'll most likely encounter a few buckets at the beginning that
726 // have their initial buckets near the end of the table. They were
727 // placed at the beginning as the probe wrapped around the table
728 // during insertion. We must skip forward to a bucket that won't
729 // get reinserted too early and won't unfairly steal others spot.
730 // This eliminates the need for robin hood.
732 bucket = match bucket.peek() {
734 if full.displacement() == 0 {
735 // This bucket occupies its ideal spot.
736 // It indicates the start of another "cluster".
737 bucket = full.into_bucket();
740 // Leaving this bucket in the last cluster for later.
744 // Encountered a hole between clusters.
751 // This is how the buckets might be laid out in memory:
752 // ($ marks an initialized bucket)
754 // |$$$_$$$$$$_$$$$$|
756 // But we've skipped the entire initial cluster of buckets
757 // and will continue iteration in this order:
760 // ^ wrap around once end is reached
763 // ^ exit once table.size == 0
765 bucket = match bucket.peek() {
767 let h = bucket.hash();
768 let (b, k, v) = bucket.take();
769 self.insert_hashed_ordered(h, k, v);
770 if b.table().size() == 0 {
775 Empty(b) => b.into_bucket(),
780 assert_eq!(self.table.size(), old_size);
783 /// Shrinks the capacity of the map as much as possible. It will drop
784 /// down as much as possible while maintaining the internal rules
785 /// and possibly leaving some space in accordance with the resize policy.
790 /// use std::collections::HashMap;
792 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
793 /// map.insert(1, 2);
794 /// map.insert(3, 4);
795 /// assert!(map.capacity() >= 100);
796 /// map.shrink_to_fit();
797 /// assert!(map.capacity() >= 2);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn shrink_to_fit(&mut self) {
801 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
802 if self.raw_capacity() != new_raw_cap {
803 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
804 let old_size = old_table.size();
806 // Shrink the table. Naive algorithm for resizing:
807 for (h, k, v) in old_table.into_iter() {
808 self.insert_hashed_nocheck(h, k, v);
811 debug_assert_eq!(self.table.size(), old_size);
815 /// Insert a pre-hashed key-value pair, without first checking
816 /// that there's enough room in the buckets. Returns a reference to the
817 /// newly insert value.
819 /// If the key already exists, the hashtable will be returned untouched
820 /// and a reference to the existing element will be returned.
821 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
822 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
824 Some(Occupied(mut elem)) => Some(elem.insert(v)),
825 Some(Vacant(elem)) => {
829 None => unreachable!(),
833 /// An iterator visiting all keys in arbitrary order.
834 /// Iterator element type is `&'a K`.
839 /// use std::collections::HashMap;
841 /// let mut map = HashMap::new();
842 /// map.insert("a", 1);
843 /// map.insert("b", 2);
844 /// map.insert("c", 3);
846 /// for key in map.keys() {
847 /// println!("{}", key);
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub fn keys(&self) -> Keys<K, V> {
852 Keys { inner: self.iter() }
855 /// An iterator visiting all values in arbitrary order.
856 /// Iterator element type is `&'a V`.
861 /// use std::collections::HashMap;
863 /// let mut map = HashMap::new();
864 /// map.insert("a", 1);
865 /// map.insert("b", 2);
866 /// map.insert("c", 3);
868 /// for val in map.values() {
869 /// println!("{}", val);
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn values(&self) -> Values<K, V> {
874 Values { inner: self.iter() }
877 /// An iterator visiting all values mutably in arbitrary order.
878 /// Iterator element type is `&'a mut V`.
883 /// use std::collections::HashMap;
885 /// let mut map = HashMap::new();
887 /// map.insert("a", 1);
888 /// map.insert("b", 2);
889 /// map.insert("c", 3);
891 /// for val in map.values_mut() {
892 /// *val = *val + 10;
895 /// for val in map.values() {
896 /// println!("{}", val);
899 #[stable(feature = "map_values_mut", since = "1.10.0")]
900 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
901 ValuesMut { inner: self.iter_mut() }
904 /// An iterator visiting all key-value pairs in arbitrary order.
905 /// Iterator element type is `(&'a K, &'a V)`.
910 /// use std::collections::HashMap;
912 /// let mut map = HashMap::new();
913 /// map.insert("a", 1);
914 /// map.insert("b", 2);
915 /// map.insert("c", 3);
917 /// for (key, val) in map.iter() {
918 /// println!("key: {} val: {}", key, val);
921 #[stable(feature = "rust1", since = "1.0.0")]
922 pub fn iter(&self) -> Iter<K, V> {
923 Iter { inner: self.table.iter() }
926 /// An iterator visiting all key-value pairs in arbitrary order,
927 /// with mutable references to the values.
928 /// Iterator element type is `(&'a K, &'a mut V)`.
933 /// use std::collections::HashMap;
935 /// let mut map = HashMap::new();
936 /// map.insert("a", 1);
937 /// map.insert("b", 2);
938 /// map.insert("c", 3);
940 /// // Update all values
941 /// for (_, val) in map.iter_mut() {
945 /// for (key, val) in &map {
946 /// println!("key: {} val: {}", key, val);
949 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn iter_mut(&mut self) -> IterMut<K, V> {
951 IterMut { inner: self.table.iter_mut() }
954 /// Gets the given key's corresponding entry in the map for in-place manipulation.
959 /// use std::collections::HashMap;
961 /// let mut letters = HashMap::new();
963 /// for ch in "a short treatise on fungi".chars() {
964 /// let counter = letters.entry(ch).or_insert(0);
968 /// assert_eq!(letters[&'s'], 2);
969 /// assert_eq!(letters[&'t'], 3);
970 /// assert_eq!(letters[&'u'], 1);
971 /// assert_eq!(letters.get(&'y'), None);
973 #[stable(feature = "rust1", since = "1.0.0")]
974 pub fn entry(&mut self, key: K) -> Entry<K, V> {
977 self.search_mut(&key).into_entry(key).expect("unreachable")
980 /// Returns the number of elements in the map.
985 /// use std::collections::HashMap;
987 /// let mut a = HashMap::new();
988 /// assert_eq!(a.len(), 0);
989 /// a.insert(1, "a");
990 /// assert_eq!(a.len(), 1);
992 #[stable(feature = "rust1", since = "1.0.0")]
993 pub fn len(&self) -> usize {
997 /// Returns true if the map contains no elements.
1002 /// use std::collections::HashMap;
1004 /// let mut a = HashMap::new();
1005 /// assert!(a.is_empty());
1006 /// a.insert(1, "a");
1007 /// assert!(!a.is_empty());
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 pub fn is_empty(&self) -> bool {
1015 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1016 /// allocated memory for reuse.
1021 /// use std::collections::HashMap;
1023 /// let mut a = HashMap::new();
1024 /// a.insert(1, "a");
1025 /// a.insert(2, "b");
1027 /// for (k, v) in a.drain().take(1) {
1028 /// assert!(k == 1 || k == 2);
1029 /// assert!(v == "a" || v == "b");
1032 /// assert!(a.is_empty());
1035 #[stable(feature = "drain", since = "1.6.0")]
1036 pub fn drain(&mut self) -> Drain<K, V> {
1037 Drain { inner: self.table.drain() }
1040 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1046 /// use std::collections::HashMap;
1048 /// let mut a = HashMap::new();
1049 /// a.insert(1, "a");
1051 /// assert!(a.is_empty());
1053 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn clear(&mut self) {
1059 /// Returns a reference to the value corresponding to the key.
1061 /// The key may be any borrowed form of the map's key type, but
1062 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1065 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1066 /// [`Hash`]: ../../std/hash/trait.Hash.html
1071 /// use std::collections::HashMap;
1073 /// let mut map = HashMap::new();
1074 /// map.insert(1, "a");
1075 /// assert_eq!(map.get(&1), Some(&"a"));
1076 /// assert_eq!(map.get(&2), None);
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1083 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1086 /// Returns true if the map contains a value for the specified key.
1088 /// The key may be any borrowed form of the map's key type, but
1089 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1092 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1093 /// [`Hash`]: ../../std/hash/trait.Hash.html
1098 /// use std::collections::HashMap;
1100 /// let mut map = HashMap::new();
1101 /// map.insert(1, "a");
1102 /// assert_eq!(map.contains_key(&1), true);
1103 /// assert_eq!(map.contains_key(&2), false);
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1110 self.search(k).into_occupied_bucket().is_some()
1113 /// Returns a mutable reference to the value corresponding to the key.
1115 /// The key may be any borrowed form of the map's key type, but
1116 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1119 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1120 /// [`Hash`]: ../../std/hash/trait.Hash.html
1125 /// use std::collections::HashMap;
1127 /// let mut map = HashMap::new();
1128 /// map.insert(1, "a");
1129 /// if let Some(x) = map.get_mut(&1) {
1132 /// assert_eq!(map[&1], "b");
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1139 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1142 /// Inserts a key-value pair into the map.
1144 /// If the map did not have this key present, `None` is returned.
1146 /// If the map did have this key present, the value is updated, and the old
1147 /// value is returned. The key is not updated, though; this matters for
1148 /// types that can be `==` without being identical. See the [module-level
1149 /// documentation] for more.
1151 /// [module-level documentation]: index.html#insert-and-complex-keys
1156 /// use std::collections::HashMap;
1158 /// let mut map = HashMap::new();
1159 /// assert_eq!(map.insert(37, "a"), None);
1160 /// assert_eq!(map.is_empty(), false);
1162 /// map.insert(37, "b");
1163 /// assert_eq!(map.insert(37, "c"), Some("b"));
1164 /// assert_eq!(map[&37], "c");
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1168 let hash = self.make_hash(&k);
1170 self.insert_hashed_nocheck(hash, k, v)
1173 /// Removes a key from the map, returning the value at the key if the key
1174 /// was previously in the map.
1176 /// The key may be any borrowed form of the map's key type, but
1177 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1180 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1181 /// [`Hash`]: ../../std/hash/trait.Hash.html
1186 /// use std::collections::HashMap;
1188 /// let mut map = HashMap::new();
1189 /// map.insert(1, "a");
1190 /// assert_eq!(map.remove(&1), Some("a"));
1191 /// assert_eq!(map.remove(&1), None);
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1198 if self.table.size() == 0 {
1202 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl<K, V, S> PartialEq for HashMap<K, V, S>
1212 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1213 if self.len() != other.len() {
1217 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<K, V, S> Eq for HashMap<K, V, S>
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<K, V, S> Debug for HashMap<K, V, S>
1231 where K: Eq + Hash + Debug,
1235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1236 f.debug_map().entries(self.iter()).finish()
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 impl<K, V, S> Default for HashMap<K, V, S>
1243 S: BuildHasher + Default
1245 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1246 fn default() -> HashMap<K, V, S> {
1247 HashMap::with_hasher(Default::default())
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1253 where K: Eq + Hash + Borrow<Q>,
1260 fn index(&self, index: &Q) -> &V {
1261 self.get(index).expect("no entry found for key")
1265 /// HashMap iterator.
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub struct Iter<'a, K: 'a, V: 'a> {
1268 inner: table::Iter<'a, K, V>,
1271 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<'a, K, V> Clone for Iter<'a, K, V> {
1274 fn clone(&self) -> Iter<'a, K, V> {
1275 Iter { inner: self.inner.clone() }
1279 #[stable(feature = "std_debug", since = "1.16.0")]
1280 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1283 .entries(self.clone())
1288 /// HashMap mutable values iterator.
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 pub struct IterMut<'a, K: 'a, V: 'a> {
1291 inner: table::IterMut<'a, K, V>,
1294 /// HashMap move iterator.
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub struct IntoIter<K, V> {
1297 pub(super) inner: table::IntoIter<K, V>,
1300 /// HashMap keys iterator.
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub struct Keys<'a, K: 'a, V: 'a> {
1303 inner: Iter<'a, K, V>,
1306 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 impl<'a, K, V> Clone for Keys<'a, K, V> {
1309 fn clone(&self) -> Keys<'a, K, V> {
1310 Keys { inner: self.inner.clone() }
1314 #[stable(feature = "std_debug", since = "1.16.0")]
1315 impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> {
1316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 .entries(self.clone())
1323 /// HashMap values iterator.
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 pub struct Values<'a, K: 'a, V: 'a> {
1326 inner: Iter<'a, K, V>,
1329 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<'a, K, V> Clone for Values<'a, K, V> {
1332 fn clone(&self) -> Values<'a, K, V> {
1333 Values { inner: self.inner.clone() }
1337 #[stable(feature = "std_debug", since = "1.16.0")]
1338 impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> {
1339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1341 .entries(self.clone())
1346 /// HashMap drain iterator.
1347 #[stable(feature = "drain", since = "1.6.0")]
1348 pub struct Drain<'a, K: 'a, V: 'a> {
1349 pub(super) inner: table::Drain<'a, K, V>,
1352 /// Mutable HashMap values iterator.
1353 #[stable(feature = "map_values_mut", since = "1.10.0")]
1354 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1355 inner: IterMut<'a, K, V>,
1358 enum InternalEntry<K, V, M> {
1359 Occupied { elem: FullBucket<K, V, M> },
1362 elem: VacantEntryState<K, V, M>,
1367 impl<K, V, M> InternalEntry<K, V, M> {
1369 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1371 InternalEntry::Occupied { elem } => Some(elem),
1377 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1379 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1381 InternalEntry::Occupied { elem } => {
1382 Some(Occupied(OccupiedEntry {
1387 InternalEntry::Vacant { hash, elem } => {
1388 Some(Vacant(VacantEntry {
1394 InternalEntry::TableIsEmpty => None,
1399 /// A view into a single location in a map, which may be vacant or occupied.
1400 /// This enum is constructed from the [`entry`] method on [`HashMap`].
1402 /// [`HashMap`]: struct.HashMap.html
1403 /// [`entry`]: struct.HashMap.html#method.entry
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub enum Entry<'a, K: 'a, V: 'a> {
1406 /// An occupied Entry.
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1409 OccupiedEntry<'a, K, V>),
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1414 VacantEntry<'a, K, V>),
1417 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1418 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1419 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1422 f.debug_tuple("Entry")
1426 Occupied(ref o) => {
1427 f.debug_tuple("Entry")
1435 /// A view into a single occupied location in a HashMap.
1436 /// It is part of the [`Entry`] enum.
1438 /// [`Entry`]: enum.Entry.html
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1442 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1445 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1446 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 f.debug_struct("OccupiedEntry")
1449 .field("key", self.key())
1450 .field("value", self.get())
1455 /// A view into a single empty location in a HashMap.
1456 /// It is part of the [`Entry`] enum.
1458 /// [`Entry`]: enum.Entry.html
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1463 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1466 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1467 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1469 f.debug_tuple("VacantEntry")
1475 /// Possible states of a VacantEntry.
1476 enum VacantEntryState<K, V, M> {
1477 /// The index is occupied, but the key to insert has precedence,
1478 /// and will kick the current one out on insertion.
1479 NeqElem(FullBucket<K, V, M>, usize),
1480 /// The index is genuinely vacant.
1481 NoElem(EmptyBucket<K, V, M>),
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1489 type Item = (&'a K, &'a V);
1490 type IntoIter = Iter<'a, K, V>;
1492 fn into_iter(self) -> Iter<'a, K, V> {
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1502 type Item = (&'a K, &'a mut V);
1503 type IntoIter = IterMut<'a, K, V>;
1505 fn into_iter(mut self) -> IterMut<'a, K, V> {
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1516 type IntoIter = IntoIter<K, V>;
1518 /// Creates a consuming iterator, that is, one that moves each key-value
1519 /// pair out of the map in arbitrary order. The map cannot be used after
1525 /// use std::collections::HashMap;
1527 /// let mut map = HashMap::new();
1528 /// map.insert("a", 1);
1529 /// map.insert("b", 2);
1530 /// map.insert("c", 3);
1532 /// // Not possible with .iter()
1533 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1535 fn into_iter(self) -> IntoIter<K, V> {
1536 IntoIter { inner: self.table.into_iter() }
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1542 type Item = (&'a K, &'a V);
1545 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1549 fn size_hint(&self) -> (usize, Option<usize>) {
1550 self.inner.size_hint()
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1556 fn len(&self) -> usize {
1561 #[unstable(feature = "fused", issue = "35602")]
1562 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1566 type Item = (&'a K, &'a mut V);
1569 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1573 fn size_hint(&self) -> (usize, Option<usize>) {
1574 self.inner.size_hint()
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1580 fn len(&self) -> usize {
1584 #[unstable(feature = "fused", issue = "35602")]
1585 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1587 #[stable(feature = "std_debug", since = "1.16.0")]
1588 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1589 where K: fmt::Debug,
1592 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1594 .entries(self.inner.iter())
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<K, V> Iterator for IntoIter<K, V> {
1604 fn next(&mut self) -> Option<(K, V)> {
1605 self.inner.next().map(|(_, k, v)| (k, v))
1608 fn size_hint(&self) -> (usize, Option<usize>) {
1609 self.inner.size_hint()
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1615 fn len(&self) -> usize {
1619 #[unstable(feature = "fused", issue = "35602")]
1620 impl<K, V> FusedIterator for IntoIter<K, V> {}
1622 #[stable(feature = "std_debug", since = "1.16.0")]
1623 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1626 .entries(self.inner.iter())
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1636 fn next(&mut self) -> Option<(&'a K)> {
1637 self.inner.next().map(|(k, _)| k)
1640 fn size_hint(&self) -> (usize, Option<usize>) {
1641 self.inner.size_hint()
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1647 fn len(&self) -> usize {
1651 #[unstable(feature = "fused", issue = "35602")]
1652 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<'a, K, V> Iterator for Values<'a, K, V> {
1659 fn next(&mut self) -> Option<(&'a V)> {
1660 self.inner.next().map(|(_, v)| v)
1663 fn size_hint(&self) -> (usize, Option<usize>) {
1664 self.inner.size_hint()
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1670 fn len(&self) -> usize {
1674 #[unstable(feature = "fused", issue = "35602")]
1675 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1677 #[stable(feature = "map_values_mut", since = "1.10.0")]
1678 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1679 type Item = &'a mut V;
1682 fn next(&mut self) -> Option<(&'a mut V)> {
1683 self.inner.next().map(|(_, v)| v)
1686 fn size_hint(&self) -> (usize, Option<usize>) {
1687 self.inner.size_hint()
1690 #[stable(feature = "map_values_mut", since = "1.10.0")]
1691 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1693 fn len(&self) -> usize {
1697 #[unstable(feature = "fused", issue = "35602")]
1698 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1700 #[stable(feature = "std_debug", since = "1.16.0")]
1701 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1702 where K: fmt::Debug,
1705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1707 .entries(self.inner.inner.iter())
1712 #[stable(feature = "drain", since = "1.6.0")]
1713 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1717 fn next(&mut self) -> Option<(K, V)> {
1718 self.inner.next().map(|(_, k, v)| (k, v))
1721 fn size_hint(&self) -> (usize, Option<usize>) {
1722 self.inner.size_hint()
1725 #[stable(feature = "drain", since = "1.6.0")]
1726 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1728 fn len(&self) -> usize {
1732 #[unstable(feature = "fused", issue = "35602")]
1733 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1735 #[stable(feature = "std_debug", since = "1.16.0")]
1736 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1737 where K: fmt::Debug,
1740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1742 .entries(self.inner.iter())
1747 impl<'a, K, V> Entry<'a, K, V> {
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 /// Ensures a value is in the entry by inserting the default if empty, and returns
1750 /// a mutable reference to the value in the entry.
1755 /// use std::collections::HashMap;
1757 /// let mut map: HashMap<&str, u32> = HashMap::new();
1758 /// map.entry("poneyland").or_insert(12);
1760 /// assert_eq!(map["poneyland"], 12);
1762 /// *map.entry("poneyland").or_insert(12) += 10;
1763 /// assert_eq!(map["poneyland"], 22);
1765 pub fn or_insert(self, default: V) -> &'a mut V {
1767 Occupied(entry) => entry.into_mut(),
1768 Vacant(entry) => entry.insert(default),
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1774 /// and returns a mutable reference to the value in the entry.
1779 /// use std::collections::HashMap;
1781 /// let mut map: HashMap<&str, String> = HashMap::new();
1782 /// let s = "hoho".to_string();
1784 /// map.entry("poneyland").or_insert_with(|| s);
1786 /// assert_eq!(map["poneyland"], "hoho".to_string());
1788 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1790 Occupied(entry) => entry.into_mut(),
1791 Vacant(entry) => entry.insert(default()),
1795 /// Returns a reference to this entry's key.
1800 /// use std::collections::HashMap;
1802 /// let mut map: HashMap<&str, u32> = HashMap::new();
1803 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1805 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1806 pub fn key(&self) -> &K {
1808 Occupied(ref entry) => entry.key(),
1809 Vacant(ref entry) => entry.key(),
1814 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1815 /// Gets a reference to the key in the entry.
1820 /// use std::collections::HashMap;
1822 /// let mut map: HashMap<&str, u32> = HashMap::new();
1823 /// map.entry("poneyland").or_insert(12);
1824 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1826 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1827 pub fn key(&self) -> &K {
1831 /// Deprecated, renamed to `remove_entry`
1832 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1833 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
1834 pub fn remove_pair(self) -> (K, V) {
1838 /// Take the ownership of the key and value from the map.
1843 /// use std::collections::HashMap;
1844 /// use std::collections::hash_map::Entry;
1846 /// let mut map: HashMap<&str, u32> = HashMap::new();
1847 /// map.entry("poneyland").or_insert(12);
1849 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1850 /// // We delete the entry from the map.
1851 /// o.remove_entry();
1854 /// assert_eq!(map.contains_key("poneyland"), false);
1856 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
1857 pub fn remove_entry(self) -> (K, V) {
1858 pop_internal(self.elem)
1861 /// Gets a reference to the value in the entry.
1866 /// use std::collections::HashMap;
1867 /// use std::collections::hash_map::Entry;
1869 /// let mut map: HashMap<&str, u32> = HashMap::new();
1870 /// map.entry("poneyland").or_insert(12);
1872 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1873 /// assert_eq!(o.get(), &12);
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 pub fn get(&self) -> &V {
1881 /// Gets a mutable reference to the value in the entry.
1886 /// use std::collections::HashMap;
1887 /// use std::collections::hash_map::Entry;
1889 /// let mut map: HashMap<&str, u32> = HashMap::new();
1890 /// map.entry("poneyland").or_insert(12);
1892 /// assert_eq!(map["poneyland"], 12);
1893 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
1894 /// *o.get_mut() += 10;
1897 /// assert_eq!(map["poneyland"], 22);
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 pub fn get_mut(&mut self) -> &mut V {
1901 self.elem.read_mut().1
1904 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1905 /// with a lifetime bound to the map itself.
1910 /// use std::collections::HashMap;
1911 /// use std::collections::hash_map::Entry;
1913 /// let mut map: HashMap<&str, u32> = HashMap::new();
1914 /// map.entry("poneyland").or_insert(12);
1916 /// assert_eq!(map["poneyland"], 12);
1917 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1918 /// *o.into_mut() += 10;
1921 /// assert_eq!(map["poneyland"], 22);
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 pub fn into_mut(self) -> &'a mut V {
1925 self.elem.into_mut_refs().1
1928 /// Sets the value of the entry, and returns the entry's old value.
1933 /// use std::collections::HashMap;
1934 /// use std::collections::hash_map::Entry;
1936 /// let mut map: HashMap<&str, u32> = HashMap::new();
1937 /// map.entry("poneyland").or_insert(12);
1939 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
1940 /// assert_eq!(o.insert(15), 12);
1943 /// assert_eq!(map["poneyland"], 15);
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 pub fn insert(&mut self, mut value: V) -> V {
1947 let old_value = self.get_mut();
1948 mem::swap(&mut value, old_value);
1952 /// Takes the value out of the entry, and returns it.
1957 /// use std::collections::HashMap;
1958 /// use std::collections::hash_map::Entry;
1960 /// let mut map: HashMap<&str, u32> = HashMap::new();
1961 /// map.entry("poneyland").or_insert(12);
1963 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1964 /// assert_eq!(o.remove(), 12);
1967 /// assert_eq!(map.contains_key("poneyland"), false);
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 pub fn remove(self) -> V {
1971 pop_internal(self.elem).1
1974 /// Returns a key that was used for search.
1976 /// The key was retained for further use.
1977 fn take_key(&mut self) -> Option<K> {
1982 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1983 /// Gets a reference to the key that would be used when inserting a value
1984 /// through the `VacantEntry`.
1989 /// use std::collections::HashMap;
1991 /// let mut map: HashMap<&str, u32> = HashMap::new();
1992 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1994 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1995 pub fn key(&self) -> &K {
1999 /// Take ownership of the key.
2004 /// use std::collections::HashMap;
2005 /// use std::collections::hash_map::Entry;
2007 /// let mut map: HashMap<&str, u32> = HashMap::new();
2009 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2013 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2014 pub fn into_key(self) -> K {
2018 /// Sets the value of the entry with the VacantEntry's key,
2019 /// and returns a mutable reference to it.
2024 /// use std::collections::HashMap;
2025 /// use std::collections::hash_map::Entry;
2027 /// let mut map: HashMap<&str, u32> = HashMap::new();
2029 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2032 /// assert_eq!(map["poneyland"], 37);
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 pub fn insert(self, value: V) -> &'a mut V {
2037 NeqElem(bucket, disp) => robin_hood(bucket, disp, self.hash, self.key, value),
2038 NoElem(bucket) => bucket.put(self.hash, self.key, value).into_mut_refs().1,
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2046 S: BuildHasher + Default
2048 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2049 let mut map = HashMap::with_hasher(Default::default());
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2060 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2061 // Keys may be already present or show multiple times in the iterator.
2062 // Reserve the entire hint lower bound if the map is empty.
2063 // Otherwise reserve half the hint (rounded up), so the map
2064 // will only resize twice in the worst case.
2065 let iter = iter.into_iter();
2066 let reserve = if self.is_empty() {
2069 (iter.size_hint().0 + 1) / 2
2071 self.reserve(reserve);
2072 for (k, v) in iter {
2078 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2079 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2080 where K: Eq + Hash + Copy,
2084 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2085 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2089 /// `RandomState` is the default state for [`HashMap`] types.
2091 /// A particular instance `RandomState` will create the same instances of
2092 /// [`Hasher`], but the hashers created by two different `RandomState`
2093 /// instances are unlikely to produce the same result for the same values.
2095 /// [`HashMap`]: struct.HashMap.html
2096 /// [`Hasher`]: ../../hash/trait.Hasher.html
2101 /// use std::collections::HashMap;
2102 /// use std::collections::hash_map::RandomState;
2104 /// let s = RandomState::new();
2105 /// let mut map = HashMap::with_hasher(s);
2106 /// map.insert(1, 2);
2109 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2110 pub struct RandomState {
2116 /// Constructs a new `RandomState` that is initialized with random keys.
2121 /// use std::collections::hash_map::RandomState;
2123 /// let s = RandomState::new();
2126 #[allow(deprecated)]
2128 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2129 pub fn new() -> RandomState {
2130 // Historically this function did not cache keys from the OS and instead
2131 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2132 // was discovered, however, that because we re-seed the thread-local RNG
2133 // from the OS periodically that this can cause excessive slowdown when
2134 // many hash maps are created on a thread. To solve this performance
2135 // trap we cache the first set of randomly generated keys per-thread.
2137 // Later in #36481 it was discovered that exposing a deterministic
2138 // iteration order allows a form of DOS attack. To counter that we
2139 // increment one of the seeds on every RandomState creation, giving
2140 // every corresponding HashMap a different iteration order.
2141 thread_local!(static KEYS: Cell<(u64, u64)> = {
2142 let r = rand::OsRng::new();
2143 let mut r = r.expect("failed to create an OS RNG");
2144 Cell::new((r.gen(), r.gen()))
2148 let (k0, k1) = keys.get();
2149 keys.set((k0.wrapping_add(1), k1));
2150 RandomState { k0: k0, k1: k1 }
2155 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2156 impl BuildHasher for RandomState {
2157 type Hasher = DefaultHasher;
2159 #[allow(deprecated)]
2160 fn build_hasher(&self) -> DefaultHasher {
2161 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2165 /// The default [`Hasher`] used by [`RandomState`].
2167 /// The internal algorithm is not specified, and so it and its hashes should
2168 /// not be relied upon over releases.
2170 /// [`RandomState`]: struct.RandomState.html
2171 /// [`Hasher`]: ../../hash/trait.Hasher.html
2172 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2173 #[allow(deprecated)]
2175 pub struct DefaultHasher(SipHasher13);
2177 impl DefaultHasher {
2178 /// Creates a new `DefaultHasher`.
2180 /// This hasher is not guaranteed to be the same as all other
2181 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2182 /// instances created through `new` or `default`.
2183 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2184 #[allow(deprecated)]
2185 pub fn new() -> DefaultHasher {
2186 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2190 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2191 impl Default for DefaultHasher {
2192 /// Creates a new `DefaultHasher` using [`DefaultHasher::new`]. See
2193 /// [`DefaultHasher::new`] documentation for more information.
2195 /// [`DefaultHasher::new`]: #method.new
2196 fn default() -> DefaultHasher {
2197 DefaultHasher::new()
2201 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2202 impl Hasher for DefaultHasher {
2204 fn write(&mut self, msg: &[u8]) {
2209 fn finish(&self) -> u64 {
2214 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2215 impl Default for RandomState {
2216 /// Constructs a new `RandomState`.
2218 fn default() -> RandomState {
2223 #[stable(feature = "std_debug", since = "1.16.0")]
2224 impl fmt::Debug for RandomState {
2225 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2226 f.pad("RandomState { .. }")
2230 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2231 where K: Eq + Hash + Borrow<Q>,
2237 fn get(&self, key: &Q) -> Option<&K> {
2238 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2241 fn take(&mut self, key: &Q) -> Option<K> {
2242 if self.table.size() == 0 {
2246 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2249 fn replace(&mut self, key: K) -> Option<K> {
2252 match self.entry(key) {
2253 Occupied(mut occupied) => {
2254 let key = occupied.take_key().unwrap();
2255 Some(mem::replace(occupied.elem.read_mut().0, key))
2266 fn assert_covariance() {
2267 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2270 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2273 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2276 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2279 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2282 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2285 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2288 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2291 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2294 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2297 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2298 -> Drain<'new, &'new str, &'new str> {
2306 use super::Entry::{Occupied, Vacant};
2307 use super::RandomState;
2309 use rand::{thread_rng, Rng};
2312 fn test_zero_capacities() {
2313 type HM = HashMap<i32, i32>;
2316 assert_eq!(m.capacity(), 0);
2318 let m = HM::default();
2319 assert_eq!(m.capacity(), 0);
2321 let m = HM::with_hasher(RandomState::new());
2322 assert_eq!(m.capacity(), 0);
2324 let m = HM::with_capacity(0);
2325 assert_eq!(m.capacity(), 0);
2327 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2328 assert_eq!(m.capacity(), 0);
2330 let mut m = HM::new();
2336 assert_eq!(m.capacity(), 0);
2338 let mut m = HM::new();
2340 assert_eq!(m.capacity(), 0);
2344 fn test_create_capacity_zero() {
2345 let mut m = HashMap::with_capacity(0);
2347 assert!(m.insert(1, 1).is_none());
2349 assert!(m.contains_key(&1));
2350 assert!(!m.contains_key(&0));
2355 let mut m = HashMap::new();
2356 assert_eq!(m.len(), 0);
2357 assert!(m.insert(1, 2).is_none());
2358 assert_eq!(m.len(), 1);
2359 assert!(m.insert(2, 4).is_none());
2360 assert_eq!(m.len(), 2);
2361 assert_eq!(*m.get(&1).unwrap(), 2);
2362 assert_eq!(*m.get(&2).unwrap(), 4);
2367 let mut m = HashMap::new();
2368 assert_eq!(m.len(), 0);
2369 assert!(m.insert(1, 2).is_none());
2370 assert_eq!(m.len(), 1);
2371 assert!(m.insert(2, 4).is_none());
2372 assert_eq!(m.len(), 2);
2374 assert_eq!(*m2.get(&1).unwrap(), 2);
2375 assert_eq!(*m2.get(&2).unwrap(), 4);
2376 assert_eq!(m2.len(), 2);
2379 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2381 #[derive(Hash, PartialEq, Eq)]
2387 fn new(k: usize) -> Dropable {
2388 DROP_VECTOR.with(|slot| {
2389 slot.borrow_mut()[k] += 1;
2396 impl Drop for Dropable {
2397 fn drop(&mut self) {
2398 DROP_VECTOR.with(|slot| {
2399 slot.borrow_mut()[self.k] -= 1;
2404 impl Clone for Dropable {
2405 fn clone(&self) -> Dropable {
2406 Dropable::new(self.k)
2412 DROP_VECTOR.with(|slot| {
2413 *slot.borrow_mut() = vec![0; 200];
2417 let mut m = HashMap::new();
2419 DROP_VECTOR.with(|v| {
2421 assert_eq!(v.borrow()[i], 0);
2426 let d1 = Dropable::new(i);
2427 let d2 = Dropable::new(i + 100);
2431 DROP_VECTOR.with(|v| {
2433 assert_eq!(v.borrow()[i], 1);
2438 let k = Dropable::new(i);
2439 let v = m.remove(&k);
2441 assert!(v.is_some());
2443 DROP_VECTOR.with(|v| {
2444 assert_eq!(v.borrow()[i], 1);
2445 assert_eq!(v.borrow()[i+100], 1);
2449 DROP_VECTOR.with(|v| {
2451 assert_eq!(v.borrow()[i], 0);
2452 assert_eq!(v.borrow()[i+100], 0);
2456 assert_eq!(v.borrow()[i], 1);
2457 assert_eq!(v.borrow()[i+100], 1);
2462 DROP_VECTOR.with(|v| {
2464 assert_eq!(v.borrow()[i], 0);
2470 fn test_into_iter_drops() {
2471 DROP_VECTOR.with(|v| {
2472 *v.borrow_mut() = vec![0; 200];
2476 let mut hm = HashMap::new();
2478 DROP_VECTOR.with(|v| {
2480 assert_eq!(v.borrow()[i], 0);
2485 let d1 = Dropable::new(i);
2486 let d2 = Dropable::new(i + 100);
2490 DROP_VECTOR.with(|v| {
2492 assert_eq!(v.borrow()[i], 1);
2499 // By the way, ensure that cloning doesn't screw up the dropping.
2503 let mut half = hm.into_iter().take(50);
2505 DROP_VECTOR.with(|v| {
2507 assert_eq!(v.borrow()[i], 1);
2511 for _ in half.by_ref() {}
2513 DROP_VECTOR.with(|v| {
2515 .filter(|&i| v.borrow()[i] == 1)
2519 .filter(|&i| v.borrow()[i + 100] == 1)
2527 DROP_VECTOR.with(|v| {
2529 assert_eq!(v.borrow()[i], 0);
2535 fn test_empty_remove() {
2536 let mut m: HashMap<isize, bool> = HashMap::new();
2537 assert_eq!(m.remove(&0), None);
2541 fn test_empty_entry() {
2542 let mut m: HashMap<isize, bool> = HashMap::new();
2544 Occupied(_) => panic!(),
2547 assert!(*m.entry(0).or_insert(true));
2548 assert_eq!(m.len(), 1);
2552 fn test_empty_iter() {
2553 let mut m: HashMap<isize, bool> = HashMap::new();
2554 assert_eq!(m.drain().next(), None);
2555 assert_eq!(m.keys().next(), None);
2556 assert_eq!(m.values().next(), None);
2557 assert_eq!(m.values_mut().next(), None);
2558 assert_eq!(m.iter().next(), None);
2559 assert_eq!(m.iter_mut().next(), None);
2560 assert_eq!(m.len(), 0);
2561 assert!(m.is_empty());
2562 assert_eq!(m.into_iter().next(), None);
2566 fn test_lots_of_insertions() {
2567 let mut m = HashMap::new();
2569 // Try this a few times to make sure we never screw up the hashmap's
2572 assert!(m.is_empty());
2575 assert!(m.insert(i, i).is_none());
2579 assert_eq!(r, Some(&j));
2582 for j in i + 1..1001 {
2584 assert_eq!(r, None);
2588 for i in 1001..2001 {
2589 assert!(!m.contains_key(&i));
2594 assert!(m.remove(&i).is_some());
2597 assert!(!m.contains_key(&j));
2600 for j in i + 1..1001 {
2601 assert!(m.contains_key(&j));
2606 assert!(!m.contains_key(&i));
2610 assert!(m.insert(i, i).is_none());
2614 for i in (1..1001).rev() {
2615 assert!(m.remove(&i).is_some());
2618 assert!(!m.contains_key(&j));
2622 assert!(m.contains_key(&j));
2629 fn test_find_mut() {
2630 let mut m = HashMap::new();
2631 assert!(m.insert(1, 12).is_none());
2632 assert!(m.insert(2, 8).is_none());
2633 assert!(m.insert(5, 14).is_none());
2635 match m.get_mut(&5) {
2637 Some(x) => *x = new,
2639 assert_eq!(m.get(&5), Some(&new));
2643 fn test_insert_overwrite() {
2644 let mut m = HashMap::new();
2645 assert!(m.insert(1, 2).is_none());
2646 assert_eq!(*m.get(&1).unwrap(), 2);
2647 assert!(!m.insert(1, 3).is_none());
2648 assert_eq!(*m.get(&1).unwrap(), 3);
2652 fn test_insert_conflicts() {
2653 let mut m = HashMap::with_capacity(4);
2654 assert!(m.insert(1, 2).is_none());
2655 assert!(m.insert(5, 3).is_none());
2656 assert!(m.insert(9, 4).is_none());
2657 assert_eq!(*m.get(&9).unwrap(), 4);
2658 assert_eq!(*m.get(&5).unwrap(), 3);
2659 assert_eq!(*m.get(&1).unwrap(), 2);
2663 fn test_conflict_remove() {
2664 let mut m = HashMap::with_capacity(4);
2665 assert!(m.insert(1, 2).is_none());
2666 assert_eq!(*m.get(&1).unwrap(), 2);
2667 assert!(m.insert(5, 3).is_none());
2668 assert_eq!(*m.get(&1).unwrap(), 2);
2669 assert_eq!(*m.get(&5).unwrap(), 3);
2670 assert!(m.insert(9, 4).is_none());
2671 assert_eq!(*m.get(&1).unwrap(), 2);
2672 assert_eq!(*m.get(&5).unwrap(), 3);
2673 assert_eq!(*m.get(&9).unwrap(), 4);
2674 assert!(m.remove(&1).is_some());
2675 assert_eq!(*m.get(&9).unwrap(), 4);
2676 assert_eq!(*m.get(&5).unwrap(), 3);
2680 fn test_is_empty() {
2681 let mut m = HashMap::with_capacity(4);
2682 assert!(m.insert(1, 2).is_none());
2683 assert!(!m.is_empty());
2684 assert!(m.remove(&1).is_some());
2685 assert!(m.is_empty());
2690 let mut m = HashMap::new();
2692 assert_eq!(m.remove(&1), Some(2));
2693 assert_eq!(m.remove(&1), None);
2698 let mut m = HashMap::with_capacity(4);
2700 assert!(m.insert(i, i*2).is_none());
2702 assert_eq!(m.len(), 32);
2704 let mut observed: u32 = 0;
2707 assert_eq!(*v, *k * 2);
2708 observed |= 1 << *k;
2710 assert_eq!(observed, 0xFFFF_FFFF);
2715 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2716 let map: HashMap<_, _> = vec.into_iter().collect();
2717 let keys: Vec<_> = map.keys().cloned().collect();
2718 assert_eq!(keys.len(), 3);
2719 assert!(keys.contains(&1));
2720 assert!(keys.contains(&2));
2721 assert!(keys.contains(&3));
2726 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2727 let map: HashMap<_, _> = vec.into_iter().collect();
2728 let values: Vec<_> = map.values().cloned().collect();
2729 assert_eq!(values.len(), 3);
2730 assert!(values.contains(&'a'));
2731 assert!(values.contains(&'b'));
2732 assert!(values.contains(&'c'));
2736 fn test_values_mut() {
2737 let vec = vec![(1, 1), (2, 2), (3, 3)];
2738 let mut map: HashMap<_, _> = vec.into_iter().collect();
2739 for value in map.values_mut() {
2740 *value = (*value) * 2
2742 let values: Vec<_> = map.values().cloned().collect();
2743 assert_eq!(values.len(), 3);
2744 assert!(values.contains(&2));
2745 assert!(values.contains(&4));
2746 assert!(values.contains(&6));
2751 let mut m = HashMap::new();
2752 assert!(m.get(&1).is_none());
2756 Some(v) => assert_eq!(*v, 2),
2762 let mut m1 = HashMap::new();
2767 let mut m2 = HashMap::new();
2780 let mut map = HashMap::new();
2781 let empty: HashMap<i32, i32> = HashMap::new();
2786 let map_str = format!("{:?}", map);
2788 assert!(map_str == "{1: 2, 3: 4}" ||
2789 map_str == "{3: 4, 1: 2}");
2790 assert_eq!(format!("{:?}", empty), "{}");
2795 let mut m = HashMap::new();
2797 assert_eq!(m.len(), 0);
2798 assert!(m.is_empty());
2801 let old_raw_cap = m.raw_capacity();
2802 while old_raw_cap == m.raw_capacity() {
2807 assert_eq!(m.len(), i);
2808 assert!(!m.is_empty());
2812 fn test_behavior_resize_policy() {
2813 let mut m = HashMap::new();
2815 assert_eq!(m.len(), 0);
2816 assert_eq!(m.raw_capacity(), 0);
2817 assert!(m.is_empty());
2821 assert!(m.is_empty());
2822 let initial_raw_cap = m.raw_capacity();
2823 m.reserve(initial_raw_cap);
2824 let raw_cap = m.raw_capacity();
2826 assert_eq!(raw_cap, initial_raw_cap * 2);
2829 for _ in 0..raw_cap * 3 / 4 {
2833 // three quarters full
2835 assert_eq!(m.len(), i);
2836 assert_eq!(m.raw_capacity(), raw_cap);
2838 for _ in 0..raw_cap / 4 {
2844 let new_raw_cap = m.raw_capacity();
2845 assert_eq!(new_raw_cap, raw_cap * 2);
2847 for _ in 0..raw_cap / 2 - 1 {
2850 assert_eq!(m.raw_capacity(), new_raw_cap);
2852 // A little more than one quarter full.
2854 assert_eq!(m.raw_capacity(), raw_cap);
2855 // again, a little more than half full
2856 for _ in 0..raw_cap / 2 - 1 {
2862 assert_eq!(m.len(), i);
2863 assert!(!m.is_empty());
2864 assert_eq!(m.raw_capacity(), initial_raw_cap);
2868 fn test_reserve_shrink_to_fit() {
2869 let mut m = HashMap::new();
2872 assert!(m.capacity() >= m.len());
2878 let usable_cap = m.capacity();
2879 for i in 128..(128 + 256) {
2881 assert_eq!(m.capacity(), usable_cap);
2884 for i in 100..(128 + 256) {
2885 assert_eq!(m.remove(&i), Some(i));
2889 assert_eq!(m.len(), 100);
2890 assert!(!m.is_empty());
2891 assert!(m.capacity() >= m.len());
2894 assert_eq!(m.remove(&i), Some(i));
2899 assert_eq!(m.len(), 1);
2900 assert!(m.capacity() >= m.len());
2901 assert_eq!(m.remove(&0), Some(0));
2905 fn test_from_iter() {
2906 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2908 let map: HashMap<_, _> = xs.iter().cloned().collect();
2910 for &(k, v) in &xs {
2911 assert_eq!(map.get(&k), Some(&v));
2916 fn test_size_hint() {
2917 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2919 let map: HashMap<_, _> = xs.iter().cloned().collect();
2921 let mut iter = map.iter();
2923 for _ in iter.by_ref().take(3) {}
2925 assert_eq!(iter.size_hint(), (3, Some(3)));
2929 fn test_iter_len() {
2930 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2932 let map: HashMap<_, _> = xs.iter().cloned().collect();
2934 let mut iter = map.iter();
2936 for _ in iter.by_ref().take(3) {}
2938 assert_eq!(iter.len(), 3);
2942 fn test_mut_size_hint() {
2943 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2945 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2947 let mut iter = map.iter_mut();
2949 for _ in iter.by_ref().take(3) {}
2951 assert_eq!(iter.size_hint(), (3, Some(3)));
2955 fn test_iter_mut_len() {
2956 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2958 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2960 let mut iter = map.iter_mut();
2962 for _ in iter.by_ref().take(3) {}
2964 assert_eq!(iter.len(), 3);
2969 let mut map = HashMap::new();
2975 assert_eq!(map[&2], 1);
2980 fn test_index_nonexistent() {
2981 let mut map = HashMap::new();
2992 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2994 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2996 // Existing key (insert)
2997 match map.entry(1) {
2998 Vacant(_) => unreachable!(),
2999 Occupied(mut view) => {
3000 assert_eq!(view.get(), &10);
3001 assert_eq!(view.insert(100), 10);
3004 assert_eq!(map.get(&1).unwrap(), &100);
3005 assert_eq!(map.len(), 6);
3008 // Existing key (update)
3009 match map.entry(2) {
3010 Vacant(_) => unreachable!(),
3011 Occupied(mut view) => {
3012 let v = view.get_mut();
3013 let new_v = (*v) * 10;
3017 assert_eq!(map.get(&2).unwrap(), &200);
3018 assert_eq!(map.len(), 6);
3020 // Existing key (take)
3021 match map.entry(3) {
3022 Vacant(_) => unreachable!(),
3024 assert_eq!(view.remove(), 30);
3027 assert_eq!(map.get(&3), None);
3028 assert_eq!(map.len(), 5);
3031 // Inexistent key (insert)
3032 match map.entry(10) {
3033 Occupied(_) => unreachable!(),
3035 assert_eq!(*view.insert(1000), 1000);
3038 assert_eq!(map.get(&10).unwrap(), &1000);
3039 assert_eq!(map.len(), 6);
3043 fn test_entry_take_doesnt_corrupt() {
3044 #![allow(deprecated)] //rand
3046 fn check(m: &HashMap<isize, ()>) {
3048 assert!(m.contains_key(k),
3049 "{} is in keys() but not in the map?", k);
3053 let mut m = HashMap::new();
3054 let mut rng = thread_rng();
3056 // Populate the map with some items.
3058 let x = rng.gen_range(-10, 10);
3063 let x = rng.gen_range(-10, 10);
3067 println!("{}: remove {}", i, x);
3077 fn test_extend_ref() {
3078 let mut a = HashMap::new();
3080 let mut b = HashMap::new();
3082 b.insert(3, "three");
3086 assert_eq!(a.len(), 3);
3087 assert_eq!(a[&1], "one");
3088 assert_eq!(a[&2], "two");
3089 assert_eq!(a[&3], "three");
3093 fn test_capacity_not_less_than_len() {
3094 let mut a = HashMap::new();
3102 assert!(a.capacity() > a.len());
3104 let free = a.capacity() - a.len();
3110 assert_eq!(a.len(), a.capacity());
3112 // Insert at capacity should cause allocation.
3114 assert!(a.capacity() > a.len());
3118 fn test_occupied_entry_key() {
3119 let mut a = HashMap::new();
3120 let key = "hello there";
3121 let value = "value goes here";
3122 assert!(a.is_empty());
3123 a.insert(key.clone(), value.clone());
3124 assert_eq!(a.len(), 1);
3125 assert_eq!(a[key], value);
3127 match a.entry(key.clone()) {
3128 Vacant(_) => panic!(),
3129 Occupied(e) => assert_eq!(key, *e.key()),
3131 assert_eq!(a.len(), 1);
3132 assert_eq!(a[key], value);
3136 fn test_vacant_entry_key() {
3137 let mut a = HashMap::new();
3138 let key = "hello there";
3139 let value = "value goes here";
3141 assert!(a.is_empty());
3142 match a.entry(key.clone()) {
3143 Occupied(_) => panic!(),
3145 assert_eq!(key, *e.key());
3146 e.insert(value.clone());
3149 assert_eq!(a.len(), 1);
3150 assert_eq!(a[key], value);