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();
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn reserve(&mut self, additional: usize) {
854 match self.reserve_internal(additional, Infallible) {
855 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
856 Err(CollectionAllocErr::AllocErr) => unreachable!(),
857 Ok(()) => { /* yay */ }
861 /// Tries to reserve capacity for at least `additional` more elements to be inserted
862 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
863 /// frequent reallocations.
867 /// If the capacity overflows, or the allocator reports a failure, then an error
873 /// #![feature(try_reserve)]
874 /// use std::collections::HashMap;
875 /// let mut map: HashMap<&str, isize> = HashMap::new();
876 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
878 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
879 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
880 self.reserve_internal(additional, Fallible)
883 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
884 -> Result<(), CollectionAllocErr> {
886 let remaining = self.capacity() - self.len(); // this can't overflow
887 if remaining < additional {
888 let min_cap = self.len()
889 .checked_add(additional)
890 .ok_or(CollectionAllocErr::CapacityOverflow)?;
891 let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
892 self.try_resize(raw_cap, fallibility)?;
893 } else if self.table.tag() && remaining <= self.len() {
894 // Probe sequence is too long and table is half full,
895 // resize early to reduce probing length.
896 let new_capacity = self.table.capacity() * 2;
897 self.try_resize(new_capacity, fallibility)?;
902 /// Resizes the internal vectors to a new capacity. It's your
903 /// responsibility to:
904 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
905 /// for the load factor.
906 /// 2) Ensure `new_raw_cap` is a power of two or zero.
912 fallibility: Fallibility,
913 ) -> Result<(), CollectionAllocErr> {
914 assert!(self.table.size() <= new_raw_cap);
915 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
917 let mut old_table = replace(
920 Infallible => RawTable::new(new_raw_cap),
921 Fallible => RawTable::try_new(new_raw_cap)?,
924 let old_size = old_table.size();
926 if old_table.size() == 0 {
930 let mut bucket = Bucket::head_bucket(&mut old_table);
932 // This is how the buckets might be laid out in memory:
933 // ($ marks an initialized bucket)
935 // |$$$_$$$$$$_$$$$$|
937 // But we've skipped the entire initial cluster of buckets
938 // and will continue iteration in this order:
941 // ^ wrap around once end is reached
944 // ^ exit once table.size == 0
946 bucket = match bucket.peek() {
948 let h = bucket.hash();
949 let (b, k, v) = bucket.take();
950 self.insert_hashed_ordered(h, k, v);
951 if b.table().size() == 0 {
956 Empty(b) => b.into_bucket(),
961 assert_eq!(self.table.size(), old_size);
965 /// Shrinks the capacity of the map as much as possible. It will drop
966 /// down as much as possible while maintaining the internal rules
967 /// and possibly leaving some space in accordance with the resize policy.
972 /// use std::collections::HashMap;
974 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
975 /// map.insert(1, 2);
976 /// map.insert(3, 4);
977 /// assert!(map.capacity() >= 100);
978 /// map.shrink_to_fit();
979 /// assert!(map.capacity() >= 2);
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn shrink_to_fit(&mut self) {
983 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
984 if self.raw_capacity() != new_raw_cap {
985 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
986 let old_size = old_table.size();
988 // Shrink the table. Naive algorithm for resizing:
989 for (h, k, v) in old_table.into_iter() {
990 self.insert_hashed_nocheck(h, k, v);
993 debug_assert_eq!(self.table.size(), old_size);
997 /// Shrinks the capacity of the map with a lower limit. It will drop
998 /// down no lower than the supplied limit while maintaining the internal rules
999 /// and possibly leaving some space in accordance with the resize policy.
1001 /// Panics if the current capacity is smaller than the supplied
1002 /// minimum capacity.
1007 /// #![feature(shrink_to)]
1008 /// use std::collections::HashMap;
1010 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1011 /// map.insert(1, 2);
1012 /// map.insert(3, 4);
1013 /// assert!(map.capacity() >= 100);
1014 /// map.shrink_to(10);
1015 /// assert!(map.capacity() >= 10);
1016 /// map.shrink_to(0);
1017 /// assert!(map.capacity() >= 2);
1019 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
1020 pub fn shrink_to(&mut self, min_capacity: usize) {
1021 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1023 let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1024 if self.raw_capacity() != new_raw_cap {
1025 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1026 let old_size = old_table.size();
1028 // Shrink the table. Naive algorithm for resizing:
1029 for (h, k, v) in old_table.into_iter() {
1030 self.insert_hashed_nocheck(h, k, v);
1033 debug_assert_eq!(self.table.size(), old_size);
1037 /// Insert a pre-hashed key-value pair, without first checking
1038 /// that there's enough room in the buckets. Returns a reference to the
1039 /// newly insert value.
1041 /// If the key already exists, the hashtable will be returned untouched
1042 /// and a reference to the existing element will be returned.
1043 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1044 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1046 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1047 Some(Vacant(elem)) => {
1051 None => unreachable!(),
1055 /// An iterator visiting all keys in arbitrary order.
1056 /// The iterator element type is `&'a K`.
1061 /// use std::collections::HashMap;
1063 /// let mut map = HashMap::new();
1064 /// map.insert("a", 1);
1065 /// map.insert("b", 2);
1066 /// map.insert("c", 3);
1068 /// for key in map.keys() {
1069 /// println!("{}", key);
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn keys(&self) -> Keys<K, V> {
1074 Keys { inner: self.iter() }
1077 /// An iterator visiting all values in arbitrary order.
1078 /// The iterator element type is `&'a V`.
1083 /// use std::collections::HashMap;
1085 /// let mut map = HashMap::new();
1086 /// map.insert("a", 1);
1087 /// map.insert("b", 2);
1088 /// map.insert("c", 3);
1090 /// for val in map.values() {
1091 /// println!("{}", val);
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub fn values(&self) -> Values<K, V> {
1096 Values { inner: self.iter() }
1099 /// An iterator visiting all values mutably in arbitrary order.
1100 /// The iterator element type is `&'a mut V`.
1105 /// use std::collections::HashMap;
1107 /// let mut map = HashMap::new();
1109 /// map.insert("a", 1);
1110 /// map.insert("b", 2);
1111 /// map.insert("c", 3);
1113 /// for val in map.values_mut() {
1114 /// *val = *val + 10;
1117 /// for val in map.values() {
1118 /// println!("{}", val);
1121 #[stable(feature = "map_values_mut", since = "1.10.0")]
1122 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1123 ValuesMut { inner: self.iter_mut() }
1126 /// An iterator visiting all key-value pairs in arbitrary order.
1127 /// The iterator element type is `(&'a K, &'a V)`.
1132 /// use std::collections::HashMap;
1134 /// let mut map = HashMap::new();
1135 /// map.insert("a", 1);
1136 /// map.insert("b", 2);
1137 /// map.insert("c", 3);
1139 /// for (key, val) in map.iter() {
1140 /// println!("key: {} val: {}", key, val);
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn iter(&self) -> Iter<K, V> {
1145 Iter { inner: self.table.iter() }
1148 /// An iterator visiting all key-value pairs in arbitrary order,
1149 /// with mutable references to the values.
1150 /// The iterator element type is `(&'a K, &'a mut V)`.
1155 /// use std::collections::HashMap;
1157 /// let mut map = HashMap::new();
1158 /// map.insert("a", 1);
1159 /// map.insert("b", 2);
1160 /// map.insert("c", 3);
1162 /// // Update all values
1163 /// for (_, val) in map.iter_mut() {
1167 /// for (key, val) in &map {
1168 /// println!("key: {} val: {}", key, val);
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1173 IterMut { inner: self.table.iter_mut() }
1176 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1181 /// use std::collections::HashMap;
1183 /// let mut letters = HashMap::new();
1185 /// for ch in "a short treatise on fungi".chars() {
1186 /// let counter = letters.entry(ch).or_insert(0);
1190 /// assert_eq!(letters[&'s'], 2);
1191 /// assert_eq!(letters[&'t'], 3);
1192 /// assert_eq!(letters[&'u'], 1);
1193 /// assert_eq!(letters.get(&'y'), None);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1197 // Gotta resize now.
1199 let hash = self.make_hash(&key);
1200 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1201 .into_entry(key).expect("unreachable")
1204 /// Returns the number of elements in the map.
1209 /// use std::collections::HashMap;
1211 /// let mut a = HashMap::new();
1212 /// assert_eq!(a.len(), 0);
1213 /// a.insert(1, "a");
1214 /// assert_eq!(a.len(), 1);
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 pub fn len(&self) -> usize {
1221 /// Returns true if the map contains no elements.
1226 /// use std::collections::HashMap;
1228 /// let mut a = HashMap::new();
1229 /// assert!(a.is_empty());
1230 /// a.insert(1, "a");
1231 /// assert!(!a.is_empty());
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub fn is_empty(&self) -> bool {
1239 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1240 /// allocated memory for reuse.
1245 /// use std::collections::HashMap;
1247 /// let mut a = HashMap::new();
1248 /// a.insert(1, "a");
1249 /// a.insert(2, "b");
1251 /// for (k, v) in a.drain().take(1) {
1252 /// assert!(k == 1 || k == 2);
1253 /// assert!(v == "a" || v == "b");
1256 /// assert!(a.is_empty());
1259 #[stable(feature = "drain", since = "1.6.0")]
1260 pub fn drain(&mut self) -> Drain<K, V> {
1261 Drain { inner: self.table.drain() }
1264 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1270 /// use std::collections::HashMap;
1272 /// let mut a = HashMap::new();
1273 /// a.insert(1, "a");
1275 /// assert!(a.is_empty());
1277 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn clear(&mut self) {
1283 /// Returns a reference to the value corresponding to the key.
1285 /// The key may be any borrowed form of the map's key type, but
1286 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1289 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1290 /// [`Hash`]: ../../std/hash/trait.Hash.html
1295 /// use std::collections::HashMap;
1297 /// let mut map = HashMap::new();
1298 /// map.insert(1, "a");
1299 /// assert_eq!(map.get(&1), Some(&"a"));
1300 /// assert_eq!(map.get(&2), None);
1302 #[stable(feature = "rust1", since = "1.0.0")]
1304 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1308 self.search(k).map(|bucket| bucket.into_refs().1)
1311 /// Returns the key-value pair corresponding to the supplied key.
1313 /// The supplied key may be any borrowed form of the map's key type, but
1314 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1317 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1318 /// [`Hash`]: ../../std/hash/trait.Hash.html
1323 /// #![feature(map_get_key_value)]
1324 /// use std::collections::HashMap;
1326 /// let mut map = HashMap::new();
1327 /// map.insert(1, "a");
1328 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1329 /// assert_eq!(map.get_key_value(&2), None);
1331 #[unstable(feature = "map_get_key_value", issue = "49347")]
1332 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1336 self.search(k).map(|bucket| bucket.into_refs())
1339 /// Returns true if the map contains a value for the specified key.
1341 /// The key may be any borrowed form of the map's key type, but
1342 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1345 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1346 /// [`Hash`]: ../../std/hash/trait.Hash.html
1351 /// use std::collections::HashMap;
1353 /// let mut map = HashMap::new();
1354 /// map.insert(1, "a");
1355 /// assert_eq!(map.contains_key(&1), true);
1356 /// assert_eq!(map.contains_key(&2), false);
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1363 self.search(k).is_some()
1366 /// Returns a mutable reference to the value corresponding to the key.
1368 /// The key may be any borrowed form of the map's key type, but
1369 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1372 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1373 /// [`Hash`]: ../../std/hash/trait.Hash.html
1378 /// use std::collections::HashMap;
1380 /// let mut map = HashMap::new();
1381 /// map.insert(1, "a");
1382 /// if let Some(x) = map.get_mut(&1) {
1385 /// assert_eq!(map[&1], "b");
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1392 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1395 /// Inserts a key-value pair into the map.
1397 /// If the map did not have this key present, [`None`] is returned.
1399 /// If the map did have this key present, the value is updated, and the old
1400 /// value is returned. The key is not updated, though; this matters for
1401 /// types that can be `==` without being identical. See the [module-level
1402 /// documentation] for more.
1404 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1405 /// [module-level documentation]: index.html#insert-and-complex-keys
1410 /// use std::collections::HashMap;
1412 /// let mut map = HashMap::new();
1413 /// assert_eq!(map.insert(37, "a"), None);
1414 /// assert_eq!(map.is_empty(), false);
1416 /// map.insert(37, "b");
1417 /// assert_eq!(map.insert(37, "c"), Some("b"));
1418 /// assert_eq!(map[&37], "c");
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1422 let hash = self.make_hash(&k);
1424 self.insert_hashed_nocheck(hash, k, v)
1427 /// Removes a key from the map, returning the value at the key if the key
1428 /// was previously in the map.
1430 /// The key may be any borrowed form of the map's key type, but
1431 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1434 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1435 /// [`Hash`]: ../../std/hash/trait.Hash.html
1440 /// use std::collections::HashMap;
1442 /// let mut map = HashMap::new();
1443 /// map.insert(1, "a");
1444 /// assert_eq!(map.remove(&1), Some("a"));
1445 /// assert_eq!(map.remove(&1), None);
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1452 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1455 /// Removes a key from the map, returning the stored key and value if the
1456 /// key was previously in the map.
1458 /// The key may be any borrowed form of the map's key type, but
1459 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1462 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1463 /// [`Hash`]: ../../std/hash/trait.Hash.html
1468 /// use std::collections::HashMap;
1471 /// let mut map = HashMap::new();
1472 /// map.insert(1, "a");
1473 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1474 /// assert_eq!(map.remove(&1), None);
1477 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1478 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1484 let (k, v, _) = pop_internal(bucket);
1489 /// Retains only the elements specified by the predicate.
1491 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1496 /// use std::collections::HashMap;
1498 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1499 /// map.retain(|&k, _| k % 2 == 0);
1500 /// assert_eq!(map.len(), 4);
1502 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1503 pub fn retain<F>(&mut self, mut f: F)
1504 where F: FnMut(&K, &mut V) -> bool
1506 if self.table.size() == 0 {
1509 let mut elems_left = self.table.size();
1510 let mut bucket = Bucket::head_bucket(&mut self.table);
1512 let start_index = bucket.index();
1513 while elems_left != 0 {
1514 bucket = match bucket.peek() {
1517 let should_remove = {
1518 let (k, v) = full.read_mut();
1522 let prev_raw = full.raw();
1523 let (_, _, t) = pop_internal(full);
1524 Bucket::new_from(prev_raw, t)
1533 bucket.prev(); // reverse iteration
1534 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1539 impl<K, V, S> HashMap<K, V, S>
1543 /// Creates a raw entry builder for the HashMap.
1545 /// Raw entries provide the lowest level of control for searching and
1546 /// manipulating a map. They must be manually initialized with a hash and
1547 /// then manually searched. After this, insertions into a vacant entry
1548 /// still require an owned key to be provided.
1550 /// Raw entries are useful for such exotic situations as:
1552 /// * Hash memoization
1553 /// * Deferring the creation of an owned key until it is known to be required
1554 /// * Using a search key that doesn't work with the Borrow trait
1555 /// * Using custom comparison logic without newtype wrappers
1557 /// Because raw entries provide much more low-level control, it's much easier
1558 /// to put the HashMap into an inconsistent state which, while memory-safe,
1559 /// will cause the map to produce seemingly random results. Higher-level and
1560 /// more foolproof APIs like `entry` should be preferred when possible.
1562 /// In particular, the hash used to initialized the raw entry must still be
1563 /// consistent with the hash of the key that is ultimately stored in the entry.
1564 /// This is because implementations of HashMap may need to recompute hashes
1565 /// when resizing, at which point only the keys are available.
1567 /// Raw entries give mutable access to the keys. This must not be used
1568 /// to modify how the key would compare or hash, as the map will not re-evaluate
1569 /// where the key should go, meaning the keys may become "lost" if their
1570 /// location does not reflect their state. For instance, if you change a key
1571 /// so that the map now contains keys which compare equal, search may start
1572 /// acting erratically, with two keys randomly masking each other. Implementations
1573 /// are free to assume this doesn't happen (within the limits of memory-safety).
1574 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1575 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1577 RawEntryBuilderMut { map: self }
1580 /// Creates a raw immutable entry builder for the HashMap.
1582 /// Raw entries provide the lowest level of control for searching and
1583 /// manipulating a map. They must be manually initialized with a hash and
1584 /// then manually searched.
1586 /// This is useful for
1587 /// * Hash memoization
1588 /// * Using a search key that doesn't work with the Borrow trait
1589 /// * Using custom comparison logic without newtype wrappers
1591 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1592 /// `get` should be preferred.
1594 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1595 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1596 pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1597 RawEntryBuilder { map: self }
1601 #[stable(feature = "rust1", since = "1.0.0")]
1602 impl<K, V, S> PartialEq for HashMap<K, V, S>
1607 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1608 if self.len() != other.len() {
1612 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<K, V, S> Eq for HashMap<K, V, S>
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<K, V, S> Debug for HashMap<K, V, S>
1626 where K: Eq + Hash + Debug,
1630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1631 f.debug_map().entries(self.iter()).finish()
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<K, V, S> Default for HashMap<K, V, S>
1638 S: BuildHasher + Default
1640 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1641 fn default() -> HashMap<K, V, S> {
1642 HashMap::with_hasher(Default::default())
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1648 where K: Eq + Hash + Borrow<Q>,
1654 /// Returns a reference to the value corresponding to the supplied key.
1658 /// Panics if the key is not present in the `HashMap`.
1660 fn index(&self, key: &Q) -> &V {
1661 self.get(key).expect("no entry found for key")
1665 /// An iterator over the entries of a `HashMap`.
1667 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1668 /// documentation for more.
1670 /// [`iter`]: struct.HashMap.html#method.iter
1671 /// [`HashMap`]: struct.HashMap.html
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 pub struct Iter<'a, K: 'a, V: 'a> {
1674 inner: table::Iter<'a, K, V>,
1677 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl<'a, K, V> Clone for Iter<'a, K, V> {
1680 fn clone(&self) -> Iter<'a, K, V> {
1681 Iter { inner: self.inner.clone() }
1685 #[stable(feature = "std_debug", since = "1.16.0")]
1686 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1689 .entries(self.clone())
1694 /// A mutable iterator over the entries of a `HashMap`.
1696 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1697 /// documentation for more.
1699 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1700 /// [`HashMap`]: struct.HashMap.html
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub struct IterMut<'a, K: 'a, V: 'a> {
1703 inner: table::IterMut<'a, K, V>,
1706 /// An owning iterator over the entries of a `HashMap`.
1708 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1709 /// (provided by the `IntoIterator` trait). See its documentation for more.
1711 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1712 /// [`HashMap`]: struct.HashMap.html
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub struct IntoIter<K, V> {
1715 pub(super) inner: table::IntoIter<K, V>,
1718 /// An iterator over the keys of a `HashMap`.
1720 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1721 /// documentation for more.
1723 /// [`keys`]: struct.HashMap.html#method.keys
1724 /// [`HashMap`]: struct.HashMap.html
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 pub struct Keys<'a, K: 'a, V: 'a> {
1727 inner: Iter<'a, K, V>,
1730 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 impl<'a, K, V> Clone for Keys<'a, K, V> {
1733 fn clone(&self) -> Keys<'a, K, V> {
1734 Keys { inner: self.inner.clone() }
1738 #[stable(feature = "std_debug", since = "1.16.0")]
1739 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1742 .entries(self.clone())
1747 /// An iterator over the values of a `HashMap`.
1749 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1750 /// documentation for more.
1752 /// [`values`]: struct.HashMap.html#method.values
1753 /// [`HashMap`]: struct.HashMap.html
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub struct Values<'a, K: 'a, V: 'a> {
1756 inner: Iter<'a, K, V>,
1759 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl<'a, K, V> Clone for Values<'a, K, V> {
1762 fn clone(&self) -> Values<'a, K, V> {
1763 Values { inner: self.inner.clone() }
1767 #[stable(feature = "std_debug", since = "1.16.0")]
1768 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1771 .entries(self.clone())
1776 /// A draining iterator over the entries of a `HashMap`.
1778 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1779 /// documentation for more.
1781 /// [`drain`]: struct.HashMap.html#method.drain
1782 /// [`HashMap`]: struct.HashMap.html
1783 #[stable(feature = "drain", since = "1.6.0")]
1784 pub struct Drain<'a, K: 'a, V: 'a> {
1785 pub(super) inner: table::Drain<'a, K, V>,
1788 /// A mutable iterator over the values of a `HashMap`.
1790 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1791 /// documentation for more.
1793 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1794 /// [`HashMap`]: struct.HashMap.html
1795 #[stable(feature = "map_values_mut", since = "1.10.0")]
1796 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1797 inner: IterMut<'a, K, V>,
1800 enum InternalEntry<K, V, M> {
1801 Occupied { elem: FullBucket<K, V, M> },
1804 elem: VacantEntryState<K, V, M>,
1809 impl<K, V, M> InternalEntry<K, V, M> {
1811 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1813 InternalEntry::Occupied { elem } => Some(elem),
1819 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1821 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1823 InternalEntry::Occupied { elem } => {
1824 Some(Occupied(OccupiedEntry {
1829 InternalEntry::Vacant { hash, elem } => {
1830 Some(Vacant(VacantEntry {
1836 InternalEntry::TableIsEmpty => None,
1841 /// A builder for computing where in a HashMap a key-value pair would be stored.
1843 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1845 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1847 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1848 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1849 map: &'a mut HashMap<K, V, S>,
1852 /// A view into a single entry in a map, which may either be vacant or occupied.
1854 /// This is a lower-level version of [`Entry`].
1856 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1858 /// [`HashMap`]: struct.HashMap.html
1859 /// [`Entry`]: enum.Entry.html
1860 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1861 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1862 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1863 /// An occupied entry.
1864 Occupied(RawOccupiedEntryMut<'a, K, V>),
1866 Vacant(RawVacantEntryMut<'a, K, V, S>),
1869 /// A view into an occupied entry in a `HashMap`.
1870 /// It is part of the [`RawEntryMut`] enum.
1872 /// [`RawEntryMut`]: enum.RawEntryMut.html
1873 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1874 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1875 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1878 /// A view into a vacant entry in a `HashMap`.
1879 /// It is part of the [`RawEntryMut`] enum.
1881 /// [`RawEntryMut`]: enum.RawEntryMut.html
1882 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1883 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1884 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1885 hash_builder: &'a S,
1888 /// A builder for computing where in a HashMap a key-value pair would be stored.
1890 /// See the [`HashMap::raw_entry`] docs for usage examples.
1892 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1893 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1894 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1895 map: &'a HashMap<K, V, S>,
1898 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1899 where S: BuildHasher,
1902 /// Create a `RawEntryMut` from the given key.
1903 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1904 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1908 let mut hasher = self.map.hash_builder.build_hasher();
1909 k.hash(&mut hasher);
1910 self.from_key_hashed_nocheck(hasher.finish(), k)
1913 /// Create a `RawEntryMut` from the given key and its hash.
1914 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1915 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1919 self.from_hash(hash, |q| q.borrow().eq(k))
1922 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> RawEntryMut<'a, K, V, S>
1923 where for<'b> F: FnMut(&'b K) -> bool,
1925 match search_hashed_nonempty_mut(&mut self.map.table,
1926 SafeHash::new(hash),
1929 InternalEntry::Occupied { elem } => {
1930 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1932 InternalEntry::Vacant { elem, .. } => {
1933 RawEntryMut::Vacant(RawVacantEntryMut {
1935 hash_builder: &self.map.hash_builder,
1938 InternalEntry::TableIsEmpty => {
1943 /// Create a `RawEntryMut` from the given hash.
1944 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1945 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1946 where for<'b> F: FnMut(&'b K) -> bool,
1948 self.search(hash, is_match, true)
1951 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1952 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1954 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1955 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1956 where for<'b> F: FnMut(&'b K) -> bool,
1958 self.search(hash, is_match, false)
1962 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1963 where S: BuildHasher,
1965 /// Access an entry by key.
1966 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1967 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1971 let mut hasher = self.map.hash_builder.build_hasher();
1972 k.hash(&mut hasher);
1973 self.from_key_hashed_nocheck(hasher.finish(), k)
1976 /// Access an entry by a key and its hash.
1977 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1978 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1983 self.from_hash(hash, |q| q.borrow().eq(k))
1986 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1987 where F: FnMut(&K) -> bool
1989 match search_hashed_nonempty(&self.map.table,
1990 SafeHash::new(hash),
1993 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
1994 InternalEntry::Vacant { .. } => None,
1995 InternalEntry::TableIsEmpty => unreachable!(),
1999 /// Access an entry by hash.
2000 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2001 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2002 where F: FnMut(&K) -> bool
2004 self.search(hash, is_match, true)
2007 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2008 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2010 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2011 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2012 where F: FnMut(&K) -> bool
2014 self.search(hash, is_match, false)
2018 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2019 /// Ensures a value is in the entry by inserting the default if empty, and returns
2020 /// mutable references to the key and value in the entry.
2025 /// #![feature(hash_raw_entry)]
2026 /// use std::collections::HashMap;
2028 /// let mut map: HashMap<&str, u32> = HashMap::new();
2030 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2031 /// assert_eq!(map["poneyland"], 3);
2033 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2034 /// assert_eq!(map["poneyland"], 6);
2036 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2037 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2042 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2043 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2047 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2048 /// and returns mutable references to the key and value in the entry.
2053 /// #![feature(hash_raw_entry)]
2054 /// use std::collections::HashMap;
2056 /// let mut map: HashMap<&str, String> = HashMap::new();
2058 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2059 /// ("poneyland", "hoho".to_string())
2062 /// assert_eq!(map["poneyland"], "hoho".to_string());
2064 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2065 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2066 where F: FnOnce() -> (K, V),
2071 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2072 RawEntryMut::Vacant(entry) => {
2073 let (k, v) = default();
2079 /// Provides in-place mutable access to an occupied entry before any
2080 /// potential inserts into the map.
2085 /// #![feature(hash_raw_entry)]
2086 /// use std::collections::HashMap;
2088 /// let mut map: HashMap<&str, u32> = HashMap::new();
2090 /// map.raw_entry_mut()
2091 /// .from_key("poneyland")
2092 /// .and_modify(|_k, v| { *v += 1 })
2093 /// .or_insert("poneyland", 42);
2094 /// assert_eq!(map["poneyland"], 42);
2096 /// map.raw_entry_mut()
2097 /// .from_key("poneyland")
2098 /// .and_modify(|_k, v| { *v += 1 })
2099 /// .or_insert("poneyland", 0);
2100 /// assert_eq!(map["poneyland"], 43);
2102 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2103 pub fn and_modify<F>(self, f: F) -> Self
2104 where F: FnOnce(&mut K, &mut V)
2107 RawEntryMut::Occupied(mut entry) => {
2109 let (k, v) = entry.get_key_value_mut();
2112 RawEntryMut::Occupied(entry)
2114 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2119 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2120 /// Gets a reference to the key in the entry.
2121 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2122 pub fn key(&self) -> &K {
2126 /// Gets a mutable reference to the key in the entry.
2127 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2128 pub fn key_mut(&mut self) -> &mut K {
2129 self.elem.read_mut().0
2132 /// Converts the entry into a mutable reference to the key in the entry
2133 /// with a lifetime bound to the map itself.
2134 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2135 pub fn into_key(self) -> &'a mut K {
2136 self.elem.into_mut_refs().0
2139 /// Gets a reference to the value in the entry.
2140 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2141 pub fn get(&self) -> &V {
2145 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2146 /// with a lifetime bound to the map itself.
2147 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2148 pub fn into_mut(self) -> &'a mut V {
2149 self.elem.into_mut_refs().1
2152 /// Gets a mutable reference to the value in the entry.
2153 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2154 pub fn get_mut(&mut self) -> &mut V {
2155 self.elem.read_mut().1
2158 /// Gets a reference to the key and value in the entry.
2159 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2160 pub fn get_key_value(&mut self) -> (&K, &V) {
2164 /// Gets a mutable reference to the key and value in the entry.
2165 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2166 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2167 self.elem.read_mut()
2170 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2171 /// with a lifetime bound to the map itself.
2172 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2173 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2174 self.elem.into_mut_refs()
2177 /// Sets the value of the entry, and returns the entry's old value.
2178 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2179 pub fn insert(&mut self, value: V) -> V {
2180 mem::replace(self.get_mut(), value)
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_key(&mut self, key: K) -> K {
2186 mem::replace(self.key_mut(), key)
2189 /// Takes the value out of the entry, and returns it.
2190 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2191 pub fn remove(self) -> V {
2192 pop_internal(self.elem).1
2195 /// Take the ownership of the key and value from the map.
2196 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2197 pub fn remove_entry(self) -> (K, V) {
2198 let (k, v, _) = pop_internal(self.elem);
2203 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2204 /// Sets the value of the entry with the VacantEntry's key,
2205 /// and returns a mutable reference to it.
2206 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2207 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2211 let mut hasher = self.hash_builder.build_hasher();
2212 key.hash(&mut hasher);
2213 self.insert_hashed_nocheck(hasher.finish(), key, value)
2216 /// Sets the value of the entry with the VacantEntry's key,
2217 /// and returns a mutable reference to it.
2218 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2219 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2220 let hash = SafeHash::new(hash);
2221 let b = match self.elem {
2222 NeqElem(mut bucket, disp) => {
2223 if disp >= DISPLACEMENT_THRESHOLD {
2224 bucket.table_mut().set_tag(true);
2226 robin_hood(bucket, disp, hash, key, value)
2228 NoElem(mut bucket, disp) => {
2229 if disp >= DISPLACEMENT_THRESHOLD {
2230 bucket.table_mut().set_tag(true);
2232 bucket.put(hash, key, value)
2239 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2240 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2241 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2242 f.debug_struct("RawEntryBuilder")
2247 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2248 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2249 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2251 RawEntryMut::Vacant(ref v) => {
2252 f.debug_tuple("RawEntry")
2256 RawEntryMut::Occupied(ref o) => {
2257 f.debug_tuple("RawEntry")
2265 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2266 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2268 f.debug_struct("RawOccupiedEntryMut")
2269 .field("key", self.key())
2270 .field("value", self.get())
2275 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2276 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2277 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2278 f.debug_struct("RawVacantEntryMut")
2283 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2284 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2285 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2286 f.debug_struct("RawEntryBuilder")
2291 /// A view into a single entry in a map, which may either be vacant or occupied.
2293 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2295 /// [`HashMap`]: struct.HashMap.html
2296 /// [`entry`]: struct.HashMap.html#method.entry
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 pub enum Entry<'a, K: 'a, V: 'a> {
2299 /// An occupied entry.
2300 #[stable(feature = "rust1", since = "1.0.0")]
2301 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2302 OccupiedEntry<'a, K, V>),
2305 #[stable(feature = "rust1", since = "1.0.0")]
2306 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2307 VacantEntry<'a, K, V>),
2310 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2311 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2315 f.debug_tuple("Entry")
2319 Occupied(ref o) => {
2320 f.debug_tuple("Entry")
2328 /// A view into an occupied entry in a `HashMap`.
2329 /// It is part of the [`Entry`] enum.
2331 /// [`Entry`]: enum.Entry.html
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2335 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2338 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2339 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2341 f.debug_struct("OccupiedEntry")
2342 .field("key", self.key())
2343 .field("value", self.get())
2348 /// A view into a vacant entry in a `HashMap`.
2349 /// It is part of the [`Entry`] enum.
2351 /// [`Entry`]: enum.Entry.html
2352 #[stable(feature = "rust1", since = "1.0.0")]
2353 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2356 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2359 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2360 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2362 f.debug_tuple("VacantEntry")
2368 /// Possible states of a VacantEntry.
2369 enum VacantEntryState<K, V, M> {
2370 /// The index is occupied, but the key to insert has precedence,
2371 /// and will kick the current one out on insertion.
2372 NeqElem(FullBucket<K, V, M>, usize),
2373 /// The index is genuinely vacant.
2374 NoElem(EmptyBucket<K, V, M>, usize),
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2382 type Item = (&'a K, &'a V);
2383 type IntoIter = Iter<'a, K, V>;
2385 fn into_iter(self) -> Iter<'a, K, V> {
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2395 type Item = (&'a K, &'a mut V);
2396 type IntoIter = IterMut<'a, K, V>;
2398 fn into_iter(self) -> IterMut<'a, K, V> {
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2409 type IntoIter = IntoIter<K, V>;
2411 /// Creates a consuming iterator, that is, one that moves each key-value
2412 /// pair out of the map in arbitrary order. The map cannot be used after
2418 /// use std::collections::HashMap;
2420 /// let mut map = HashMap::new();
2421 /// map.insert("a", 1);
2422 /// map.insert("b", 2);
2423 /// map.insert("c", 3);
2425 /// // Not possible with .iter()
2426 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2428 fn into_iter(self) -> IntoIter<K, V> {
2429 IntoIter { inner: self.table.into_iter() }
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2435 type Item = (&'a K, &'a V);
2438 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2442 fn size_hint(&self) -> (usize, Option<usize>) {
2443 self.inner.size_hint()
2446 #[stable(feature = "rust1", since = "1.0.0")]
2447 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2449 fn len(&self) -> usize {
2454 #[stable(feature = "fused", since = "1.26.0")]
2455 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2459 type Item = (&'a K, &'a mut V);
2462 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2466 fn size_hint(&self) -> (usize, Option<usize>) {
2467 self.inner.size_hint()
2470 #[stable(feature = "rust1", since = "1.0.0")]
2471 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2473 fn len(&self) -> usize {
2477 #[stable(feature = "fused", since = "1.26.0")]
2478 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2480 #[stable(feature = "std_debug", since = "1.16.0")]
2481 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2482 where K: fmt::Debug,
2485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2487 .entries(self.inner.iter())
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl<K, V> Iterator for IntoIter<K, V> {
2497 fn next(&mut self) -> Option<(K, V)> {
2498 self.inner.next().map(|(_, k, v)| (k, v))
2501 fn size_hint(&self) -> (usize, Option<usize>) {
2502 self.inner.size_hint()
2505 #[stable(feature = "rust1", since = "1.0.0")]
2506 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2508 fn len(&self) -> usize {
2512 #[stable(feature = "fused", since = "1.26.0")]
2513 impl<K, V> FusedIterator for IntoIter<K, V> {}
2515 #[stable(feature = "std_debug", since = "1.16.0")]
2516 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2519 .entries(self.inner.iter())
2524 #[stable(feature = "rust1", since = "1.0.0")]
2525 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2529 fn next(&mut self) -> Option<(&'a K)> {
2530 self.inner.next().map(|(k, _)| k)
2533 fn size_hint(&self) -> (usize, Option<usize>) {
2534 self.inner.size_hint()
2537 #[stable(feature = "rust1", since = "1.0.0")]
2538 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2540 fn len(&self) -> usize {
2544 #[stable(feature = "fused", since = "1.26.0")]
2545 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<'a, K, V> Iterator for Values<'a, K, V> {
2552 fn next(&mut self) -> Option<(&'a V)> {
2553 self.inner.next().map(|(_, v)| v)
2556 fn size_hint(&self) -> (usize, Option<usize>) {
2557 self.inner.size_hint()
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2563 fn len(&self) -> usize {
2567 #[stable(feature = "fused", since = "1.26.0")]
2568 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2570 #[stable(feature = "map_values_mut", since = "1.10.0")]
2571 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2572 type Item = &'a mut V;
2575 fn next(&mut self) -> Option<(&'a mut V)> {
2576 self.inner.next().map(|(_, v)| v)
2579 fn size_hint(&self) -> (usize, Option<usize>) {
2580 self.inner.size_hint()
2583 #[stable(feature = "map_values_mut", since = "1.10.0")]
2584 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2586 fn len(&self) -> usize {
2590 #[stable(feature = "fused", since = "1.26.0")]
2591 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2593 #[stable(feature = "std_debug", since = "1.16.0")]
2594 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2595 where K: fmt::Debug,
2598 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2600 .entries(self.inner.inner.iter())
2605 #[stable(feature = "drain", since = "1.6.0")]
2606 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2610 fn next(&mut self) -> Option<(K, V)> {
2611 self.inner.next().map(|(_, k, v)| (k, v))
2614 fn size_hint(&self) -> (usize, Option<usize>) {
2615 self.inner.size_hint()
2618 #[stable(feature = "drain", since = "1.6.0")]
2619 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2621 fn len(&self) -> usize {
2625 #[stable(feature = "fused", since = "1.26.0")]
2626 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2628 #[stable(feature = "std_debug", since = "1.16.0")]
2629 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2630 where K: fmt::Debug,
2633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2635 .entries(self.inner.iter())
2640 impl<'a, K, V> Entry<'a, K, V> {
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 /// Ensures a value is in the entry by inserting the default if empty, and returns
2643 /// a mutable reference to the value in the entry.
2648 /// use std::collections::HashMap;
2650 /// let mut map: HashMap<&str, u32> = HashMap::new();
2652 /// map.entry("poneyland").or_insert(3);
2653 /// assert_eq!(map["poneyland"], 3);
2655 /// *map.entry("poneyland").or_insert(10) *= 2;
2656 /// assert_eq!(map["poneyland"], 6);
2658 pub fn or_insert(self, default: V) -> &'a mut V {
2660 Occupied(entry) => entry.into_mut(),
2661 Vacant(entry) => entry.insert(default),
2665 #[stable(feature = "rust1", since = "1.0.0")]
2666 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2667 /// and returns a mutable reference to the value in the entry.
2672 /// use std::collections::HashMap;
2674 /// let mut map: HashMap<&str, String> = HashMap::new();
2675 /// let s = "hoho".to_string();
2677 /// map.entry("poneyland").or_insert_with(|| s);
2679 /// assert_eq!(map["poneyland"], "hoho".to_string());
2681 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2683 Occupied(entry) => entry.into_mut(),
2684 Vacant(entry) => entry.insert(default()),
2688 /// Returns a reference to this entry's key.
2693 /// use std::collections::HashMap;
2695 /// let mut map: HashMap<&str, u32> = HashMap::new();
2696 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2698 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2699 pub fn key(&self) -> &K {
2701 Occupied(ref entry) => entry.key(),
2702 Vacant(ref entry) => entry.key(),
2706 /// Provides in-place mutable access to an occupied entry before any
2707 /// potential inserts into the map.
2712 /// use std::collections::HashMap;
2714 /// let mut map: HashMap<&str, u32> = HashMap::new();
2716 /// map.entry("poneyland")
2717 /// .and_modify(|e| { *e += 1 })
2719 /// assert_eq!(map["poneyland"], 42);
2721 /// map.entry("poneyland")
2722 /// .and_modify(|e| { *e += 1 })
2724 /// assert_eq!(map["poneyland"], 43);
2726 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2727 pub fn and_modify<F>(self, f: F) -> Self
2728 where F: FnOnce(&mut V)
2731 Occupied(mut entry) => {
2735 Vacant(entry) => Vacant(entry),
2741 impl<'a, K, V: Default> Entry<'a, K, V> {
2742 #[stable(feature = "entry_or_default", since = "1.28.0")]
2743 /// Ensures a value is in the entry by inserting the default value if empty,
2744 /// and returns a mutable reference to the value in the entry.
2750 /// use std::collections::HashMap;
2752 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2753 /// map.entry("poneyland").or_default();
2755 /// assert_eq!(map["poneyland"], None);
2758 pub fn or_default(self) -> &'a mut V {
2760 Occupied(entry) => entry.into_mut(),
2761 Vacant(entry) => entry.insert(Default::default()),
2766 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2767 /// Gets a reference to the key in the entry.
2772 /// use std::collections::HashMap;
2774 /// let mut map: HashMap<&str, u32> = HashMap::new();
2775 /// map.entry("poneyland").or_insert(12);
2776 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2778 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2779 pub fn key(&self) -> &K {
2783 /// Take the ownership of the key and value from the map.
2788 /// use std::collections::HashMap;
2789 /// use std::collections::hash_map::Entry;
2791 /// let mut map: HashMap<&str, u32> = HashMap::new();
2792 /// map.entry("poneyland").or_insert(12);
2794 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2795 /// // We delete the entry from the map.
2796 /// o.remove_entry();
2799 /// assert_eq!(map.contains_key("poneyland"), false);
2801 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2802 pub fn remove_entry(self) -> (K, V) {
2803 let (k, v, _) = pop_internal(self.elem);
2807 /// Gets a reference to the value in the entry.
2812 /// use std::collections::HashMap;
2813 /// use std::collections::hash_map::Entry;
2815 /// let mut map: HashMap<&str, u32> = HashMap::new();
2816 /// map.entry("poneyland").or_insert(12);
2818 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2819 /// assert_eq!(o.get(), &12);
2822 #[stable(feature = "rust1", since = "1.0.0")]
2823 pub fn get(&self) -> &V {
2827 /// Gets a mutable reference to the value in the entry.
2829 /// If you need a reference to the `OccupiedEntry` which may outlive the
2830 /// destruction of the `Entry` value, see [`into_mut`].
2832 /// [`into_mut`]: #method.into_mut
2837 /// use std::collections::HashMap;
2838 /// use std::collections::hash_map::Entry;
2840 /// let mut map: HashMap<&str, u32> = HashMap::new();
2841 /// map.entry("poneyland").or_insert(12);
2843 /// assert_eq!(map["poneyland"], 12);
2844 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2845 /// *o.get_mut() += 10;
2846 /// assert_eq!(*o.get(), 22);
2848 /// // We can use the same Entry multiple times.
2849 /// *o.get_mut() += 2;
2852 /// assert_eq!(map["poneyland"], 24);
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub fn get_mut(&mut self) -> &mut V {
2856 self.elem.read_mut().1
2859 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2860 /// with a lifetime bound to the map itself.
2862 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2864 /// [`get_mut`]: #method.get_mut
2869 /// use std::collections::HashMap;
2870 /// use std::collections::hash_map::Entry;
2872 /// let mut map: HashMap<&str, u32> = HashMap::new();
2873 /// map.entry("poneyland").or_insert(12);
2875 /// assert_eq!(map["poneyland"], 12);
2876 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2877 /// *o.into_mut() += 10;
2880 /// assert_eq!(map["poneyland"], 22);
2882 #[stable(feature = "rust1", since = "1.0.0")]
2883 pub fn into_mut(self) -> &'a mut V {
2884 self.elem.into_mut_refs().1
2887 /// Sets the value of the entry, and returns the entry's old value.
2892 /// use std::collections::HashMap;
2893 /// use std::collections::hash_map::Entry;
2895 /// let mut map: HashMap<&str, u32> = HashMap::new();
2896 /// map.entry("poneyland").or_insert(12);
2898 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2899 /// assert_eq!(o.insert(15), 12);
2902 /// assert_eq!(map["poneyland"], 15);
2904 #[stable(feature = "rust1", since = "1.0.0")]
2905 pub fn insert(&mut self, mut value: V) -> V {
2906 let old_value = self.get_mut();
2907 mem::swap(&mut value, old_value);
2911 /// Takes the value out of the entry, and returns it.
2916 /// use std::collections::HashMap;
2917 /// use std::collections::hash_map::Entry;
2919 /// let mut map: HashMap<&str, u32> = HashMap::new();
2920 /// map.entry("poneyland").or_insert(12);
2922 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2923 /// assert_eq!(o.remove(), 12);
2926 /// assert_eq!(map.contains_key("poneyland"), false);
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 pub fn remove(self) -> V {
2930 pop_internal(self.elem).1
2933 /// Returns a key that was used for search.
2935 /// The key was retained for further use.
2936 fn take_key(&mut self) -> Option<K> {
2940 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2941 /// the key used to create this entry.
2946 /// #![feature(map_entry_replace)]
2947 /// use std::collections::hash_map::{Entry, HashMap};
2948 /// use std::rc::Rc;
2950 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2951 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2953 /// let my_key = Rc::new("Stringthing".to_string());
2955 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2956 /// // Also replace the key with a handle to our other key.
2957 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2961 #[unstable(feature = "map_entry_replace", issue = "44286")]
2962 pub fn replace_entry(mut self, value: V) -> (K, V) {
2963 let (old_key, old_value) = self.elem.read_mut();
2965 let old_key = mem::replace(old_key, self.key.unwrap());
2966 let old_value = mem::replace(old_value, value);
2968 (old_key, old_value)
2971 /// Replaces the key in the hash map with the key used to create this entry.
2976 /// #![feature(map_entry_replace)]
2977 /// use std::collections::hash_map::{Entry, HashMap};
2978 /// use std::rc::Rc;
2980 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2981 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2983 /// // Initialise known strings, run program, etc.
2985 /// reclaim_memory(&mut map, &known_strings);
2987 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2988 /// for s in known_strings {
2989 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2990 /// // Replaces the entry's key with our version of it in `known_strings`.
2991 /// entry.replace_key();
2996 #[unstable(feature = "map_entry_replace", issue = "44286")]
2997 pub fn replace_key(mut self) -> K {
2998 let (old_key, _) = self.elem.read_mut();
2999 mem::replace(old_key, self.key.unwrap())
3003 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3004 /// Gets a reference to the key that would be used when inserting a value
3005 /// through the `VacantEntry`.
3010 /// use std::collections::HashMap;
3012 /// let mut map: HashMap<&str, u32> = HashMap::new();
3013 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3015 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3016 pub fn key(&self) -> &K {
3020 /// Take ownership of the key.
3025 /// use std::collections::HashMap;
3026 /// use std::collections::hash_map::Entry;
3028 /// let mut map: HashMap<&str, u32> = HashMap::new();
3030 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3034 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3035 pub fn into_key(self) -> K {
3039 /// Sets the value of the entry with the VacantEntry's key,
3040 /// and returns a mutable reference to it.
3045 /// use std::collections::HashMap;
3046 /// use std::collections::hash_map::Entry;
3048 /// let mut map: HashMap<&str, u32> = HashMap::new();
3050 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3053 /// assert_eq!(map["poneyland"], 37);
3055 #[stable(feature = "rust1", since = "1.0.0")]
3056 pub fn insert(self, value: V) -> &'a mut V {
3057 let b = match self.elem {
3058 NeqElem(mut bucket, disp) => {
3059 if disp >= DISPLACEMENT_THRESHOLD {
3060 bucket.table_mut().set_tag(true);
3062 robin_hood(bucket, disp, self.hash, self.key, value)
3064 NoElem(mut bucket, disp) => {
3065 if disp >= DISPLACEMENT_THRESHOLD {
3066 bucket.table_mut().set_tag(true);
3068 bucket.put(self.hash, self.key, value)
3075 #[stable(feature = "rust1", since = "1.0.0")]
3076 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3078 S: BuildHasher + Default
3080 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3081 let mut map = HashMap::with_hasher(Default::default());
3087 #[stable(feature = "rust1", since = "1.0.0")]
3088 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3092 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3093 // Keys may be already present or show multiple times in the iterator.
3094 // Reserve the entire hint lower bound if the map is empty.
3095 // Otherwise reserve half the hint (rounded up), so the map
3096 // will only resize twice in the worst case.
3097 let iter = iter.into_iter();
3098 let reserve = if self.is_empty() {
3101 (iter.size_hint().0 + 1) / 2
3103 self.reserve(reserve);
3104 for (k, v) in iter {
3110 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3111 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3112 where K: Eq + Hash + Copy,
3116 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3117 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3121 /// `RandomState` is the default state for [`HashMap`] types.
3123 /// A particular instance `RandomState` will create the same instances of
3124 /// [`Hasher`], but the hashers created by two different `RandomState`
3125 /// instances are unlikely to produce the same result for the same values.
3127 /// [`HashMap`]: struct.HashMap.html
3128 /// [`Hasher`]: ../../hash/trait.Hasher.html
3133 /// use std::collections::HashMap;
3134 /// use std::collections::hash_map::RandomState;
3136 /// let s = RandomState::new();
3137 /// let mut map = HashMap::with_hasher(s);
3138 /// map.insert(1, 2);
3141 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3142 pub struct RandomState {
3148 /// Constructs a new `RandomState` that is initialized with random keys.
3153 /// use std::collections::hash_map::RandomState;
3155 /// let s = RandomState::new();
3158 #[allow(deprecated)]
3160 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3161 pub fn new() -> RandomState {
3162 // Historically this function did not cache keys from the OS and instead
3163 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3164 // was discovered, however, that because we re-seed the thread-local RNG
3165 // from the OS periodically that this can cause excessive slowdown when
3166 // many hash maps are created on a thread. To solve this performance
3167 // trap we cache the first set of randomly generated keys per-thread.
3169 // Later in #36481 it was discovered that exposing a deterministic
3170 // iteration order allows a form of DOS attack. To counter that we
3171 // increment one of the seeds on every RandomState creation, giving
3172 // every corresponding HashMap a different iteration order.
3173 thread_local!(static KEYS: Cell<(u64, u64)> = {
3174 Cell::new(sys::hashmap_random_keys())
3178 let (k0, k1) = keys.get();
3179 keys.set((k0.wrapping_add(1), k1));
3180 RandomState { k0: k0, k1: k1 }
3185 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3186 impl BuildHasher for RandomState {
3187 type Hasher = DefaultHasher;
3189 #[allow(deprecated)]
3190 fn build_hasher(&self) -> DefaultHasher {
3191 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3195 /// The default [`Hasher`] used by [`RandomState`].
3197 /// The internal algorithm is not specified, and so it and its hashes should
3198 /// not be relied upon over releases.
3200 /// [`RandomState`]: struct.RandomState.html
3201 /// [`Hasher`]: ../../hash/trait.Hasher.html
3202 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3203 #[allow(deprecated)]
3204 #[derive(Clone, Debug)]
3205 pub struct DefaultHasher(SipHasher13);
3207 impl DefaultHasher {
3208 /// Creates a new `DefaultHasher`.
3210 /// This hasher is not guaranteed to be the same as all other
3211 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3212 /// instances created through `new` or `default`.
3213 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3214 #[allow(deprecated)]
3215 pub fn new() -> DefaultHasher {
3216 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3220 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3221 impl Default for DefaultHasher {
3222 /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3223 /// See its documentation for more.
3224 fn default() -> DefaultHasher {
3225 DefaultHasher::new()
3229 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3230 impl Hasher for DefaultHasher {
3232 fn write(&mut self, msg: &[u8]) {
3237 fn finish(&self) -> u64 {
3242 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3243 impl Default for RandomState {
3244 /// Constructs a new `RandomState`.
3246 fn default() -> RandomState {
3251 #[stable(feature = "std_debug", since = "1.16.0")]
3252 impl fmt::Debug for RandomState {
3253 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3254 f.pad("RandomState { .. }")
3258 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3259 where K: Eq + Hash + Borrow<Q>,
3266 fn get(&self, key: &Q) -> Option<&K> {
3267 self.search(key).map(|bucket| bucket.into_refs().0)
3270 fn take(&mut self, key: &Q) -> Option<K> {
3271 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3275 fn replace(&mut self, key: K) -> Option<K> {
3278 match self.entry(key) {
3279 Occupied(mut occupied) => {
3280 let key = occupied.take_key().unwrap();
3281 Some(mem::replace(occupied.elem.read_mut().0, key))
3292 fn assert_covariance() {
3293 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3296 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3299 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3302 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3305 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3308 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3311 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3314 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3317 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3320 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3323 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3324 -> Drain<'new, &'new str, &'new str> {
3332 use super::Entry::{Occupied, Vacant};
3333 use super::RandomState;
3335 use rand::{thread_rng, Rng};
3336 use realstd::collections::CollectionAllocErr::*;
3337 use realstd::mem::size_of;
3341 fn test_zero_capacities() {
3342 type HM = HashMap<i32, i32>;
3345 assert_eq!(m.capacity(), 0);
3347 let m = HM::default();
3348 assert_eq!(m.capacity(), 0);
3350 let m = HM::with_hasher(RandomState::new());
3351 assert_eq!(m.capacity(), 0);
3353 let m = HM::with_capacity(0);
3354 assert_eq!(m.capacity(), 0);
3356 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3357 assert_eq!(m.capacity(), 0);
3359 let mut m = HM::new();
3365 assert_eq!(m.capacity(), 0);
3367 let mut m = HM::new();
3369 assert_eq!(m.capacity(), 0);
3373 fn test_create_capacity_zero() {
3374 let mut m = HashMap::with_capacity(0);
3376 assert!(m.insert(1, 1).is_none());
3378 assert!(m.contains_key(&1));
3379 assert!(!m.contains_key(&0));
3384 let mut m = HashMap::new();
3385 assert_eq!(m.len(), 0);
3386 assert!(m.insert(1, 2).is_none());
3387 assert_eq!(m.len(), 1);
3388 assert!(m.insert(2, 4).is_none());
3389 assert_eq!(m.len(), 2);
3390 assert_eq!(*m.get(&1).unwrap(), 2);
3391 assert_eq!(*m.get(&2).unwrap(), 4);
3396 let mut m = HashMap::new();
3397 assert_eq!(m.len(), 0);
3398 assert!(m.insert(1, 2).is_none());
3399 assert_eq!(m.len(), 1);
3400 assert!(m.insert(2, 4).is_none());
3401 assert_eq!(m.len(), 2);
3403 assert_eq!(*m2.get(&1).unwrap(), 2);
3404 assert_eq!(*m2.get(&2).unwrap(), 4);
3405 assert_eq!(m2.len(), 2);
3408 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3410 #[derive(Hash, PartialEq, Eq)]
3416 fn new(k: usize) -> Droppable {
3417 DROP_VECTOR.with(|slot| {
3418 slot.borrow_mut()[k] += 1;
3425 impl Drop for Droppable {
3426 fn drop(&mut self) {
3427 DROP_VECTOR.with(|slot| {
3428 slot.borrow_mut()[self.k] -= 1;
3433 impl Clone for Droppable {
3434 fn clone(&self) -> Droppable {
3435 Droppable::new(self.k)
3441 DROP_VECTOR.with(|slot| {
3442 *slot.borrow_mut() = vec![0; 200];
3446 let mut m = HashMap::new();
3448 DROP_VECTOR.with(|v| {
3450 assert_eq!(v.borrow()[i], 0);
3455 let d1 = Droppable::new(i);
3456 let d2 = Droppable::new(i + 100);
3460 DROP_VECTOR.with(|v| {
3462 assert_eq!(v.borrow()[i], 1);
3467 let k = Droppable::new(i);
3468 let v = m.remove(&k);
3470 assert!(v.is_some());
3472 DROP_VECTOR.with(|v| {
3473 assert_eq!(v.borrow()[i], 1);
3474 assert_eq!(v.borrow()[i+100], 1);
3478 DROP_VECTOR.with(|v| {
3480 assert_eq!(v.borrow()[i], 0);
3481 assert_eq!(v.borrow()[i+100], 0);
3485 assert_eq!(v.borrow()[i], 1);
3486 assert_eq!(v.borrow()[i+100], 1);
3491 DROP_VECTOR.with(|v| {
3493 assert_eq!(v.borrow()[i], 0);
3499 fn test_into_iter_drops() {
3500 DROP_VECTOR.with(|v| {
3501 *v.borrow_mut() = vec![0; 200];
3505 let mut hm = HashMap::new();
3507 DROP_VECTOR.with(|v| {
3509 assert_eq!(v.borrow()[i], 0);
3514 let d1 = Droppable::new(i);
3515 let d2 = Droppable::new(i + 100);
3519 DROP_VECTOR.with(|v| {
3521 assert_eq!(v.borrow()[i], 1);
3528 // By the way, ensure that cloning doesn't screw up the dropping.
3532 let mut half = hm.into_iter().take(50);
3534 DROP_VECTOR.with(|v| {
3536 assert_eq!(v.borrow()[i], 1);
3540 for _ in half.by_ref() {}
3542 DROP_VECTOR.with(|v| {
3544 .filter(|&i| v.borrow()[i] == 1)
3548 .filter(|&i| v.borrow()[i + 100] == 1)
3556 DROP_VECTOR.with(|v| {
3558 assert_eq!(v.borrow()[i], 0);
3564 fn test_empty_remove() {
3565 let mut m: HashMap<i32, bool> = HashMap::new();
3566 assert_eq!(m.remove(&0), None);
3570 fn test_empty_entry() {
3571 let mut m: HashMap<i32, bool> = HashMap::new();
3573 Occupied(_) => panic!(),
3576 assert!(*m.entry(0).or_insert(true));
3577 assert_eq!(m.len(), 1);
3581 fn test_empty_iter() {
3582 let mut m: HashMap<i32, bool> = HashMap::new();
3583 assert_eq!(m.drain().next(), None);
3584 assert_eq!(m.keys().next(), None);
3585 assert_eq!(m.values().next(), None);
3586 assert_eq!(m.values_mut().next(), None);
3587 assert_eq!(m.iter().next(), None);
3588 assert_eq!(m.iter_mut().next(), None);
3589 assert_eq!(m.len(), 0);
3590 assert!(m.is_empty());
3591 assert_eq!(m.into_iter().next(), None);
3595 fn test_lots_of_insertions() {
3596 let mut m = HashMap::new();
3598 // Try this a few times to make sure we never screw up the hashmap's
3601 assert!(m.is_empty());
3604 assert!(m.insert(i, i).is_none());
3608 assert_eq!(r, Some(&j));
3611 for j in i + 1..1001 {
3613 assert_eq!(r, None);
3617 for i in 1001..2001 {
3618 assert!(!m.contains_key(&i));
3623 assert!(m.remove(&i).is_some());
3626 assert!(!m.contains_key(&j));
3629 for j in i + 1..1001 {
3630 assert!(m.contains_key(&j));
3635 assert!(!m.contains_key(&i));
3639 assert!(m.insert(i, i).is_none());
3643 for i in (1..1001).rev() {
3644 assert!(m.remove(&i).is_some());
3647 assert!(!m.contains_key(&j));
3651 assert!(m.contains_key(&j));
3658 fn test_find_mut() {
3659 let mut m = HashMap::new();
3660 assert!(m.insert(1, 12).is_none());
3661 assert!(m.insert(2, 8).is_none());
3662 assert!(m.insert(5, 14).is_none());
3664 match m.get_mut(&5) {
3666 Some(x) => *x = new,
3668 assert_eq!(m.get(&5), Some(&new));
3672 fn test_insert_overwrite() {
3673 let mut m = HashMap::new();
3674 assert!(m.insert(1, 2).is_none());
3675 assert_eq!(*m.get(&1).unwrap(), 2);
3676 assert!(!m.insert(1, 3).is_none());
3677 assert_eq!(*m.get(&1).unwrap(), 3);
3681 fn test_insert_conflicts() {
3682 let mut m = HashMap::with_capacity(4);
3683 assert!(m.insert(1, 2).is_none());
3684 assert!(m.insert(5, 3).is_none());
3685 assert!(m.insert(9, 4).is_none());
3686 assert_eq!(*m.get(&9).unwrap(), 4);
3687 assert_eq!(*m.get(&5).unwrap(), 3);
3688 assert_eq!(*m.get(&1).unwrap(), 2);
3692 fn test_conflict_remove() {
3693 let mut m = HashMap::with_capacity(4);
3694 assert!(m.insert(1, 2).is_none());
3695 assert_eq!(*m.get(&1).unwrap(), 2);
3696 assert!(m.insert(5, 3).is_none());
3697 assert_eq!(*m.get(&1).unwrap(), 2);
3698 assert_eq!(*m.get(&5).unwrap(), 3);
3699 assert!(m.insert(9, 4).is_none());
3700 assert_eq!(*m.get(&1).unwrap(), 2);
3701 assert_eq!(*m.get(&5).unwrap(), 3);
3702 assert_eq!(*m.get(&9).unwrap(), 4);
3703 assert!(m.remove(&1).is_some());
3704 assert_eq!(*m.get(&9).unwrap(), 4);
3705 assert_eq!(*m.get(&5).unwrap(), 3);
3709 fn test_is_empty() {
3710 let mut m = HashMap::with_capacity(4);
3711 assert!(m.insert(1, 2).is_none());
3712 assert!(!m.is_empty());
3713 assert!(m.remove(&1).is_some());
3714 assert!(m.is_empty());
3719 let mut m = HashMap::new();
3721 assert_eq!(m.remove(&1), Some(2));
3722 assert_eq!(m.remove(&1), None);
3726 fn test_remove_entry() {
3727 let mut m = HashMap::new();
3729 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3730 assert_eq!(m.remove(&1), None);
3735 let mut m = HashMap::with_capacity(4);
3737 assert!(m.insert(i, i*2).is_none());
3739 assert_eq!(m.len(), 32);
3741 let mut observed: u32 = 0;
3744 assert_eq!(*v, *k * 2);
3745 observed |= 1 << *k;
3747 assert_eq!(observed, 0xFFFF_FFFF);
3752 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3753 let map: HashMap<_, _> = vec.into_iter().collect();
3754 let keys: Vec<_> = map.keys().cloned().collect();
3755 assert_eq!(keys.len(), 3);
3756 assert!(keys.contains(&1));
3757 assert!(keys.contains(&2));
3758 assert!(keys.contains(&3));
3763 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3764 let map: HashMap<_, _> = vec.into_iter().collect();
3765 let values: Vec<_> = map.values().cloned().collect();
3766 assert_eq!(values.len(), 3);
3767 assert!(values.contains(&'a'));
3768 assert!(values.contains(&'b'));
3769 assert!(values.contains(&'c'));
3773 fn test_values_mut() {
3774 let vec = vec![(1, 1), (2, 2), (3, 3)];
3775 let mut map: HashMap<_, _> = vec.into_iter().collect();
3776 for value in map.values_mut() {
3777 *value = (*value) * 2
3779 let values: Vec<_> = map.values().cloned().collect();
3780 assert_eq!(values.len(), 3);
3781 assert!(values.contains(&2));
3782 assert!(values.contains(&4));
3783 assert!(values.contains(&6));
3788 let mut m = HashMap::new();
3789 assert!(m.get(&1).is_none());
3793 Some(v) => assert_eq!(*v, 2),
3799 let mut m1 = HashMap::new();
3804 let mut m2 = HashMap::new();
3817 let mut map = HashMap::new();
3818 let empty: HashMap<i32, i32> = HashMap::new();
3823 let map_str = format!("{:?}", map);
3825 assert!(map_str == "{1: 2, 3: 4}" ||
3826 map_str == "{3: 4, 1: 2}");
3827 assert_eq!(format!("{:?}", empty), "{}");
3832 let mut m = HashMap::new();
3834 assert_eq!(m.len(), 0);
3835 assert!(m.is_empty());
3838 let old_raw_cap = m.raw_capacity();
3839 while old_raw_cap == m.raw_capacity() {
3844 assert_eq!(m.len(), i);
3845 assert!(!m.is_empty());
3849 fn test_behavior_resize_policy() {
3850 let mut m = HashMap::new();
3852 assert_eq!(m.len(), 0);
3853 assert_eq!(m.raw_capacity(), 0);
3854 assert!(m.is_empty());
3858 assert!(m.is_empty());
3859 let initial_raw_cap = m.raw_capacity();
3860 m.reserve(initial_raw_cap);
3861 let raw_cap = m.raw_capacity();
3863 assert_eq!(raw_cap, initial_raw_cap * 2);
3866 for _ in 0..raw_cap * 3 / 4 {
3870 // three quarters full
3872 assert_eq!(m.len(), i);
3873 assert_eq!(m.raw_capacity(), raw_cap);
3875 for _ in 0..raw_cap / 4 {
3881 let new_raw_cap = m.raw_capacity();
3882 assert_eq!(new_raw_cap, raw_cap * 2);
3884 for _ in 0..raw_cap / 2 - 1 {
3887 assert_eq!(m.raw_capacity(), new_raw_cap);
3889 // A little more than one quarter full.
3891 assert_eq!(m.raw_capacity(), raw_cap);
3892 // again, a little more than half full
3893 for _ in 0..raw_cap / 2 - 1 {
3899 assert_eq!(m.len(), i);
3900 assert!(!m.is_empty());
3901 assert_eq!(m.raw_capacity(), initial_raw_cap);
3905 fn test_reserve_shrink_to_fit() {
3906 let mut m = HashMap::new();
3909 assert!(m.capacity() >= m.len());
3915 let usable_cap = m.capacity();
3916 for i in 128..(128 + 256) {
3918 assert_eq!(m.capacity(), usable_cap);
3921 for i in 100..(128 + 256) {
3922 assert_eq!(m.remove(&i), Some(i));
3926 assert_eq!(m.len(), 100);
3927 assert!(!m.is_empty());
3928 assert!(m.capacity() >= m.len());
3931 assert_eq!(m.remove(&i), Some(i));
3936 assert_eq!(m.len(), 1);
3937 assert!(m.capacity() >= m.len());
3938 assert_eq!(m.remove(&0), Some(0));
3942 fn test_from_iter() {
3943 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3945 let map: HashMap<_, _> = xs.iter().cloned().collect();
3947 for &(k, v) in &xs {
3948 assert_eq!(map.get(&k), Some(&v));
3953 fn test_size_hint() {
3954 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3956 let map: HashMap<_, _> = xs.iter().cloned().collect();
3958 let mut iter = map.iter();
3960 for _ in iter.by_ref().take(3) {}
3962 assert_eq!(iter.size_hint(), (3, Some(3)));
3966 fn test_iter_len() {
3967 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3969 let map: HashMap<_, _> = xs.iter().cloned().collect();
3971 let mut iter = map.iter();
3973 for _ in iter.by_ref().take(3) {}
3975 assert_eq!(iter.len(), 3);
3979 fn test_mut_size_hint() {
3980 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3982 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3984 let mut iter = map.iter_mut();
3986 for _ in iter.by_ref().take(3) {}
3988 assert_eq!(iter.size_hint(), (3, Some(3)));
3992 fn test_iter_mut_len() {
3993 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3995 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3997 let mut iter = map.iter_mut();
3999 for _ in iter.by_ref().take(3) {}
4001 assert_eq!(iter.len(), 3);
4006 let mut map = HashMap::new();
4012 assert_eq!(map[&2], 1);
4017 fn test_index_nonexistent() {
4018 let mut map = HashMap::new();
4029 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4031 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4033 // Existing key (insert)
4034 match map.entry(1) {
4035 Vacant(_) => unreachable!(),
4036 Occupied(mut view) => {
4037 assert_eq!(view.get(), &10);
4038 assert_eq!(view.insert(100), 10);
4041 assert_eq!(map.get(&1).unwrap(), &100);
4042 assert_eq!(map.len(), 6);
4045 // Existing key (update)
4046 match map.entry(2) {
4047 Vacant(_) => unreachable!(),
4048 Occupied(mut view) => {
4049 let v = view.get_mut();
4050 let new_v = (*v) * 10;
4054 assert_eq!(map.get(&2).unwrap(), &200);
4055 assert_eq!(map.len(), 6);
4057 // Existing key (take)
4058 match map.entry(3) {
4059 Vacant(_) => unreachable!(),
4061 assert_eq!(view.remove(), 30);
4064 assert_eq!(map.get(&3), None);
4065 assert_eq!(map.len(), 5);
4068 // Inexistent key (insert)
4069 match map.entry(10) {
4070 Occupied(_) => unreachable!(),
4072 assert_eq!(*view.insert(1000), 1000);
4075 assert_eq!(map.get(&10).unwrap(), &1000);
4076 assert_eq!(map.len(), 6);
4080 fn test_entry_take_doesnt_corrupt() {
4081 #![allow(deprecated)] //rand
4083 fn check(m: &HashMap<i32, ()>) {
4085 assert!(m.contains_key(k),
4086 "{} is in keys() but not in the map?", k);
4090 let mut m = HashMap::new();
4091 let mut rng = thread_rng();
4093 // Populate the map with some items.
4095 let x = rng.gen_range(-10, 10);
4100 let x = rng.gen_range(-10, 10);
4113 fn test_extend_ref() {
4114 let mut a = HashMap::new();
4116 let mut b = HashMap::new();
4118 b.insert(3, "three");
4122 assert_eq!(a.len(), 3);
4123 assert_eq!(a[&1], "one");
4124 assert_eq!(a[&2], "two");
4125 assert_eq!(a[&3], "three");
4129 fn test_capacity_not_less_than_len() {
4130 let mut a = HashMap::new();
4138 assert!(a.capacity() > a.len());
4140 let free = a.capacity() - a.len();
4146 assert_eq!(a.len(), a.capacity());
4148 // Insert at capacity should cause allocation.
4150 assert!(a.capacity() > a.len());
4154 fn test_occupied_entry_key() {
4155 let mut a = HashMap::new();
4156 let key = "hello there";
4157 let value = "value goes here";
4158 assert!(a.is_empty());
4159 a.insert(key.clone(), value.clone());
4160 assert_eq!(a.len(), 1);
4161 assert_eq!(a[key], value);
4163 match a.entry(key.clone()) {
4164 Vacant(_) => panic!(),
4165 Occupied(e) => assert_eq!(key, *e.key()),
4167 assert_eq!(a.len(), 1);
4168 assert_eq!(a[key], value);
4172 fn test_vacant_entry_key() {
4173 let mut a = HashMap::new();
4174 let key = "hello there";
4175 let value = "value goes here";
4177 assert!(a.is_empty());
4178 match a.entry(key.clone()) {
4179 Occupied(_) => panic!(),
4181 assert_eq!(key, *e.key());
4182 e.insert(value.clone());
4185 assert_eq!(a.len(), 1);
4186 assert_eq!(a[key], value);
4191 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4193 map.retain(|&k, _| k % 2 == 0);
4194 assert_eq!(map.len(), 50);
4195 assert_eq!(map[&2], 20);
4196 assert_eq!(map[&4], 40);
4197 assert_eq!(map[&6], 60);
4201 fn test_adaptive() {
4202 const TEST_LEN: usize = 5000;
4203 // by cloning we get maps with the same hasher seed
4204 let mut first = HashMap::new();
4205 let mut second = first.clone();
4206 first.extend((0..TEST_LEN).map(|i| (i, i)));
4207 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4209 for (&k, &v) in &second {
4210 let prev_cap = first.capacity();
4211 let expect_grow = first.len() == prev_cap;
4213 if !expect_grow && first.capacity() != prev_cap {
4217 panic!("Adaptive early resize failed");
4221 fn test_try_reserve() {
4223 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4225 const MAX_USIZE: usize = usize::MAX;
4227 // HashMap and RawTables use complicated size calculations
4228 // hashes_size is sizeof(HashUint) * capacity;
4229 // pairs_size is sizeof((K. V)) * capacity;
4230 // alignment_hashes_size is 8
4231 // alignment_pairs size is 4
4232 let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4233 // The following formula is used to calculate the new capacity
4234 let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4236 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4237 } else { panic!("usize::MAX should trigger an overflow!"); }
4239 if size_of::<usize>() < 8 {
4240 if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4241 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4243 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4244 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4249 fn test_raw_entry() {
4250 use super::RawEntryMut::{Occupied, Vacant};
4252 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4254 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4256 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4257 use core::hash::{BuildHasher, Hash, Hasher};
4259 let mut hasher = map.hasher().build_hasher();
4260 k.hash(&mut hasher);
4264 // Existing key (insert)
4265 match map.raw_entry_mut().from_key(&1) {
4266 Vacant(_) => unreachable!(),
4267 Occupied(mut view) => {
4268 assert_eq!(view.get(), &10);
4269 assert_eq!(view.insert(100), 10);
4272 let hash1 = compute_hash(&map, 1);
4273 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4274 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4275 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4276 assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4277 assert_eq!(map.len(), 6);
4279 // Existing key (update)
4280 match map.raw_entry_mut().from_key(&2) {
4281 Vacant(_) => unreachable!(),
4282 Occupied(mut view) => {
4283 let v = view.get_mut();
4284 let new_v = (*v) * 10;
4288 let hash2 = compute_hash(&map, 2);
4289 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4290 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4291 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4292 assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4293 assert_eq!(map.len(), 6);
4295 // Existing key (take)
4296 let hash3 = compute_hash(&map, 3);
4297 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4298 Vacant(_) => unreachable!(),
4300 assert_eq!(view.remove_entry(), (3, 30));
4303 assert_eq!(map.raw_entry().from_key(&3), None);
4304 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4305 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4306 assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4307 assert_eq!(map.len(), 5);
4310 // Nonexistent key (insert)
4311 match map.raw_entry_mut().from_key(&10) {
4312 Occupied(_) => unreachable!(),
4314 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4317 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4318 assert_eq!(map.len(), 6);
4320 // Ensure all lookup methods produce equivalent results.
4322 let hash = compute_hash(&map, k);
4323 let v = map.get(&k).cloned();
4324 let kv = v.as_ref().map(|v| (&k, v));
4326 assert_eq!(map.raw_entry().from_key(&k), kv);
4327 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4328 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4329 assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4331 match map.raw_entry_mut().from_key(&k) {
4332 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4333 Vacant(_) => assert_eq!(v, None),
4335 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
4336 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4337 Vacant(_) => assert_eq!(v, None),
4339 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
4340 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4341 Vacant(_) => assert_eq!(v, None),
4343 match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4344 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4345 Vacant(_) => assert_eq!(v, None),