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::*;
14 use collections::CollectionAllocErr;
18 use fmt::{self, Debug};
20 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
21 use iter::{FromIterator, FusedIterator};
22 use mem::{self, replace};
23 use ops::{Deref, DerefMut, Index};
26 use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
28 use super::table::BucketState::{Empty, Full};
29 use super::table::Fallibility::{Fallible, Infallible};
31 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
33 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
35 struct DefaultResizePolicy;
37 impl DefaultResizePolicy {
39 fn new() -> DefaultResizePolicy {
43 /// A hash map's "capacity" is the number of elements it can hold without
44 /// being resized. Its "raw capacity" is the number of slots required to
45 /// provide that capacity, accounting for maximum loading. The raw capacity
46 /// is always zero or a power of two.
48 fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
52 // 1. Account for loading: `raw_capacity >= len * 1.1`.
53 // 2. Ensure it is a power of two.
54 // 3. Ensure it is at least the minimum size.
55 let mut raw_cap = len.checked_mul(11)
57 .and_then(|l| l.checked_next_power_of_two())
58 .ok_or(CollectionAllocErr::CapacityOverflow)?;
60 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
66 fn raw_capacity(&self, len: usize) -> usize {
67 self.try_raw_capacity(len).expect("raw_capacity overflow")
70 /// The capacity of the given raw capacity.
72 fn capacity(&self, raw_cap: usize) -> usize {
73 // This doesn't have to be checked for overflow since allocation size
74 // in bytes will overflow earlier than multiplication by 10.
76 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
77 // to be: (raw_cap * den + den - 1) / num
78 (raw_cap * 10 + 10 - 1) / 11
82 // The main performance trick in this hashmap is called Robin Hood Hashing.
83 // It gains its excellent performance from one essential operation:
85 // If an insertion collides with an existing element, and that element's
86 // "probe distance" (how far away the element is from its ideal location)
87 // is higher than how far we've already probed, swap the elements.
89 // This massively lowers variance in probe distance, and allows us to get very
90 // high load factors with good performance. The 90% load factor I use is rather
93 // > Why a load factor of approximately 90%?
95 // In general, all the distances to initial buckets will converge on the mean.
96 // At a load factor of α, the odds of finding the target bucket after k
97 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
98 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
99 // this down to make the math easier on the CPU and avoid its FPU.
100 // Since on average we start the probing in the middle of a cache line, this
101 // strategy pulls in two cache lines of hashes on every lookup. I think that's
102 // pretty good, but if you want to trade off some space, it could go down to one
103 // cache line on average with an α of 0.84.
105 // > Wait, what? Where did you get 1-α^k from?
107 // On the first probe, your odds of a collision with an existing element is α.
108 // The odds of doing this twice in a row is approximately α^2. For three times,
109 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
110 // colliding after k tries is 1-α^k.
112 // The paper from 1986 cited below mentions an implementation which keeps track
113 // of the distance-to-initial-bucket histogram. This approach is not suitable
114 // for modern architectures because it requires maintaining an internal data
115 // structure. This allows very good first guesses, but we are most concerned
116 // with guessing entire cache lines, not individual indexes. Furthermore, array
117 // accesses are no longer linear and in one direction, as we have now. There
118 // is also memory and cache pressure that this would entail that would be very
119 // difficult to properly see in a microbenchmark.
121 // ## Future Improvements (FIXME!)
123 // Allow the load factor to be changed dynamically and/or at initialization.
125 // Also, would it be possible for us to reuse storage when growing the
126 // underlying table? This is exactly the use case for 'realloc', and may
127 // be worth exploring.
129 // ## Future Optimizations (FIXME!)
131 // Another possible design choice that I made without any real reason is
132 // parameterizing the raw table over keys and values. Technically, all we need
133 // is the size and alignment of keys and values, and the code should be just as
134 // efficient (well, we might need one for power-of-two size and one for not...).
135 // This has the potential to reduce code bloat in rust executables, without
136 // really losing anything except 4 words (key size, key alignment, val size,
137 // val alignment) which can be passed in to every call of a `RawTable` function.
138 // This would definitely be an avenue worth exploring if people start complaining
139 // about the size of rust executables.
141 // Annotate exceedingly likely branches in `table::make_hash`
142 // and `search_hashed` to reduce instruction cache pressure
143 // and mispredictions once it becomes possible (blocked on issue #11092).
145 // Shrinking the table could simply reallocate in place after moving buckets
146 // to the first half.
148 // The growth algorithm (fragment of the Proof of Correctness)
149 // --------------------
151 // The growth algorithm is basically a fast path of the naive reinsertion-
152 // during-resize algorithm. Other paths should never be taken.
154 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
155 // by allocating a new table of capacity `2n`, and then individually reinsert
156 // each element in the old table into the new one. This guarantees that the
157 // new table is a valid robin hood hashtable with all the desired statistical
158 // properties. Remark that the order we reinsert the elements in should not
159 // matter. For simplicity and efficiency, we will consider only linear
160 // reinsertions, which consist of reinserting all elements in the old table
161 // into the new one by increasing order of index. However we will not be
162 // starting our reinsertions from index 0 in general. If we start from index
163 // i, for the purpose of reinsertion we will consider all elements with real
164 // index j < i to have virtual index n + j.
166 // Our hash generation scheme consists of generating a 64-bit hash and
167 // truncating the most significant bits. When moving to the new table, we
168 // simply introduce a new bit to the front of the hash. Therefore, if an
169 // element has ideal index i in the old table, it can have one of two ideal
170 // locations in the new table. If the new bit is 0, then the new ideal index
171 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
172 // we are producing two independent tables of size n, and for each element we
173 // independently choose which table to insert it into with equal probability.
174 // However, rather than wrapping around themselves on overflowing their
175 // indexes, the first table overflows into the second, and the second into the
176 // first. Visually, our new table will look something like:
178 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
180 // Where x's are elements inserted into the first table, y's are elements
181 // inserted into the second, and _'s are empty sections. We now define a few
182 // key concepts that we will use later. Note that this is a very abstract
183 // perspective of the table. A real resized table would be at least half
186 // Theorem: A linear robin hood reinsertion from the first ideal element
187 // produces identical results to a linear naive reinsertion from the same
190 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
192 // Adaptive early resizing
193 // ----------------------
194 // To protect against degenerate performance scenarios (including DOS attacks),
195 // the implementation includes an adaptive behavior that can resize the map
196 // early (before its capacity is exceeded) when suspiciously long probe sequences
199 // With this algorithm in place it would be possible to turn a CPU attack into
200 // a memory attack due to the aggressive resizing. To prevent that the
201 // adaptive behavior only triggers when the map is at least half full.
202 // This reduces the effectiveness of the algorithm but also makes it completely safe.
204 // The previous safety measure also prevents degenerate interactions with
205 // really bad quality hash algorithms that can make normal inputs look like a
208 const DISPLACEMENT_THRESHOLD: usize = 128;
210 // The threshold of 128 is chosen to minimize the chance of exceeding it.
211 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
212 // For displacement, the smallest constant that fits our needs is 90,
213 // so we round that up to 128.
215 // At a load factor of α, the odds of finding the target bucket after exactly n
216 // unsuccessful probes[1] are
218 // Pr_α{displacement = n} =
219 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
221 // We use this formula to find the probability of triggering the adaptive behavior
223 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
225 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
226 // hashing with buckets.
228 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
230 /// By default, `HashMap` uses a hashing algorithm selected to provide
231 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
232 /// reasonable best-effort is made to generate this seed from a high quality,
233 /// secure source of randomness provided by the host without blocking the
234 /// program. Because of this, the randomness of the seed depends on the output
235 /// quality of the system's random number generator when the seed is created.
236 /// In particular, seeds generated when the system's entropy pool is abnormally
237 /// low such as during system boot may be of a lower quality.
239 /// The default hashing algorithm is currently SipHash 1-3, though this is
240 /// subject to change at any point in the future. While its performance is very
241 /// competitive for medium sized keys, other hashing algorithms will outperform
242 /// it for small keys such as integers as well as large keys such as long
243 /// strings, though those algorithms will typically *not* protect against
244 /// attacks such as HashDoS.
246 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
247 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
248 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
250 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
251 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
252 /// If you implement these yourself, it is important that the following
256 /// k1 == k2 -> hash(k1) == hash(k2)
259 /// In other words, if two keys are equal, their hashes must be equal.
261 /// It is a logic error for a key to be modified in such a way that the key's
262 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
263 /// the [`Eq`] trait, changes while it is in the map. This is normally only
264 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
266 /// Relevant papers/articles:
268 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
269 /// 2. Emmanuel Goossaert. ["Robin Hood
270 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
271 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
272 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
277 /// use std::collections::HashMap;
279 /// // Type inference lets us omit an explicit type signature (which
280 /// // would be `HashMap<String, String>` in this example).
281 /// let mut book_reviews = HashMap::new();
283 /// // Review some books.
284 /// book_reviews.insert(
285 /// "Adventures of Huckleberry Finn".to_string(),
286 /// "My favorite book.".to_string(),
288 /// book_reviews.insert(
289 /// "Grimms' Fairy Tales".to_string(),
290 /// "Masterpiece.".to_string(),
292 /// book_reviews.insert(
293 /// "Pride and Prejudice".to_string(),
294 /// "Very enjoyable.".to_string(),
296 /// book_reviews.insert(
297 /// "The Adventures of Sherlock Holmes".to_string(),
298 /// "Eye lyked it alot.".to_string(),
301 /// // Check for a specific one.
302 /// // When collections store owned values (String), they can still be
303 /// // queried using references (&str).
304 /// if !book_reviews.contains_key("Les Misérables") {
305 /// println!("We've got {} reviews, but Les Misérables ain't one.",
306 /// book_reviews.len());
309 /// // oops, this review has a lot of spelling mistakes, let's delete it.
310 /// book_reviews.remove("The Adventures of Sherlock Holmes");
312 /// // Look up the values associated with some keys.
313 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
314 /// for &book in &to_find {
315 /// match book_reviews.get(book) {
316 /// Some(review) => println!("{}: {}", book, review),
317 /// None => println!("{} is unreviewed.", book)
321 /// // Iterate over everything.
322 /// for (book, review) in &book_reviews {
323 /// println!("{}: \"{}\"", book, review);
327 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
328 /// for more complex methods of getting, setting, updating and removing keys and
332 /// use std::collections::HashMap;
334 /// // type inference lets us omit an explicit type signature (which
335 /// // would be `HashMap<&str, u8>` in this example).
336 /// let mut player_stats = HashMap::new();
338 /// fn random_stat_buff() -> u8 {
339 /// // could actually return some random value here - let's just return
340 /// // some fixed value for now
344 /// // insert a key only if it doesn't already exist
345 /// player_stats.entry("health").or_insert(100);
347 /// // insert a key using a function that provides a new value only if it
348 /// // doesn't already exist
349 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
351 /// // update a key, guarding against the key possibly not being set
352 /// let stat = player_stats.entry("attack").or_insert(100);
353 /// *stat += random_stat_buff();
356 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
357 /// We must also derive [`PartialEq`].
359 /// [`Eq`]: ../../std/cmp/trait.Eq.html
360 /// [`Hash`]: ../../std/hash/trait.Hash.html
361 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
362 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
363 /// [`Cell`]: ../../std/cell/struct.Cell.html
364 /// [`default`]: #method.default
365 /// [`with_hasher`]: #method.with_hasher
366 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
367 /// [`fnv`]: https://crates.io/crates/fnv
370 /// use std::collections::HashMap;
372 /// #[derive(Hash, Eq, PartialEq, Debug)]
379 /// /// Create a new Viking.
380 /// fn new(name: &str, country: &str) -> Viking {
381 /// Viking { name: name.to_string(), country: country.to_string() }
385 /// // Use a HashMap to store the vikings' health points.
386 /// let mut vikings = HashMap::new();
388 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
389 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
390 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
392 /// // Use derived implementation to print the status of the vikings.
393 /// for (viking, health) in &vikings {
394 /// println!("{:?} has {} hp", viking, health);
398 /// A `HashMap` with fixed list of elements can be initialized from an array:
401 /// use std::collections::HashMap;
404 /// let timber_resources: HashMap<&str, i32> =
405 /// [("Norway", 100),
408 /// .iter().cloned().collect();
409 /// // use the values stored in map
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub struct HashMap<K, V, S = RandomState> {
416 // All hashes are keyed on these values, to prevent hash collision attacks.
419 table: RawTable<K, V>,
421 resize_policy: DefaultResizePolicy,
424 /// Search for a pre-hashed key.
425 /// If you don't already know the hash, use search or search_mut instead
427 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
428 where M: Deref<Target = RawTable<K, V>>,
431 // This is the only function where capacity can be zero. To avoid
432 // undefined behavior when Bucket::new gets the raw bucket in this
433 // case, immediately return the appropriate search result.
434 if table.capacity() == 0 {
435 return InternalEntry::TableIsEmpty;
438 search_hashed_nonempty(table, hash, is_match, true)
441 /// Search for a pre-hashed key when the hash map is known to be non-empty.
443 fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
444 compare_hashes: bool)
445 -> InternalEntry<K, V, M>
446 where M: Deref<Target = RawTable<K, V>>,
449 // Do not check the capacity as an extra branch could slow the lookup.
451 let size = table.size();
452 let mut probe = Bucket::new(table, hash);
453 let mut displacement = 0;
456 let full = match probe.peek() {
459 return InternalEntry::Vacant {
461 elem: NoElem(bucket, displacement),
464 Full(bucket) => bucket,
467 let probe_displacement = full.displacement();
469 if probe_displacement < displacement {
470 // Found a luckier bucket than me.
471 // We can finish the search early if we hit any bucket
472 // with a lower distance to initial bucket than we've probed.
473 return InternalEntry::Vacant {
475 elem: NeqElem(full, probe_displacement),
479 // If the hash doesn't match, it can't be this one..
480 if !compare_hashes || hash == full.hash() {
481 // If the key doesn't match, it can't be this one..
482 if is_match(full.read().0) {
483 return InternalEntry::Occupied { elem: full };
488 debug_assert!(displacement <= size);
492 /// Same as `search_hashed_nonempty` but for mutable access.
494 fn search_hashed_nonempty_mut<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
495 compare_hashes: bool)
496 -> InternalEntry<K, V, M>
497 where M: DerefMut<Target = RawTable<K, V>>,
500 // Do not check the capacity as an extra branch could slow the lookup.
502 let size = table.size();
503 let mut probe = Bucket::new(table, hash);
504 let mut displacement = 0;
507 let mut full = match probe.peek() {
510 return InternalEntry::Vacant {
512 elem: NoElem(bucket, displacement),
515 Full(bucket) => bucket,
518 let probe_displacement = full.displacement();
520 if probe_displacement < displacement {
521 // Found a luckier bucket than me.
522 // We can finish the search early if we hit any bucket
523 // with a lower distance to initial bucket than we've probed.
524 return InternalEntry::Vacant {
526 elem: NeqElem(full, probe_displacement),
530 // If the hash doesn't match, it can't be this one..
531 if hash == full.hash() || !compare_hashes {
532 // If the key doesn't match, it can't be this one..
533 if is_match(full.read_mut().0) {
534 return InternalEntry::Occupied { elem: full };
539 debug_assert!(displacement <= size);
543 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
544 -> (K, V, &mut RawTable<K, V>)
546 let (empty, retkey, retval) = starting_bucket.take();
547 let mut gap = match empty.gap_peek() {
549 Err(b) => return (retkey, retval, b.into_table()),
552 while gap.full().displacement() != 0 {
553 gap = match gap.shift() {
556 return (retkey, retval, b.into_table());
561 // Now we've done all our shifting. Return the value we grabbed earlier.
562 (retkey, retval, gap.into_table())
565 /// Perform robin hood bucket stealing at the given `bucket`. You must
566 /// also pass that bucket's displacement so we don't have to recalculate it.
568 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
569 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
570 mut displacement: usize,
574 -> FullBucketMut<'a, K, V> {
575 let size = bucket.table().size();
576 let raw_capacity = bucket.table().capacity();
577 // There can be at most `size - dib` buckets to displace, because
578 // in the worst case, there are `size` elements and we already are
579 // `displacement` buckets away from the initial one.
580 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
581 // Save the *starting point*.
582 let mut bucket = bucket.stash();
585 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
592 let probe = bucket.next();
593 debug_assert!(probe.index() != idx_end);
595 let full_bucket = match probe.peek() {
598 let bucket = bucket.put(hash, key, val);
599 // Now that it's stolen, just read the value's pointer
600 // right out of the table! Go back to the *starting point*.
602 // This use of `into_table` is misleading. It turns the
603 // bucket, which is a FullBucket on top of a
604 // FullBucketMut, into just one FullBucketMut. The "table"
605 // refers to the inner FullBucketMut in this context.
606 return bucket.into_table();
608 Full(bucket) => bucket,
611 let probe_displacement = full_bucket.displacement();
613 bucket = full_bucket;
615 // Robin hood! Steal the spot.
616 if probe_displacement < displacement {
617 displacement = probe_displacement;
624 impl<K, V, S> HashMap<K, V, S>
628 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
631 table::make_hash(&self.hash_builder, x)
634 /// Search for a key, yielding the index if it's found in the hashtable.
635 /// If you already have the hash for the key lying around, or if you need an
636 /// InternalEntry, use search_hashed or search_hashed_nonempty.
638 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
639 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
647 let hash = self.make_hash(q);
648 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()), true)
649 .into_occupied_bucket()
653 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
654 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
662 let hash = self.make_hash(q);
663 search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()), true)
664 .into_occupied_bucket()
667 // The caller should ensure that invariants by Robin Hood Hashing hold
668 // and that there's space in the underlying table.
669 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
670 let mut buckets = Bucket::new(&mut self.table, hash);
671 let start_index = buckets.index();
674 // We don't need to compare hashes for value swap.
675 // Not even DIBs for Robin Hood.
676 buckets = match buckets.peek() {
678 empty.put(hash, k, v);
681 Full(b) => b.into_bucket(),
684 debug_assert!(buckets.index() != start_index);
689 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
690 /// Creates an empty `HashMap`.
692 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
693 /// is first inserted into.
698 /// use std::collections::HashMap;
699 /// let mut map: HashMap<&str, i32> = HashMap::new();
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn new() -> HashMap<K, V, RandomState> {
707 /// Creates an empty `HashMap` with the specified capacity.
709 /// The hash map will be able to hold at least `capacity` elements without
710 /// reallocating. If `capacity` is 0, the hash map will not allocate.
715 /// use std::collections::HashMap;
716 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
721 HashMap::with_capacity_and_hasher(capacity, Default::default())
725 impl<K, V, S> HashMap<K, V, S>
729 /// Creates an empty `HashMap` which will use the given hash builder to hash
732 /// The created map has the default initial capacity.
734 /// Warning: `hash_builder` is normally randomly generated, and
735 /// is designed to allow HashMaps to be resistant to attacks that
736 /// cause many collisions and very poor performance. Setting it
737 /// manually using this function can expose a DoS attack vector.
742 /// use std::collections::HashMap;
743 /// use std::collections::hash_map::RandomState;
745 /// let s = RandomState::new();
746 /// let mut map = HashMap::with_hasher(s);
747 /// map.insert(1, 2);
750 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
751 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
754 resize_policy: DefaultResizePolicy::new(),
755 table: RawTable::new(0),
759 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
760 /// to hash the keys.
762 /// The hash map will be able to hold at least `capacity` elements without
763 /// reallocating. If `capacity` is 0, the hash map will not allocate.
765 /// Warning: `hash_builder` is normally randomly generated, and
766 /// is designed to allow HashMaps to be resistant to attacks that
767 /// cause many collisions and very poor performance. Setting it
768 /// manually using this function can expose a DoS attack vector.
773 /// use std::collections::HashMap;
774 /// use std::collections::hash_map::RandomState;
776 /// let s = RandomState::new();
777 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
778 /// map.insert(1, 2);
781 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
782 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
783 let resize_policy = DefaultResizePolicy::new();
784 let raw_cap = resize_policy.raw_capacity(capacity);
788 table: RawTable::new(raw_cap),
792 /// Returns a reference to the map's [`BuildHasher`].
794 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
799 /// use std::collections::HashMap;
800 /// use std::collections::hash_map::RandomState;
802 /// let hasher = RandomState::new();
803 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
804 /// let hasher: &RandomState = map.hasher();
806 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
807 pub fn hasher(&self) -> &S {
811 /// Returns the number of elements the map can hold without reallocating.
813 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
814 /// more, but is guaranteed to be able to hold at least this many.
819 /// use std::collections::HashMap;
820 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
821 /// assert!(map.capacity() >= 100);
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn capacity(&self) -> usize {
826 self.resize_policy.capacity(self.raw_capacity())
829 /// Returns the hash map's raw capacity.
831 fn raw_capacity(&self) -> usize {
832 self.table.capacity()
835 /// Reserves capacity for at least `additional` more elements to be inserted
836 /// in the `HashMap`. The collection may reserve more space to avoid
837 /// frequent reallocations.
841 /// Panics if the new allocation size overflows [`usize`].
843 /// [`usize`]: ../../std/primitive.usize.html
848 /// use std::collections::HashMap;
849 /// let mut map: HashMap<&str, i32> = HashMap::new();
853 #[stable(feature = "rust1", since = "1.0.0")]
854 pub fn reserve(&mut self, additional: usize) {
855 match self.reserve_internal(additional, Infallible) {
856 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
857 Err(CollectionAllocErr::AllocErr) => unreachable!(),
858 Ok(()) => { /* yay */ }
862 /// Tries to reserve capacity for at least `additional` more elements to be inserted
863 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
864 /// frequent reallocations.
868 /// If the capacity overflows, or the allocator reports a failure, then an error
874 /// #![feature(try_reserve)]
875 /// use std::collections::HashMap;
876 /// let mut map: HashMap<&str, isize> = HashMap::new();
877 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
879 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
880 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
881 self.reserve_internal(additional, Fallible)
885 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
886 -> Result<(), CollectionAllocErr> {
888 let remaining = self.capacity() - self.len(); // this can't overflow
889 if remaining < additional {
890 let min_cap = self.len()
891 .checked_add(additional)
892 .ok_or(CollectionAllocErr::CapacityOverflow)?;
893 let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
894 self.try_resize(raw_cap, fallibility)?;
895 } else if self.table.tag() && remaining <= self.len() {
896 // Probe sequence is too long and table is half full,
897 // resize early to reduce probing length.
898 let new_capacity = self.table.capacity() * 2;
899 self.try_resize(new_capacity, fallibility)?;
904 /// Resizes the internal vectors to a new capacity. It's your
905 /// responsibility to:
906 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
907 /// for the load factor.
908 /// 2) Ensure `new_raw_cap` is a power of two or zero.
914 fallibility: Fallibility,
915 ) -> Result<(), CollectionAllocErr> {
916 assert!(self.table.size() <= new_raw_cap);
917 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
919 let mut old_table = replace(
922 Infallible => RawTable::new(new_raw_cap),
923 Fallible => RawTable::try_new(new_raw_cap)?,
926 let old_size = old_table.size();
928 if old_table.size() == 0 {
932 let mut bucket = Bucket::head_bucket(&mut old_table);
934 // This is how the buckets might be laid out in memory:
935 // ($ marks an initialized bucket)
937 // |$$$_$$$$$$_$$$$$|
939 // But we've skipped the entire initial cluster of buckets
940 // and will continue iteration in this order:
943 // ^ wrap around once end is reached
946 // ^ exit once table.size == 0
948 bucket = match bucket.peek() {
950 let h = bucket.hash();
951 let (b, k, v) = bucket.take();
952 self.insert_hashed_ordered(h, k, v);
953 if b.table().size() == 0 {
958 Empty(b) => b.into_bucket(),
963 assert_eq!(self.table.size(), old_size);
967 /// Shrinks the capacity of the map as much as possible. It will drop
968 /// down as much as possible while maintaining the internal rules
969 /// and possibly leaving some space in accordance with the resize policy.
974 /// use std::collections::HashMap;
976 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
977 /// map.insert(1, 2);
978 /// map.insert(3, 4);
979 /// assert!(map.capacity() >= 100);
980 /// map.shrink_to_fit();
981 /// assert!(map.capacity() >= 2);
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn shrink_to_fit(&mut self) {
985 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
986 if self.raw_capacity() != new_raw_cap {
987 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
988 let old_size = old_table.size();
990 // Shrink the table. Naive algorithm for resizing:
991 for (h, k, v) in old_table.into_iter() {
992 self.insert_hashed_nocheck(h, k, v);
995 debug_assert_eq!(self.table.size(), old_size);
999 /// Shrinks the capacity of the map with a lower limit. It will drop
1000 /// down no lower than the supplied limit while maintaining the internal rules
1001 /// and possibly leaving some space in accordance with the resize policy.
1003 /// Panics if the current capacity is smaller than the supplied
1004 /// minimum capacity.
1009 /// #![feature(shrink_to)]
1010 /// use std::collections::HashMap;
1012 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1013 /// map.insert(1, 2);
1014 /// map.insert(3, 4);
1015 /// assert!(map.capacity() >= 100);
1016 /// map.shrink_to(10);
1017 /// assert!(map.capacity() >= 10);
1018 /// map.shrink_to(0);
1019 /// assert!(map.capacity() >= 2);
1021 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1022 pub fn shrink_to(&mut self, min_capacity: usize) {
1023 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1025 let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1026 if self.raw_capacity() != new_raw_cap {
1027 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1028 let old_size = old_table.size();
1030 // Shrink the table. Naive algorithm for resizing:
1031 for (h, k, v) in old_table.into_iter() {
1032 self.insert_hashed_nocheck(h, k, v);
1035 debug_assert_eq!(self.table.size(), old_size);
1039 /// Insert a pre-hashed key-value pair, without first checking
1040 /// that there's enough room in the buckets. Returns a reference to the
1041 /// newly insert value.
1043 /// If the key already exists, the hashtable will be returned untouched
1044 /// and a reference to the existing element will be returned.
1045 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1046 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1048 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1049 Some(Vacant(elem)) => {
1053 None => unreachable!(),
1057 /// An iterator visiting all keys in arbitrary order.
1058 /// The iterator element type is `&'a K`.
1063 /// use std::collections::HashMap;
1065 /// let mut map = HashMap::new();
1066 /// map.insert("a", 1);
1067 /// map.insert("b", 2);
1068 /// map.insert("c", 3);
1070 /// for key in map.keys() {
1071 /// println!("{}", key);
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn keys(&self) -> Keys<K, V> {
1076 Keys { inner: self.iter() }
1079 /// An iterator visiting all values in arbitrary order.
1080 /// The iterator element type is `&'a V`.
1085 /// use std::collections::HashMap;
1087 /// let mut map = HashMap::new();
1088 /// map.insert("a", 1);
1089 /// map.insert("b", 2);
1090 /// map.insert("c", 3);
1092 /// for val in map.values() {
1093 /// println!("{}", val);
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 pub fn values(&self) -> Values<K, V> {
1098 Values { inner: self.iter() }
1101 /// An iterator visiting all values mutably in arbitrary order.
1102 /// The iterator element type is `&'a mut V`.
1107 /// use std::collections::HashMap;
1109 /// let mut map = HashMap::new();
1111 /// map.insert("a", 1);
1112 /// map.insert("b", 2);
1113 /// map.insert("c", 3);
1115 /// for val in map.values_mut() {
1116 /// *val = *val + 10;
1119 /// for val in map.values() {
1120 /// println!("{}", val);
1123 #[stable(feature = "map_values_mut", since = "1.10.0")]
1124 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1125 ValuesMut { inner: self.iter_mut() }
1128 /// An iterator visiting all key-value pairs in arbitrary order.
1129 /// The iterator element type is `(&'a K, &'a V)`.
1134 /// use std::collections::HashMap;
1136 /// let mut map = HashMap::new();
1137 /// map.insert("a", 1);
1138 /// map.insert("b", 2);
1139 /// map.insert("c", 3);
1141 /// for (key, val) in map.iter() {
1142 /// println!("key: {} val: {}", key, val);
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn iter(&self) -> Iter<K, V> {
1147 Iter { inner: self.table.iter() }
1150 /// An iterator visiting all key-value pairs in arbitrary order,
1151 /// with mutable references to the values.
1152 /// The iterator element type is `(&'a K, &'a mut V)`.
1157 /// use std::collections::HashMap;
1159 /// let mut map = HashMap::new();
1160 /// map.insert("a", 1);
1161 /// map.insert("b", 2);
1162 /// map.insert("c", 3);
1164 /// // Update all values
1165 /// for (_, val) in map.iter_mut() {
1169 /// for (key, val) in &map {
1170 /// println!("key: {} val: {}", key, val);
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1175 IterMut { inner: self.table.iter_mut() }
1178 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1183 /// use std::collections::HashMap;
1185 /// let mut letters = HashMap::new();
1187 /// for ch in "a short treatise on fungi".chars() {
1188 /// let counter = letters.entry(ch).or_insert(0);
1192 /// assert_eq!(letters[&'s'], 2);
1193 /// assert_eq!(letters[&'t'], 3);
1194 /// assert_eq!(letters[&'u'], 1);
1195 /// assert_eq!(letters.get(&'y'), None);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1199 // Gotta resize now.
1201 let hash = self.make_hash(&key);
1202 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1203 .into_entry(key).expect("unreachable")
1206 /// Returns the number of elements in the map.
1211 /// use std::collections::HashMap;
1213 /// let mut a = HashMap::new();
1214 /// assert_eq!(a.len(), 0);
1215 /// a.insert(1, "a");
1216 /// assert_eq!(a.len(), 1);
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn len(&self) -> usize {
1223 /// Returns true if the map contains no elements.
1228 /// use std::collections::HashMap;
1230 /// let mut a = HashMap::new();
1231 /// assert!(a.is_empty());
1232 /// a.insert(1, "a");
1233 /// assert!(!a.is_empty());
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn is_empty(&self) -> bool {
1241 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1242 /// allocated memory for reuse.
1247 /// use std::collections::HashMap;
1249 /// let mut a = HashMap::new();
1250 /// a.insert(1, "a");
1251 /// a.insert(2, "b");
1253 /// for (k, v) in a.drain().take(1) {
1254 /// assert!(k == 1 || k == 2);
1255 /// assert!(v == "a" || v == "b");
1258 /// assert!(a.is_empty());
1261 #[stable(feature = "drain", since = "1.6.0")]
1262 pub fn drain(&mut self) -> Drain<K, V> {
1263 Drain { inner: self.table.drain() }
1266 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1272 /// use std::collections::HashMap;
1274 /// let mut a = HashMap::new();
1275 /// a.insert(1, "a");
1277 /// assert!(a.is_empty());
1279 #[stable(feature = "rust1", since = "1.0.0")]
1281 pub fn clear(&mut self) {
1285 /// Returns a reference to the value corresponding to the key.
1287 /// The key may be any borrowed form of the map's key type, but
1288 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1291 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1292 /// [`Hash`]: ../../std/hash/trait.Hash.html
1297 /// use std::collections::HashMap;
1299 /// let mut map = HashMap::new();
1300 /// map.insert(1, "a");
1301 /// assert_eq!(map.get(&1), Some(&"a"));
1302 /// assert_eq!(map.get(&2), None);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1310 self.search(k).map(|bucket| bucket.into_refs().1)
1313 /// Returns the key-value pair corresponding to the supplied key.
1315 /// The supplied key may be any borrowed form of the map's key type, but
1316 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1319 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1320 /// [`Hash`]: ../../std/hash/trait.Hash.html
1325 /// #![feature(map_get_key_value)]
1326 /// use std::collections::HashMap;
1328 /// let mut map = HashMap::new();
1329 /// map.insert(1, "a");
1330 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1331 /// assert_eq!(map.get_key_value(&2), None);
1333 #[unstable(feature = "map_get_key_value", issue = "49347")]
1334 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1338 self.search(k).map(|bucket| bucket.into_refs())
1341 /// Returns true if the map contains a value for the specified key.
1343 /// The key may be any borrowed form of the map's key type, but
1344 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1347 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1348 /// [`Hash`]: ../../std/hash/trait.Hash.html
1353 /// use std::collections::HashMap;
1355 /// let mut map = HashMap::new();
1356 /// map.insert(1, "a");
1357 /// assert_eq!(map.contains_key(&1), true);
1358 /// assert_eq!(map.contains_key(&2), false);
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1365 self.search(k).is_some()
1368 /// Returns a mutable reference to the value corresponding to the key.
1370 /// The key may be any borrowed form of the map's key type, but
1371 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1374 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1375 /// [`Hash`]: ../../std/hash/trait.Hash.html
1380 /// use std::collections::HashMap;
1382 /// let mut map = HashMap::new();
1383 /// map.insert(1, "a");
1384 /// if let Some(x) = map.get_mut(&1) {
1387 /// assert_eq!(map[&1], "b");
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1394 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1397 /// Inserts a key-value pair into the map.
1399 /// If the map did not have this key present, [`None`] is returned.
1401 /// If the map did have this key present, the value is updated, and the old
1402 /// value is returned. The key is not updated, though; this matters for
1403 /// types that can be `==` without being identical. See the [module-level
1404 /// documentation] for more.
1406 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1407 /// [module-level documentation]: index.html#insert-and-complex-keys
1412 /// use std::collections::HashMap;
1414 /// let mut map = HashMap::new();
1415 /// assert_eq!(map.insert(37, "a"), None);
1416 /// assert_eq!(map.is_empty(), false);
1418 /// map.insert(37, "b");
1419 /// assert_eq!(map.insert(37, "c"), Some("b"));
1420 /// assert_eq!(map[&37], "c");
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1424 let hash = self.make_hash(&k);
1426 self.insert_hashed_nocheck(hash, k, v)
1429 /// Removes a key from the map, returning the value at the key if the key
1430 /// was previously in the map.
1432 /// The key may be any borrowed form of the map's key type, but
1433 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1436 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1437 /// [`Hash`]: ../../std/hash/trait.Hash.html
1442 /// use std::collections::HashMap;
1444 /// let mut map = HashMap::new();
1445 /// map.insert(1, "a");
1446 /// assert_eq!(map.remove(&1), Some("a"));
1447 /// assert_eq!(map.remove(&1), None);
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1454 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1457 /// Removes a key from the map, returning the stored key and value if the
1458 /// key was previously in the map.
1460 /// The key may be any borrowed form of the map's key type, but
1461 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1464 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1465 /// [`Hash`]: ../../std/hash/trait.Hash.html
1470 /// use std::collections::HashMap;
1473 /// let mut map = HashMap::new();
1474 /// map.insert(1, "a");
1475 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1476 /// assert_eq!(map.remove(&1), None);
1479 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1480 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1486 let (k, v, _) = pop_internal(bucket);
1491 /// Retains only the elements specified by the predicate.
1493 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1498 /// use std::collections::HashMap;
1500 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1501 /// map.retain(|&k, _| k % 2 == 0);
1502 /// assert_eq!(map.len(), 4);
1504 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1505 pub fn retain<F>(&mut self, mut f: F)
1506 where F: FnMut(&K, &mut V) -> bool
1508 if self.table.size() == 0 {
1511 let mut elems_left = self.table.size();
1512 let mut bucket = Bucket::head_bucket(&mut self.table);
1514 let start_index = bucket.index();
1515 while elems_left != 0 {
1516 bucket = match bucket.peek() {
1519 let should_remove = {
1520 let (k, v) = full.read_mut();
1524 let prev_raw = full.raw();
1525 let (_, _, t) = pop_internal(full);
1526 Bucket::new_from(prev_raw, t)
1535 bucket.prev(); // reverse iteration
1536 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1541 impl<K, V, S> HashMap<K, V, S>
1545 /// Creates a raw entry builder for the HashMap.
1547 /// Raw entries provide the lowest level of control for searching and
1548 /// manipulating a map. They must be manually initialized with a hash and
1549 /// then manually searched. After this, insertions into a vacant entry
1550 /// still require an owned key to be provided.
1552 /// Raw entries are useful for such exotic situations as:
1554 /// * Hash memoization
1555 /// * Deferring the creation of an owned key until it is known to be required
1556 /// * Using a search key that doesn't work with the Borrow trait
1557 /// * Using custom comparison logic without newtype wrappers
1559 /// Because raw entries provide much more low-level control, it's much easier
1560 /// to put the HashMap into an inconsistent state which, while memory-safe,
1561 /// will cause the map to produce seemingly random results. Higher-level and
1562 /// more foolproof APIs like `entry` should be preferred when possible.
1564 /// In particular, the hash used to initialized the raw entry must still be
1565 /// consistent with the hash of the key that is ultimately stored in the entry.
1566 /// This is because implementations of HashMap may need to recompute hashes
1567 /// when resizing, at which point only the keys are available.
1569 /// Raw entries give mutable access to the keys. This must not be used
1570 /// to modify how the key would compare or hash, as the map will not re-evaluate
1571 /// where the key should go, meaning the keys may become "lost" if their
1572 /// location does not reflect their state. For instance, if you change a key
1573 /// so that the map now contains keys which compare equal, search may start
1574 /// acting erratically, with two keys randomly masking each other. Implementations
1575 /// are free to assume this doesn't happen (within the limits of memory-safety).
1577 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1578 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1580 RawEntryBuilderMut { map: self }
1583 /// Creates a raw immutable entry builder for the HashMap.
1585 /// Raw entries provide the lowest level of control for searching and
1586 /// manipulating a map. They must be manually initialized with a hash and
1587 /// then manually searched.
1589 /// This is useful for
1590 /// * Hash memoization
1591 /// * Using a search key that doesn't work with the Borrow trait
1592 /// * Using custom comparison logic without newtype wrappers
1594 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1595 /// `get` should be preferred.
1597 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1598 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1599 pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1600 RawEntryBuilder { map: self }
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<K, V, S> PartialEq for HashMap<K, V, S>
1610 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1611 if self.len() != other.len() {
1615 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<K, V, S> Eq for HashMap<K, V, S>
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<K, V, S> Debug for HashMap<K, V, S>
1629 where K: Eq + Hash + Debug,
1633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1634 f.debug_map().entries(self.iter()).finish()
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<K, V, S> Default for HashMap<K, V, S>
1641 S: BuildHasher + Default
1643 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1644 fn default() -> HashMap<K, V, S> {
1645 HashMap::with_hasher(Default::default())
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1651 where K: Eq + Hash + Borrow<Q>,
1657 /// Returns a reference to the value corresponding to the supplied key.
1661 /// Panics if the key is not present in the `HashMap`.
1663 fn index(&self, key: &Q) -> &V {
1664 self.get(key).expect("no entry found for key")
1668 /// An iterator over the entries of a `HashMap`.
1670 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1671 /// documentation for more.
1673 /// [`iter`]: struct.HashMap.html#method.iter
1674 /// [`HashMap`]: struct.HashMap.html
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 pub struct Iter<'a, K: 'a, V: 'a> {
1677 inner: table::Iter<'a, K, V>,
1680 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<'a, K, V> Clone for Iter<'a, K, V> {
1683 fn clone(&self) -> Iter<'a, K, V> {
1684 Iter { inner: self.inner.clone() }
1688 #[stable(feature = "std_debug", since = "1.16.0")]
1689 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1690 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1692 .entries(self.clone())
1697 /// A mutable iterator over the entries of a `HashMap`.
1699 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1700 /// documentation for more.
1702 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1703 /// [`HashMap`]: struct.HashMap.html
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub struct IterMut<'a, K: 'a, V: 'a> {
1706 inner: table::IterMut<'a, K, V>,
1709 /// An owning iterator over the entries of a `HashMap`.
1711 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1712 /// (provided by the `IntoIterator` trait). See its documentation for more.
1714 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1715 /// [`HashMap`]: struct.HashMap.html
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub struct IntoIter<K, V> {
1718 pub(super) inner: table::IntoIter<K, V>,
1721 /// An iterator over the keys of a `HashMap`.
1723 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1724 /// documentation for more.
1726 /// [`keys`]: struct.HashMap.html#method.keys
1727 /// [`HashMap`]: struct.HashMap.html
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub struct Keys<'a, K: 'a, V: 'a> {
1730 inner: Iter<'a, K, V>,
1733 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl<'a, K, V> Clone for Keys<'a, K, V> {
1736 fn clone(&self) -> Keys<'a, K, V> {
1737 Keys { inner: self.inner.clone() }
1741 #[stable(feature = "std_debug", since = "1.16.0")]
1742 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1743 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1745 .entries(self.clone())
1750 /// An iterator over the values of a `HashMap`.
1752 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1753 /// documentation for more.
1755 /// [`values`]: struct.HashMap.html#method.values
1756 /// [`HashMap`]: struct.HashMap.html
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 pub struct Values<'a, K: 'a, V: 'a> {
1759 inner: Iter<'a, K, V>,
1762 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<'a, K, V> Clone for Values<'a, K, V> {
1765 fn clone(&self) -> Values<'a, K, V> {
1766 Values { inner: self.inner.clone() }
1770 #[stable(feature = "std_debug", since = "1.16.0")]
1771 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1774 .entries(self.clone())
1779 /// A draining iterator over the entries of a `HashMap`.
1781 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1782 /// documentation for more.
1784 /// [`drain`]: struct.HashMap.html#method.drain
1785 /// [`HashMap`]: struct.HashMap.html
1786 #[stable(feature = "drain", since = "1.6.0")]
1787 pub struct Drain<'a, K: 'a, V: 'a> {
1788 pub(super) inner: table::Drain<'a, K, V>,
1791 /// A mutable iterator over the values of a `HashMap`.
1793 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1794 /// documentation for more.
1796 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1797 /// [`HashMap`]: struct.HashMap.html
1798 #[stable(feature = "map_values_mut", since = "1.10.0")]
1799 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1800 inner: IterMut<'a, K, V>,
1803 enum InternalEntry<K, V, M> {
1804 Occupied { elem: FullBucket<K, V, M> },
1807 elem: VacantEntryState<K, V, M>,
1812 impl<K, V, M> InternalEntry<K, V, M> {
1814 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1816 InternalEntry::Occupied { elem } => Some(elem),
1822 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1824 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1826 InternalEntry::Occupied { elem } => {
1827 Some(Occupied(OccupiedEntry {
1832 InternalEntry::Vacant { hash, elem } => {
1833 Some(Vacant(VacantEntry {
1839 InternalEntry::TableIsEmpty => None,
1844 /// A builder for computing where in a HashMap a key-value pair would be stored.
1846 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1848 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1850 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1851 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1852 map: &'a mut HashMap<K, V, S>,
1855 /// A view into a single entry in a map, which may either be vacant or occupied.
1857 /// This is a lower-level version of [`Entry`].
1859 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1861 /// [`HashMap`]: struct.HashMap.html
1862 /// [`Entry`]: enum.Entry.html
1863 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1864 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1865 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1866 /// An occupied entry.
1867 Occupied(RawOccupiedEntryMut<'a, K, V>),
1869 Vacant(RawVacantEntryMut<'a, K, V, S>),
1872 /// A view into an occupied entry in a `HashMap`.
1873 /// It is part of the [`RawEntryMut`] enum.
1875 /// [`RawEntryMut`]: enum.RawEntryMut.html
1876 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1877 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1878 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1881 /// A view into a vacant entry in a `HashMap`.
1882 /// It is part of the [`RawEntryMut`] enum.
1884 /// [`RawEntryMut`]: enum.RawEntryMut.html
1885 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1886 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1887 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1888 hash_builder: &'a S,
1891 /// A builder for computing where in a HashMap a key-value pair would be stored.
1893 /// See the [`HashMap::raw_entry`] docs for usage examples.
1895 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1896 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1897 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1898 map: &'a HashMap<K, V, S>,
1901 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1902 where S: BuildHasher,
1905 /// Create a `RawEntryMut` from the given key.
1906 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1907 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1911 let mut hasher = self.map.hash_builder.build_hasher();
1912 k.hash(&mut hasher);
1913 self.from_key_hashed_nocheck(hasher.finish(), k)
1916 /// Create a `RawEntryMut` from the given key and its hash.
1918 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1919 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1923 self.from_hash(hash, |q| q.borrow().eq(k))
1927 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> RawEntryMut<'a, K, V, S>
1928 where for<'b> F: FnMut(&'b K) -> bool,
1930 match search_hashed_nonempty_mut(&mut self.map.table,
1931 SafeHash::new(hash),
1934 InternalEntry::Occupied { elem } => {
1935 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1937 InternalEntry::Vacant { elem, .. } => {
1938 RawEntryMut::Vacant(RawVacantEntryMut {
1940 hash_builder: &self.map.hash_builder,
1943 InternalEntry::TableIsEmpty => {
1948 /// Create a `RawEntryMut` from the given hash.
1950 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1951 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1952 where for<'b> F: FnMut(&'b K) -> bool,
1954 self.search(hash, is_match, true)
1957 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1958 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1960 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1961 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1962 where for<'b> F: FnMut(&'b K) -> bool,
1964 self.search(hash, is_match, false)
1968 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1969 where S: BuildHasher,
1971 /// Access an entry by key.
1972 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1973 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1977 let mut hasher = self.map.hash_builder.build_hasher();
1978 k.hash(&mut hasher);
1979 self.from_key_hashed_nocheck(hasher.finish(), k)
1982 /// Access an entry by a key and its hash.
1983 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1984 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1989 self.from_hash(hash, |q| q.borrow().eq(k))
1992 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1993 where F: FnMut(&K) -> bool
1995 match search_hashed_nonempty(&self.map.table,
1996 SafeHash::new(hash),
1999 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
2000 InternalEntry::Vacant { .. } => None,
2001 InternalEntry::TableIsEmpty => unreachable!(),
2005 /// Access an entry by hash.
2006 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2007 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2008 where F: FnMut(&K) -> bool
2010 self.search(hash, is_match, true)
2013 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2014 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2016 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2017 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2018 where F: FnMut(&K) -> bool
2020 self.search(hash, is_match, false)
2024 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2025 /// Ensures a value is in the entry by inserting the default if empty, and returns
2026 /// mutable references to the key and value in the entry.
2031 /// #![feature(hash_raw_entry)]
2032 /// use std::collections::HashMap;
2034 /// let mut map: HashMap<&str, u32> = HashMap::new();
2036 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2037 /// assert_eq!(map["poneyland"], 3);
2039 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2040 /// assert_eq!(map["poneyland"], 6);
2042 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2043 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2048 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2049 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2053 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2054 /// and returns mutable references to the key and value in the entry.
2059 /// #![feature(hash_raw_entry)]
2060 /// use std::collections::HashMap;
2062 /// let mut map: HashMap<&str, String> = HashMap::new();
2064 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2065 /// ("poneyland", "hoho".to_string())
2068 /// assert_eq!(map["poneyland"], "hoho".to_string());
2070 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2071 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2072 where F: FnOnce() -> (K, V),
2077 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2078 RawEntryMut::Vacant(entry) => {
2079 let (k, v) = default();
2085 /// Provides in-place mutable access to an occupied entry before any
2086 /// potential inserts into the map.
2091 /// #![feature(hash_raw_entry)]
2092 /// use std::collections::HashMap;
2094 /// let mut map: HashMap<&str, u32> = HashMap::new();
2096 /// map.raw_entry_mut()
2097 /// .from_key("poneyland")
2098 /// .and_modify(|_k, v| { *v += 1 })
2099 /// .or_insert("poneyland", 42);
2100 /// assert_eq!(map["poneyland"], 42);
2102 /// map.raw_entry_mut()
2103 /// .from_key("poneyland")
2104 /// .and_modify(|_k, v| { *v += 1 })
2105 /// .or_insert("poneyland", 0);
2106 /// assert_eq!(map["poneyland"], 43);
2108 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2109 pub fn and_modify<F>(self, f: F) -> Self
2110 where F: FnOnce(&mut K, &mut V)
2113 RawEntryMut::Occupied(mut entry) => {
2115 let (k, v) = entry.get_key_value_mut();
2118 RawEntryMut::Occupied(entry)
2120 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2125 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2126 /// Gets a reference to the key in the entry.
2127 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2128 pub fn key(&self) -> &K {
2132 /// Gets a mutable reference to the key in the entry.
2133 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2134 pub fn key_mut(&mut self) -> &mut K {
2135 self.elem.read_mut().0
2138 /// Converts the entry into a mutable reference to the key in the entry
2139 /// with a lifetime bound to the map itself.
2140 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2141 pub fn into_key(self) -> &'a mut K {
2142 self.elem.into_mut_refs().0
2145 /// Gets a reference to the value in the entry.
2146 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2147 pub fn get(&self) -> &V {
2151 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2152 /// with a lifetime bound to the map itself.
2153 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2154 pub fn into_mut(self) -> &'a mut V {
2155 self.elem.into_mut_refs().1
2158 /// Gets a mutable reference to the value in the entry.
2159 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2160 pub fn get_mut(&mut self) -> &mut V {
2161 self.elem.read_mut().1
2164 /// Gets a reference to the key and value in the entry.
2165 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2166 pub fn get_key_value(&mut self) -> (&K, &V) {
2170 /// Gets a mutable reference to the key and value in the entry.
2171 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2172 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2173 self.elem.read_mut()
2176 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2177 /// with a lifetime bound to the map itself.
2178 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2179 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2180 self.elem.into_mut_refs()
2183 /// Sets the value of the entry, and returns the entry's old value.
2184 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2185 pub fn insert(&mut self, value: V) -> V {
2186 mem::replace(self.get_mut(), value)
2189 /// Sets the value of the entry, and returns the entry's old value.
2190 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2191 pub fn insert_key(&mut self, key: K) -> K {
2192 mem::replace(self.key_mut(), key)
2195 /// Takes the value out of the entry, and returns it.
2196 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2197 pub fn remove(self) -> V {
2198 pop_internal(self.elem).1
2201 /// Take the ownership of the key and value from the map.
2202 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2203 pub fn remove_entry(self) -> (K, V) {
2204 let (k, v, _) = pop_internal(self.elem);
2209 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2210 /// Sets the value of the entry with the VacantEntry's key,
2211 /// and returns a mutable reference to it.
2212 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2213 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2217 let mut hasher = self.hash_builder.build_hasher();
2218 key.hash(&mut hasher);
2219 self.insert_hashed_nocheck(hasher.finish(), key, value)
2222 /// Sets the value of the entry with the VacantEntry's key,
2223 /// and returns a mutable reference to it.
2225 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2226 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2227 let hash = SafeHash::new(hash);
2228 let b = match self.elem {
2229 NeqElem(mut bucket, disp) => {
2230 if disp >= DISPLACEMENT_THRESHOLD {
2231 bucket.table_mut().set_tag(true);
2233 robin_hood(bucket, disp, hash, key, value)
2235 NoElem(mut bucket, disp) => {
2236 if disp >= DISPLACEMENT_THRESHOLD {
2237 bucket.table_mut().set_tag(true);
2239 bucket.put(hash, key, value)
2246 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2247 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2249 f.debug_struct("RawEntryBuilder")
2254 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2255 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2258 RawEntryMut::Vacant(ref v) => {
2259 f.debug_tuple("RawEntry")
2263 RawEntryMut::Occupied(ref o) => {
2264 f.debug_tuple("RawEntry")
2272 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2273 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2275 f.debug_struct("RawOccupiedEntryMut")
2276 .field("key", self.key())
2277 .field("value", self.get())
2282 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2283 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2285 f.debug_struct("RawVacantEntryMut")
2290 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2291 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2293 f.debug_struct("RawEntryBuilder")
2298 /// A view into a single entry in a map, which may either be vacant or occupied.
2300 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2302 /// [`HashMap`]: struct.HashMap.html
2303 /// [`entry`]: struct.HashMap.html#method.entry
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 pub enum Entry<'a, K: 'a, V: 'a> {
2306 /// An occupied entry.
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2309 OccupiedEntry<'a, K, V>),
2312 #[stable(feature = "rust1", since = "1.0.0")]
2313 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2314 VacantEntry<'a, K, V>),
2317 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2318 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2322 f.debug_tuple("Entry")
2326 Occupied(ref o) => {
2327 f.debug_tuple("Entry")
2335 /// A view into an occupied entry in a `HashMap`.
2336 /// It is part of the [`Entry`] enum.
2338 /// [`Entry`]: enum.Entry.html
2339 #[stable(feature = "rust1", since = "1.0.0")]
2340 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2342 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2345 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2346 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2348 f.debug_struct("OccupiedEntry")
2349 .field("key", self.key())
2350 .field("value", self.get())
2355 /// A view into a vacant entry in a `HashMap`.
2356 /// It is part of the [`Entry`] enum.
2358 /// [`Entry`]: enum.Entry.html
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2363 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2366 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2367 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2369 f.debug_tuple("VacantEntry")
2375 /// Possible states of a VacantEntry.
2376 enum VacantEntryState<K, V, M> {
2377 /// The index is occupied, but the key to insert has precedence,
2378 /// and will kick the current one out on insertion.
2379 NeqElem(FullBucket<K, V, M>, usize),
2380 /// The index is genuinely vacant.
2381 NoElem(EmptyBucket<K, V, M>, usize),
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2389 type Item = (&'a K, &'a V);
2390 type IntoIter = Iter<'a, K, V>;
2392 fn into_iter(self) -> Iter<'a, K, V> {
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2402 type Item = (&'a K, &'a mut V);
2403 type IntoIter = IterMut<'a, K, V>;
2405 fn into_iter(self) -> IterMut<'a, K, V> {
2410 #[stable(feature = "rust1", since = "1.0.0")]
2411 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2416 type IntoIter = IntoIter<K, V>;
2418 /// Creates a consuming iterator, that is, one that moves each key-value
2419 /// pair out of the map in arbitrary order. The map cannot be used after
2425 /// use std::collections::HashMap;
2427 /// let mut map = HashMap::new();
2428 /// map.insert("a", 1);
2429 /// map.insert("b", 2);
2430 /// map.insert("c", 3);
2432 /// // Not possible with .iter()
2433 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2435 fn into_iter(self) -> IntoIter<K, V> {
2436 IntoIter { inner: self.table.into_iter() }
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2442 type Item = (&'a K, &'a V);
2445 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2449 fn size_hint(&self) -> (usize, Option<usize>) {
2450 self.inner.size_hint()
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2456 fn len(&self) -> usize {
2461 #[stable(feature = "fused", since = "1.26.0")]
2462 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2466 type Item = (&'a K, &'a mut V);
2469 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2473 fn size_hint(&self) -> (usize, Option<usize>) {
2474 self.inner.size_hint()
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2480 fn len(&self) -> usize {
2484 #[stable(feature = "fused", since = "1.26.0")]
2485 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2487 #[stable(feature = "std_debug", since = "1.16.0")]
2488 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2489 where K: fmt::Debug,
2492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2494 .entries(self.inner.iter())
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 impl<K, V> Iterator for IntoIter<K, V> {
2504 fn next(&mut self) -> Option<(K, V)> {
2505 self.inner.next().map(|(_, k, v)| (k, v))
2508 fn size_hint(&self) -> (usize, Option<usize>) {
2509 self.inner.size_hint()
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2515 fn len(&self) -> usize {
2519 #[stable(feature = "fused", since = "1.26.0")]
2520 impl<K, V> FusedIterator for IntoIter<K, V> {}
2522 #[stable(feature = "std_debug", since = "1.16.0")]
2523 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2526 .entries(self.inner.iter())
2531 #[stable(feature = "rust1", since = "1.0.0")]
2532 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2536 fn next(&mut self) -> Option<(&'a K)> {
2537 self.inner.next().map(|(k, _)| k)
2540 fn size_hint(&self) -> (usize, Option<usize>) {
2541 self.inner.size_hint()
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2547 fn len(&self) -> usize {
2551 #[stable(feature = "fused", since = "1.26.0")]
2552 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2554 #[stable(feature = "rust1", since = "1.0.0")]
2555 impl<'a, K, V> Iterator for Values<'a, K, V> {
2559 fn next(&mut self) -> Option<(&'a V)> {
2560 self.inner.next().map(|(_, v)| v)
2563 fn size_hint(&self) -> (usize, Option<usize>) {
2564 self.inner.size_hint()
2567 #[stable(feature = "rust1", since = "1.0.0")]
2568 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2570 fn len(&self) -> usize {
2574 #[stable(feature = "fused", since = "1.26.0")]
2575 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2577 #[stable(feature = "map_values_mut", since = "1.10.0")]
2578 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2579 type Item = &'a mut V;
2582 fn next(&mut self) -> Option<(&'a mut V)> {
2583 self.inner.next().map(|(_, v)| v)
2586 fn size_hint(&self) -> (usize, Option<usize>) {
2587 self.inner.size_hint()
2590 #[stable(feature = "map_values_mut", since = "1.10.0")]
2591 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2593 fn len(&self) -> usize {
2597 #[stable(feature = "fused", since = "1.26.0")]
2598 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2600 #[stable(feature = "std_debug", since = "1.16.0")]
2601 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2602 where K: fmt::Debug,
2605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2607 .entries(self.inner.inner.iter())
2612 #[stable(feature = "drain", since = "1.6.0")]
2613 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2617 fn next(&mut self) -> Option<(K, V)> {
2618 self.inner.next().map(|(_, k, v)| (k, v))
2621 fn size_hint(&self) -> (usize, Option<usize>) {
2622 self.inner.size_hint()
2625 #[stable(feature = "drain", since = "1.6.0")]
2626 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2628 fn len(&self) -> usize {
2632 #[stable(feature = "fused", since = "1.26.0")]
2633 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2635 #[stable(feature = "std_debug", since = "1.16.0")]
2636 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2637 where K: fmt::Debug,
2640 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2642 .entries(self.inner.iter())
2647 impl<'a, K, V> Entry<'a, K, V> {
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 /// Ensures a value is in the entry by inserting the default if empty, and returns
2650 /// a mutable reference to the value in the entry.
2655 /// use std::collections::HashMap;
2657 /// let mut map: HashMap<&str, u32> = HashMap::new();
2659 /// map.entry("poneyland").or_insert(3);
2660 /// assert_eq!(map["poneyland"], 3);
2662 /// *map.entry("poneyland").or_insert(10) *= 2;
2663 /// assert_eq!(map["poneyland"], 6);
2665 pub fn or_insert(self, default: V) -> &'a mut V {
2667 Occupied(entry) => entry.into_mut(),
2668 Vacant(entry) => entry.insert(default),
2672 #[stable(feature = "rust1", since = "1.0.0")]
2673 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2674 /// and returns a mutable reference to the value in the entry.
2679 /// use std::collections::HashMap;
2681 /// let mut map: HashMap<&str, String> = HashMap::new();
2682 /// let s = "hoho".to_string();
2684 /// map.entry("poneyland").or_insert_with(|| s);
2686 /// assert_eq!(map["poneyland"], "hoho".to_string());
2688 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2690 Occupied(entry) => entry.into_mut(),
2691 Vacant(entry) => entry.insert(default()),
2695 /// Returns a reference to this entry's key.
2700 /// use std::collections::HashMap;
2702 /// let mut map: HashMap<&str, u32> = HashMap::new();
2703 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2705 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2706 pub fn key(&self) -> &K {
2708 Occupied(ref entry) => entry.key(),
2709 Vacant(ref entry) => entry.key(),
2713 /// Provides in-place mutable access to an occupied entry before any
2714 /// potential inserts into the map.
2719 /// use std::collections::HashMap;
2721 /// let mut map: HashMap<&str, u32> = HashMap::new();
2723 /// map.entry("poneyland")
2724 /// .and_modify(|e| { *e += 1 })
2726 /// assert_eq!(map["poneyland"], 42);
2728 /// map.entry("poneyland")
2729 /// .and_modify(|e| { *e += 1 })
2731 /// assert_eq!(map["poneyland"], 43);
2733 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2734 pub fn and_modify<F>(self, f: F) -> Self
2735 where F: FnOnce(&mut V)
2738 Occupied(mut entry) => {
2742 Vacant(entry) => Vacant(entry),
2748 impl<'a, K, V: Default> Entry<'a, K, V> {
2749 #[stable(feature = "entry_or_default", since = "1.28.0")]
2750 /// Ensures a value is in the entry by inserting the default value if empty,
2751 /// and returns a mutable reference to the value in the entry.
2757 /// use std::collections::HashMap;
2759 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2760 /// map.entry("poneyland").or_default();
2762 /// assert_eq!(map["poneyland"], None);
2765 pub fn or_default(self) -> &'a mut V {
2767 Occupied(entry) => entry.into_mut(),
2768 Vacant(entry) => entry.insert(Default::default()),
2773 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2774 /// Gets a reference to the key in the entry.
2779 /// use std::collections::HashMap;
2781 /// let mut map: HashMap<&str, u32> = HashMap::new();
2782 /// map.entry("poneyland").or_insert(12);
2783 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2785 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2786 pub fn key(&self) -> &K {
2790 /// Take the ownership of the key and value from the map.
2795 /// use std::collections::HashMap;
2796 /// use std::collections::hash_map::Entry;
2798 /// let mut map: HashMap<&str, u32> = HashMap::new();
2799 /// map.entry("poneyland").or_insert(12);
2801 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2802 /// // We delete the entry from the map.
2803 /// o.remove_entry();
2806 /// assert_eq!(map.contains_key("poneyland"), false);
2808 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2809 pub fn remove_entry(self) -> (K, V) {
2810 let (k, v, _) = pop_internal(self.elem);
2814 /// Gets a reference to the value in the entry.
2819 /// use std::collections::HashMap;
2820 /// use std::collections::hash_map::Entry;
2822 /// let mut map: HashMap<&str, u32> = HashMap::new();
2823 /// map.entry("poneyland").or_insert(12);
2825 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2826 /// assert_eq!(o.get(), &12);
2829 #[stable(feature = "rust1", since = "1.0.0")]
2830 pub fn get(&self) -> &V {
2834 /// Gets a mutable reference to the value in the entry.
2836 /// If you need a reference to the `OccupiedEntry` which may outlive the
2837 /// destruction of the `Entry` value, see [`into_mut`].
2839 /// [`into_mut`]: #method.into_mut
2844 /// use std::collections::HashMap;
2845 /// use std::collections::hash_map::Entry;
2847 /// let mut map: HashMap<&str, u32> = HashMap::new();
2848 /// map.entry("poneyland").or_insert(12);
2850 /// assert_eq!(map["poneyland"], 12);
2851 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2852 /// *o.get_mut() += 10;
2853 /// assert_eq!(*o.get(), 22);
2855 /// // We can use the same Entry multiple times.
2856 /// *o.get_mut() += 2;
2859 /// assert_eq!(map["poneyland"], 24);
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 pub fn get_mut(&mut self) -> &mut V {
2863 self.elem.read_mut().1
2866 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2867 /// with a lifetime bound to the map itself.
2869 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2871 /// [`get_mut`]: #method.get_mut
2876 /// use std::collections::HashMap;
2877 /// use std::collections::hash_map::Entry;
2879 /// let mut map: HashMap<&str, u32> = HashMap::new();
2880 /// map.entry("poneyland").or_insert(12);
2882 /// assert_eq!(map["poneyland"], 12);
2883 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2884 /// *o.into_mut() += 10;
2887 /// assert_eq!(map["poneyland"], 22);
2889 #[stable(feature = "rust1", since = "1.0.0")]
2890 pub fn into_mut(self) -> &'a mut V {
2891 self.elem.into_mut_refs().1
2894 /// Sets the value of the entry, and returns the entry's old value.
2899 /// use std::collections::HashMap;
2900 /// use std::collections::hash_map::Entry;
2902 /// let mut map: HashMap<&str, u32> = HashMap::new();
2903 /// map.entry("poneyland").or_insert(12);
2905 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2906 /// assert_eq!(o.insert(15), 12);
2909 /// assert_eq!(map["poneyland"], 15);
2911 #[stable(feature = "rust1", since = "1.0.0")]
2912 pub fn insert(&mut self, mut value: V) -> V {
2913 let old_value = self.get_mut();
2914 mem::swap(&mut value, old_value);
2918 /// Takes the value out of the entry, and returns it.
2923 /// use std::collections::HashMap;
2924 /// use std::collections::hash_map::Entry;
2926 /// let mut map: HashMap<&str, u32> = HashMap::new();
2927 /// map.entry("poneyland").or_insert(12);
2929 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2930 /// assert_eq!(o.remove(), 12);
2933 /// assert_eq!(map.contains_key("poneyland"), false);
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 pub fn remove(self) -> V {
2937 pop_internal(self.elem).1
2940 /// Returns a key that was used for search.
2942 /// The key was retained for further use.
2943 fn take_key(&mut self) -> Option<K> {
2947 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2948 /// the key used to create this entry.
2953 /// #![feature(map_entry_replace)]
2954 /// use std::collections::hash_map::{Entry, HashMap};
2955 /// use std::rc::Rc;
2957 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2958 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2960 /// let my_key = Rc::new("Stringthing".to_string());
2962 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2963 /// // Also replace the key with a handle to our other key.
2964 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2968 #[unstable(feature = "map_entry_replace", issue = "44286")]
2969 pub fn replace_entry(mut self, value: V) -> (K, V) {
2970 let (old_key, old_value) = self.elem.read_mut();
2972 let old_key = mem::replace(old_key, self.key.unwrap());
2973 let old_value = mem::replace(old_value, value);
2975 (old_key, old_value)
2978 /// Replaces the key in the hash map with the key used to create this entry.
2983 /// #![feature(map_entry_replace)]
2984 /// use std::collections::hash_map::{Entry, HashMap};
2985 /// use std::rc::Rc;
2987 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2988 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2990 /// // Initialise known strings, run program, etc.
2992 /// reclaim_memory(&mut map, &known_strings);
2994 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2995 /// for s in known_strings {
2996 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2997 /// // Replaces the entry's key with our version of it in `known_strings`.
2998 /// entry.replace_key();
3003 #[unstable(feature = "map_entry_replace", issue = "44286")]
3004 pub fn replace_key(mut self) -> K {
3005 let (old_key, _) = self.elem.read_mut();
3006 mem::replace(old_key, self.key.unwrap())
3010 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3011 /// Gets a reference to the key that would be used when inserting a value
3012 /// through the `VacantEntry`.
3017 /// use std::collections::HashMap;
3019 /// let mut map: HashMap<&str, u32> = HashMap::new();
3020 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3022 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3023 pub fn key(&self) -> &K {
3027 /// Take ownership of the key.
3032 /// use std::collections::HashMap;
3033 /// use std::collections::hash_map::Entry;
3035 /// let mut map: HashMap<&str, u32> = HashMap::new();
3037 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3041 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3042 pub fn into_key(self) -> K {
3046 /// Sets the value of the entry with the VacantEntry's key,
3047 /// and returns a mutable reference to it.
3052 /// use std::collections::HashMap;
3053 /// use std::collections::hash_map::Entry;
3055 /// let mut map: HashMap<&str, u32> = HashMap::new();
3057 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3060 /// assert_eq!(map["poneyland"], 37);
3062 #[stable(feature = "rust1", since = "1.0.0")]
3063 pub fn insert(self, value: V) -> &'a mut V {
3064 let b = match self.elem {
3065 NeqElem(mut bucket, disp) => {
3066 if disp >= DISPLACEMENT_THRESHOLD {
3067 bucket.table_mut().set_tag(true);
3069 robin_hood(bucket, disp, self.hash, self.key, value)
3071 NoElem(mut bucket, disp) => {
3072 if disp >= DISPLACEMENT_THRESHOLD {
3073 bucket.table_mut().set_tag(true);
3075 bucket.put(self.hash, self.key, value)
3082 #[stable(feature = "rust1", since = "1.0.0")]
3083 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3085 S: BuildHasher + Default
3087 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3088 let mut map = HashMap::with_hasher(Default::default());
3094 #[stable(feature = "rust1", since = "1.0.0")]
3095 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3099 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3100 // Keys may be already present or show multiple times in the iterator.
3101 // Reserve the entire hint lower bound if the map is empty.
3102 // Otherwise reserve half the hint (rounded up), so the map
3103 // will only resize twice in the worst case.
3104 let iter = iter.into_iter();
3105 let reserve = if self.is_empty() {
3108 (iter.size_hint().0 + 1) / 2
3110 self.reserve(reserve);
3111 for (k, v) in iter {
3117 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3118 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3119 where K: Eq + Hash + Copy,
3123 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3124 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3128 /// `RandomState` is the default state for [`HashMap`] types.
3130 /// A particular instance `RandomState` will create the same instances of
3131 /// [`Hasher`], but the hashers created by two different `RandomState`
3132 /// instances are unlikely to produce the same result for the same values.
3134 /// [`HashMap`]: struct.HashMap.html
3135 /// [`Hasher`]: ../../hash/trait.Hasher.html
3140 /// use std::collections::HashMap;
3141 /// use std::collections::hash_map::RandomState;
3143 /// let s = RandomState::new();
3144 /// let mut map = HashMap::with_hasher(s);
3145 /// map.insert(1, 2);
3148 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3149 pub struct RandomState {
3155 /// Constructs a new `RandomState` that is initialized with random keys.
3160 /// use std::collections::hash_map::RandomState;
3162 /// let s = RandomState::new();
3165 #[allow(deprecated)]
3167 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3168 pub fn new() -> RandomState {
3169 // Historically this function did not cache keys from the OS and instead
3170 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3171 // was discovered, however, that because we re-seed the thread-local RNG
3172 // from the OS periodically that this can cause excessive slowdown when
3173 // many hash maps are created on a thread. To solve this performance
3174 // trap we cache the first set of randomly generated keys per-thread.
3176 // Later in #36481 it was discovered that exposing a deterministic
3177 // iteration order allows a form of DOS attack. To counter that we
3178 // increment one of the seeds on every RandomState creation, giving
3179 // every corresponding HashMap a different iteration order.
3180 thread_local!(static KEYS: Cell<(u64, u64)> = {
3181 Cell::new(sys::hashmap_random_keys())
3185 let (k0, k1) = keys.get();
3186 keys.set((k0.wrapping_add(1), k1));
3187 RandomState { k0: k0, k1: k1 }
3192 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3193 impl BuildHasher for RandomState {
3194 type Hasher = DefaultHasher;
3196 #[allow(deprecated)]
3197 fn build_hasher(&self) -> DefaultHasher {
3198 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3202 /// The default [`Hasher`] used by [`RandomState`].
3204 /// The internal algorithm is not specified, and so it and its hashes should
3205 /// not be relied upon over releases.
3207 /// [`RandomState`]: struct.RandomState.html
3208 /// [`Hasher`]: ../../hash/trait.Hasher.html
3209 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3210 #[allow(deprecated)]
3211 #[derive(Clone, Debug)]
3212 pub struct DefaultHasher(SipHasher13);
3214 impl DefaultHasher {
3215 /// Creates a new `DefaultHasher`.
3217 /// This hasher is not guaranteed to be the same as all other
3218 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3219 /// instances created through `new` or `default`.
3220 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3221 #[allow(deprecated)]
3222 pub fn new() -> DefaultHasher {
3223 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3227 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3228 impl Default for DefaultHasher {
3229 /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3230 /// See its documentation for more.
3231 fn default() -> DefaultHasher {
3232 DefaultHasher::new()
3236 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3237 impl Hasher for DefaultHasher {
3239 fn write(&mut self, msg: &[u8]) {
3244 fn finish(&self) -> u64 {
3249 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3250 impl Default for RandomState {
3251 /// Constructs a new `RandomState`.
3253 fn default() -> RandomState {
3258 #[stable(feature = "std_debug", since = "1.16.0")]
3259 impl fmt::Debug for RandomState {
3260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3261 f.pad("RandomState { .. }")
3265 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3266 where K: Eq + Hash + Borrow<Q>,
3273 fn get(&self, key: &Q) -> Option<&K> {
3274 self.search(key).map(|bucket| bucket.into_refs().0)
3277 fn take(&mut self, key: &Q) -> Option<K> {
3278 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3282 fn replace(&mut self, key: K) -> Option<K> {
3285 match self.entry(key) {
3286 Occupied(mut occupied) => {
3287 let key = occupied.take_key().unwrap();
3288 Some(mem::replace(occupied.elem.read_mut().0, key))
3299 fn assert_covariance() {
3300 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3303 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3306 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3309 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3312 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3315 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3318 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3321 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3324 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3327 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3330 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3331 -> Drain<'new, &'new str, &'new str> {
3339 use super::Entry::{Occupied, Vacant};
3340 use super::RandomState;
3342 use rand::{thread_rng, Rng};
3343 use realstd::collections::CollectionAllocErr::*;
3344 use realstd::mem::size_of;
3348 fn test_zero_capacities() {
3349 type HM = HashMap<i32, i32>;
3352 assert_eq!(m.capacity(), 0);
3354 let m = HM::default();
3355 assert_eq!(m.capacity(), 0);
3357 let m = HM::with_hasher(RandomState::new());
3358 assert_eq!(m.capacity(), 0);
3360 let m = HM::with_capacity(0);
3361 assert_eq!(m.capacity(), 0);
3363 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3364 assert_eq!(m.capacity(), 0);
3366 let mut m = HM::new();
3372 assert_eq!(m.capacity(), 0);
3374 let mut m = HM::new();
3376 assert_eq!(m.capacity(), 0);
3380 fn test_create_capacity_zero() {
3381 let mut m = HashMap::with_capacity(0);
3383 assert!(m.insert(1, 1).is_none());
3385 assert!(m.contains_key(&1));
3386 assert!(!m.contains_key(&0));
3391 let mut m = HashMap::new();
3392 assert_eq!(m.len(), 0);
3393 assert!(m.insert(1, 2).is_none());
3394 assert_eq!(m.len(), 1);
3395 assert!(m.insert(2, 4).is_none());
3396 assert_eq!(m.len(), 2);
3397 assert_eq!(*m.get(&1).unwrap(), 2);
3398 assert_eq!(*m.get(&2).unwrap(), 4);
3403 let mut m = HashMap::new();
3404 assert_eq!(m.len(), 0);
3405 assert!(m.insert(1, 2).is_none());
3406 assert_eq!(m.len(), 1);
3407 assert!(m.insert(2, 4).is_none());
3408 assert_eq!(m.len(), 2);
3410 assert_eq!(*m2.get(&1).unwrap(), 2);
3411 assert_eq!(*m2.get(&2).unwrap(), 4);
3412 assert_eq!(m2.len(), 2);
3415 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3417 #[derive(Hash, PartialEq, Eq)]
3423 fn new(k: usize) -> Droppable {
3424 DROP_VECTOR.with(|slot| {
3425 slot.borrow_mut()[k] += 1;
3432 impl Drop for Droppable {
3433 fn drop(&mut self) {
3434 DROP_VECTOR.with(|slot| {
3435 slot.borrow_mut()[self.k] -= 1;
3440 impl Clone for Droppable {
3441 fn clone(&self) -> Droppable {
3442 Droppable::new(self.k)
3448 DROP_VECTOR.with(|slot| {
3449 *slot.borrow_mut() = vec![0; 200];
3453 let mut m = HashMap::new();
3455 DROP_VECTOR.with(|v| {
3457 assert_eq!(v.borrow()[i], 0);
3462 let d1 = Droppable::new(i);
3463 let d2 = Droppable::new(i + 100);
3467 DROP_VECTOR.with(|v| {
3469 assert_eq!(v.borrow()[i], 1);
3474 let k = Droppable::new(i);
3475 let v = m.remove(&k);
3477 assert!(v.is_some());
3479 DROP_VECTOR.with(|v| {
3480 assert_eq!(v.borrow()[i], 1);
3481 assert_eq!(v.borrow()[i+100], 1);
3485 DROP_VECTOR.with(|v| {
3487 assert_eq!(v.borrow()[i], 0);
3488 assert_eq!(v.borrow()[i+100], 0);
3492 assert_eq!(v.borrow()[i], 1);
3493 assert_eq!(v.borrow()[i+100], 1);
3498 DROP_VECTOR.with(|v| {
3500 assert_eq!(v.borrow()[i], 0);
3506 fn test_into_iter_drops() {
3507 DROP_VECTOR.with(|v| {
3508 *v.borrow_mut() = vec![0; 200];
3512 let mut hm = HashMap::new();
3514 DROP_VECTOR.with(|v| {
3516 assert_eq!(v.borrow()[i], 0);
3521 let d1 = Droppable::new(i);
3522 let d2 = Droppable::new(i + 100);
3526 DROP_VECTOR.with(|v| {
3528 assert_eq!(v.borrow()[i], 1);
3535 // By the way, ensure that cloning doesn't screw up the dropping.
3539 let mut half = hm.into_iter().take(50);
3541 DROP_VECTOR.with(|v| {
3543 assert_eq!(v.borrow()[i], 1);
3547 for _ in half.by_ref() {}
3549 DROP_VECTOR.with(|v| {
3551 .filter(|&i| v.borrow()[i] == 1)
3555 .filter(|&i| v.borrow()[i + 100] == 1)
3563 DROP_VECTOR.with(|v| {
3565 assert_eq!(v.borrow()[i], 0);
3571 fn test_empty_remove() {
3572 let mut m: HashMap<i32, bool> = HashMap::new();
3573 assert_eq!(m.remove(&0), None);
3577 fn test_empty_entry() {
3578 let mut m: HashMap<i32, bool> = HashMap::new();
3580 Occupied(_) => panic!(),
3583 assert!(*m.entry(0).or_insert(true));
3584 assert_eq!(m.len(), 1);
3588 fn test_empty_iter() {
3589 let mut m: HashMap<i32, bool> = HashMap::new();
3590 assert_eq!(m.drain().next(), None);
3591 assert_eq!(m.keys().next(), None);
3592 assert_eq!(m.values().next(), None);
3593 assert_eq!(m.values_mut().next(), None);
3594 assert_eq!(m.iter().next(), None);
3595 assert_eq!(m.iter_mut().next(), None);
3596 assert_eq!(m.len(), 0);
3597 assert!(m.is_empty());
3598 assert_eq!(m.into_iter().next(), None);
3602 fn test_lots_of_insertions() {
3603 let mut m = HashMap::new();
3605 // Try this a few times to make sure we never screw up the hashmap's
3608 assert!(m.is_empty());
3611 assert!(m.insert(i, i).is_none());
3615 assert_eq!(r, Some(&j));
3618 for j in i + 1..1001 {
3620 assert_eq!(r, None);
3624 for i in 1001..2001 {
3625 assert!(!m.contains_key(&i));
3630 assert!(m.remove(&i).is_some());
3633 assert!(!m.contains_key(&j));
3636 for j in i + 1..1001 {
3637 assert!(m.contains_key(&j));
3642 assert!(!m.contains_key(&i));
3646 assert!(m.insert(i, i).is_none());
3650 for i in (1..1001).rev() {
3651 assert!(m.remove(&i).is_some());
3654 assert!(!m.contains_key(&j));
3658 assert!(m.contains_key(&j));
3665 fn test_find_mut() {
3666 let mut m = HashMap::new();
3667 assert!(m.insert(1, 12).is_none());
3668 assert!(m.insert(2, 8).is_none());
3669 assert!(m.insert(5, 14).is_none());
3671 match m.get_mut(&5) {
3673 Some(x) => *x = new,
3675 assert_eq!(m.get(&5), Some(&new));
3679 fn test_insert_overwrite() {
3680 let mut m = HashMap::new();
3681 assert!(m.insert(1, 2).is_none());
3682 assert_eq!(*m.get(&1).unwrap(), 2);
3683 assert!(!m.insert(1, 3).is_none());
3684 assert_eq!(*m.get(&1).unwrap(), 3);
3688 fn test_insert_conflicts() {
3689 let mut m = HashMap::with_capacity(4);
3690 assert!(m.insert(1, 2).is_none());
3691 assert!(m.insert(5, 3).is_none());
3692 assert!(m.insert(9, 4).is_none());
3693 assert_eq!(*m.get(&9).unwrap(), 4);
3694 assert_eq!(*m.get(&5).unwrap(), 3);
3695 assert_eq!(*m.get(&1).unwrap(), 2);
3699 fn test_conflict_remove() {
3700 let mut m = HashMap::with_capacity(4);
3701 assert!(m.insert(1, 2).is_none());
3702 assert_eq!(*m.get(&1).unwrap(), 2);
3703 assert!(m.insert(5, 3).is_none());
3704 assert_eq!(*m.get(&1).unwrap(), 2);
3705 assert_eq!(*m.get(&5).unwrap(), 3);
3706 assert!(m.insert(9, 4).is_none());
3707 assert_eq!(*m.get(&1).unwrap(), 2);
3708 assert_eq!(*m.get(&5).unwrap(), 3);
3709 assert_eq!(*m.get(&9).unwrap(), 4);
3710 assert!(m.remove(&1).is_some());
3711 assert_eq!(*m.get(&9).unwrap(), 4);
3712 assert_eq!(*m.get(&5).unwrap(), 3);
3716 fn test_is_empty() {
3717 let mut m = HashMap::with_capacity(4);
3718 assert!(m.insert(1, 2).is_none());
3719 assert!(!m.is_empty());
3720 assert!(m.remove(&1).is_some());
3721 assert!(m.is_empty());
3726 let mut m = HashMap::new();
3728 assert_eq!(m.remove(&1), Some(2));
3729 assert_eq!(m.remove(&1), None);
3733 fn test_remove_entry() {
3734 let mut m = HashMap::new();
3736 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3737 assert_eq!(m.remove(&1), None);
3742 let mut m = HashMap::with_capacity(4);
3744 assert!(m.insert(i, i*2).is_none());
3746 assert_eq!(m.len(), 32);
3748 let mut observed: u32 = 0;
3751 assert_eq!(*v, *k * 2);
3752 observed |= 1 << *k;
3754 assert_eq!(observed, 0xFFFF_FFFF);
3759 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3760 let map: HashMap<_, _> = vec.into_iter().collect();
3761 let keys: Vec<_> = map.keys().cloned().collect();
3762 assert_eq!(keys.len(), 3);
3763 assert!(keys.contains(&1));
3764 assert!(keys.contains(&2));
3765 assert!(keys.contains(&3));
3770 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3771 let map: HashMap<_, _> = vec.into_iter().collect();
3772 let values: Vec<_> = map.values().cloned().collect();
3773 assert_eq!(values.len(), 3);
3774 assert!(values.contains(&'a'));
3775 assert!(values.contains(&'b'));
3776 assert!(values.contains(&'c'));
3780 fn test_values_mut() {
3781 let vec = vec![(1, 1), (2, 2), (3, 3)];
3782 let mut map: HashMap<_, _> = vec.into_iter().collect();
3783 for value in map.values_mut() {
3784 *value = (*value) * 2
3786 let values: Vec<_> = map.values().cloned().collect();
3787 assert_eq!(values.len(), 3);
3788 assert!(values.contains(&2));
3789 assert!(values.contains(&4));
3790 assert!(values.contains(&6));
3795 let mut m = HashMap::new();
3796 assert!(m.get(&1).is_none());
3800 Some(v) => assert_eq!(*v, 2),
3806 let mut m1 = HashMap::new();
3811 let mut m2 = HashMap::new();
3824 let mut map = HashMap::new();
3825 let empty: HashMap<i32, i32> = HashMap::new();
3830 let map_str = format!("{:?}", map);
3832 assert!(map_str == "{1: 2, 3: 4}" ||
3833 map_str == "{3: 4, 1: 2}");
3834 assert_eq!(format!("{:?}", empty), "{}");
3839 let mut m = HashMap::new();
3841 assert_eq!(m.len(), 0);
3842 assert!(m.is_empty());
3845 let old_raw_cap = m.raw_capacity();
3846 while old_raw_cap == m.raw_capacity() {
3851 assert_eq!(m.len(), i);
3852 assert!(!m.is_empty());
3856 fn test_behavior_resize_policy() {
3857 let mut m = HashMap::new();
3859 assert_eq!(m.len(), 0);
3860 assert_eq!(m.raw_capacity(), 0);
3861 assert!(m.is_empty());
3865 assert!(m.is_empty());
3866 let initial_raw_cap = m.raw_capacity();
3867 m.reserve(initial_raw_cap);
3868 let raw_cap = m.raw_capacity();
3870 assert_eq!(raw_cap, initial_raw_cap * 2);
3873 for _ in 0..raw_cap * 3 / 4 {
3877 // three quarters full
3879 assert_eq!(m.len(), i);
3880 assert_eq!(m.raw_capacity(), raw_cap);
3882 for _ in 0..raw_cap / 4 {
3888 let new_raw_cap = m.raw_capacity();
3889 assert_eq!(new_raw_cap, raw_cap * 2);
3891 for _ in 0..raw_cap / 2 - 1 {
3894 assert_eq!(m.raw_capacity(), new_raw_cap);
3896 // A little more than one quarter full.
3898 assert_eq!(m.raw_capacity(), raw_cap);
3899 // again, a little more than half full
3900 for _ in 0..raw_cap / 2 - 1 {
3906 assert_eq!(m.len(), i);
3907 assert!(!m.is_empty());
3908 assert_eq!(m.raw_capacity(), initial_raw_cap);
3912 fn test_reserve_shrink_to_fit() {
3913 let mut m = HashMap::new();
3916 assert!(m.capacity() >= m.len());
3922 let usable_cap = m.capacity();
3923 for i in 128..(128 + 256) {
3925 assert_eq!(m.capacity(), usable_cap);
3928 for i in 100..(128 + 256) {
3929 assert_eq!(m.remove(&i), Some(i));
3933 assert_eq!(m.len(), 100);
3934 assert!(!m.is_empty());
3935 assert!(m.capacity() >= m.len());
3938 assert_eq!(m.remove(&i), Some(i));
3943 assert_eq!(m.len(), 1);
3944 assert!(m.capacity() >= m.len());
3945 assert_eq!(m.remove(&0), Some(0));
3949 fn test_from_iter() {
3950 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3952 let map: HashMap<_, _> = xs.iter().cloned().collect();
3954 for &(k, v) in &xs {
3955 assert_eq!(map.get(&k), Some(&v));
3960 fn test_size_hint() {
3961 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3963 let map: HashMap<_, _> = xs.iter().cloned().collect();
3965 let mut iter = map.iter();
3967 for _ in iter.by_ref().take(3) {}
3969 assert_eq!(iter.size_hint(), (3, Some(3)));
3973 fn test_iter_len() {
3974 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3976 let map: HashMap<_, _> = xs.iter().cloned().collect();
3978 let mut iter = map.iter();
3980 for _ in iter.by_ref().take(3) {}
3982 assert_eq!(iter.len(), 3);
3986 fn test_mut_size_hint() {
3987 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3989 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3991 let mut iter = map.iter_mut();
3993 for _ in iter.by_ref().take(3) {}
3995 assert_eq!(iter.size_hint(), (3, Some(3)));
3999 fn test_iter_mut_len() {
4000 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
4002 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4004 let mut iter = map.iter_mut();
4006 for _ in iter.by_ref().take(3) {}
4008 assert_eq!(iter.len(), 3);
4013 let mut map = HashMap::new();
4019 assert_eq!(map[&2], 1);
4024 fn test_index_nonexistent() {
4025 let mut map = HashMap::new();
4036 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4038 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4040 // Existing key (insert)
4041 match map.entry(1) {
4042 Vacant(_) => unreachable!(),
4043 Occupied(mut view) => {
4044 assert_eq!(view.get(), &10);
4045 assert_eq!(view.insert(100), 10);
4048 assert_eq!(map.get(&1).unwrap(), &100);
4049 assert_eq!(map.len(), 6);
4052 // Existing key (update)
4053 match map.entry(2) {
4054 Vacant(_) => unreachable!(),
4055 Occupied(mut view) => {
4056 let v = view.get_mut();
4057 let new_v = (*v) * 10;
4061 assert_eq!(map.get(&2).unwrap(), &200);
4062 assert_eq!(map.len(), 6);
4064 // Existing key (take)
4065 match map.entry(3) {
4066 Vacant(_) => unreachable!(),
4068 assert_eq!(view.remove(), 30);
4071 assert_eq!(map.get(&3), None);
4072 assert_eq!(map.len(), 5);
4075 // Inexistent key (insert)
4076 match map.entry(10) {
4077 Occupied(_) => unreachable!(),
4079 assert_eq!(*view.insert(1000), 1000);
4082 assert_eq!(map.get(&10).unwrap(), &1000);
4083 assert_eq!(map.len(), 6);
4087 fn test_entry_take_doesnt_corrupt() {
4088 #![allow(deprecated)] //rand
4090 fn check(m: &HashMap<i32, ()>) {
4092 assert!(m.contains_key(k),
4093 "{} is in keys() but not in the map?", k);
4097 let mut m = HashMap::new();
4098 let mut rng = thread_rng();
4100 // Populate the map with some items.
4102 let x = rng.gen_range(-10, 10);
4107 let x = rng.gen_range(-10, 10);
4120 fn test_extend_ref() {
4121 let mut a = HashMap::new();
4123 let mut b = HashMap::new();
4125 b.insert(3, "three");
4129 assert_eq!(a.len(), 3);
4130 assert_eq!(a[&1], "one");
4131 assert_eq!(a[&2], "two");
4132 assert_eq!(a[&3], "three");
4136 fn test_capacity_not_less_than_len() {
4137 let mut a = HashMap::new();
4145 assert!(a.capacity() > a.len());
4147 let free = a.capacity() - a.len();
4153 assert_eq!(a.len(), a.capacity());
4155 // Insert at capacity should cause allocation.
4157 assert!(a.capacity() > a.len());
4161 fn test_occupied_entry_key() {
4162 let mut a = HashMap::new();
4163 let key = "hello there";
4164 let value = "value goes here";
4165 assert!(a.is_empty());
4166 a.insert(key.clone(), value.clone());
4167 assert_eq!(a.len(), 1);
4168 assert_eq!(a[key], value);
4170 match a.entry(key.clone()) {
4171 Vacant(_) => panic!(),
4172 Occupied(e) => assert_eq!(key, *e.key()),
4174 assert_eq!(a.len(), 1);
4175 assert_eq!(a[key], value);
4179 fn test_vacant_entry_key() {
4180 let mut a = HashMap::new();
4181 let key = "hello there";
4182 let value = "value goes here";
4184 assert!(a.is_empty());
4185 match a.entry(key.clone()) {
4186 Occupied(_) => panic!(),
4188 assert_eq!(key, *e.key());
4189 e.insert(value.clone());
4192 assert_eq!(a.len(), 1);
4193 assert_eq!(a[key], value);
4198 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4200 map.retain(|&k, _| k % 2 == 0);
4201 assert_eq!(map.len(), 50);
4202 assert_eq!(map[&2], 20);
4203 assert_eq!(map[&4], 40);
4204 assert_eq!(map[&6], 60);
4208 fn test_adaptive() {
4209 const TEST_LEN: usize = 5000;
4210 // by cloning we get maps with the same hasher seed
4211 let mut first = HashMap::new();
4212 let mut second = first.clone();
4213 first.extend((0..TEST_LEN).map(|i| (i, i)));
4214 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4216 for (&k, &v) in &second {
4217 let prev_cap = first.capacity();
4218 let expect_grow = first.len() == prev_cap;
4220 if !expect_grow && first.capacity() != prev_cap {
4224 panic!("Adaptive early resize failed");
4228 fn test_try_reserve() {
4230 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4232 const MAX_USIZE: usize = usize::MAX;
4234 // HashMap and RawTables use complicated size calculations
4235 // hashes_size is sizeof(HashUint) * capacity;
4236 // pairs_size is sizeof((K. V)) * capacity;
4237 // alignment_hashes_size is 8
4238 // alignment_pairs size is 4
4239 let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4240 // The following formula is used to calculate the new capacity
4241 let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4243 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4244 } else { panic!("usize::MAX should trigger an overflow!"); }
4246 if size_of::<usize>() < 8 {
4247 if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4248 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4250 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4251 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4256 fn test_raw_entry() {
4257 use super::RawEntryMut::{Occupied, Vacant};
4259 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4261 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4263 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4264 use core::hash::{BuildHasher, Hash, Hasher};
4266 let mut hasher = map.hasher().build_hasher();
4267 k.hash(&mut hasher);
4271 // Existing key (insert)
4272 match map.raw_entry_mut().from_key(&1) {
4273 Vacant(_) => unreachable!(),
4274 Occupied(mut view) => {
4275 assert_eq!(view.get(), &10);
4276 assert_eq!(view.insert(100), 10);
4279 let hash1 = compute_hash(&map, 1);
4280 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4281 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4282 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4283 assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4284 assert_eq!(map.len(), 6);
4286 // Existing key (update)
4287 match map.raw_entry_mut().from_key(&2) {
4288 Vacant(_) => unreachable!(),
4289 Occupied(mut view) => {
4290 let v = view.get_mut();
4291 let new_v = (*v) * 10;
4295 let hash2 = compute_hash(&map, 2);
4296 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4297 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4298 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4299 assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4300 assert_eq!(map.len(), 6);
4302 // Existing key (take)
4303 let hash3 = compute_hash(&map, 3);
4304 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4305 Vacant(_) => unreachable!(),
4307 assert_eq!(view.remove_entry(), (3, 30));
4310 assert_eq!(map.raw_entry().from_key(&3), None);
4311 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4312 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4313 assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4314 assert_eq!(map.len(), 5);
4317 // Nonexistent key (insert)
4318 match map.raw_entry_mut().from_key(&10) {
4319 Occupied(_) => unreachable!(),
4321 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4324 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4325 assert_eq!(map.len(), 6);
4327 // Ensure all lookup methods produce equivalent results.
4329 let hash = compute_hash(&map, k);
4330 let v = map.get(&k).cloned();
4331 let kv = v.as_ref().map(|v| (&k, v));
4333 assert_eq!(map.raw_entry().from_key(&k), kv);
4334 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4335 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4336 assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4338 match map.raw_entry_mut().from_key(&k) {
4339 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4340 Vacant(_) => assert_eq!(v, None),
4342 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
4343 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4344 Vacant(_) => assert_eq!(v, None),
4346 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
4347 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4348 Vacant(_) => assert_eq!(v, None),
4350 match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4351 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4352 Vacant(_) => assert_eq!(v, None),