1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use self::VacantEntryState::*;
17 use fmt::{self, Debug};
19 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
20 use iter::{FromIterator, FusedIterator};
21 use mem::{self, replace};
22 use ops::{Deref, Index, InPlace, Place, Placer};
23 use rand::{self, Rng};
26 use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash};
27 use super::table::BucketState::{Empty, Full};
29 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
31 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
33 struct DefaultResizePolicy;
35 impl DefaultResizePolicy {
36 fn new() -> DefaultResizePolicy {
40 /// A hash map's "capacity" is the number of elements it can hold without
41 /// being resized. Its "raw capacity" is the number of slots required to
42 /// provide that capacity, accounting for maximum loading. The raw capacity
43 /// is always zero or a power of two.
45 fn raw_capacity(&self, len: usize) -> usize {
49 // 1. Account for loading: `raw_capacity >= len * 1.1`.
50 // 2. Ensure it is a power of two.
51 // 3. Ensure it is at least the minimum size.
52 let mut raw_cap = len * 11 / 10;
53 assert!(raw_cap >= len, "raw_cap overflow");
54 raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow");
55 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
60 /// The capacity of the given raw capacity.
62 fn capacity(&self, raw_cap: usize) -> usize {
63 // This doesn't have to be checked for overflow since allocation size
64 // in bytes will overflow earlier than multiplication by 10.
66 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
67 // to be: (raw_cap * den + den - 1) / num
68 (raw_cap * 10 + 10 - 1) / 11
72 // The main performance trick in this hashmap is called Robin Hood Hashing.
73 // It gains its excellent performance from one essential operation:
75 // If an insertion collides with an existing element, and that element's
76 // "probe distance" (how far away the element is from its ideal location)
77 // is higher than how far we've already probed, swap the elements.
79 // This massively lowers variance in probe distance, and allows us to get very
80 // high load factors with good performance. The 90% load factor I use is rather
83 // > Why a load factor of approximately 90%?
85 // In general, all the distances to initial buckets will converge on the mean.
86 // At a load factor of α, the odds of finding the target bucket after k
87 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
88 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
89 // this down to make the math easier on the CPU and avoid its FPU.
90 // Since on average we start the probing in the middle of a cache line, this
91 // strategy pulls in two cache lines of hashes on every lookup. I think that's
92 // pretty good, but if you want to trade off some space, it could go down to one
93 // cache line on average with an α of 0.84.
95 // > Wait, what? Where did you get 1-α^k from?
97 // On the first probe, your odds of a collision with an existing element is α.
98 // The odds of doing this twice in a row is approximately α^2. For three times,
99 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
100 // colliding after k tries is 1-α^k.
102 // The paper from 1986 cited below mentions an implementation which keeps track
103 // of the distance-to-initial-bucket histogram. This approach is not suitable
104 // for modern architectures because it requires maintaining an internal data
105 // structure. This allows very good first guesses, but we are most concerned
106 // with guessing entire cache lines, not individual indexes. Furthermore, array
107 // accesses are no longer linear and in one direction, as we have now. There
108 // is also memory and cache pressure that this would entail that would be very
109 // difficult to properly see in a microbenchmark.
111 // ## Future Improvements (FIXME!)
113 // Allow the load factor to be changed dynamically and/or at initialization.
115 // Also, would it be possible for us to reuse storage when growing the
116 // underlying table? This is exactly the use case for 'realloc', and may
117 // be worth exploring.
119 // ## Future Optimizations (FIXME!)
121 // Another possible design choice that I made without any real reason is
122 // parameterizing the raw table over keys and values. Technically, all we need
123 // is the size and alignment of keys and values, and the code should be just as
124 // efficient (well, we might need one for power-of-two size and one for not...).
125 // This has the potential to reduce code bloat in rust executables, without
126 // really losing anything except 4 words (key size, key alignment, val size,
127 // val alignment) which can be passed in to every call of a `RawTable` function.
128 // This would definitely be an avenue worth exploring if people start complaining
129 // about the size of rust executables.
131 // Annotate exceedingly likely branches in `table::make_hash`
132 // and `search_hashed` to reduce instruction cache pressure
133 // and mispredictions once it becomes possible (blocked on issue #11092).
135 // Shrinking the table could simply reallocate in place after moving buckets
136 // to the first half.
138 // The growth algorithm (fragment of the Proof of Correctness)
139 // --------------------
141 // The growth algorithm is basically a fast path of the naive reinsertion-
142 // during-resize algorithm. Other paths should never be taken.
144 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
145 // by allocating a new table of capacity `2n`, and then individually reinsert
146 // each element in the old table into the new one. This guarantees that the
147 // new table is a valid robin hood hashtable with all the desired statistical
148 // properties. Remark that the order we reinsert the elements in should not
149 // matter. For simplicity and efficiency, we will consider only linear
150 // reinsertions, which consist of reinserting all elements in the old table
151 // into the new one by increasing order of index. However we will not be
152 // starting our reinsertions from index 0 in general. If we start from index
153 // i, for the purpose of reinsertion we will consider all elements with real
154 // index j < i to have virtual index n + j.
156 // Our hash generation scheme consists of generating a 64-bit hash and
157 // truncating the most significant bits. When moving to the new table, we
158 // simply introduce a new bit to the front of the hash. Therefore, if an
159 // elements has ideal index i in the old table, it can have one of two ideal
160 // locations in the new table. If the new bit is 0, then the new ideal index
161 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
162 // we are producing two independent tables of size n, and for each element we
163 // independently choose which table to insert it into with equal probability.
164 // However the rather than wrapping around themselves on overflowing their
165 // indexes, the first table overflows into the first, and the first into the
166 // second. Visually, our new table will look something like:
168 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
170 // Where x's are elements inserted into the first table, y's are elements
171 // inserted into the second, and _'s are empty sections. We now define a few
172 // key concepts that we will use later. Note that this is a very abstract
173 // perspective of the table. A real resized table would be at least half
176 // Theorem: A linear robin hood reinsertion from the first ideal element
177 // produces identical results to a linear naive reinsertion from the same
180 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
182 // Adaptive early resizing
183 // ----------------------
184 // To protect against degenerate performance scenarios (including DOS attacks),
185 // the implementation includes an adaptive behavior that can resize the map
186 // early (before its capacity is exceeded) when suspiciously long probe sequences
189 // With this algorithm in place it would be possible to turn a CPU attack into
190 // a memory attack due to the aggressive resizing. To prevent that the
191 // adaptive behavior only triggers when the map is at least half full.
192 // This reduces the effectiveness of the algorithm but also makes it completely safe.
194 // The previous safety measure also prevents degenerate interactions with
195 // really bad quality hash algorithms that can make normal inputs look like a
198 const DISPLACEMENT_THRESHOLD: usize = 128;
200 // The threshold of 128 is chosen to minimize the chance of exceeding it.
201 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
202 // For displacement, the smallest constant that fits our needs is 90,
203 // so we round that up to 128.
205 // At a load factor of α, the odds of finding the target bucket after exactly n
206 // unsuccesful probes[1] are
208 // Pr_α{displacement = n} =
209 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
211 // We use this formula to find the probability of triggering the adaptive behavior
213 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
215 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
216 // hashing with buckets.
218 /// A hash map implementation which uses linear probing with Robin Hood bucket
221 /// By default, `HashMap` uses a hashing algorithm selected to provide
222 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
223 /// reasonable best-effort is made to generate this seed from a high quality,
224 /// secure source of randomness provided by the host without blocking the
225 /// program. Because of this, the randomness of the seed depends on the output
226 /// quality of the system's random number generator when the seed is created.
227 /// In particular, seeds generated when the system's entropy pool is abnormally
228 /// low such as during system boot may be of a lower quality.
230 /// The default hashing algorithm is currently SipHash 1-3, though this is
231 /// subject to change at any point in the future. While its performance is very
232 /// competitive for medium sized keys, other hashing algorithms will outperform
233 /// it for small keys such as integers as well as large keys such as long
234 /// strings, though those algorithms will typically *not* protect against
235 /// attacks such as HashDoS.
237 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
238 /// [`HashMap::default`], [`HashMap::with_hasher`], and
239 /// [`HashMap::with_capacity_and_hasher`] methods. Many alternative algorithms
240 /// are available on crates.io, such as the [`fnv`] crate.
242 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
243 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
244 /// If you implement these yourself, it is important that the following
248 /// k1 == k2 -> hash(k1) == hash(k2)
251 /// In other words, if two keys are equal, their hashes must be equal.
253 /// It is a logic error for a key to be modified in such a way that the key's
254 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
255 /// the [`Eq`] trait, changes while it is in the map. This is normally only
256 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
258 /// Relevant papers/articles:
260 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
261 /// 2. Emmanuel Goossaert. ["Robin Hood
262 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
263 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
264 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
269 /// use std::collections::HashMap;
271 /// // type inference lets us omit an explicit type signature (which
272 /// // would be `HashMap<&str, &str>` in this example).
273 /// let mut book_reviews = HashMap::new();
275 /// // review some books.
276 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
277 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
278 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
279 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
281 /// // check for a specific one.
282 /// if !book_reviews.contains_key("Les Misérables") {
283 /// println!("We've got {} reviews, but Les Misérables ain't one.",
284 /// book_reviews.len());
287 /// // oops, this review has a lot of spelling mistakes, let's delete it.
288 /// book_reviews.remove("The Adventures of Sherlock Holmes");
290 /// // look up the values associated with some keys.
291 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
292 /// for book in &to_find {
293 /// match book_reviews.get(book) {
294 /// Some(review) => println!("{}: {}", book, review),
295 /// None => println!("{} is unreviewed.", book)
299 /// // iterate over everything.
300 /// for (book, review) in &book_reviews {
301 /// println!("{}: \"{}\"", book, review);
305 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
306 /// for more complex methods of getting, setting, updating and removing keys and
310 /// use std::collections::HashMap;
312 /// // type inference lets us omit an explicit type signature (which
313 /// // would be `HashMap<&str, u8>` in this example).
314 /// let mut player_stats = HashMap::new();
316 /// fn random_stat_buff() -> u8 {
317 /// // could actually return some random value here - let's just return
318 /// // some fixed value for now
322 /// // insert a key only if it doesn't already exist
323 /// player_stats.entry("health").or_insert(100);
325 /// // insert a key using a function that provides a new value only if it
326 /// // doesn't already exist
327 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
329 /// // update a key, guarding against the key possibly not being set
330 /// let stat = player_stats.entry("attack").or_insert(100);
331 /// *stat += random_stat_buff();
334 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
335 /// We must also derive [`PartialEq`].
337 /// [`Eq`]: ../../std/cmp/trait.Eq.html
338 /// [`Hash`]: ../../std/hash/trait.Hash.html
339 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
340 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
341 /// [`Cell`]: ../../std/cell/struct.Cell.html
342 /// [`HashMap::default`]: #method.default
343 /// [`HashMap::with_hasher`]: #method.with_hasher
344 /// [`HashMap::with_capacity_and_hasher`]: #method.with_capacity_and_hasher
345 /// [`fnv`]: https://crates.io/crates/fnv
348 /// use std::collections::HashMap;
350 /// #[derive(Hash, Eq, PartialEq, Debug)]
357 /// /// Create a new Viking.
358 /// fn new(name: &str, country: &str) -> Viking {
359 /// Viking { name: name.to_string(), country: country.to_string() }
363 /// // Use a HashMap to store the vikings' health points.
364 /// let mut vikings = HashMap::new();
366 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
367 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
368 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
370 /// // Use derived implementation to print the status of the vikings.
371 /// for (viking, health) in &vikings {
372 /// println!("{:?} has {} hp", viking, health);
376 /// A HashMap with fixed list of elements can be initialized from an array:
379 /// use std::collections::HashMap;
382 /// let timber_resources: HashMap<&str, i32> =
383 /// [("Norway", 100),
386 /// .iter().cloned().collect();
387 /// // use the values stored in map
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub struct HashMap<K, V, S = RandomState> {
394 // All hashes are keyed on these values, to prevent hash collision attacks.
397 table: RawTable<K, V>,
399 resize_policy: DefaultResizePolicy,
402 /// Search for a pre-hashed key.
404 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
405 where M: Deref<Target = RawTable<K, V>>,
408 // This is the only function where capacity can be zero. To avoid
409 // undefined behavior when Bucket::new gets the raw bucket in this
410 // case, immediately return the appropriate search result.
411 if table.capacity() == 0 {
412 return InternalEntry::TableIsEmpty;
415 let size = table.size();
416 let mut probe = Bucket::new(table, hash);
417 let mut displacement = 0;
420 let full = match probe.peek() {
423 return InternalEntry::Vacant {
425 elem: NoElem(bucket, displacement),
428 Full(bucket) => bucket,
431 let probe_displacement = full.displacement();
433 if probe_displacement < displacement {
434 // Found a luckier bucket than me.
435 // We can finish the search early if we hit any bucket
436 // with a lower distance to initial bucket than we've probed.
437 return InternalEntry::Vacant {
439 elem: NeqElem(full, probe_displacement),
443 // If the hash doesn't match, it can't be this one..
444 if hash == full.hash() {
445 // If the key doesn't match, it can't be this one..
446 if is_match(full.read().0) {
447 return InternalEntry::Occupied { elem: full };
452 debug_assert!(displacement <= size);
456 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
457 -> (K, V, &mut RawTable<K, V>)
459 let (empty, retkey, retval) = starting_bucket.take();
460 let mut gap = match empty.gap_peek() {
462 Err(b) => return (retkey, retval, b.into_table()),
465 while gap.full().displacement() != 0 {
466 gap = match gap.shift() {
469 return (retkey, retval, b.into_table());
474 // Now we've done all our shifting. Return the value we grabbed earlier.
475 (retkey, retval, gap.into_table())
478 /// Perform robin hood bucket stealing at the given `bucket`. You must
479 /// also pass that bucket's displacement so we don't have to recalculate it.
481 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
482 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
483 mut displacement: usize,
487 -> FullBucketMut<'a, K, V> {
488 let size = bucket.table().size();
489 let raw_capacity = bucket.table().capacity();
490 // There can be at most `size - dib` buckets to displace, because
491 // in the worst case, there are `size` elements and we already are
492 // `displacement` buckets away from the initial one.
493 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
494 // Save the *starting point*.
495 let mut bucket = bucket.stash();
498 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
505 let probe = bucket.next();
506 debug_assert!(probe.index() != idx_end);
508 let full_bucket = match probe.peek() {
511 let bucket = bucket.put(hash, key, val);
512 // Now that it's stolen, just read the value's pointer
513 // right out of the table! Go back to the *starting point*.
515 // This use of `into_table` is misleading. It turns the
516 // bucket, which is a FullBucket on top of a
517 // FullBucketMut, into just one FullBucketMut. The "table"
518 // refers to the inner FullBucketMut in this context.
519 return bucket.into_table();
521 Full(bucket) => bucket,
524 let probe_displacement = full_bucket.displacement();
526 bucket = full_bucket;
528 // Robin hood! Steal the spot.
529 if probe_displacement < displacement {
530 displacement = probe_displacement;
537 impl<K, V, S> HashMap<K, V, S>
541 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
544 table::make_hash(&self.hash_builder, x)
547 /// Search for a key, yielding the index if it's found in the hashtable.
548 /// If you already have the hash for the key lying around, use
551 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
555 let hash = self.make_hash(q);
556 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
560 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
564 let hash = self.make_hash(q);
565 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
568 // The caller should ensure that invariants by Robin Hood Hashing hold
569 // and that there's space in the underlying table.
570 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
571 let mut buckets = Bucket::new(&mut self.table, hash);
572 let start_index = buckets.index();
575 // We don't need to compare hashes for value swap.
576 // Not even DIBs for Robin Hood.
577 buckets = match buckets.peek() {
579 empty.put(hash, k, v);
582 Full(b) => b.into_bucket(),
585 debug_assert!(buckets.index() != start_index);
590 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
591 /// Creates an empty `HashMap`.
596 /// use std::collections::HashMap;
597 /// let mut map: HashMap<&str, isize> = HashMap::new();
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub fn new() -> HashMap<K, V, RandomState> {
605 /// Creates an empty `HashMap` with the specified capacity.
607 /// The hash map will be able to hold at least `capacity` elements without
608 /// reallocating. If `capacity` is 0, the hash map will not allocate.
613 /// use std::collections::HashMap;
614 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
619 HashMap::with_capacity_and_hasher(capacity, Default::default())
623 impl<K, V, S> HashMap<K, V, S>
627 /// Creates an empty `HashMap` which will use the given hash builder to hash
630 /// The created map has the default initial capacity.
632 /// Warning: `hash_builder` is normally randomly generated, and
633 /// is designed to allow HashMaps to be resistant to attacks that
634 /// cause many collisions and very poor performance. Setting it
635 /// manually using this function can expose a DoS attack vector.
640 /// use std::collections::HashMap;
641 /// use std::collections::hash_map::RandomState;
643 /// let s = RandomState::new();
644 /// let mut map = HashMap::with_hasher(s);
645 /// map.insert(1, 2);
648 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
649 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
651 hash_builder: hash_builder,
652 resize_policy: DefaultResizePolicy::new(),
653 table: RawTable::new(0),
657 /// Creates an empty `HashMap` with the specified capacity, using `hasher`
658 /// to hash the keys.
660 /// The hash map will be able to hold at least `capacity` elements without
661 /// reallocating. If `capacity` is 0, the hash map will not allocate.
662 /// Warning: `hasher` is normally randomly generated, and
663 /// is designed to allow HashMaps to be resistant to attacks that
664 /// cause many collisions and very poor performance. Setting it
665 /// manually using this function can expose a DoS attack vector.
670 /// use std::collections::HashMap;
671 /// use std::collections::hash_map::RandomState;
673 /// let s = RandomState::new();
674 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
675 /// map.insert(1, 2);
678 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
679 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
680 let resize_policy = DefaultResizePolicy::new();
681 let raw_cap = resize_policy.raw_capacity(capacity);
683 hash_builder: hash_builder,
684 resize_policy: resize_policy,
685 table: RawTable::new(raw_cap),
689 /// Returns a reference to the map's hasher.
690 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
691 pub fn hasher(&self) -> &S {
695 /// Returns the number of elements the map can hold without reallocating.
697 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
698 /// more, but is guaranteed to be able to hold at least this many.
703 /// use std::collections::HashMap;
704 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
705 /// assert!(map.capacity() >= 100);
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn capacity(&self) -> usize {
710 self.resize_policy.capacity(self.raw_capacity())
713 /// Returns the hash map's raw capacity.
715 fn raw_capacity(&self) -> usize {
716 self.table.capacity()
719 /// Reserves capacity for at least `additional` more elements to be inserted
720 /// in the `HashMap`. The collection may reserve more space to avoid
721 /// frequent reallocations.
725 /// Panics if the new allocation size overflows [`usize`].
727 /// [`usize`]: ../../std/primitive.usize.html
732 /// use std::collections::HashMap;
733 /// let mut map: HashMap<&str, isize> = HashMap::new();
736 #[stable(feature = "rust1", since = "1.0.0")]
737 pub fn reserve(&mut self, additional: usize) {
738 let remaining = self.capacity() - self.len(); // this can't overflow
739 if remaining < additional {
740 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
741 let raw_cap = self.resize_policy.raw_capacity(min_cap);
742 self.resize(raw_cap);
743 } else if self.table.tag() && remaining <= self.len() {
744 // Probe sequence is too long and table is half full,
745 // resize early to reduce probing length.
746 let new_capacity = self.table.capacity() * 2;
747 self.resize(new_capacity);
751 /// Resizes the internal vectors to a new capacity. It's your
752 /// responsibility to:
753 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
754 /// for the load factor.
755 /// 2) Ensure `new_raw_cap` is a power of two or zero.
756 fn resize(&mut self, new_raw_cap: usize) {
757 assert!(self.table.size() <= new_raw_cap);
758 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
760 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
761 let old_size = old_table.size();
763 if old_table.size() == 0 {
767 let mut bucket = Bucket::head_bucket(&mut old_table);
769 // This is how the buckets might be laid out in memory:
770 // ($ marks an initialized bucket)
772 // |$$$_$$$$$$_$$$$$|
774 // But we've skipped the entire initial cluster of buckets
775 // and will continue iteration in this order:
778 // ^ wrap around once end is reached
781 // ^ exit once table.size == 0
783 bucket = match bucket.peek() {
785 let h = bucket.hash();
786 let (b, k, v) = bucket.take();
787 self.insert_hashed_ordered(h, k, v);
788 if b.table().size() == 0 {
793 Empty(b) => b.into_bucket(),
798 assert_eq!(self.table.size(), old_size);
801 /// Shrinks the capacity of the map as much as possible. It will drop
802 /// down as much as possible while maintaining the internal rules
803 /// and possibly leaving some space in accordance with the resize policy.
808 /// use std::collections::HashMap;
810 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
811 /// map.insert(1, 2);
812 /// map.insert(3, 4);
813 /// assert!(map.capacity() >= 100);
814 /// map.shrink_to_fit();
815 /// assert!(map.capacity() >= 2);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn shrink_to_fit(&mut self) {
819 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
820 if self.raw_capacity() != new_raw_cap {
821 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
822 let old_size = old_table.size();
824 // Shrink the table. Naive algorithm for resizing:
825 for (h, k, v) in old_table.into_iter() {
826 self.insert_hashed_nocheck(h, k, v);
829 debug_assert_eq!(self.table.size(), old_size);
833 /// Insert a pre-hashed key-value pair, without first checking
834 /// that there's enough room in the buckets. Returns a reference to the
835 /// newly insert value.
837 /// If the key already exists, the hashtable will be returned untouched
838 /// and a reference to the existing element will be returned.
839 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
840 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
842 Some(Occupied(mut elem)) => Some(elem.insert(v)),
843 Some(Vacant(elem)) => {
847 None => unreachable!(),
851 /// An iterator visiting all keys in arbitrary order.
852 /// Iterator element type is `&'a K`.
857 /// use std::collections::HashMap;
859 /// let mut map = HashMap::new();
860 /// map.insert("a", 1);
861 /// map.insert("b", 2);
862 /// map.insert("c", 3);
864 /// for key in map.keys() {
865 /// println!("{}", key);
868 #[stable(feature = "rust1", since = "1.0.0")]
869 pub fn keys(&self) -> Keys<K, V> {
870 Keys { inner: self.iter() }
873 /// An iterator visiting all values in arbitrary order.
874 /// Iterator element type is `&'a V`.
879 /// use std::collections::HashMap;
881 /// let mut map = HashMap::new();
882 /// map.insert("a", 1);
883 /// map.insert("b", 2);
884 /// map.insert("c", 3);
886 /// for val in map.values() {
887 /// println!("{}", val);
890 #[stable(feature = "rust1", since = "1.0.0")]
891 pub fn values(&self) -> Values<K, V> {
892 Values { inner: self.iter() }
895 /// An iterator visiting all values mutably in arbitrary order.
896 /// Iterator element type is `&'a mut V`.
901 /// use std::collections::HashMap;
903 /// let mut map = HashMap::new();
905 /// map.insert("a", 1);
906 /// map.insert("b", 2);
907 /// map.insert("c", 3);
909 /// for val in map.values_mut() {
910 /// *val = *val + 10;
913 /// for val in map.values() {
914 /// println!("{}", val);
917 #[stable(feature = "map_values_mut", since = "1.10.0")]
918 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
919 ValuesMut { inner: self.iter_mut() }
922 /// An iterator visiting all key-value pairs in arbitrary order.
923 /// Iterator element type is `(&'a K, &'a V)`.
928 /// use std::collections::HashMap;
930 /// let mut map = HashMap::new();
931 /// map.insert("a", 1);
932 /// map.insert("b", 2);
933 /// map.insert("c", 3);
935 /// for (key, val) in map.iter() {
936 /// println!("key: {} val: {}", key, val);
939 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn iter(&self) -> Iter<K, V> {
941 Iter { inner: self.table.iter() }
944 /// An iterator visiting all key-value pairs in arbitrary order,
945 /// with mutable references to the values.
946 /// Iterator element type is `(&'a K, &'a mut V)`.
951 /// use std::collections::HashMap;
953 /// let mut map = HashMap::new();
954 /// map.insert("a", 1);
955 /// map.insert("b", 2);
956 /// map.insert("c", 3);
958 /// // Update all values
959 /// for (_, val) in map.iter_mut() {
963 /// for (key, val) in &map {
964 /// println!("key: {} val: {}", key, val);
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn iter_mut(&mut self) -> IterMut<K, V> {
969 IterMut { inner: self.table.iter_mut() }
972 /// Gets the given key's corresponding entry in the map for in-place manipulation.
977 /// use std::collections::HashMap;
979 /// let mut letters = HashMap::new();
981 /// for ch in "a short treatise on fungi".chars() {
982 /// let counter = letters.entry(ch).or_insert(0);
986 /// assert_eq!(letters[&'s'], 2);
987 /// assert_eq!(letters[&'t'], 3);
988 /// assert_eq!(letters[&'u'], 1);
989 /// assert_eq!(letters.get(&'y'), None);
991 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn entry(&mut self, key: K) -> Entry<K, V> {
995 let hash = self.make_hash(&key);
996 search_hashed(&mut self.table, hash, |q| q.eq(&key))
997 .into_entry(key).expect("unreachable")
1000 /// Returns the number of elements in the map.
1005 /// use std::collections::HashMap;
1007 /// let mut a = HashMap::new();
1008 /// assert_eq!(a.len(), 0);
1009 /// a.insert(1, "a");
1010 /// assert_eq!(a.len(), 1);
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn len(&self) -> usize {
1017 /// Returns true if the map contains no elements.
1022 /// use std::collections::HashMap;
1024 /// let mut a = HashMap::new();
1025 /// assert!(a.is_empty());
1026 /// a.insert(1, "a");
1027 /// assert!(!a.is_empty());
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn is_empty(&self) -> bool {
1035 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1036 /// allocated memory for reuse.
1041 /// use std::collections::HashMap;
1043 /// let mut a = HashMap::new();
1044 /// a.insert(1, "a");
1045 /// a.insert(2, "b");
1047 /// for (k, v) in a.drain().take(1) {
1048 /// assert!(k == 1 || k == 2);
1049 /// assert!(v == "a" || v == "b");
1052 /// assert!(a.is_empty());
1055 #[stable(feature = "drain", since = "1.6.0")]
1056 pub fn drain(&mut self) -> Drain<K, V> {
1057 Drain { inner: self.table.drain() }
1060 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1066 /// use std::collections::HashMap;
1068 /// let mut a = HashMap::new();
1069 /// a.insert(1, "a");
1071 /// assert!(a.is_empty());
1073 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn clear(&mut self) {
1079 /// Returns a reference to the value corresponding to the key.
1081 /// The key may be any borrowed form of the map's key type, but
1082 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1085 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1086 /// [`Hash`]: ../../std/hash/trait.Hash.html
1091 /// use std::collections::HashMap;
1093 /// let mut map = HashMap::new();
1094 /// map.insert(1, "a");
1095 /// assert_eq!(map.get(&1), Some(&"a"));
1096 /// assert_eq!(map.get(&2), None);
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1103 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1106 /// Returns true if the map contains a value for the specified key.
1108 /// The key may be any borrowed form of the map's key type, but
1109 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1112 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1113 /// [`Hash`]: ../../std/hash/trait.Hash.html
1118 /// use std::collections::HashMap;
1120 /// let mut map = HashMap::new();
1121 /// map.insert(1, "a");
1122 /// assert_eq!(map.contains_key(&1), true);
1123 /// assert_eq!(map.contains_key(&2), false);
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1130 self.search(k).into_occupied_bucket().is_some()
1133 /// Returns a mutable reference to the value corresponding to the key.
1135 /// The key may be any borrowed form of the map's key type, but
1136 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1139 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1140 /// [`Hash`]: ../../std/hash/trait.Hash.html
1145 /// use std::collections::HashMap;
1147 /// let mut map = HashMap::new();
1148 /// map.insert(1, "a");
1149 /// if let Some(x) = map.get_mut(&1) {
1152 /// assert_eq!(map[&1], "b");
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1159 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1162 /// Inserts a key-value pair into the map.
1164 /// If the map did not have this key present, [`None`] is returned.
1166 /// If the map did have this key present, the value is updated, and the old
1167 /// value is returned. The key is not updated, though; this matters for
1168 /// types that can be `==` without being identical. See the [module-level
1169 /// documentation] for more.
1171 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1172 /// [module-level documentation]: index.html#insert-and-complex-keys
1177 /// use std::collections::HashMap;
1179 /// let mut map = HashMap::new();
1180 /// assert_eq!(map.insert(37, "a"), None);
1181 /// assert_eq!(map.is_empty(), false);
1183 /// map.insert(37, "b");
1184 /// assert_eq!(map.insert(37, "c"), Some("b"));
1185 /// assert_eq!(map[&37], "c");
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1189 let hash = self.make_hash(&k);
1191 self.insert_hashed_nocheck(hash, k, v)
1194 /// Removes a key from the map, returning the value at the key if the key
1195 /// was previously in the map.
1197 /// The key may be any borrowed form of the map's key type, but
1198 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1201 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1202 /// [`Hash`]: ../../std/hash/trait.Hash.html
1207 /// use std::collections::HashMap;
1209 /// let mut map = HashMap::new();
1210 /// map.insert(1, "a");
1211 /// assert_eq!(map.remove(&1), Some("a"));
1212 /// assert_eq!(map.remove(&1), None);
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1219 if self.table.size() == 0 {
1223 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1226 /// Retains only the elements specified by the predicate.
1228 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1233 /// #![feature(retain_hash_collection)]
1234 /// use std::collections::HashMap;
1236 /// let mut map: HashMap<isize, isize> = (0..8).map(|x|(x, x*10)).collect();
1237 /// map.retain(|&k, _| k % 2 == 0);
1238 /// assert_eq!(map.len(), 4);
1240 #[unstable(feature = "retain_hash_collection", issue = "36648")]
1241 pub fn retain<F>(&mut self, mut f: F)
1242 where F: FnMut(&K, &mut V) -> bool
1244 if self.table.size() == 0 {
1247 let mut elems_left = self.table.size();
1248 let mut bucket = Bucket::head_bucket(&mut self.table);
1250 let start_index = bucket.index();
1251 while elems_left != 0 {
1252 bucket = match bucket.peek() {
1255 let should_remove = {
1256 let (k, v) = full.read_mut();
1260 let prev_raw = full.raw();
1261 let (_, _, t) = pop_internal(full);
1262 Bucket::new_from(prev_raw, t)
1271 bucket.prev(); // reverse iteration
1272 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<K, V, S> PartialEq for HashMap<K, V, S>
1283 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1284 if self.len() != other.len() {
1288 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<K, V, S> Eq for HashMap<K, V, S>
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl<K, V, S> Debug for HashMap<K, V, S>
1302 where K: Eq + Hash + Debug,
1306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1307 f.debug_map().entries(self.iter()).finish()
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<K, V, S> Default for HashMap<K, V, S>
1314 S: BuildHasher + Default
1316 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1317 fn default() -> HashMap<K, V, S> {
1318 HashMap::with_hasher(Default::default())
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1324 where K: Eq + Hash + Borrow<Q>,
1331 fn index(&self, index: &Q) -> &V {
1332 self.get(index).expect("no entry found for key")
1336 /// HashMap iterator.
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub struct Iter<'a, K: 'a, V: 'a> {
1339 inner: table::Iter<'a, K, V>,
1342 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl<'a, K, V> Clone for Iter<'a, K, V> {
1345 fn clone(&self) -> Iter<'a, K, V> {
1346 Iter { inner: self.inner.clone() }
1350 #[stable(feature = "std_debug", since = "1.16.0")]
1351 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1354 .entries(self.clone())
1359 /// HashMap mutable values iterator.
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub struct IterMut<'a, K: 'a, V: 'a> {
1362 inner: table::IterMut<'a, K, V>,
1365 /// HashMap move iterator.
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 pub struct IntoIter<K, V> {
1368 pub(super) inner: table::IntoIter<K, V>,
1371 /// HashMap keys iterator.
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 pub struct Keys<'a, K: 'a, V: 'a> {
1374 inner: Iter<'a, K, V>,
1377 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<'a, K, V> Clone for Keys<'a, K, V> {
1380 fn clone(&self) -> Keys<'a, K, V> {
1381 Keys { inner: self.inner.clone() }
1385 #[stable(feature = "std_debug", since = "1.16.0")]
1386 impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> {
1387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1389 .entries(self.clone())
1394 /// HashMap values iterator.
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub struct Values<'a, K: 'a, V: 'a> {
1397 inner: Iter<'a, K, V>,
1400 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<'a, K, V> Clone for Values<'a, K, V> {
1403 fn clone(&self) -> Values<'a, K, V> {
1404 Values { inner: self.inner.clone() }
1408 #[stable(feature = "std_debug", since = "1.16.0")]
1409 impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> {
1410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1412 .entries(self.clone())
1417 /// HashMap drain iterator.
1418 #[stable(feature = "drain", since = "1.6.0")]
1419 pub struct Drain<'a, K: 'a, V: 'a> {
1420 pub(super) inner: table::Drain<'a, K, V>,
1423 /// Mutable HashMap values iterator.
1424 #[stable(feature = "map_values_mut", since = "1.10.0")]
1425 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1426 inner: IterMut<'a, K, V>,
1429 enum InternalEntry<K, V, M> {
1430 Occupied { elem: FullBucket<K, V, M> },
1433 elem: VacantEntryState<K, V, M>,
1438 impl<K, V, M> InternalEntry<K, V, M> {
1440 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1442 InternalEntry::Occupied { elem } => Some(elem),
1448 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1450 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1452 InternalEntry::Occupied { elem } => {
1453 Some(Occupied(OccupiedEntry {
1458 InternalEntry::Vacant { hash, elem } => {
1459 Some(Vacant(VacantEntry {
1465 InternalEntry::TableIsEmpty => None,
1470 /// A view into a single location in a map, which may be vacant or occupied.
1471 /// This enum is constructed from the [`entry`] method on [`HashMap`].
1473 /// [`HashMap`]: struct.HashMap.html
1474 /// [`entry`]: struct.HashMap.html#method.entry
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub enum Entry<'a, K: 'a, V: 'a> {
1477 /// An occupied Entry.
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1480 OccupiedEntry<'a, K, V>),
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1485 VacantEntry<'a, K, V>),
1488 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1489 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1493 f.debug_tuple("Entry")
1497 Occupied(ref o) => {
1498 f.debug_tuple("Entry")
1506 /// A view into a single occupied location in a HashMap.
1507 /// It is part of the [`Entry`] enum.
1509 /// [`Entry`]: enum.Entry.html
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1513 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1516 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1517 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1519 f.debug_struct("OccupiedEntry")
1520 .field("key", self.key())
1521 .field("value", self.get())
1526 /// A view into a single empty location in a HashMap.
1527 /// It is part of the [`Entry`] enum.
1529 /// [`Entry`]: enum.Entry.html
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1534 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1537 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1538 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1540 f.debug_tuple("VacantEntry")
1546 /// Possible states of a VacantEntry.
1547 enum VacantEntryState<K, V, M> {
1548 /// The index is occupied, but the key to insert has precedence,
1549 /// and will kick the current one out on insertion.
1550 NeqElem(FullBucket<K, V, M>, usize),
1551 /// The index is genuinely vacant.
1552 NoElem(EmptyBucket<K, V, M>, usize),
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1560 type Item = (&'a K, &'a V);
1561 type IntoIter = Iter<'a, K, V>;
1563 fn into_iter(self) -> Iter<'a, K, V> {
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1573 type Item = (&'a K, &'a mut V);
1574 type IntoIter = IterMut<'a, K, V>;
1576 fn into_iter(mut self) -> IterMut<'a, K, V> {
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1587 type IntoIter = IntoIter<K, V>;
1589 /// Creates a consuming iterator, that is, one that moves each key-value
1590 /// pair out of the map in arbitrary order. The map cannot be used after
1596 /// use std::collections::HashMap;
1598 /// let mut map = HashMap::new();
1599 /// map.insert("a", 1);
1600 /// map.insert("b", 2);
1601 /// map.insert("c", 3);
1603 /// // Not possible with .iter()
1604 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1606 fn into_iter(self) -> IntoIter<K, V> {
1607 IntoIter { inner: self.table.into_iter() }
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1613 type Item = (&'a K, &'a V);
1616 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1620 fn size_hint(&self) -> (usize, Option<usize>) {
1621 self.inner.size_hint()
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1627 fn len(&self) -> usize {
1632 #[unstable(feature = "fused", issue = "35602")]
1633 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1637 type Item = (&'a K, &'a mut V);
1640 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1644 fn size_hint(&self) -> (usize, Option<usize>) {
1645 self.inner.size_hint()
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1651 fn len(&self) -> usize {
1655 #[unstable(feature = "fused", issue = "35602")]
1656 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1658 #[stable(feature = "std_debug", since = "1.16.0")]
1659 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1660 where K: fmt::Debug,
1663 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1665 .entries(self.inner.iter())
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<K, V> Iterator for IntoIter<K, V> {
1675 fn next(&mut self) -> Option<(K, V)> {
1676 self.inner.next().map(|(_, k, v)| (k, v))
1679 fn size_hint(&self) -> (usize, Option<usize>) {
1680 self.inner.size_hint()
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1686 fn len(&self) -> usize {
1690 #[unstable(feature = "fused", issue = "35602")]
1691 impl<K, V> FusedIterator for IntoIter<K, V> {}
1693 #[stable(feature = "std_debug", since = "1.16.0")]
1694 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1695 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1697 .entries(self.inner.iter())
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1707 fn next(&mut self) -> Option<(&'a K)> {
1708 self.inner.next().map(|(k, _)| k)
1711 fn size_hint(&self) -> (usize, Option<usize>) {
1712 self.inner.size_hint()
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1718 fn len(&self) -> usize {
1722 #[unstable(feature = "fused", issue = "35602")]
1723 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 impl<'a, K, V> Iterator for Values<'a, K, V> {
1730 fn next(&mut self) -> Option<(&'a V)> {
1731 self.inner.next().map(|(_, v)| v)
1734 fn size_hint(&self) -> (usize, Option<usize>) {
1735 self.inner.size_hint()
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1741 fn len(&self) -> usize {
1745 #[unstable(feature = "fused", issue = "35602")]
1746 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1748 #[stable(feature = "map_values_mut", since = "1.10.0")]
1749 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1750 type Item = &'a mut V;
1753 fn next(&mut self) -> Option<(&'a mut V)> {
1754 self.inner.next().map(|(_, v)| v)
1757 fn size_hint(&self) -> (usize, Option<usize>) {
1758 self.inner.size_hint()
1761 #[stable(feature = "map_values_mut", since = "1.10.0")]
1762 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1764 fn len(&self) -> usize {
1768 #[unstable(feature = "fused", issue = "35602")]
1769 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1771 #[stable(feature = "std_debug", since = "1.16.0")]
1772 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1773 where K: fmt::Debug,
1776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1778 .entries(self.inner.inner.iter())
1783 #[stable(feature = "drain", since = "1.6.0")]
1784 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1788 fn next(&mut self) -> Option<(K, V)> {
1789 self.inner.next().map(|(_, k, v)| (k, v))
1792 fn size_hint(&self) -> (usize, Option<usize>) {
1793 self.inner.size_hint()
1796 #[stable(feature = "drain", since = "1.6.0")]
1797 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1799 fn len(&self) -> usize {
1803 #[unstable(feature = "fused", issue = "35602")]
1804 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1806 #[stable(feature = "std_debug", since = "1.16.0")]
1807 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1808 where K: fmt::Debug,
1811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1813 .entries(self.inner.iter())
1818 /// A place for insertion to a `Entry`.
1820 /// See [`HashMap::entry`](struct.HashMap.html#method.entry) for details.
1821 #[must_use = "places do nothing unless written to with `<-` syntax"]
1822 #[unstable(feature = "collection_placement",
1823 reason = "struct name and placement protocol is subject to change",
1825 pub struct EntryPlace<'a, K: 'a, V: 'a> {
1826 bucket: FullBucketMut<'a, K, V>,
1829 #[unstable(feature = "collection_placement",
1830 reason = "struct name and placement protocol is subject to change",
1832 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for EntryPlace<'a, K, V> {
1833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1834 f.debug_struct("EntryPlace")
1835 .field("key", self.bucket.read().0)
1836 .field("value", self.bucket.read().1)
1841 #[unstable(feature = "collection_placement",
1842 reason = "struct name and placement protocol is subject to change",
1844 impl<'a, K, V> Drop for EntryPlace<'a, K, V> {
1845 fn drop(&mut self) {
1846 // Inplacement insertion failed. Only key need to drop.
1847 // The value is failed to insert into map.
1848 unsafe { self.bucket.remove_key() };
1852 #[unstable(feature = "collection_placement",
1853 reason = "placement protocol is subject to change",
1855 impl<'a, K, V> Placer<V> for Entry<'a, K, V> {
1856 type Place = EntryPlace<'a, K, V>;
1858 fn make_place(self) -> EntryPlace<'a, K, V> {
1859 let b = match self {
1860 Occupied(mut o) => {
1861 unsafe { ptr::drop_in_place(o.elem.read_mut().1); }
1865 unsafe { v.insert_key() }
1868 EntryPlace { bucket: b }
1872 #[unstable(feature = "collection_placement",
1873 reason = "placement protocol is subject to change",
1875 impl<'a, K, V> Place<V> for EntryPlace<'a, K, V> {
1876 fn pointer(&mut self) -> *mut V {
1877 self.bucket.read_mut().1
1881 #[unstable(feature = "collection_placement",
1882 reason = "placement protocol is subject to change",
1884 impl<'a, K, V> InPlace<V> for EntryPlace<'a, K, V> {
1887 unsafe fn finalize(self) {
1892 impl<'a, K, V> Entry<'a, K, V> {
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 /// Ensures a value is in the entry by inserting the default if empty, and returns
1895 /// a mutable reference to the value in the entry.
1900 /// use std::collections::HashMap;
1902 /// let mut map: HashMap<&str, u32> = HashMap::new();
1903 /// map.entry("poneyland").or_insert(12);
1905 /// assert_eq!(map["poneyland"], 12);
1907 /// *map.entry("poneyland").or_insert(12) += 10;
1908 /// assert_eq!(map["poneyland"], 22);
1910 pub fn or_insert(self, default: V) -> &'a mut V {
1912 Occupied(entry) => entry.into_mut(),
1913 Vacant(entry) => entry.insert(default),
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1919 /// and returns a mutable reference to the value in the entry.
1924 /// use std::collections::HashMap;
1926 /// let mut map: HashMap<&str, String> = HashMap::new();
1927 /// let s = "hoho".to_string();
1929 /// map.entry("poneyland").or_insert_with(|| s);
1931 /// assert_eq!(map["poneyland"], "hoho".to_string());
1933 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1935 Occupied(entry) => entry.into_mut(),
1936 Vacant(entry) => entry.insert(default()),
1940 /// Returns a reference to this entry's key.
1945 /// use std::collections::HashMap;
1947 /// let mut map: HashMap<&str, u32> = HashMap::new();
1948 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1950 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1951 pub fn key(&self) -> &K {
1953 Occupied(ref entry) => entry.key(),
1954 Vacant(ref entry) => entry.key(),
1959 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1960 /// Gets a reference to the key in the entry.
1965 /// use std::collections::HashMap;
1967 /// let mut map: HashMap<&str, u32> = HashMap::new();
1968 /// map.entry("poneyland").or_insert(12);
1969 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1971 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1972 pub fn key(&self) -> &K {
1976 /// Deprecated, renamed to `remove_entry`
1977 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
1978 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
1979 pub fn remove_pair(self) -> (K, V) {
1983 /// Take the ownership of the key and value from the map.
1988 /// use std::collections::HashMap;
1989 /// use std::collections::hash_map::Entry;
1991 /// let mut map: HashMap<&str, u32> = HashMap::new();
1992 /// map.entry("poneyland").or_insert(12);
1994 /// if let Entry::Occupied(o) = map.entry("poneyland") {
1995 /// // We delete the entry from the map.
1996 /// o.remove_entry();
1999 /// assert_eq!(map.contains_key("poneyland"), false);
2001 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2002 pub fn remove_entry(self) -> (K, V) {
2003 let (k, v, _) = pop_internal(self.elem);
2007 /// Gets a reference to the value in the entry.
2012 /// use std::collections::HashMap;
2013 /// use std::collections::hash_map::Entry;
2015 /// let mut map: HashMap<&str, u32> = HashMap::new();
2016 /// map.entry("poneyland").or_insert(12);
2018 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2019 /// assert_eq!(o.get(), &12);
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub fn get(&self) -> &V {
2027 /// Gets a mutable reference to the value in the entry.
2032 /// use std::collections::HashMap;
2033 /// use std::collections::hash_map::Entry;
2035 /// let mut map: HashMap<&str, u32> = HashMap::new();
2036 /// map.entry("poneyland").or_insert(12);
2038 /// assert_eq!(map["poneyland"], 12);
2039 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2040 /// *o.get_mut() += 10;
2043 /// assert_eq!(map["poneyland"], 22);
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 pub fn get_mut(&mut self) -> &mut V {
2047 self.elem.read_mut().1
2050 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2051 /// with a lifetime bound to the map itself.
2056 /// use std::collections::HashMap;
2057 /// use std::collections::hash_map::Entry;
2059 /// let mut map: HashMap<&str, u32> = HashMap::new();
2060 /// map.entry("poneyland").or_insert(12);
2062 /// assert_eq!(map["poneyland"], 12);
2063 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2064 /// *o.into_mut() += 10;
2067 /// assert_eq!(map["poneyland"], 22);
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 pub fn into_mut(self) -> &'a mut V {
2071 self.elem.into_mut_refs().1
2074 /// Sets the value of the entry, and returns the entry's old value.
2079 /// use std::collections::HashMap;
2080 /// use std::collections::hash_map::Entry;
2082 /// let mut map: HashMap<&str, u32> = HashMap::new();
2083 /// map.entry("poneyland").or_insert(12);
2085 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2086 /// assert_eq!(o.insert(15), 12);
2089 /// assert_eq!(map["poneyland"], 15);
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 pub fn insert(&mut self, mut value: V) -> V {
2093 let old_value = self.get_mut();
2094 mem::swap(&mut value, old_value);
2098 /// Takes the value out of the entry, and returns it.
2103 /// use std::collections::HashMap;
2104 /// use std::collections::hash_map::Entry;
2106 /// let mut map: HashMap<&str, u32> = HashMap::new();
2107 /// map.entry("poneyland").or_insert(12);
2109 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2110 /// assert_eq!(o.remove(), 12);
2113 /// assert_eq!(map.contains_key("poneyland"), false);
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 pub fn remove(self) -> V {
2117 pop_internal(self.elem).1
2120 /// Returns a key that was used for search.
2122 /// The key was retained for further use.
2123 fn take_key(&mut self) -> Option<K> {
2128 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2129 /// Gets a reference to the key that would be used when inserting a value
2130 /// through the `VacantEntry`.
2135 /// use std::collections::HashMap;
2137 /// let mut map: HashMap<&str, u32> = HashMap::new();
2138 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2140 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2141 pub fn key(&self) -> &K {
2145 /// Take ownership of the key.
2150 /// use std::collections::HashMap;
2151 /// use std::collections::hash_map::Entry;
2153 /// let mut map: HashMap<&str, u32> = HashMap::new();
2155 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2159 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2160 pub fn into_key(self) -> K {
2164 /// Sets the value of the entry with the VacantEntry's key,
2165 /// and returns a mutable reference to it.
2170 /// use std::collections::HashMap;
2171 /// use std::collections::hash_map::Entry;
2173 /// let mut map: HashMap<&str, u32> = HashMap::new();
2175 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2178 /// assert_eq!(map["poneyland"], 37);
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 pub fn insert(self, value: V) -> &'a mut V {
2182 let b = match self.elem {
2183 NeqElem(mut bucket, disp) => {
2184 if disp >= DISPLACEMENT_THRESHOLD {
2185 bucket.table_mut().set_tag(true);
2187 robin_hood(bucket, disp, self.hash, self.key, value)
2189 NoElem(mut bucket, disp) => {
2190 if disp >= DISPLACEMENT_THRESHOLD {
2191 bucket.table_mut().set_tag(true);
2193 bucket.put(self.hash, self.key, value)
2199 // Only used for InPlacement insert. Avoid unnecessary value copy.
2200 // The value remains uninitialized.
2201 unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2203 NeqElem(mut bucket, disp) => {
2204 if disp >= DISPLACEMENT_THRESHOLD {
2205 bucket.table_mut().set_tag(true);
2207 let uninit = mem::uninitialized();
2208 robin_hood(bucket, disp, self.hash, self.key, uninit)
2210 NoElem(mut bucket, disp) => {
2211 if disp >= DISPLACEMENT_THRESHOLD {
2212 bucket.table_mut().set_tag(true);
2214 bucket.put_key(self.hash, self.key)
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2223 S: BuildHasher + Default
2225 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2226 let mut map = HashMap::with_hasher(Default::default());
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2237 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2238 // Keys may be already present or show multiple times in the iterator.
2239 // Reserve the entire hint lower bound if the map is empty.
2240 // Otherwise reserve half the hint (rounded up), so the map
2241 // will only resize twice in the worst case.
2242 let iter = iter.into_iter();
2243 let reserve = if self.is_empty() {
2246 (iter.size_hint().0 + 1) / 2
2248 self.reserve(reserve);
2249 for (k, v) in iter {
2255 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2256 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2257 where K: Eq + Hash + Copy,
2261 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2262 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2266 /// `RandomState` is the default state for [`HashMap`] types.
2268 /// A particular instance `RandomState` will create the same instances of
2269 /// [`Hasher`], but the hashers created by two different `RandomState`
2270 /// instances are unlikely to produce the same result for the same values.
2272 /// [`HashMap`]: struct.HashMap.html
2273 /// [`Hasher`]: ../../hash/trait.Hasher.html
2278 /// use std::collections::HashMap;
2279 /// use std::collections::hash_map::RandomState;
2281 /// let s = RandomState::new();
2282 /// let mut map = HashMap::with_hasher(s);
2283 /// map.insert(1, 2);
2286 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2287 pub struct RandomState {
2293 /// Constructs a new `RandomState` that is initialized with random keys.
2298 /// use std::collections::hash_map::RandomState;
2300 /// let s = RandomState::new();
2303 #[allow(deprecated)]
2305 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2306 pub fn new() -> RandomState {
2307 // Historically this function did not cache keys from the OS and instead
2308 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2309 // was discovered, however, that because we re-seed the thread-local RNG
2310 // from the OS periodically that this can cause excessive slowdown when
2311 // many hash maps are created on a thread. To solve this performance
2312 // trap we cache the first set of randomly generated keys per-thread.
2314 // Later in #36481 it was discovered that exposing a deterministic
2315 // iteration order allows a form of DOS attack. To counter that we
2316 // increment one of the seeds on every RandomState creation, giving
2317 // every corresponding HashMap a different iteration order.
2318 thread_local!(static KEYS: Cell<(u64, u64)> = {
2319 let r = rand::OsRng::new();
2320 let mut r = r.expect("failed to create an OS RNG");
2321 Cell::new((r.gen(), r.gen()))
2325 let (k0, k1) = keys.get();
2326 keys.set((k0.wrapping_add(1), k1));
2327 RandomState { k0: k0, k1: k1 }
2332 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2333 impl BuildHasher for RandomState {
2334 type Hasher = DefaultHasher;
2336 #[allow(deprecated)]
2337 fn build_hasher(&self) -> DefaultHasher {
2338 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2342 /// The default [`Hasher`] used by [`RandomState`].
2344 /// The internal algorithm is not specified, and so it and its hashes should
2345 /// not be relied upon over releases.
2347 /// [`RandomState`]: struct.RandomState.html
2348 /// [`Hasher`]: ../../hash/trait.Hasher.html
2349 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2350 #[allow(deprecated)]
2352 pub struct DefaultHasher(SipHasher13);
2354 impl DefaultHasher {
2355 /// Creates a new `DefaultHasher`.
2357 /// This hasher is not guaranteed to be the same as all other
2358 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2359 /// instances created through `new` or `default`.
2360 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2361 #[allow(deprecated)]
2362 pub fn new() -> DefaultHasher {
2363 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2367 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2368 impl Default for DefaultHasher {
2369 /// Creates a new `DefaultHasher` using [`DefaultHasher::new`]. See
2370 /// [`DefaultHasher::new`] documentation for more information.
2372 /// [`DefaultHasher::new`]: #method.new
2373 fn default() -> DefaultHasher {
2374 DefaultHasher::new()
2378 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2379 impl Hasher for DefaultHasher {
2381 fn write(&mut self, msg: &[u8]) {
2386 fn finish(&self) -> u64 {
2391 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2392 impl Default for RandomState {
2393 /// Constructs a new `RandomState`.
2395 fn default() -> RandomState {
2400 #[stable(feature = "std_debug", since = "1.16.0")]
2401 impl fmt::Debug for RandomState {
2402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2403 f.pad("RandomState { .. }")
2407 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2408 where K: Eq + Hash + Borrow<Q>,
2414 fn get(&self, key: &Q) -> Option<&K> {
2415 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2418 fn take(&mut self, key: &Q) -> Option<K> {
2419 if self.table.size() == 0 {
2423 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2426 fn replace(&mut self, key: K) -> Option<K> {
2429 match self.entry(key) {
2430 Occupied(mut occupied) => {
2431 let key = occupied.take_key().unwrap();
2432 Some(mem::replace(occupied.elem.read_mut().0, key))
2443 fn assert_covariance() {
2444 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2447 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2450 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2453 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2456 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2459 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2462 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2465 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2468 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2471 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2474 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2475 -> Drain<'new, &'new str, &'new str> {
2483 use super::Entry::{Occupied, Vacant};
2484 use super::RandomState;
2486 use rand::{thread_rng, Rng};
2490 fn test_zero_capacities() {
2491 type HM = HashMap<i32, i32>;
2494 assert_eq!(m.capacity(), 0);
2496 let m = HM::default();
2497 assert_eq!(m.capacity(), 0);
2499 let m = HM::with_hasher(RandomState::new());
2500 assert_eq!(m.capacity(), 0);
2502 let m = HM::with_capacity(0);
2503 assert_eq!(m.capacity(), 0);
2505 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2506 assert_eq!(m.capacity(), 0);
2508 let mut m = HM::new();
2514 assert_eq!(m.capacity(), 0);
2516 let mut m = HM::new();
2518 assert_eq!(m.capacity(), 0);
2522 fn test_create_capacity_zero() {
2523 let mut m = HashMap::with_capacity(0);
2525 assert!(m.insert(1, 1).is_none());
2527 assert!(m.contains_key(&1));
2528 assert!(!m.contains_key(&0));
2533 let mut m = HashMap::new();
2534 assert_eq!(m.len(), 0);
2535 assert!(m.insert(1, 2).is_none());
2536 assert_eq!(m.len(), 1);
2537 assert!(m.insert(2, 4).is_none());
2538 assert_eq!(m.len(), 2);
2539 assert_eq!(*m.get(&1).unwrap(), 2);
2540 assert_eq!(*m.get(&2).unwrap(), 4);
2545 let mut m = HashMap::new();
2546 assert_eq!(m.len(), 0);
2547 assert!(m.insert(1, 2).is_none());
2548 assert_eq!(m.len(), 1);
2549 assert!(m.insert(2, 4).is_none());
2550 assert_eq!(m.len(), 2);
2552 assert_eq!(*m2.get(&1).unwrap(), 2);
2553 assert_eq!(*m2.get(&2).unwrap(), 4);
2554 assert_eq!(m2.len(), 2);
2557 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2559 #[derive(Hash, PartialEq, Eq)]
2565 fn new(k: usize) -> Dropable {
2566 DROP_VECTOR.with(|slot| {
2567 slot.borrow_mut()[k] += 1;
2574 impl Drop for Dropable {
2575 fn drop(&mut self) {
2576 DROP_VECTOR.with(|slot| {
2577 slot.borrow_mut()[self.k] -= 1;
2582 impl Clone for Dropable {
2583 fn clone(&self) -> Dropable {
2584 Dropable::new(self.k)
2590 DROP_VECTOR.with(|slot| {
2591 *slot.borrow_mut() = vec![0; 200];
2595 let mut m = HashMap::new();
2597 DROP_VECTOR.with(|v| {
2599 assert_eq!(v.borrow()[i], 0);
2604 let d1 = Dropable::new(i);
2605 let d2 = Dropable::new(i + 100);
2609 DROP_VECTOR.with(|v| {
2611 assert_eq!(v.borrow()[i], 1);
2616 let k = Dropable::new(i);
2617 let v = m.remove(&k);
2619 assert!(v.is_some());
2621 DROP_VECTOR.with(|v| {
2622 assert_eq!(v.borrow()[i], 1);
2623 assert_eq!(v.borrow()[i+100], 1);
2627 DROP_VECTOR.with(|v| {
2629 assert_eq!(v.borrow()[i], 0);
2630 assert_eq!(v.borrow()[i+100], 0);
2634 assert_eq!(v.borrow()[i], 1);
2635 assert_eq!(v.borrow()[i+100], 1);
2640 DROP_VECTOR.with(|v| {
2642 assert_eq!(v.borrow()[i], 0);
2648 fn test_into_iter_drops() {
2649 DROP_VECTOR.with(|v| {
2650 *v.borrow_mut() = vec![0; 200];
2654 let mut hm = HashMap::new();
2656 DROP_VECTOR.with(|v| {
2658 assert_eq!(v.borrow()[i], 0);
2663 let d1 = Dropable::new(i);
2664 let d2 = Dropable::new(i + 100);
2668 DROP_VECTOR.with(|v| {
2670 assert_eq!(v.borrow()[i], 1);
2677 // By the way, ensure that cloning doesn't screw up the dropping.
2681 let mut half = hm.into_iter().take(50);
2683 DROP_VECTOR.with(|v| {
2685 assert_eq!(v.borrow()[i], 1);
2689 for _ in half.by_ref() {}
2691 DROP_VECTOR.with(|v| {
2693 .filter(|&i| v.borrow()[i] == 1)
2697 .filter(|&i| v.borrow()[i + 100] == 1)
2705 DROP_VECTOR.with(|v| {
2707 assert_eq!(v.borrow()[i], 0);
2713 fn test_empty_remove() {
2714 let mut m: HashMap<isize, bool> = HashMap::new();
2715 assert_eq!(m.remove(&0), None);
2719 fn test_empty_entry() {
2720 let mut m: HashMap<isize, bool> = HashMap::new();
2722 Occupied(_) => panic!(),
2725 assert!(*m.entry(0).or_insert(true));
2726 assert_eq!(m.len(), 1);
2730 fn test_empty_iter() {
2731 let mut m: HashMap<isize, bool> = HashMap::new();
2732 assert_eq!(m.drain().next(), None);
2733 assert_eq!(m.keys().next(), None);
2734 assert_eq!(m.values().next(), None);
2735 assert_eq!(m.values_mut().next(), None);
2736 assert_eq!(m.iter().next(), None);
2737 assert_eq!(m.iter_mut().next(), None);
2738 assert_eq!(m.len(), 0);
2739 assert!(m.is_empty());
2740 assert_eq!(m.into_iter().next(), None);
2744 fn test_lots_of_insertions() {
2745 let mut m = HashMap::new();
2747 // Try this a few times to make sure we never screw up the hashmap's
2750 assert!(m.is_empty());
2753 assert!(m.insert(i, i).is_none());
2757 assert_eq!(r, Some(&j));
2760 for j in i + 1..1001 {
2762 assert_eq!(r, None);
2766 for i in 1001..2001 {
2767 assert!(!m.contains_key(&i));
2772 assert!(m.remove(&i).is_some());
2775 assert!(!m.contains_key(&j));
2778 for j in i + 1..1001 {
2779 assert!(m.contains_key(&j));
2784 assert!(!m.contains_key(&i));
2788 assert!(m.insert(i, i).is_none());
2792 for i in (1..1001).rev() {
2793 assert!(m.remove(&i).is_some());
2796 assert!(!m.contains_key(&j));
2800 assert!(m.contains_key(&j));
2807 fn test_find_mut() {
2808 let mut m = HashMap::new();
2809 assert!(m.insert(1, 12).is_none());
2810 assert!(m.insert(2, 8).is_none());
2811 assert!(m.insert(5, 14).is_none());
2813 match m.get_mut(&5) {
2815 Some(x) => *x = new,
2817 assert_eq!(m.get(&5), Some(&new));
2821 fn test_insert_overwrite() {
2822 let mut m = HashMap::new();
2823 assert!(m.insert(1, 2).is_none());
2824 assert_eq!(*m.get(&1).unwrap(), 2);
2825 assert!(!m.insert(1, 3).is_none());
2826 assert_eq!(*m.get(&1).unwrap(), 3);
2830 fn test_insert_conflicts() {
2831 let mut m = HashMap::with_capacity(4);
2832 assert!(m.insert(1, 2).is_none());
2833 assert!(m.insert(5, 3).is_none());
2834 assert!(m.insert(9, 4).is_none());
2835 assert_eq!(*m.get(&9).unwrap(), 4);
2836 assert_eq!(*m.get(&5).unwrap(), 3);
2837 assert_eq!(*m.get(&1).unwrap(), 2);
2841 fn test_conflict_remove() {
2842 let mut m = HashMap::with_capacity(4);
2843 assert!(m.insert(1, 2).is_none());
2844 assert_eq!(*m.get(&1).unwrap(), 2);
2845 assert!(m.insert(5, 3).is_none());
2846 assert_eq!(*m.get(&1).unwrap(), 2);
2847 assert_eq!(*m.get(&5).unwrap(), 3);
2848 assert!(m.insert(9, 4).is_none());
2849 assert_eq!(*m.get(&1).unwrap(), 2);
2850 assert_eq!(*m.get(&5).unwrap(), 3);
2851 assert_eq!(*m.get(&9).unwrap(), 4);
2852 assert!(m.remove(&1).is_some());
2853 assert_eq!(*m.get(&9).unwrap(), 4);
2854 assert_eq!(*m.get(&5).unwrap(), 3);
2858 fn test_is_empty() {
2859 let mut m = HashMap::with_capacity(4);
2860 assert!(m.insert(1, 2).is_none());
2861 assert!(!m.is_empty());
2862 assert!(m.remove(&1).is_some());
2863 assert!(m.is_empty());
2868 let mut m = HashMap::new();
2870 assert_eq!(m.remove(&1), Some(2));
2871 assert_eq!(m.remove(&1), None);
2876 let mut m = HashMap::with_capacity(4);
2878 assert!(m.insert(i, i*2).is_none());
2880 assert_eq!(m.len(), 32);
2882 let mut observed: u32 = 0;
2885 assert_eq!(*v, *k * 2);
2886 observed |= 1 << *k;
2888 assert_eq!(observed, 0xFFFF_FFFF);
2893 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2894 let map: HashMap<_, _> = vec.into_iter().collect();
2895 let keys: Vec<_> = map.keys().cloned().collect();
2896 assert_eq!(keys.len(), 3);
2897 assert!(keys.contains(&1));
2898 assert!(keys.contains(&2));
2899 assert!(keys.contains(&3));
2904 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2905 let map: HashMap<_, _> = vec.into_iter().collect();
2906 let values: Vec<_> = map.values().cloned().collect();
2907 assert_eq!(values.len(), 3);
2908 assert!(values.contains(&'a'));
2909 assert!(values.contains(&'b'));
2910 assert!(values.contains(&'c'));
2914 fn test_values_mut() {
2915 let vec = vec![(1, 1), (2, 2), (3, 3)];
2916 let mut map: HashMap<_, _> = vec.into_iter().collect();
2917 for value in map.values_mut() {
2918 *value = (*value) * 2
2920 let values: Vec<_> = map.values().cloned().collect();
2921 assert_eq!(values.len(), 3);
2922 assert!(values.contains(&2));
2923 assert!(values.contains(&4));
2924 assert!(values.contains(&6));
2929 let mut m = HashMap::new();
2930 assert!(m.get(&1).is_none());
2934 Some(v) => assert_eq!(*v, 2),
2940 let mut m1 = HashMap::new();
2945 let mut m2 = HashMap::new();
2958 let mut map = HashMap::new();
2959 let empty: HashMap<i32, i32> = HashMap::new();
2964 let map_str = format!("{:?}", map);
2966 assert!(map_str == "{1: 2, 3: 4}" ||
2967 map_str == "{3: 4, 1: 2}");
2968 assert_eq!(format!("{:?}", empty), "{}");
2973 let mut m = HashMap::new();
2975 assert_eq!(m.len(), 0);
2976 assert!(m.is_empty());
2979 let old_raw_cap = m.raw_capacity();
2980 while old_raw_cap == m.raw_capacity() {
2985 assert_eq!(m.len(), i);
2986 assert!(!m.is_empty());
2990 fn test_behavior_resize_policy() {
2991 let mut m = HashMap::new();
2993 assert_eq!(m.len(), 0);
2994 assert_eq!(m.raw_capacity(), 0);
2995 assert!(m.is_empty());
2999 assert!(m.is_empty());
3000 let initial_raw_cap = m.raw_capacity();
3001 m.reserve(initial_raw_cap);
3002 let raw_cap = m.raw_capacity();
3004 assert_eq!(raw_cap, initial_raw_cap * 2);
3007 for _ in 0..raw_cap * 3 / 4 {
3011 // three quarters full
3013 assert_eq!(m.len(), i);
3014 assert_eq!(m.raw_capacity(), raw_cap);
3016 for _ in 0..raw_cap / 4 {
3022 let new_raw_cap = m.raw_capacity();
3023 assert_eq!(new_raw_cap, raw_cap * 2);
3025 for _ in 0..raw_cap / 2 - 1 {
3028 assert_eq!(m.raw_capacity(), new_raw_cap);
3030 // A little more than one quarter full.
3032 assert_eq!(m.raw_capacity(), raw_cap);
3033 // again, a little more than half full
3034 for _ in 0..raw_cap / 2 - 1 {
3040 assert_eq!(m.len(), i);
3041 assert!(!m.is_empty());
3042 assert_eq!(m.raw_capacity(), initial_raw_cap);
3046 fn test_reserve_shrink_to_fit() {
3047 let mut m = HashMap::new();
3050 assert!(m.capacity() >= m.len());
3056 let usable_cap = m.capacity();
3057 for i in 128..(128 + 256) {
3059 assert_eq!(m.capacity(), usable_cap);
3062 for i in 100..(128 + 256) {
3063 assert_eq!(m.remove(&i), Some(i));
3067 assert_eq!(m.len(), 100);
3068 assert!(!m.is_empty());
3069 assert!(m.capacity() >= m.len());
3072 assert_eq!(m.remove(&i), Some(i));
3077 assert_eq!(m.len(), 1);
3078 assert!(m.capacity() >= m.len());
3079 assert_eq!(m.remove(&0), Some(0));
3083 fn test_from_iter() {
3084 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3086 let map: HashMap<_, _> = xs.iter().cloned().collect();
3088 for &(k, v) in &xs {
3089 assert_eq!(map.get(&k), Some(&v));
3094 fn test_size_hint() {
3095 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3097 let map: HashMap<_, _> = xs.iter().cloned().collect();
3099 let mut iter = map.iter();
3101 for _ in iter.by_ref().take(3) {}
3103 assert_eq!(iter.size_hint(), (3, Some(3)));
3107 fn test_iter_len() {
3108 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3110 let map: HashMap<_, _> = xs.iter().cloned().collect();
3112 let mut iter = map.iter();
3114 for _ in iter.by_ref().take(3) {}
3116 assert_eq!(iter.len(), 3);
3120 fn test_mut_size_hint() {
3121 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3123 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3125 let mut iter = map.iter_mut();
3127 for _ in iter.by_ref().take(3) {}
3129 assert_eq!(iter.size_hint(), (3, Some(3)));
3133 fn test_iter_mut_len() {
3134 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3136 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3138 let mut iter = map.iter_mut();
3140 for _ in iter.by_ref().take(3) {}
3142 assert_eq!(iter.len(), 3);
3147 let mut map = HashMap::new();
3153 assert_eq!(map[&2], 1);
3158 fn test_index_nonexistent() {
3159 let mut map = HashMap::new();
3170 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3172 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3174 // Existing key (insert)
3175 match map.entry(1) {
3176 Vacant(_) => unreachable!(),
3177 Occupied(mut view) => {
3178 assert_eq!(view.get(), &10);
3179 assert_eq!(view.insert(100), 10);
3182 assert_eq!(map.get(&1).unwrap(), &100);
3183 assert_eq!(map.len(), 6);
3186 // Existing key (update)
3187 match map.entry(2) {
3188 Vacant(_) => unreachable!(),
3189 Occupied(mut view) => {
3190 let v = view.get_mut();
3191 let new_v = (*v) * 10;
3195 assert_eq!(map.get(&2).unwrap(), &200);
3196 assert_eq!(map.len(), 6);
3198 // Existing key (take)
3199 match map.entry(3) {
3200 Vacant(_) => unreachable!(),
3202 assert_eq!(view.remove(), 30);
3205 assert_eq!(map.get(&3), None);
3206 assert_eq!(map.len(), 5);
3209 // Inexistent key (insert)
3210 match map.entry(10) {
3211 Occupied(_) => unreachable!(),
3213 assert_eq!(*view.insert(1000), 1000);
3216 assert_eq!(map.get(&10).unwrap(), &1000);
3217 assert_eq!(map.len(), 6);
3221 fn test_entry_take_doesnt_corrupt() {
3222 #![allow(deprecated)] //rand
3224 fn check(m: &HashMap<isize, ()>) {
3226 assert!(m.contains_key(k),
3227 "{} is in keys() but not in the map?", k);
3231 let mut m = HashMap::new();
3232 let mut rng = thread_rng();
3234 // Populate the map with some items.
3236 let x = rng.gen_range(-10, 10);
3241 let x = rng.gen_range(-10, 10);
3245 println!("{}: remove {}", i, x);
3255 fn test_extend_ref() {
3256 let mut a = HashMap::new();
3258 let mut b = HashMap::new();
3260 b.insert(3, "three");
3264 assert_eq!(a.len(), 3);
3265 assert_eq!(a[&1], "one");
3266 assert_eq!(a[&2], "two");
3267 assert_eq!(a[&3], "three");
3271 fn test_capacity_not_less_than_len() {
3272 let mut a = HashMap::new();
3280 assert!(a.capacity() > a.len());
3282 let free = a.capacity() - a.len();
3288 assert_eq!(a.len(), a.capacity());
3290 // Insert at capacity should cause allocation.
3292 assert!(a.capacity() > a.len());
3296 fn test_occupied_entry_key() {
3297 let mut a = HashMap::new();
3298 let key = "hello there";
3299 let value = "value goes here";
3300 assert!(a.is_empty());
3301 a.insert(key.clone(), value.clone());
3302 assert_eq!(a.len(), 1);
3303 assert_eq!(a[key], value);
3305 match a.entry(key.clone()) {
3306 Vacant(_) => panic!(),
3307 Occupied(e) => assert_eq!(key, *e.key()),
3309 assert_eq!(a.len(), 1);
3310 assert_eq!(a[key], value);
3314 fn test_vacant_entry_key() {
3315 let mut a = HashMap::new();
3316 let key = "hello there";
3317 let value = "value goes here";
3319 assert!(a.is_empty());
3320 match a.entry(key.clone()) {
3321 Occupied(_) => panic!(),
3323 assert_eq!(key, *e.key());
3324 e.insert(value.clone());
3327 assert_eq!(a.len(), 1);
3328 assert_eq!(a[key], value);
3333 let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3335 map.retain(|&k, _| k % 2 == 0);
3336 assert_eq!(map.len(), 50);
3337 assert_eq!(map[&2], 20);
3338 assert_eq!(map[&4], 40);
3339 assert_eq!(map[&6], 60);
3343 fn test_adaptive() {
3344 const TEST_LEN: usize = 5000;
3345 // by cloning we get maps with the same hasher seed
3346 let mut first = HashMap::new();
3347 let mut second = first.clone();
3348 first.extend((0..TEST_LEN).map(|i| (i, i)));
3349 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3351 for (&k, &v) in &second {
3352 let prev_cap = first.capacity();
3353 let expect_grow = first.len() == prev_cap;
3355 if !expect_grow && first.capacity() != prev_cap {
3359 panic!("Adaptive early resize failed");
3363 fn test_placement_in() {
3364 let mut map = HashMap::new();
3365 map.extend((0..10).map(|i| (i, i)));
3367 map.entry(100) <- 100;
3368 assert_eq!(map[&100], 100);
3371 assert_eq!(map[&0], 10);
3373 assert_eq!(map.len(), 11);
3377 fn test_placement_panic() {
3378 let mut map = HashMap::new();
3379 map.extend((0..10).map(|i| (i, i)));
3381 fn mkpanic() -> usize { panic!() }
3383 // modify existing key
3384 // when panic happens, previous key is removed.
3385 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3386 assert_eq!(map.len(), 9);
3387 assert!(!map.contains_key(&0));
3390 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3391 assert_eq!(map.len(), 9);
3392 assert!(!map.contains_key(&100));
3396 fn test_placement_drop() {
3398 struct TestV<'a>(&'a mut bool);
3399 impl<'a> Drop for TestV<'a> {
3400 fn drop(&mut self) {
3401 if !*self.0 { panic!("value double drop!"); } // no double drop
3406 fn makepanic<'a>() -> TestV<'a> { panic!() }
3408 let mut can_drop = true;
3409 let mut hm = HashMap::new();
3410 hm.insert(0, TestV(&mut can_drop));
3411 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3412 assert_eq!(hm.len(), 0);