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 implemented with linear probing and Robin Hood bucket stealing.
220 /// By default, `HashMap` uses a hashing algorithm selected to provide
221 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
222 /// reasonable best-effort is made to generate this seed from a high quality,
223 /// secure source of randomness provided by the host without blocking the
224 /// program. Because of this, the randomness of the seed depends on the output
225 /// quality of the system's random number generator when the seed is created.
226 /// In particular, seeds generated when the system's entropy pool is abnormally
227 /// low such as during system boot may be of a lower quality.
229 /// The default hashing algorithm is currently SipHash 1-3, though this is
230 /// subject to change at any point in the future. While its performance is very
231 /// competitive for medium sized keys, other hashing algorithms will outperform
232 /// it for small keys such as integers as well as large keys such as long
233 /// strings, though those algorithms will typically *not* protect against
234 /// attacks such as HashDoS.
236 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
237 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
238 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
240 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
241 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
242 /// If you implement these yourself, it is important that the following
246 /// k1 == k2 -> hash(k1) == hash(k2)
249 /// In other words, if two keys are equal, their hashes must be equal.
251 /// It is a logic error for a key to be modified in such a way that the key's
252 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
253 /// the [`Eq`] trait, changes while it is in the map. This is normally only
254 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
256 /// Relevant papers/articles:
258 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
259 /// 2. Emmanuel Goossaert. ["Robin Hood
260 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
261 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
262 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
267 /// use std::collections::HashMap;
269 /// // type inference lets us omit an explicit type signature (which
270 /// // would be `HashMap<&str, &str>` in this example).
271 /// let mut book_reviews = HashMap::new();
273 /// // review some books.
274 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
275 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
276 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
277 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
279 /// // check for a specific one.
280 /// if !book_reviews.contains_key("Les Misérables") {
281 /// println!("We've got {} reviews, but Les Misérables ain't one.",
282 /// book_reviews.len());
285 /// // oops, this review has a lot of spelling mistakes, let's delete it.
286 /// book_reviews.remove("The Adventures of Sherlock Holmes");
288 /// // look up the values associated with some keys.
289 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
290 /// for book in &to_find {
291 /// match book_reviews.get(book) {
292 /// Some(review) => println!("{}: {}", book, review),
293 /// None => println!("{} is unreviewed.", book)
297 /// // iterate over everything.
298 /// for (book, review) in &book_reviews {
299 /// println!("{}: \"{}\"", book, review);
303 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
304 /// for more complex methods of getting, setting, updating and removing keys and
308 /// use std::collections::HashMap;
310 /// // type inference lets us omit an explicit type signature (which
311 /// // would be `HashMap<&str, u8>` in this example).
312 /// let mut player_stats = HashMap::new();
314 /// fn random_stat_buff() -> u8 {
315 /// // could actually return some random value here - let's just return
316 /// // some fixed value for now
320 /// // insert a key only if it doesn't already exist
321 /// player_stats.entry("health").or_insert(100);
323 /// // insert a key using a function that provides a new value only if it
324 /// // doesn't already exist
325 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
327 /// // update a key, guarding against the key possibly not being set
328 /// let stat = player_stats.entry("attack").or_insert(100);
329 /// *stat += random_stat_buff();
332 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
333 /// We must also derive [`PartialEq`].
335 /// [`Eq`]: ../../std/cmp/trait.Eq.html
336 /// [`Hash`]: ../../std/hash/trait.Hash.html
337 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
338 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
339 /// [`Cell`]: ../../std/cell/struct.Cell.html
340 /// [`default`]: #method.default
341 /// [`with_hasher`]: #method.with_hasher
342 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
343 /// [`fnv`]: https://crates.io/crates/fnv
346 /// use std::collections::HashMap;
348 /// #[derive(Hash, Eq, PartialEq, Debug)]
355 /// /// Create a new Viking.
356 /// fn new(name: &str, country: &str) -> Viking {
357 /// Viking { name: name.to_string(), country: country.to_string() }
361 /// // Use a HashMap to store the vikings' health points.
362 /// let mut vikings = HashMap::new();
364 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
365 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
366 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
368 /// // Use derived implementation to print the status of the vikings.
369 /// for (viking, health) in &vikings {
370 /// println!("{:?} has {} hp", viking, health);
374 /// A `HashMap` with fixed list of elements can be initialized from an array:
377 /// use std::collections::HashMap;
380 /// let timber_resources: HashMap<&str, i32> =
381 /// [("Norway", 100),
384 /// .iter().cloned().collect();
385 /// // use the values stored in map
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub struct HashMap<K, V, S = RandomState> {
392 // All hashes are keyed on these values, to prevent hash collision attacks.
395 table: RawTable<K, V>,
397 resize_policy: DefaultResizePolicy,
400 /// Search for a pre-hashed key.
402 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
403 where M: Deref<Target = RawTable<K, V>>,
406 // This is the only function where capacity can be zero. To avoid
407 // undefined behavior when Bucket::new gets the raw bucket in this
408 // case, immediately return the appropriate search result.
409 if table.capacity() == 0 {
410 return InternalEntry::TableIsEmpty;
413 let size = table.size();
414 let mut probe = Bucket::new(table, hash);
415 let mut displacement = 0;
418 let full = match probe.peek() {
421 return InternalEntry::Vacant {
423 elem: NoElem(bucket, displacement),
426 Full(bucket) => bucket,
429 let probe_displacement = full.displacement();
431 if probe_displacement < displacement {
432 // Found a luckier bucket than me.
433 // We can finish the search early if we hit any bucket
434 // with a lower distance to initial bucket than we've probed.
435 return InternalEntry::Vacant {
437 elem: NeqElem(full, probe_displacement),
441 // If the hash doesn't match, it can't be this one..
442 if hash == full.hash() {
443 // If the key doesn't match, it can't be this one..
444 if is_match(full.read().0) {
445 return InternalEntry::Occupied { elem: full };
450 debug_assert!(displacement <= size);
454 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
455 -> (K, V, &mut RawTable<K, V>)
457 let (empty, retkey, retval) = starting_bucket.take();
458 let mut gap = match empty.gap_peek() {
460 Err(b) => return (retkey, retval, b.into_table()),
463 while gap.full().displacement() != 0 {
464 gap = match gap.shift() {
467 return (retkey, retval, b.into_table());
472 // Now we've done all our shifting. Return the value we grabbed earlier.
473 (retkey, retval, gap.into_table())
476 /// Perform robin hood bucket stealing at the given `bucket`. You must
477 /// also pass that bucket's displacement so we don't have to recalculate it.
479 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
480 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
481 mut displacement: usize,
485 -> FullBucketMut<'a, K, V> {
486 let size = bucket.table().size();
487 let raw_capacity = bucket.table().capacity();
488 // There can be at most `size - dib` buckets to displace, because
489 // in the worst case, there are `size` elements and we already are
490 // `displacement` buckets away from the initial one.
491 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
492 // Save the *starting point*.
493 let mut bucket = bucket.stash();
496 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
503 let probe = bucket.next();
504 debug_assert!(probe.index() != idx_end);
506 let full_bucket = match probe.peek() {
509 let bucket = bucket.put(hash, key, val);
510 // Now that it's stolen, just read the value's pointer
511 // right out of the table! Go back to the *starting point*.
513 // This use of `into_table` is misleading. It turns the
514 // bucket, which is a FullBucket on top of a
515 // FullBucketMut, into just one FullBucketMut. The "table"
516 // refers to the inner FullBucketMut in this context.
517 return bucket.into_table();
519 Full(bucket) => bucket,
522 let probe_displacement = full_bucket.displacement();
524 bucket = full_bucket;
526 // Robin hood! Steal the spot.
527 if probe_displacement < displacement {
528 displacement = probe_displacement;
535 impl<K, V, S> HashMap<K, V, S>
539 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
542 table::make_hash(&self.hash_builder, x)
545 /// Search for a key, yielding the index if it's found in the hashtable.
546 /// If you already have the hash for the key lying around, use
549 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
553 let hash = self.make_hash(q);
554 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
558 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
562 let hash = self.make_hash(q);
563 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
566 // The caller should ensure that invariants by Robin Hood Hashing hold
567 // and that there's space in the underlying table.
568 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
569 let mut buckets = Bucket::new(&mut self.table, hash);
570 let start_index = buckets.index();
573 // We don't need to compare hashes for value swap.
574 // Not even DIBs for Robin Hood.
575 buckets = match buckets.peek() {
577 empty.put(hash, k, v);
580 Full(b) => b.into_bucket(),
583 debug_assert!(buckets.index() != start_index);
588 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
589 /// Creates an empty `HashMap`.
594 /// use std::collections::HashMap;
595 /// let mut map: HashMap<&str, isize> = HashMap::new();
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn new() -> HashMap<K, V, RandomState> {
603 /// Creates an empty `HashMap` with the specified capacity.
605 /// The hash map will be able to hold at least `capacity` elements without
606 /// reallocating. If `capacity` is 0, the hash map will not allocate.
611 /// use std::collections::HashMap;
612 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
617 HashMap::with_capacity_and_hasher(capacity, Default::default())
621 impl<K, V, S> HashMap<K, V, S>
625 /// Creates an empty `HashMap` which will use the given hash builder to hash
628 /// The created map has the default initial capacity.
630 /// Warning: `hash_builder` is normally randomly generated, and
631 /// is designed to allow HashMaps to be resistant to attacks that
632 /// cause many collisions and very poor performance. Setting it
633 /// manually using this function can expose a DoS attack vector.
638 /// use std::collections::HashMap;
639 /// use std::collections::hash_map::RandomState;
641 /// let s = RandomState::new();
642 /// let mut map = HashMap::with_hasher(s);
643 /// map.insert(1, 2);
646 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
647 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
649 hash_builder: hash_builder,
650 resize_policy: DefaultResizePolicy::new(),
651 table: RawTable::new(0),
655 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
656 /// to hash the keys.
658 /// The hash map will be able to hold at least `capacity` elements without
659 /// reallocating. If `capacity` is 0, the hash map will not allocate.
661 /// Warning: `hash_builder` is normally randomly generated, and
662 /// is designed to allow HashMaps to be resistant to attacks that
663 /// cause many collisions and very poor performance. Setting it
664 /// manually using this function can expose a DoS attack vector.
669 /// use std::collections::HashMap;
670 /// use std::collections::hash_map::RandomState;
672 /// let s = RandomState::new();
673 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
674 /// map.insert(1, 2);
677 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
678 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
679 let resize_policy = DefaultResizePolicy::new();
680 let raw_cap = resize_policy.raw_capacity(capacity);
682 hash_builder: hash_builder,
683 resize_policy: resize_policy,
684 table: RawTable::new(raw_cap),
688 /// Returns a reference to the map's [`BuildHasher`].
690 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
691 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
692 pub fn hasher(&self) -> &S {
696 /// Returns the number of elements the map can hold without reallocating.
698 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
699 /// more, but is guaranteed to be able to hold at least this many.
704 /// use std::collections::HashMap;
705 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
706 /// assert!(map.capacity() >= 100);
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn capacity(&self) -> usize {
711 self.resize_policy.capacity(self.raw_capacity())
714 /// Returns the hash map's raw capacity.
716 fn raw_capacity(&self) -> usize {
717 self.table.capacity()
720 /// Reserves capacity for at least `additional` more elements to be inserted
721 /// in the `HashMap`. The collection may reserve more space to avoid
722 /// frequent reallocations.
726 /// Panics if the new allocation size overflows [`usize`].
728 /// [`usize`]: ../../std/primitive.usize.html
733 /// use std::collections::HashMap;
734 /// let mut map: HashMap<&str, isize> = HashMap::new();
737 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn reserve(&mut self, additional: usize) {
739 let remaining = self.capacity() - self.len(); // this can't overflow
740 if remaining < additional {
741 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
742 let raw_cap = self.resize_policy.raw_capacity(min_cap);
743 self.resize(raw_cap);
744 } else if self.table.tag() && remaining <= self.len() {
745 // Probe sequence is too long and table is half full,
746 // resize early to reduce probing length.
747 let new_capacity = self.table.capacity() * 2;
748 self.resize(new_capacity);
752 /// Resizes the internal vectors to a new capacity. It's your
753 /// responsibility to:
754 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
755 /// for the load factor.
756 /// 2) Ensure `new_raw_cap` is a power of two or zero.
757 fn resize(&mut self, new_raw_cap: usize) {
758 assert!(self.table.size() <= new_raw_cap);
759 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
761 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
762 let old_size = old_table.size();
764 if old_table.size() == 0 {
768 let mut bucket = Bucket::head_bucket(&mut old_table);
770 // This is how the buckets might be laid out in memory:
771 // ($ marks an initialized bucket)
773 // |$$$_$$$$$$_$$$$$|
775 // But we've skipped the entire initial cluster of buckets
776 // and will continue iteration in this order:
779 // ^ wrap around once end is reached
782 // ^ exit once table.size == 0
784 bucket = match bucket.peek() {
786 let h = bucket.hash();
787 let (b, k, v) = bucket.take();
788 self.insert_hashed_ordered(h, k, v);
789 if b.table().size() == 0 {
794 Empty(b) => b.into_bucket(),
799 assert_eq!(self.table.size(), old_size);
802 /// Shrinks the capacity of the map as much as possible. It will drop
803 /// down as much as possible while maintaining the internal rules
804 /// and possibly leaving some space in accordance with the resize policy.
809 /// use std::collections::HashMap;
811 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
812 /// map.insert(1, 2);
813 /// map.insert(3, 4);
814 /// assert!(map.capacity() >= 100);
815 /// map.shrink_to_fit();
816 /// assert!(map.capacity() >= 2);
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn shrink_to_fit(&mut self) {
820 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
821 if self.raw_capacity() != new_raw_cap {
822 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
823 let old_size = old_table.size();
825 // Shrink the table. Naive algorithm for resizing:
826 for (h, k, v) in old_table.into_iter() {
827 self.insert_hashed_nocheck(h, k, v);
830 debug_assert_eq!(self.table.size(), old_size);
834 /// Insert a pre-hashed key-value pair, without first checking
835 /// that there's enough room in the buckets. Returns a reference to the
836 /// newly insert value.
838 /// If the key already exists, the hashtable will be returned untouched
839 /// and a reference to the existing element will be returned.
840 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
841 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
843 Some(Occupied(mut elem)) => Some(elem.insert(v)),
844 Some(Vacant(elem)) => {
848 None => unreachable!(),
852 /// An iterator visiting all keys in arbitrary order.
853 /// The iterator element type is `&'a K`.
858 /// use std::collections::HashMap;
860 /// let mut map = HashMap::new();
861 /// map.insert("a", 1);
862 /// map.insert("b", 2);
863 /// map.insert("c", 3);
865 /// for key in map.keys() {
866 /// println!("{}", key);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn keys(&self) -> Keys<K, V> {
871 Keys { inner: self.iter() }
874 /// An iterator visiting all values in arbitrary order.
875 /// The iterator element type is `&'a V`.
880 /// use std::collections::HashMap;
882 /// let mut map = HashMap::new();
883 /// map.insert("a", 1);
884 /// map.insert("b", 2);
885 /// map.insert("c", 3);
887 /// for val in map.values() {
888 /// println!("{}", val);
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn values(&self) -> Values<K, V> {
893 Values { inner: self.iter() }
896 /// An iterator visiting all values mutably in arbitrary order.
897 /// The iterator element type is `&'a mut V`.
902 /// use std::collections::HashMap;
904 /// let mut map = HashMap::new();
906 /// map.insert("a", 1);
907 /// map.insert("b", 2);
908 /// map.insert("c", 3);
910 /// for val in map.values_mut() {
911 /// *val = *val + 10;
914 /// for val in map.values() {
915 /// println!("{}", val);
918 #[stable(feature = "map_values_mut", since = "1.10.0")]
919 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
920 ValuesMut { inner: self.iter_mut() }
923 /// An iterator visiting all key-value pairs in arbitrary order.
924 /// The iterator element type is `(&'a K, &'a V)`.
929 /// use std::collections::HashMap;
931 /// let mut map = HashMap::new();
932 /// map.insert("a", 1);
933 /// map.insert("b", 2);
934 /// map.insert("c", 3);
936 /// for (key, val) in map.iter() {
937 /// println!("key: {} val: {}", key, val);
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn iter(&self) -> Iter<K, V> {
942 Iter { inner: self.table.iter() }
945 /// An iterator visiting all key-value pairs in arbitrary order,
946 /// with mutable references to the values.
947 /// The iterator element type is `(&'a K, &'a mut V)`.
952 /// use std::collections::HashMap;
954 /// let mut map = HashMap::new();
955 /// map.insert("a", 1);
956 /// map.insert("b", 2);
957 /// map.insert("c", 3);
959 /// // Update all values
960 /// for (_, val) in map.iter_mut() {
964 /// for (key, val) in &map {
965 /// println!("key: {} val: {}", key, val);
968 #[stable(feature = "rust1", since = "1.0.0")]
969 pub fn iter_mut(&mut self) -> IterMut<K, V> {
970 IterMut { inner: self.table.iter_mut() }
973 /// Gets the given key's corresponding entry in the map for in-place manipulation.
978 /// use std::collections::HashMap;
980 /// let mut letters = HashMap::new();
982 /// for ch in "a short treatise on fungi".chars() {
983 /// let counter = letters.entry(ch).or_insert(0);
987 /// assert_eq!(letters[&'s'], 2);
988 /// assert_eq!(letters[&'t'], 3);
989 /// assert_eq!(letters[&'u'], 1);
990 /// assert_eq!(letters.get(&'y'), None);
992 #[stable(feature = "rust1", since = "1.0.0")]
993 pub fn entry(&mut self, key: K) -> Entry<K, V> {
996 let hash = self.make_hash(&key);
997 search_hashed(&mut self.table, hash, |q| q.eq(&key))
998 .into_entry(key).expect("unreachable")
1001 /// Returns the number of elements in the map.
1006 /// use std::collections::HashMap;
1008 /// let mut a = HashMap::new();
1009 /// assert_eq!(a.len(), 0);
1010 /// a.insert(1, "a");
1011 /// assert_eq!(a.len(), 1);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn len(&self) -> usize {
1018 /// Returns true if the map contains no elements.
1023 /// use std::collections::HashMap;
1025 /// let mut a = HashMap::new();
1026 /// assert!(a.is_empty());
1027 /// a.insert(1, "a");
1028 /// assert!(!a.is_empty());
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn is_empty(&self) -> bool {
1036 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1037 /// allocated memory for reuse.
1042 /// use std::collections::HashMap;
1044 /// let mut a = HashMap::new();
1045 /// a.insert(1, "a");
1046 /// a.insert(2, "b");
1048 /// for (k, v) in a.drain().take(1) {
1049 /// assert!(k == 1 || k == 2);
1050 /// assert!(v == "a" || v == "b");
1053 /// assert!(a.is_empty());
1056 #[stable(feature = "drain", since = "1.6.0")]
1057 pub fn drain(&mut self) -> Drain<K, V> {
1058 Drain { inner: self.table.drain() }
1061 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1067 /// use std::collections::HashMap;
1069 /// let mut a = HashMap::new();
1070 /// a.insert(1, "a");
1072 /// assert!(a.is_empty());
1074 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn clear(&mut self) {
1080 /// Returns a reference to the value corresponding to the key.
1082 /// The key may be any borrowed form of the map's key type, but
1083 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1086 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1087 /// [`Hash`]: ../../std/hash/trait.Hash.html
1092 /// use std::collections::HashMap;
1094 /// let mut map = HashMap::new();
1095 /// map.insert(1, "a");
1096 /// assert_eq!(map.get(&1), Some(&"a"));
1097 /// assert_eq!(map.get(&2), None);
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1104 self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1)
1107 /// Returns true if the map contains a value for the specified key.
1109 /// The key may be any borrowed form of the map's key type, but
1110 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1113 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1114 /// [`Hash`]: ../../std/hash/trait.Hash.html
1119 /// use std::collections::HashMap;
1121 /// let mut map = HashMap::new();
1122 /// map.insert(1, "a");
1123 /// assert_eq!(map.contains_key(&1), true);
1124 /// assert_eq!(map.contains_key(&2), false);
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1131 self.search(k).into_occupied_bucket().is_some()
1134 /// Returns a mutable reference to the value corresponding to the key.
1136 /// The key may be any borrowed form of the map's key type, but
1137 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1140 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1141 /// [`Hash`]: ../../std/hash/trait.Hash.html
1146 /// use std::collections::HashMap;
1148 /// let mut map = HashMap::new();
1149 /// map.insert(1, "a");
1150 /// if let Some(x) = map.get_mut(&1) {
1153 /// assert_eq!(map[&1], "b");
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1160 self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1)
1163 /// Inserts a key-value pair into the map.
1165 /// If the map did not have this key present, [`None`] is returned.
1167 /// If the map did have this key present, the value is updated, and the old
1168 /// value is returned. The key is not updated, though; this matters for
1169 /// types that can be `==` without being identical. See the [module-level
1170 /// documentation] for more.
1172 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1173 /// [module-level documentation]: index.html#insert-and-complex-keys
1178 /// use std::collections::HashMap;
1180 /// let mut map = HashMap::new();
1181 /// assert_eq!(map.insert(37, "a"), None);
1182 /// assert_eq!(map.is_empty(), false);
1184 /// map.insert(37, "b");
1185 /// assert_eq!(map.insert(37, "c"), Some("b"));
1186 /// assert_eq!(map[&37], "c");
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1190 let hash = self.make_hash(&k);
1192 self.insert_hashed_nocheck(hash, k, v)
1195 /// Removes a key from the map, returning the value at the key if the key
1196 /// was previously in the map.
1198 /// The key may be any borrowed form of the map's key type, but
1199 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1202 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1203 /// [`Hash`]: ../../std/hash/trait.Hash.html
1208 /// use std::collections::HashMap;
1210 /// let mut map = HashMap::new();
1211 /// map.insert(1, "a");
1212 /// assert_eq!(map.remove(&1), Some("a"));
1213 /// assert_eq!(map.remove(&1), None);
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1220 if self.table.size() == 0 {
1224 self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1)
1227 /// Retains only the elements specified by the predicate.
1229 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1234 /// #![feature(retain_hash_collection)]
1235 /// use std::collections::HashMap;
1237 /// let mut map: HashMap<isize, isize> = (0..8).map(|x|(x, x*10)).collect();
1238 /// map.retain(|&k, _| k % 2 == 0);
1239 /// assert_eq!(map.len(), 4);
1241 #[unstable(feature = "retain_hash_collection", issue = "36648")]
1242 pub fn retain<F>(&mut self, mut f: F)
1243 where F: FnMut(&K, &mut V) -> bool
1245 if self.table.size() == 0 {
1248 let mut elems_left = self.table.size();
1249 let mut bucket = Bucket::head_bucket(&mut self.table);
1251 let start_index = bucket.index();
1252 while elems_left != 0 {
1253 bucket = match bucket.peek() {
1256 let should_remove = {
1257 let (k, v) = full.read_mut();
1261 let prev_raw = full.raw();
1262 let (_, _, t) = pop_internal(full);
1263 Bucket::new_from(prev_raw, t)
1272 bucket.prev(); // reverse iteration
1273 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl<K, V, S> PartialEq for HashMap<K, V, S>
1284 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1285 if self.len() != other.len() {
1289 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<K, V, S> Eq for HashMap<K, V, S>
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<K, V, S> Debug for HashMap<K, V, S>
1303 where K: Eq + Hash + Debug,
1307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1308 f.debug_map().entries(self.iter()).finish()
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<K, V, S> Default for HashMap<K, V, S>
1315 S: BuildHasher + Default
1317 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1318 fn default() -> HashMap<K, V, S> {
1319 HashMap::with_hasher(Default::default())
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1325 where K: Eq + Hash + Borrow<Q>,
1332 fn index(&self, index: &Q) -> &V {
1333 self.get(index).expect("no entry found for key")
1337 /// An iterator over the entries of a `HashMap`.
1339 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1340 /// documentation for more.
1342 /// [`iter`]: struct.HashMap.html#method.iter
1343 /// [`HashMap`]: struct.HashMap.html
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 pub struct Iter<'a, K: 'a, V: 'a> {
1346 inner: table::Iter<'a, K, V>,
1349 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, K, V> Clone for Iter<'a, K, V> {
1352 fn clone(&self) -> Iter<'a, K, V> {
1353 Iter { inner: self.inner.clone() }
1357 #[stable(feature = "std_debug", since = "1.16.0")]
1358 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1361 .entries(self.clone())
1366 /// A mutable iterator over the entries of a `HashMap`.
1368 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1369 /// documentation for more.
1371 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1372 /// [`HashMap`]: struct.HashMap.html
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub struct IterMut<'a, K: 'a, V: 'a> {
1375 inner: table::IterMut<'a, K, V>,
1378 /// An owning iterator over the entries of a `HashMap`.
1380 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1381 /// (provided by the `IntoIterator` trait). See its documentation for more.
1383 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1384 /// [`HashMap`]: struct.HashMap.html
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub struct IntoIter<K, V> {
1387 pub(super) inner: table::IntoIter<K, V>,
1390 /// An iterator over the keys of a `HashMap`.
1392 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1393 /// documentation for more.
1395 /// [`keys`]: struct.HashMap.html#method.keys
1396 /// [`HashMap`]: struct.HashMap.html
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub struct Keys<'a, K: 'a, V: 'a> {
1399 inner: Iter<'a, K, V>,
1402 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<'a, K, V> Clone for Keys<'a, K, V> {
1405 fn clone(&self) -> Keys<'a, K, V> {
1406 Keys { inner: self.inner.clone() }
1410 #[stable(feature = "std_debug", since = "1.16.0")]
1411 impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> {
1412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1414 .entries(self.clone())
1419 /// An iterator over the values of a `HashMap`.
1421 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1422 /// documentation for more.
1424 /// [`values`]: struct.HashMap.html#method.values
1425 /// [`HashMap`]: struct.HashMap.html
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub struct Values<'a, K: 'a, V: 'a> {
1428 inner: Iter<'a, K, V>,
1431 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<'a, K, V> Clone for Values<'a, K, V> {
1434 fn clone(&self) -> Values<'a, K, V> {
1435 Values { inner: self.inner.clone() }
1439 #[stable(feature = "std_debug", since = "1.16.0")]
1440 impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> {
1441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1443 .entries(self.clone())
1448 /// A draining iterator over the entries of a `HashMap`.
1450 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1451 /// documentation for more.
1453 /// [`drain`]: struct.HashMap.html#method.drain
1454 /// [`HashMap`]: struct.HashMap.html
1455 #[stable(feature = "drain", since = "1.6.0")]
1456 pub struct Drain<'a, K: 'a, V: 'a> {
1457 pub(super) inner: table::Drain<'a, K, V>,
1460 /// A mutable iterator over the values of a `HashMap`.
1462 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1463 /// documentation for more.
1465 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1466 /// [`HashMap`]: struct.HashMap.html
1467 #[stable(feature = "map_values_mut", since = "1.10.0")]
1468 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1469 inner: IterMut<'a, K, V>,
1472 enum InternalEntry<K, V, M> {
1473 Occupied { elem: FullBucket<K, V, M> },
1476 elem: VacantEntryState<K, V, M>,
1481 impl<K, V, M> InternalEntry<K, V, M> {
1483 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1485 InternalEntry::Occupied { elem } => Some(elem),
1491 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1493 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1495 InternalEntry::Occupied { elem } => {
1496 Some(Occupied(OccupiedEntry {
1501 InternalEntry::Vacant { hash, elem } => {
1502 Some(Vacant(VacantEntry {
1508 InternalEntry::TableIsEmpty => None,
1513 /// A view into a single entry in a map, which may either be vacant or occupied.
1515 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1517 /// [`HashMap`]: struct.HashMap.html
1518 /// [`entry`]: struct.HashMap.html#method.entry
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub enum Entry<'a, K: 'a, V: 'a> {
1521 /// An occupied entry.
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1524 OccupiedEntry<'a, K, V>),
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1529 VacantEntry<'a, K, V>),
1532 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1533 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1537 f.debug_tuple("Entry")
1541 Occupied(ref o) => {
1542 f.debug_tuple("Entry")
1550 /// A view into an occupied entry in a `HashMap`.
1551 /// It is part of the [`Entry`] enum.
1553 /// [`Entry`]: enum.Entry.html
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1557 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1560 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1561 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1563 f.debug_struct("OccupiedEntry")
1564 .field("key", self.key())
1565 .field("value", self.get())
1570 /// A view into a vacant entry in a `HashMap`.
1571 /// It is part of the [`Entry`] enum.
1573 /// [`Entry`]: enum.Entry.html
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1578 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1581 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1582 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1584 f.debug_tuple("VacantEntry")
1590 /// Possible states of a VacantEntry.
1591 enum VacantEntryState<K, V, M> {
1592 /// The index is occupied, but the key to insert has precedence,
1593 /// and will kick the current one out on insertion.
1594 NeqElem(FullBucket<K, V, M>, usize),
1595 /// The index is genuinely vacant.
1596 NoElem(EmptyBucket<K, V, M>, usize),
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1604 type Item = (&'a K, &'a V);
1605 type IntoIter = Iter<'a, K, V>;
1607 fn into_iter(self) -> Iter<'a, K, V> {
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1617 type Item = (&'a K, &'a mut V);
1618 type IntoIter = IterMut<'a, K, V>;
1620 fn into_iter(mut self) -> IterMut<'a, K, V> {
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1631 type IntoIter = IntoIter<K, V>;
1633 /// Creates a consuming iterator, that is, one that moves each key-value
1634 /// pair out of the map in arbitrary order. The map cannot be used after
1640 /// use std::collections::HashMap;
1642 /// let mut map = HashMap::new();
1643 /// map.insert("a", 1);
1644 /// map.insert("b", 2);
1645 /// map.insert("c", 3);
1647 /// // Not possible with .iter()
1648 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1650 fn into_iter(self) -> IntoIter<K, V> {
1651 IntoIter { inner: self.table.into_iter() }
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1657 type Item = (&'a K, &'a V);
1660 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1664 fn size_hint(&self) -> (usize, Option<usize>) {
1665 self.inner.size_hint()
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1671 fn len(&self) -> usize {
1676 #[unstable(feature = "fused", issue = "35602")]
1677 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1681 type Item = (&'a K, &'a mut V);
1684 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1688 fn size_hint(&self) -> (usize, Option<usize>) {
1689 self.inner.size_hint()
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1695 fn len(&self) -> usize {
1699 #[unstable(feature = "fused", issue = "35602")]
1700 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1702 #[stable(feature = "std_debug", since = "1.16.0")]
1703 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1704 where K: fmt::Debug,
1707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1709 .entries(self.inner.iter())
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl<K, V> Iterator for IntoIter<K, V> {
1719 fn next(&mut self) -> Option<(K, V)> {
1720 self.inner.next().map(|(_, k, v)| (k, v))
1723 fn size_hint(&self) -> (usize, Option<usize>) {
1724 self.inner.size_hint()
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1730 fn len(&self) -> usize {
1734 #[unstable(feature = "fused", issue = "35602")]
1735 impl<K, V> FusedIterator for IntoIter<K, V> {}
1737 #[stable(feature = "std_debug", since = "1.16.0")]
1738 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741 .entries(self.inner.iter())
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1751 fn next(&mut self) -> Option<(&'a K)> {
1752 self.inner.next().map(|(k, _)| k)
1755 fn size_hint(&self) -> (usize, Option<usize>) {
1756 self.inner.size_hint()
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1762 fn len(&self) -> usize {
1766 #[unstable(feature = "fused", issue = "35602")]
1767 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<'a, K, V> Iterator for Values<'a, K, V> {
1774 fn next(&mut self) -> Option<(&'a V)> {
1775 self.inner.next().map(|(_, v)| v)
1778 fn size_hint(&self) -> (usize, Option<usize>) {
1779 self.inner.size_hint()
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1785 fn len(&self) -> usize {
1789 #[unstable(feature = "fused", issue = "35602")]
1790 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1792 #[stable(feature = "map_values_mut", since = "1.10.0")]
1793 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1794 type Item = &'a mut V;
1797 fn next(&mut self) -> Option<(&'a mut V)> {
1798 self.inner.next().map(|(_, v)| v)
1801 fn size_hint(&self) -> (usize, Option<usize>) {
1802 self.inner.size_hint()
1805 #[stable(feature = "map_values_mut", since = "1.10.0")]
1806 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1808 fn len(&self) -> usize {
1812 #[unstable(feature = "fused", issue = "35602")]
1813 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1815 #[stable(feature = "std_debug", since = "1.16.0")]
1816 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1817 where K: fmt::Debug,
1820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1822 .entries(self.inner.inner.iter())
1827 #[stable(feature = "drain", since = "1.6.0")]
1828 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1832 fn next(&mut self) -> Option<(K, V)> {
1833 self.inner.next().map(|(_, k, v)| (k, v))
1836 fn size_hint(&self) -> (usize, Option<usize>) {
1837 self.inner.size_hint()
1840 #[stable(feature = "drain", since = "1.6.0")]
1841 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1843 fn len(&self) -> usize {
1847 #[unstable(feature = "fused", issue = "35602")]
1848 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1850 #[stable(feature = "std_debug", since = "1.16.0")]
1851 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1852 where K: fmt::Debug,
1855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1857 .entries(self.inner.iter())
1862 /// A place for insertion to a `Entry`.
1864 /// See [`HashMap::entry`](struct.HashMap.html#method.entry) for details.
1865 #[must_use = "places do nothing unless written to with `<-` syntax"]
1866 #[unstable(feature = "collection_placement",
1867 reason = "struct name and placement protocol is subject to change",
1869 pub struct EntryPlace<'a, K: 'a, V: 'a> {
1870 bucket: FullBucketMut<'a, K, V>,
1873 #[unstable(feature = "collection_placement",
1874 reason = "struct name and placement protocol is subject to change",
1876 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for EntryPlace<'a, K, V> {
1877 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1878 f.debug_struct("EntryPlace")
1879 .field("key", self.bucket.read().0)
1880 .field("value", self.bucket.read().1)
1885 #[unstable(feature = "collection_placement",
1886 reason = "struct name and placement protocol is subject to change",
1888 impl<'a, K, V> Drop for EntryPlace<'a, K, V> {
1889 fn drop(&mut self) {
1890 // Inplacement insertion failed. Only key need to drop.
1891 // The value is failed to insert into map.
1892 unsafe { self.bucket.remove_key() };
1896 #[unstable(feature = "collection_placement",
1897 reason = "placement protocol is subject to change",
1899 impl<'a, K, V> Placer<V> for Entry<'a, K, V> {
1900 type Place = EntryPlace<'a, K, V>;
1902 fn make_place(self) -> EntryPlace<'a, K, V> {
1903 let b = match self {
1904 Occupied(mut o) => {
1905 unsafe { ptr::drop_in_place(o.elem.read_mut().1); }
1909 unsafe { v.insert_key() }
1912 EntryPlace { bucket: b }
1916 #[unstable(feature = "collection_placement",
1917 reason = "placement protocol is subject to change",
1919 impl<'a, K, V> Place<V> for EntryPlace<'a, K, V> {
1920 fn pointer(&mut self) -> *mut V {
1921 self.bucket.read_mut().1
1925 #[unstable(feature = "collection_placement",
1926 reason = "placement protocol is subject to change",
1928 impl<'a, K, V> InPlace<V> for EntryPlace<'a, K, V> {
1931 unsafe fn finalize(self) {
1936 impl<'a, K, V> Entry<'a, K, V> {
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 /// Ensures a value is in the entry by inserting the default if empty, and returns
1939 /// a mutable reference to the value in the entry.
1944 /// use std::collections::HashMap;
1946 /// let mut map: HashMap<&str, u32> = HashMap::new();
1947 /// map.entry("poneyland").or_insert(12);
1949 /// assert_eq!(map["poneyland"], 12);
1951 /// *map.entry("poneyland").or_insert(12) += 10;
1952 /// assert_eq!(map["poneyland"], 22);
1954 pub fn or_insert(self, default: V) -> &'a mut V {
1956 Occupied(entry) => entry.into_mut(),
1957 Vacant(entry) => entry.insert(default),
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1963 /// and returns a mutable reference to the value in the entry.
1968 /// use std::collections::HashMap;
1970 /// let mut map: HashMap<&str, String> = HashMap::new();
1971 /// let s = "hoho".to_string();
1973 /// map.entry("poneyland").or_insert_with(|| s);
1975 /// assert_eq!(map["poneyland"], "hoho".to_string());
1977 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1979 Occupied(entry) => entry.into_mut(),
1980 Vacant(entry) => entry.insert(default()),
1984 /// Returns a reference to this entry's key.
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 {
1997 Occupied(ref entry) => entry.key(),
1998 Vacant(ref entry) => entry.key(),
2003 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2004 /// Gets a reference to the key in the entry.
2009 /// use std::collections::HashMap;
2011 /// let mut map: HashMap<&str, u32> = HashMap::new();
2012 /// map.entry("poneyland").or_insert(12);
2013 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2015 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2016 pub fn key(&self) -> &K {
2020 /// Deprecated, renamed to `remove_entry`
2021 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2022 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2023 pub fn remove_pair(self) -> (K, V) {
2027 /// Take the ownership of the key and value from the map.
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 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2039 /// // We delete the entry from the map.
2040 /// o.remove_entry();
2043 /// assert_eq!(map.contains_key("poneyland"), false);
2045 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2046 pub fn remove_entry(self) -> (K, V) {
2047 let (k, v, _) = pop_internal(self.elem);
2051 /// Gets a reference to the value in the entry.
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 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2063 /// assert_eq!(o.get(), &12);
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 pub fn get(&self) -> &V {
2071 /// Gets a mutable reference to the value in the entry.
2076 /// use std::collections::HashMap;
2077 /// use std::collections::hash_map::Entry;
2079 /// let mut map: HashMap<&str, u32> = HashMap::new();
2080 /// map.entry("poneyland").or_insert(12);
2082 /// assert_eq!(map["poneyland"], 12);
2083 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2084 /// *o.get_mut() += 10;
2087 /// assert_eq!(map["poneyland"], 22);
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 pub fn get_mut(&mut self) -> &mut V {
2091 self.elem.read_mut().1
2094 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2095 /// with a lifetime bound to the map itself.
2100 /// use std::collections::HashMap;
2101 /// use std::collections::hash_map::Entry;
2103 /// let mut map: HashMap<&str, u32> = HashMap::new();
2104 /// map.entry("poneyland").or_insert(12);
2106 /// assert_eq!(map["poneyland"], 12);
2107 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2108 /// *o.into_mut() += 10;
2111 /// assert_eq!(map["poneyland"], 22);
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 pub fn into_mut(self) -> &'a mut V {
2115 self.elem.into_mut_refs().1
2118 /// Sets the value of the entry, and returns the entry's old value.
2123 /// use std::collections::HashMap;
2124 /// use std::collections::hash_map::Entry;
2126 /// let mut map: HashMap<&str, u32> = HashMap::new();
2127 /// map.entry("poneyland").or_insert(12);
2129 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2130 /// assert_eq!(o.insert(15), 12);
2133 /// assert_eq!(map["poneyland"], 15);
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 pub fn insert(&mut self, mut value: V) -> V {
2137 let old_value = self.get_mut();
2138 mem::swap(&mut value, old_value);
2142 /// Takes the value out of the entry, and returns it.
2147 /// use std::collections::HashMap;
2148 /// use std::collections::hash_map::Entry;
2150 /// let mut map: HashMap<&str, u32> = HashMap::new();
2151 /// map.entry("poneyland").or_insert(12);
2153 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2154 /// assert_eq!(o.remove(), 12);
2157 /// assert_eq!(map.contains_key("poneyland"), false);
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 pub fn remove(self) -> V {
2161 pop_internal(self.elem).1
2164 /// Returns a key that was used for search.
2166 /// The key was retained for further use.
2167 fn take_key(&mut self) -> Option<K> {
2172 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2173 /// Gets a reference to the key that would be used when inserting a value
2174 /// through the `VacantEntry`.
2179 /// use std::collections::HashMap;
2181 /// let mut map: HashMap<&str, u32> = HashMap::new();
2182 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2184 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2185 pub fn key(&self) -> &K {
2189 /// Take ownership of the key.
2194 /// use std::collections::HashMap;
2195 /// use std::collections::hash_map::Entry;
2197 /// let mut map: HashMap<&str, u32> = HashMap::new();
2199 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2203 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2204 pub fn into_key(self) -> K {
2208 /// Sets the value of the entry with the VacantEntry's key,
2209 /// and returns a mutable reference to it.
2214 /// use std::collections::HashMap;
2215 /// use std::collections::hash_map::Entry;
2217 /// let mut map: HashMap<&str, u32> = HashMap::new();
2219 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2222 /// assert_eq!(map["poneyland"], 37);
2224 #[stable(feature = "rust1", since = "1.0.0")]
2225 pub fn insert(self, value: V) -> &'a mut V {
2226 let b = match self.elem {
2227 NeqElem(mut bucket, disp) => {
2228 if disp >= DISPLACEMENT_THRESHOLD {
2229 bucket.table_mut().set_tag(true);
2231 robin_hood(bucket, disp, self.hash, self.key, value)
2233 NoElem(mut bucket, disp) => {
2234 if disp >= DISPLACEMENT_THRESHOLD {
2235 bucket.table_mut().set_tag(true);
2237 bucket.put(self.hash, self.key, value)
2243 // Only used for InPlacement insert. Avoid unnecessary value copy.
2244 // The value remains uninitialized.
2245 unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2247 NeqElem(mut bucket, disp) => {
2248 if disp >= DISPLACEMENT_THRESHOLD {
2249 bucket.table_mut().set_tag(true);
2251 let uninit = mem::uninitialized();
2252 robin_hood(bucket, disp, self.hash, self.key, uninit)
2254 NoElem(mut bucket, disp) => {
2255 if disp >= DISPLACEMENT_THRESHOLD {
2256 bucket.table_mut().set_tag(true);
2258 bucket.put_key(self.hash, self.key)
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2267 S: BuildHasher + Default
2269 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2270 let mut map = HashMap::with_hasher(Default::default());
2276 #[stable(feature = "rust1", since = "1.0.0")]
2277 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2281 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2282 // Keys may be already present or show multiple times in the iterator.
2283 // Reserve the entire hint lower bound if the map is empty.
2284 // Otherwise reserve half the hint (rounded up), so the map
2285 // will only resize twice in the worst case.
2286 let iter = iter.into_iter();
2287 let reserve = if self.is_empty() {
2290 (iter.size_hint().0 + 1) / 2
2292 self.reserve(reserve);
2293 for (k, v) in iter {
2299 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2300 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2301 where K: Eq + Hash + Copy,
2305 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2306 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2310 /// `RandomState` is the default state for [`HashMap`] types.
2312 /// A particular instance `RandomState` will create the same instances of
2313 /// [`Hasher`], but the hashers created by two different `RandomState`
2314 /// instances are unlikely to produce the same result for the same values.
2316 /// [`HashMap`]: struct.HashMap.html
2317 /// [`Hasher`]: ../../hash/trait.Hasher.html
2322 /// use std::collections::HashMap;
2323 /// use std::collections::hash_map::RandomState;
2325 /// let s = RandomState::new();
2326 /// let mut map = HashMap::with_hasher(s);
2327 /// map.insert(1, 2);
2330 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2331 pub struct RandomState {
2337 /// Constructs a new `RandomState` that is initialized with random keys.
2342 /// use std::collections::hash_map::RandomState;
2344 /// let s = RandomState::new();
2347 #[allow(deprecated)]
2349 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2350 pub fn new() -> RandomState {
2351 // Historically this function did not cache keys from the OS and instead
2352 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2353 // was discovered, however, that because we re-seed the thread-local RNG
2354 // from the OS periodically that this can cause excessive slowdown when
2355 // many hash maps are created on a thread. To solve this performance
2356 // trap we cache the first set of randomly generated keys per-thread.
2358 // Later in #36481 it was discovered that exposing a deterministic
2359 // iteration order allows a form of DOS attack. To counter that we
2360 // increment one of the seeds on every RandomState creation, giving
2361 // every corresponding HashMap a different iteration order.
2362 thread_local!(static KEYS: Cell<(u64, u64)> = {
2363 let r = rand::OsRng::new();
2364 let mut r = r.expect("failed to create an OS RNG");
2365 Cell::new((r.gen(), r.gen()))
2369 let (k0, k1) = keys.get();
2370 keys.set((k0.wrapping_add(1), k1));
2371 RandomState { k0: k0, k1: k1 }
2376 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2377 impl BuildHasher for RandomState {
2378 type Hasher = DefaultHasher;
2380 #[allow(deprecated)]
2381 fn build_hasher(&self) -> DefaultHasher {
2382 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2386 /// The default [`Hasher`] used by [`RandomState`].
2388 /// The internal algorithm is not specified, and so it and its hashes should
2389 /// not be relied upon over releases.
2391 /// [`RandomState`]: struct.RandomState.html
2392 /// [`Hasher`]: ../../hash/trait.Hasher.html
2393 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2394 #[allow(deprecated)]
2396 pub struct DefaultHasher(SipHasher13);
2398 impl DefaultHasher {
2399 /// Creates a new `DefaultHasher`.
2401 /// This hasher is not guaranteed to be the same as all other
2402 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2403 /// instances created through `new` or `default`.
2404 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2405 #[allow(deprecated)]
2406 pub fn new() -> DefaultHasher {
2407 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2411 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2412 impl Default for DefaultHasher {
2413 /// Creates a new `DefaultHasher` using [`new`]. See its documentation for more.
2415 /// [`new`]: #method.new
2416 fn default() -> DefaultHasher {
2417 DefaultHasher::new()
2421 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2422 impl Hasher for DefaultHasher {
2424 fn write(&mut self, msg: &[u8]) {
2429 fn finish(&self) -> u64 {
2434 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2435 impl Default for RandomState {
2436 /// Constructs a new `RandomState`.
2438 fn default() -> RandomState {
2443 #[stable(feature = "std_debug", since = "1.16.0")]
2444 impl fmt::Debug for RandomState {
2445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2446 f.pad("RandomState { .. }")
2450 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2451 where K: Eq + Hash + Borrow<Q>,
2457 fn get(&self, key: &Q) -> Option<&K> {
2458 self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2461 fn take(&mut self, key: &Q) -> Option<K> {
2462 if self.table.size() == 0 {
2466 self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2469 fn replace(&mut self, key: K) -> Option<K> {
2472 match self.entry(key) {
2473 Occupied(mut occupied) => {
2474 let key = occupied.take_key().unwrap();
2475 Some(mem::replace(occupied.elem.read_mut().0, key))
2486 fn assert_covariance() {
2487 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2490 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2493 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2496 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2499 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2502 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2505 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2508 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2511 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2514 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2517 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2518 -> Drain<'new, &'new str, &'new str> {
2526 use super::Entry::{Occupied, Vacant};
2527 use super::RandomState;
2529 use rand::{thread_rng, Rng};
2533 fn test_zero_capacities() {
2534 type HM = HashMap<i32, i32>;
2537 assert_eq!(m.capacity(), 0);
2539 let m = HM::default();
2540 assert_eq!(m.capacity(), 0);
2542 let m = HM::with_hasher(RandomState::new());
2543 assert_eq!(m.capacity(), 0);
2545 let m = HM::with_capacity(0);
2546 assert_eq!(m.capacity(), 0);
2548 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2549 assert_eq!(m.capacity(), 0);
2551 let mut m = HM::new();
2557 assert_eq!(m.capacity(), 0);
2559 let mut m = HM::new();
2561 assert_eq!(m.capacity(), 0);
2565 fn test_create_capacity_zero() {
2566 let mut m = HashMap::with_capacity(0);
2568 assert!(m.insert(1, 1).is_none());
2570 assert!(m.contains_key(&1));
2571 assert!(!m.contains_key(&0));
2576 let mut m = HashMap::new();
2577 assert_eq!(m.len(), 0);
2578 assert!(m.insert(1, 2).is_none());
2579 assert_eq!(m.len(), 1);
2580 assert!(m.insert(2, 4).is_none());
2581 assert_eq!(m.len(), 2);
2582 assert_eq!(*m.get(&1).unwrap(), 2);
2583 assert_eq!(*m.get(&2).unwrap(), 4);
2588 let mut m = HashMap::new();
2589 assert_eq!(m.len(), 0);
2590 assert!(m.insert(1, 2).is_none());
2591 assert_eq!(m.len(), 1);
2592 assert!(m.insert(2, 4).is_none());
2593 assert_eq!(m.len(), 2);
2595 assert_eq!(*m2.get(&1).unwrap(), 2);
2596 assert_eq!(*m2.get(&2).unwrap(), 4);
2597 assert_eq!(m2.len(), 2);
2600 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2602 #[derive(Hash, PartialEq, Eq)]
2608 fn new(k: usize) -> Dropable {
2609 DROP_VECTOR.with(|slot| {
2610 slot.borrow_mut()[k] += 1;
2617 impl Drop for Dropable {
2618 fn drop(&mut self) {
2619 DROP_VECTOR.with(|slot| {
2620 slot.borrow_mut()[self.k] -= 1;
2625 impl Clone for Dropable {
2626 fn clone(&self) -> Dropable {
2627 Dropable::new(self.k)
2633 DROP_VECTOR.with(|slot| {
2634 *slot.borrow_mut() = vec![0; 200];
2638 let mut m = HashMap::new();
2640 DROP_VECTOR.with(|v| {
2642 assert_eq!(v.borrow()[i], 0);
2647 let d1 = Dropable::new(i);
2648 let d2 = Dropable::new(i + 100);
2652 DROP_VECTOR.with(|v| {
2654 assert_eq!(v.borrow()[i], 1);
2659 let k = Dropable::new(i);
2660 let v = m.remove(&k);
2662 assert!(v.is_some());
2664 DROP_VECTOR.with(|v| {
2665 assert_eq!(v.borrow()[i], 1);
2666 assert_eq!(v.borrow()[i+100], 1);
2670 DROP_VECTOR.with(|v| {
2672 assert_eq!(v.borrow()[i], 0);
2673 assert_eq!(v.borrow()[i+100], 0);
2677 assert_eq!(v.borrow()[i], 1);
2678 assert_eq!(v.borrow()[i+100], 1);
2683 DROP_VECTOR.with(|v| {
2685 assert_eq!(v.borrow()[i], 0);
2691 fn test_into_iter_drops() {
2692 DROP_VECTOR.with(|v| {
2693 *v.borrow_mut() = vec![0; 200];
2697 let mut hm = HashMap::new();
2699 DROP_VECTOR.with(|v| {
2701 assert_eq!(v.borrow()[i], 0);
2706 let d1 = Dropable::new(i);
2707 let d2 = Dropable::new(i + 100);
2711 DROP_VECTOR.with(|v| {
2713 assert_eq!(v.borrow()[i], 1);
2720 // By the way, ensure that cloning doesn't screw up the dropping.
2724 let mut half = hm.into_iter().take(50);
2726 DROP_VECTOR.with(|v| {
2728 assert_eq!(v.borrow()[i], 1);
2732 for _ in half.by_ref() {}
2734 DROP_VECTOR.with(|v| {
2736 .filter(|&i| v.borrow()[i] == 1)
2740 .filter(|&i| v.borrow()[i + 100] == 1)
2748 DROP_VECTOR.with(|v| {
2750 assert_eq!(v.borrow()[i], 0);
2756 fn test_empty_remove() {
2757 let mut m: HashMap<isize, bool> = HashMap::new();
2758 assert_eq!(m.remove(&0), None);
2762 fn test_empty_entry() {
2763 let mut m: HashMap<isize, bool> = HashMap::new();
2765 Occupied(_) => panic!(),
2768 assert!(*m.entry(0).or_insert(true));
2769 assert_eq!(m.len(), 1);
2773 fn test_empty_iter() {
2774 let mut m: HashMap<isize, bool> = HashMap::new();
2775 assert_eq!(m.drain().next(), None);
2776 assert_eq!(m.keys().next(), None);
2777 assert_eq!(m.values().next(), None);
2778 assert_eq!(m.values_mut().next(), None);
2779 assert_eq!(m.iter().next(), None);
2780 assert_eq!(m.iter_mut().next(), None);
2781 assert_eq!(m.len(), 0);
2782 assert!(m.is_empty());
2783 assert_eq!(m.into_iter().next(), None);
2787 fn test_lots_of_insertions() {
2788 let mut m = HashMap::new();
2790 // Try this a few times to make sure we never screw up the hashmap's
2793 assert!(m.is_empty());
2796 assert!(m.insert(i, i).is_none());
2800 assert_eq!(r, Some(&j));
2803 for j in i + 1..1001 {
2805 assert_eq!(r, None);
2809 for i in 1001..2001 {
2810 assert!(!m.contains_key(&i));
2815 assert!(m.remove(&i).is_some());
2818 assert!(!m.contains_key(&j));
2821 for j in i + 1..1001 {
2822 assert!(m.contains_key(&j));
2827 assert!(!m.contains_key(&i));
2831 assert!(m.insert(i, i).is_none());
2835 for i in (1..1001).rev() {
2836 assert!(m.remove(&i).is_some());
2839 assert!(!m.contains_key(&j));
2843 assert!(m.contains_key(&j));
2850 fn test_find_mut() {
2851 let mut m = HashMap::new();
2852 assert!(m.insert(1, 12).is_none());
2853 assert!(m.insert(2, 8).is_none());
2854 assert!(m.insert(5, 14).is_none());
2856 match m.get_mut(&5) {
2858 Some(x) => *x = new,
2860 assert_eq!(m.get(&5), Some(&new));
2864 fn test_insert_overwrite() {
2865 let mut m = HashMap::new();
2866 assert!(m.insert(1, 2).is_none());
2867 assert_eq!(*m.get(&1).unwrap(), 2);
2868 assert!(!m.insert(1, 3).is_none());
2869 assert_eq!(*m.get(&1).unwrap(), 3);
2873 fn test_insert_conflicts() {
2874 let mut m = HashMap::with_capacity(4);
2875 assert!(m.insert(1, 2).is_none());
2876 assert!(m.insert(5, 3).is_none());
2877 assert!(m.insert(9, 4).is_none());
2878 assert_eq!(*m.get(&9).unwrap(), 4);
2879 assert_eq!(*m.get(&5).unwrap(), 3);
2880 assert_eq!(*m.get(&1).unwrap(), 2);
2884 fn test_conflict_remove() {
2885 let mut m = HashMap::with_capacity(4);
2886 assert!(m.insert(1, 2).is_none());
2887 assert_eq!(*m.get(&1).unwrap(), 2);
2888 assert!(m.insert(5, 3).is_none());
2889 assert_eq!(*m.get(&1).unwrap(), 2);
2890 assert_eq!(*m.get(&5).unwrap(), 3);
2891 assert!(m.insert(9, 4).is_none());
2892 assert_eq!(*m.get(&1).unwrap(), 2);
2893 assert_eq!(*m.get(&5).unwrap(), 3);
2894 assert_eq!(*m.get(&9).unwrap(), 4);
2895 assert!(m.remove(&1).is_some());
2896 assert_eq!(*m.get(&9).unwrap(), 4);
2897 assert_eq!(*m.get(&5).unwrap(), 3);
2901 fn test_is_empty() {
2902 let mut m = HashMap::with_capacity(4);
2903 assert!(m.insert(1, 2).is_none());
2904 assert!(!m.is_empty());
2905 assert!(m.remove(&1).is_some());
2906 assert!(m.is_empty());
2911 let mut m = HashMap::new();
2913 assert_eq!(m.remove(&1), Some(2));
2914 assert_eq!(m.remove(&1), None);
2919 let mut m = HashMap::with_capacity(4);
2921 assert!(m.insert(i, i*2).is_none());
2923 assert_eq!(m.len(), 32);
2925 let mut observed: u32 = 0;
2928 assert_eq!(*v, *k * 2);
2929 observed |= 1 << *k;
2931 assert_eq!(observed, 0xFFFF_FFFF);
2936 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2937 let map: HashMap<_, _> = vec.into_iter().collect();
2938 let keys: Vec<_> = map.keys().cloned().collect();
2939 assert_eq!(keys.len(), 3);
2940 assert!(keys.contains(&1));
2941 assert!(keys.contains(&2));
2942 assert!(keys.contains(&3));
2947 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2948 let map: HashMap<_, _> = vec.into_iter().collect();
2949 let values: Vec<_> = map.values().cloned().collect();
2950 assert_eq!(values.len(), 3);
2951 assert!(values.contains(&'a'));
2952 assert!(values.contains(&'b'));
2953 assert!(values.contains(&'c'));
2957 fn test_values_mut() {
2958 let vec = vec![(1, 1), (2, 2), (3, 3)];
2959 let mut map: HashMap<_, _> = vec.into_iter().collect();
2960 for value in map.values_mut() {
2961 *value = (*value) * 2
2963 let values: Vec<_> = map.values().cloned().collect();
2964 assert_eq!(values.len(), 3);
2965 assert!(values.contains(&2));
2966 assert!(values.contains(&4));
2967 assert!(values.contains(&6));
2972 let mut m = HashMap::new();
2973 assert!(m.get(&1).is_none());
2977 Some(v) => assert_eq!(*v, 2),
2983 let mut m1 = HashMap::new();
2988 let mut m2 = HashMap::new();
3001 let mut map = HashMap::new();
3002 let empty: HashMap<i32, i32> = HashMap::new();
3007 let map_str = format!("{:?}", map);
3009 assert!(map_str == "{1: 2, 3: 4}" ||
3010 map_str == "{3: 4, 1: 2}");
3011 assert_eq!(format!("{:?}", empty), "{}");
3016 let mut m = HashMap::new();
3018 assert_eq!(m.len(), 0);
3019 assert!(m.is_empty());
3022 let old_raw_cap = m.raw_capacity();
3023 while old_raw_cap == m.raw_capacity() {
3028 assert_eq!(m.len(), i);
3029 assert!(!m.is_empty());
3033 fn test_behavior_resize_policy() {
3034 let mut m = HashMap::new();
3036 assert_eq!(m.len(), 0);
3037 assert_eq!(m.raw_capacity(), 0);
3038 assert!(m.is_empty());
3042 assert!(m.is_empty());
3043 let initial_raw_cap = m.raw_capacity();
3044 m.reserve(initial_raw_cap);
3045 let raw_cap = m.raw_capacity();
3047 assert_eq!(raw_cap, initial_raw_cap * 2);
3050 for _ in 0..raw_cap * 3 / 4 {
3054 // three quarters full
3056 assert_eq!(m.len(), i);
3057 assert_eq!(m.raw_capacity(), raw_cap);
3059 for _ in 0..raw_cap / 4 {
3065 let new_raw_cap = m.raw_capacity();
3066 assert_eq!(new_raw_cap, raw_cap * 2);
3068 for _ in 0..raw_cap / 2 - 1 {
3071 assert_eq!(m.raw_capacity(), new_raw_cap);
3073 // A little more than one quarter full.
3075 assert_eq!(m.raw_capacity(), raw_cap);
3076 // again, a little more than half full
3077 for _ in 0..raw_cap / 2 - 1 {
3083 assert_eq!(m.len(), i);
3084 assert!(!m.is_empty());
3085 assert_eq!(m.raw_capacity(), initial_raw_cap);
3089 fn test_reserve_shrink_to_fit() {
3090 let mut m = HashMap::new();
3093 assert!(m.capacity() >= m.len());
3099 let usable_cap = m.capacity();
3100 for i in 128..(128 + 256) {
3102 assert_eq!(m.capacity(), usable_cap);
3105 for i in 100..(128 + 256) {
3106 assert_eq!(m.remove(&i), Some(i));
3110 assert_eq!(m.len(), 100);
3111 assert!(!m.is_empty());
3112 assert!(m.capacity() >= m.len());
3115 assert_eq!(m.remove(&i), Some(i));
3120 assert_eq!(m.len(), 1);
3121 assert!(m.capacity() >= m.len());
3122 assert_eq!(m.remove(&0), Some(0));
3126 fn test_from_iter() {
3127 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3129 let map: HashMap<_, _> = xs.iter().cloned().collect();
3131 for &(k, v) in &xs {
3132 assert_eq!(map.get(&k), Some(&v));
3137 fn test_size_hint() {
3138 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3140 let map: HashMap<_, _> = xs.iter().cloned().collect();
3142 let mut iter = map.iter();
3144 for _ in iter.by_ref().take(3) {}
3146 assert_eq!(iter.size_hint(), (3, Some(3)));
3150 fn test_iter_len() {
3151 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3153 let map: HashMap<_, _> = xs.iter().cloned().collect();
3155 let mut iter = map.iter();
3157 for _ in iter.by_ref().take(3) {}
3159 assert_eq!(iter.len(), 3);
3163 fn test_mut_size_hint() {
3164 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3166 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3168 let mut iter = map.iter_mut();
3170 for _ in iter.by_ref().take(3) {}
3172 assert_eq!(iter.size_hint(), (3, Some(3)));
3176 fn test_iter_mut_len() {
3177 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3179 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3181 let mut iter = map.iter_mut();
3183 for _ in iter.by_ref().take(3) {}
3185 assert_eq!(iter.len(), 3);
3190 let mut map = HashMap::new();
3196 assert_eq!(map[&2], 1);
3201 fn test_index_nonexistent() {
3202 let mut map = HashMap::new();
3213 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3215 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3217 // Existing key (insert)
3218 match map.entry(1) {
3219 Vacant(_) => unreachable!(),
3220 Occupied(mut view) => {
3221 assert_eq!(view.get(), &10);
3222 assert_eq!(view.insert(100), 10);
3225 assert_eq!(map.get(&1).unwrap(), &100);
3226 assert_eq!(map.len(), 6);
3229 // Existing key (update)
3230 match map.entry(2) {
3231 Vacant(_) => unreachable!(),
3232 Occupied(mut view) => {
3233 let v = view.get_mut();
3234 let new_v = (*v) * 10;
3238 assert_eq!(map.get(&2).unwrap(), &200);
3239 assert_eq!(map.len(), 6);
3241 // Existing key (take)
3242 match map.entry(3) {
3243 Vacant(_) => unreachable!(),
3245 assert_eq!(view.remove(), 30);
3248 assert_eq!(map.get(&3), None);
3249 assert_eq!(map.len(), 5);
3252 // Inexistent key (insert)
3253 match map.entry(10) {
3254 Occupied(_) => unreachable!(),
3256 assert_eq!(*view.insert(1000), 1000);
3259 assert_eq!(map.get(&10).unwrap(), &1000);
3260 assert_eq!(map.len(), 6);
3264 fn test_entry_take_doesnt_corrupt() {
3265 #![allow(deprecated)] //rand
3267 fn check(m: &HashMap<isize, ()>) {
3269 assert!(m.contains_key(k),
3270 "{} is in keys() but not in the map?", k);
3274 let mut m = HashMap::new();
3275 let mut rng = thread_rng();
3277 // Populate the map with some items.
3279 let x = rng.gen_range(-10, 10);
3284 let x = rng.gen_range(-10, 10);
3288 println!("{}: remove {}", i, x);
3298 fn test_extend_ref() {
3299 let mut a = HashMap::new();
3301 let mut b = HashMap::new();
3303 b.insert(3, "three");
3307 assert_eq!(a.len(), 3);
3308 assert_eq!(a[&1], "one");
3309 assert_eq!(a[&2], "two");
3310 assert_eq!(a[&3], "three");
3314 fn test_capacity_not_less_than_len() {
3315 let mut a = HashMap::new();
3323 assert!(a.capacity() > a.len());
3325 let free = a.capacity() - a.len();
3331 assert_eq!(a.len(), a.capacity());
3333 // Insert at capacity should cause allocation.
3335 assert!(a.capacity() > a.len());
3339 fn test_occupied_entry_key() {
3340 let mut a = HashMap::new();
3341 let key = "hello there";
3342 let value = "value goes here";
3343 assert!(a.is_empty());
3344 a.insert(key.clone(), value.clone());
3345 assert_eq!(a.len(), 1);
3346 assert_eq!(a[key], value);
3348 match a.entry(key.clone()) {
3349 Vacant(_) => panic!(),
3350 Occupied(e) => assert_eq!(key, *e.key()),
3352 assert_eq!(a.len(), 1);
3353 assert_eq!(a[key], value);
3357 fn test_vacant_entry_key() {
3358 let mut a = HashMap::new();
3359 let key = "hello there";
3360 let value = "value goes here";
3362 assert!(a.is_empty());
3363 match a.entry(key.clone()) {
3364 Occupied(_) => panic!(),
3366 assert_eq!(key, *e.key());
3367 e.insert(value.clone());
3370 assert_eq!(a.len(), 1);
3371 assert_eq!(a[key], value);
3376 let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3378 map.retain(|&k, _| k % 2 == 0);
3379 assert_eq!(map.len(), 50);
3380 assert_eq!(map[&2], 20);
3381 assert_eq!(map[&4], 40);
3382 assert_eq!(map[&6], 60);
3386 fn test_adaptive() {
3387 const TEST_LEN: usize = 5000;
3388 // by cloning we get maps with the same hasher seed
3389 let mut first = HashMap::new();
3390 let mut second = first.clone();
3391 first.extend((0..TEST_LEN).map(|i| (i, i)));
3392 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3394 for (&k, &v) in &second {
3395 let prev_cap = first.capacity();
3396 let expect_grow = first.len() == prev_cap;
3398 if !expect_grow && first.capacity() != prev_cap {
3402 panic!("Adaptive early resize failed");
3406 fn test_placement_in() {
3407 let mut map = HashMap::new();
3408 map.extend((0..10).map(|i| (i, i)));
3410 map.entry(100) <- 100;
3411 assert_eq!(map[&100], 100);
3414 assert_eq!(map[&0], 10);
3416 assert_eq!(map.len(), 11);
3420 fn test_placement_panic() {
3421 let mut map = HashMap::new();
3422 map.extend((0..10).map(|i| (i, i)));
3424 fn mkpanic() -> usize { panic!() }
3426 // modify existing key
3427 // when panic happens, previous key is removed.
3428 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3429 assert_eq!(map.len(), 9);
3430 assert!(!map.contains_key(&0));
3433 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3434 assert_eq!(map.len(), 9);
3435 assert!(!map.contains_key(&100));
3439 fn test_placement_drop() {
3441 struct TestV<'a>(&'a mut bool);
3442 impl<'a> Drop for TestV<'a> {
3443 fn drop(&mut self) {
3444 if !*self.0 { panic!("value double drop!"); } // no double drop
3449 fn makepanic<'a>() -> TestV<'a> { panic!() }
3451 let mut can_drop = true;
3452 let mut hm = HashMap::new();
3453 hm.insert(0, TestV(&mut can_drop));
3454 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3455 assert_eq!(hm.len(), 0);