2 use self::VacantEntryState::*;
4 use intrinsics::unlikely;
5 use collections::CollectionAllocErr;
9 use fmt::{self, Debug};
11 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
12 use iter::{FromIterator, FusedIterator};
13 use mem::{self, replace};
14 use ops::{Deref, DerefMut, Index};
17 use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
19 use super::table::BucketState::{Empty, Full};
20 use super::table::Fallibility::{Fallible, Infallible};
22 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
24 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
26 struct DefaultResizePolicy;
28 impl DefaultResizePolicy {
30 fn new() -> DefaultResizePolicy {
34 /// A hash map's "capacity" is the number of elements it can hold without
35 /// being resized. Its "raw capacity" is the number of slots required to
36 /// provide that capacity, accounting for maximum loading. The raw capacity
37 /// is always zero or a power of two.
39 fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
43 // 1. Account for loading: `raw_capacity >= len * 1.1`.
44 // 2. Ensure it is a power of two.
45 // 3. Ensure it is at least the minimum size.
46 let mut raw_cap = len.checked_mul(11)
48 .and_then(|l| l.checked_next_power_of_two())
49 .ok_or(CollectionAllocErr::CapacityOverflow)?;
51 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
57 fn raw_capacity(&self, len: usize) -> usize {
58 self.try_raw_capacity(len).expect("raw_capacity overflow")
61 /// The capacity of the given raw capacity.
63 fn capacity(&self, raw_cap: usize) -> usize {
64 // This doesn't have to be checked for overflow since allocation size
65 // in bytes will overflow earlier than multiplication by 10.
67 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
68 // to be: (raw_cap * den + den - 1) / num
69 (raw_cap * 10 + 10 - 1) / 11
73 // The main performance trick in this hashmap is called Robin Hood Hashing.
74 // It gains its excellent performance from one essential operation:
76 // If an insertion collides with an existing element, and that element's
77 // "probe distance" (how far away the element is from its ideal location)
78 // is higher than how far we've already probed, swap the elements.
80 // This massively lowers variance in probe distance, and allows us to get very
81 // high load factors with good performance. The 90% load factor I use is rather
84 // > Why a load factor of approximately 90%?
86 // In general, all the distances to initial buckets will converge on the mean.
87 // At a load factor of α, the odds of finding the target bucket after k
88 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
89 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
90 // this down to make the math easier on the CPU and avoid its FPU.
91 // Since on average we start the probing in the middle of a cache line, this
92 // strategy pulls in two cache lines of hashes on every lookup. I think that's
93 // pretty good, but if you want to trade off some space, it could go down to one
94 // cache line on average with an α of 0.84.
96 // > Wait, what? Where did you get 1-α^k from?
98 // On the first probe, your odds of a collision with an existing element is α.
99 // The odds of doing this twice in a row is approximately α^2. For three times,
100 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
101 // colliding after k tries is 1-α^k.
103 // The paper from 1986 cited below mentions an implementation which keeps track
104 // of the distance-to-initial-bucket histogram. This approach is not suitable
105 // for modern architectures because it requires maintaining an internal data
106 // structure. This allows very good first guesses, but we are most concerned
107 // with guessing entire cache lines, not individual indexes. Furthermore, array
108 // accesses are no longer linear and in one direction, as we have now. There
109 // is also memory and cache pressure that this would entail that would be very
110 // difficult to properly see in a microbenchmark.
112 // ## Future Improvements (FIXME!)
114 // Allow the load factor to be changed dynamically and/or at initialization.
116 // Also, would it be possible for us to reuse storage when growing the
117 // underlying table? This is exactly the use case for 'realloc', and may
118 // be worth exploring.
120 // ## Future Optimizations (FIXME!)
122 // Another possible design choice that I made without any real reason is
123 // parameterizing the raw table over keys and values. Technically, all we need
124 // is the size and alignment of keys and values, and the code should be just as
125 // efficient (well, we might need one for power-of-two size and one for not...).
126 // This has the potential to reduce code bloat in rust executables, without
127 // really losing anything except 4 words (key size, key alignment, val size,
128 // val alignment) which can be passed in to every call of a `RawTable` function.
129 // This would definitely be an avenue worth exploring if people start complaining
130 // about the size of rust executables.
132 // Annotate exceedingly likely branches in `table::make_hash`
133 // and `search_hashed` to reduce instruction cache pressure
134 // and mispredictions once it becomes possible (blocked on issue #11092).
136 // Shrinking the table could simply reallocate in place after moving buckets
137 // to the first half.
139 // The growth algorithm (fragment of the Proof of Correctness)
140 // --------------------
142 // The growth algorithm is basically a fast path of the naive reinsertion-
143 // during-resize algorithm. Other paths should never be taken.
145 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
146 // by allocating a new table of capacity `2n`, and then individually reinsert
147 // each element in the old table into the new one. This guarantees that the
148 // new table is a valid robin hood hashtable with all the desired statistical
149 // properties. Remark that the order we reinsert the elements in should not
150 // matter. For simplicity and efficiency, we will consider only linear
151 // reinsertions, which consist of reinserting all elements in the old table
152 // into the new one by increasing order of index. However we will not be
153 // starting our reinsertions from index 0 in general. If we start from index
154 // i, for the purpose of reinsertion we will consider all elements with real
155 // index j < i to have virtual index n + j.
157 // Our hash generation scheme consists of generating a 64-bit hash and
158 // truncating the most significant bits. When moving to the new table, we
159 // simply introduce a new bit to the front of the hash. Therefore, if an
160 // element has ideal index i in the old table, it can have one of two ideal
161 // locations in the new table. If the new bit is 0, then the new ideal index
162 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
163 // we are producing two independent tables of size n, and for each element we
164 // independently choose which table to insert it into with equal probability.
165 // However, rather than wrapping around themselves on overflowing their
166 // indexes, the first table overflows into the second, and the second into the
167 // first. Visually, our new table will look something like:
169 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
171 // Where x's are elements inserted into the first table, y's are elements
172 // inserted into the second, and _'s are empty sections. We now define a few
173 // key concepts that we will use later. Note that this is a very abstract
174 // perspective of the table. A real resized table would be at least half
177 // Theorem: A linear robin hood reinsertion from the first ideal element
178 // produces identical results to a linear naive reinsertion from the same
181 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
183 // Adaptive early resizing
184 // ----------------------
185 // To protect against degenerate performance scenarios (including DOS attacks),
186 // the implementation includes an adaptive behavior that can resize the map
187 // early (before its capacity is exceeded) when suspiciously long probe sequences
190 // With this algorithm in place it would be possible to turn a CPU attack into
191 // a memory attack due to the aggressive resizing. To prevent that the
192 // adaptive behavior only triggers when the map is at least half full.
193 // This reduces the effectiveness of the algorithm but also makes it completely safe.
195 // The previous safety measure also prevents degenerate interactions with
196 // really bad quality hash algorithms that can make normal inputs look like a
199 const DISPLACEMENT_THRESHOLD: usize = 128;
201 // The threshold of 128 is chosen to minimize the chance of exceeding it.
202 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
203 // For displacement, the smallest constant that fits our needs is 90,
204 // so we round that up to 128.
206 // At a load factor of α, the odds of finding the target bucket after exactly n
207 // unsuccessful probes[1] are
209 // Pr_α{displacement = n} =
210 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
212 // We use this formula to find the probability of triggering the adaptive behavior
214 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
216 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
217 // hashing with buckets.
219 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
221 /// By default, `HashMap` uses a hashing algorithm selected to provide
222 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
223 /// reasonable best-effort is made to generate this seed from a high quality,
224 /// secure source of randomness provided by the host without blocking the
225 /// program. Because of this, the randomness of the seed depends on the output
226 /// quality of the system's random number generator when the seed is created.
227 /// In particular, seeds generated when the system's entropy pool is abnormally
228 /// low such as during system boot may be of a lower quality.
230 /// The default hashing algorithm is currently SipHash 1-3, though this is
231 /// subject to change at any point in the future. While its performance is very
232 /// competitive for medium sized keys, other hashing algorithms will outperform
233 /// it for small keys such as integers as well as large keys such as long
234 /// strings, though those algorithms will typically *not* protect against
235 /// attacks such as HashDoS.
237 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
238 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
239 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
241 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
242 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
243 /// If you implement these yourself, it is important that the following
247 /// k1 == k2 -> hash(k1) == hash(k2)
250 /// In other words, if two keys are equal, their hashes must be equal.
252 /// It is a logic error for a key to be modified in such a way that the key's
253 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
254 /// the [`Eq`] trait, changes while it is in the map. This is normally only
255 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
257 /// Relevant papers/articles:
259 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
260 /// 2. Emmanuel Goossaert. ["Robin Hood
261 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
262 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
263 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
268 /// use std::collections::HashMap;
270 /// // Type inference lets us omit an explicit type signature (which
271 /// // would be `HashMap<String, String>` in this example).
272 /// let mut book_reviews = HashMap::new();
274 /// // Review some books.
275 /// book_reviews.insert(
276 /// "Adventures of Huckleberry Finn".to_string(),
277 /// "My favorite book.".to_string(),
279 /// book_reviews.insert(
280 /// "Grimms' Fairy Tales".to_string(),
281 /// "Masterpiece.".to_string(),
283 /// book_reviews.insert(
284 /// "Pride and Prejudice".to_string(),
285 /// "Very enjoyable.".to_string(),
287 /// book_reviews.insert(
288 /// "The Adventures of Sherlock Holmes".to_string(),
289 /// "Eye lyked it alot.".to_string(),
292 /// // Check for a specific one.
293 /// // When collections store owned values (String), they can still be
294 /// // queried using references (&str).
295 /// if !book_reviews.contains_key("Les Misérables") {
296 /// println!("We've got {} reviews, but Les Misérables ain't one.",
297 /// book_reviews.len());
300 /// // oops, this review has a lot of spelling mistakes, let's delete it.
301 /// book_reviews.remove("The Adventures of Sherlock Holmes");
303 /// // Look up the values associated with some keys.
304 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
305 /// for &book in &to_find {
306 /// match book_reviews.get(book) {
307 /// Some(review) => println!("{}: {}", book, review),
308 /// None => println!("{} is unreviewed.", book)
312 /// // Look up the value for a key (will panic if the key is not found).
313 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
315 /// // Iterate over everything.
316 /// for (book, review) in &book_reviews {
317 /// println!("{}: \"{}\"", book, review);
321 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
322 /// for more complex methods of getting, setting, updating and removing keys and
326 /// use std::collections::HashMap;
328 /// // type inference lets us omit an explicit type signature (which
329 /// // would be `HashMap<&str, u8>` in this example).
330 /// let mut player_stats = HashMap::new();
332 /// fn random_stat_buff() -> u8 {
333 /// // could actually return some random value here - let's just return
334 /// // some fixed value for now
338 /// // insert a key only if it doesn't already exist
339 /// player_stats.entry("health").or_insert(100);
341 /// // insert a key using a function that provides a new value only if it
342 /// // doesn't already exist
343 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
345 /// // update a key, guarding against the key possibly not being set
346 /// let stat = player_stats.entry("attack").or_insert(100);
347 /// *stat += random_stat_buff();
350 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
351 /// We must also derive [`PartialEq`].
353 /// [`Eq`]: ../../std/cmp/trait.Eq.html
354 /// [`Hash`]: ../../std/hash/trait.Hash.html
355 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
356 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
357 /// [`Cell`]: ../../std/cell/struct.Cell.html
358 /// [`default`]: #method.default
359 /// [`with_hasher`]: #method.with_hasher
360 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
361 /// [`fnv`]: https://crates.io/crates/fnv
364 /// use std::collections::HashMap;
366 /// #[derive(Hash, Eq, PartialEq, Debug)]
373 /// /// Creates a new Viking.
374 /// fn new(name: &str, country: &str) -> Viking {
375 /// Viking { name: name.to_string(), country: country.to_string() }
379 /// // Use a HashMap to store the vikings' health points.
380 /// let mut vikings = HashMap::new();
382 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
383 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
384 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
386 /// // Use derived implementation to print the status of the vikings.
387 /// for (viking, health) in &vikings {
388 /// println!("{:?} has {} hp", viking, health);
392 /// A `HashMap` with fixed list of elements can be initialized from an array:
395 /// use std::collections::HashMap;
398 /// let timber_resources: HashMap<&str, i32> =
399 /// [("Norway", 100),
402 /// .iter().cloned().collect();
403 /// // use the values stored in map
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub struct HashMap<K, V, S = RandomState> {
410 // All hashes are keyed on these values, to prevent hash collision attacks.
413 table: RawTable<K, V>,
415 resize_policy: DefaultResizePolicy,
418 /// Search for a pre-hashed key.
419 /// If you don't already know the hash, use search or search_mut instead
421 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
422 where M: Deref<Target = RawTable<K, V>>,
425 // This is the only function where capacity can be zero. To avoid
426 // undefined behavior when Bucket::new gets the raw bucket in this
427 // case, immediately return the appropriate search result.
428 if table.capacity() == 0 {
429 return InternalEntry::TableIsEmpty;
432 search_hashed_nonempty(table, hash, is_match, true)
435 /// Search for a pre-hashed key when the hash map is known to be non-empty.
437 fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
438 compare_hashes: bool)
439 -> InternalEntry<K, V, M>
440 where M: Deref<Target = RawTable<K, V>>,
443 // Do not check the capacity as an extra branch could slow the lookup.
445 let size = table.size();
446 let mut probe = Bucket::new(table, hash);
447 let mut displacement = 0;
450 let full = match probe.peek() {
453 return InternalEntry::Vacant {
455 elem: NoElem(bucket, displacement),
458 Full(bucket) => bucket,
461 let probe_displacement = full.displacement();
463 if probe_displacement < displacement {
464 // Found a luckier bucket than me.
465 // We can finish the search early if we hit any bucket
466 // with a lower distance to initial bucket than we've probed.
467 return InternalEntry::Vacant {
469 elem: NeqElem(full, probe_displacement),
473 // If the hash doesn't match, it can't be this one..
474 if !compare_hashes || hash == full.hash() {
475 // If the key doesn't match, it can't be this one..
476 if is_match(full.read().0) {
477 return InternalEntry::Occupied { elem: full };
482 debug_assert!(displacement <= size);
486 /// Same as `search_hashed_nonempty` but for mutable access.
488 fn search_hashed_nonempty_mut<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
489 compare_hashes: bool)
490 -> InternalEntry<K, V, M>
491 where M: DerefMut<Target = RawTable<K, V>>,
494 // Do not check the capacity as an extra branch could slow the lookup.
496 let size = table.size();
497 let mut probe = Bucket::new(table, hash);
498 let mut displacement = 0;
501 let mut full = match probe.peek() {
504 return InternalEntry::Vacant {
506 elem: NoElem(bucket, displacement),
509 Full(bucket) => bucket,
512 let probe_displacement = full.displacement();
514 if probe_displacement < displacement {
515 // Found a luckier bucket than me.
516 // We can finish the search early if we hit any bucket
517 // with a lower distance to initial bucket than we've probed.
518 return InternalEntry::Vacant {
520 elem: NeqElem(full, probe_displacement),
524 // If the hash doesn't match, it can't be this one..
525 if hash == full.hash() || !compare_hashes {
526 // If the key doesn't match, it can't be this one..
527 if is_match(full.read_mut().0) {
528 return InternalEntry::Occupied { elem: full };
533 debug_assert!(displacement <= size);
537 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
538 -> (K, V, &mut RawTable<K, V>)
540 let (empty, retkey, retval) = starting_bucket.take();
541 let mut gap = match empty.gap_peek() {
543 Err(b) => return (retkey, retval, b.into_table()),
546 while gap.full().displacement() != 0 {
547 gap = match gap.shift() {
550 return (retkey, retval, b.into_table());
555 // Now we've done all our shifting. Return the value we grabbed earlier.
556 (retkey, retval, gap.into_table())
559 /// Performs robin hood bucket stealing at the given `bucket`. You must
560 /// also pass that bucket's displacement so we don't have to recalculate it.
562 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
563 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
564 mut displacement: usize,
568 -> FullBucketMut<'a, K, V> {
569 let size = bucket.table().size();
570 let raw_capacity = bucket.table().capacity();
571 // There can be at most `size - dib` buckets to displace, because
572 // in the worst case, there are `size` elements and we already are
573 // `displacement` buckets away from the initial one.
574 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
575 // Save the *starting point*.
576 let mut bucket = bucket.stash();
579 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
586 let probe = bucket.next();
587 debug_assert!(probe.index() != idx_end);
589 let full_bucket = match probe.peek() {
592 let bucket = bucket.put(hash, key, val);
593 // Now that it's stolen, just read the value's pointer
594 // right out of the table! Go back to the *starting point*.
596 // This use of `into_table` is misleading. It turns the
597 // bucket, which is a FullBucket on top of a
598 // FullBucketMut, into just one FullBucketMut. The "table"
599 // refers to the inner FullBucketMut in this context.
600 return bucket.into_table();
602 Full(bucket) => bucket,
605 let probe_displacement = full_bucket.displacement();
607 bucket = full_bucket;
609 // Robin hood! Steal the spot.
610 if probe_displacement < displacement {
611 displacement = probe_displacement;
618 impl<K, V, S> HashMap<K, V, S>
622 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
625 table::make_hash(&self.hash_builder, x)
628 /// Search for a key, yielding the index if it's found in the hashtable.
629 /// If you already have the hash for the key lying around, or if you need an
630 /// InternalEntry, use search_hashed or search_hashed_nonempty.
632 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
633 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
641 let hash = self.make_hash(q);
642 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()), true)
643 .into_occupied_bucket()
647 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
648 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
656 let hash = self.make_hash(q);
657 search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()), true)
658 .into_occupied_bucket()
661 // The caller should ensure that invariants by Robin Hood Hashing hold
662 // and that there's space in the underlying table.
663 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
664 let mut buckets = Bucket::new(&mut self.table, hash);
665 let start_index = buckets.index();
668 // We don't need to compare hashes for value swap.
669 // Not even DIBs for Robin Hood.
670 buckets = match buckets.peek() {
672 empty.put(hash, k, v);
675 Full(b) => b.into_bucket(),
678 debug_assert!(buckets.index() != start_index);
683 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
684 /// Creates an empty `HashMap`.
686 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
687 /// is first inserted into.
692 /// use std::collections::HashMap;
693 /// let mut map: HashMap<&str, i32> = HashMap::new();
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn new() -> HashMap<K, V, RandomState> {
701 /// Creates an empty `HashMap` with the specified capacity.
703 /// The hash map will be able to hold at least `capacity` elements without
704 /// reallocating. If `capacity` is 0, the hash map will not allocate.
709 /// use std::collections::HashMap;
710 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
715 HashMap::with_capacity_and_hasher(capacity, Default::default())
719 impl<K, V, S> HashMap<K, V, S>
723 /// Creates an empty `HashMap` which will use the given hash builder to hash
726 /// The created map has the default initial capacity.
728 /// Warning: `hash_builder` is normally randomly generated, and
729 /// is designed to allow HashMaps to be resistant to attacks that
730 /// cause many collisions and very poor performance. Setting it
731 /// manually using this function can expose a DoS attack vector.
736 /// use std::collections::HashMap;
737 /// use std::collections::hash_map::RandomState;
739 /// let s = RandomState::new();
740 /// let mut map = HashMap::with_hasher(s);
741 /// map.insert(1, 2);
744 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
745 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
748 resize_policy: DefaultResizePolicy::new(),
749 table: RawTable::new(0),
753 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
754 /// to hash the keys.
756 /// The hash map will be able to hold at least `capacity` elements without
757 /// reallocating. If `capacity` is 0, the hash map will not allocate.
759 /// Warning: `hash_builder` is normally randomly generated, and
760 /// is designed to allow HashMaps to be resistant to attacks that
761 /// cause many collisions and very poor performance. Setting it
762 /// manually using this function can expose a DoS attack vector.
767 /// use std::collections::HashMap;
768 /// use std::collections::hash_map::RandomState;
770 /// let s = RandomState::new();
771 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
772 /// map.insert(1, 2);
775 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
776 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
777 let resize_policy = DefaultResizePolicy::new();
778 let raw_cap = resize_policy.raw_capacity(capacity);
782 table: RawTable::new(raw_cap),
786 /// Returns a reference to the map's [`BuildHasher`].
788 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
793 /// use std::collections::HashMap;
794 /// use std::collections::hash_map::RandomState;
796 /// let hasher = RandomState::new();
797 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
798 /// let hasher: &RandomState = map.hasher();
800 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
801 pub fn hasher(&self) -> &S {
805 /// Returns the number of elements the map can hold without reallocating.
807 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
808 /// more, but is guaranteed to be able to hold at least this many.
813 /// use std::collections::HashMap;
814 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
815 /// assert!(map.capacity() >= 100);
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn capacity(&self) -> usize {
820 self.resize_policy.capacity(self.raw_capacity())
823 /// Returns the hash map's raw capacity.
825 fn raw_capacity(&self) -> usize {
826 self.table.capacity()
829 /// Reserves capacity for at least `additional` more elements to be inserted
830 /// in the `HashMap`. The collection may reserve more space to avoid
831 /// frequent reallocations.
835 /// Panics if the new allocation size overflows [`usize`].
837 /// [`usize`]: ../../std/primitive.usize.html
842 /// use std::collections::HashMap;
843 /// let mut map: HashMap<&str, i32> = HashMap::new();
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn reserve(&mut self, additional: usize) {
849 match self.reserve_internal(additional, Infallible) {
850 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
851 Err(CollectionAllocErr::AllocErr) => unreachable!(),
852 Ok(()) => { /* yay */ }
856 /// Tries to reserve capacity for at least `additional` more elements to be inserted
857 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
858 /// frequent reallocations.
862 /// If the capacity overflows, or the allocator reports a failure, then an error
868 /// #![feature(try_reserve)]
869 /// use std::collections::HashMap;
870 /// let mut map: HashMap<&str, isize> = HashMap::new();
871 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
873 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
874 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
875 self.reserve_internal(additional, Fallible)
879 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
880 -> Result<(), CollectionAllocErr> {
882 let remaining = self.capacity() - self.len(); // this can't overflow
883 if remaining < additional {
884 let min_cap = self.len()
885 .checked_add(additional)
886 .ok_or(CollectionAllocErr::CapacityOverflow)?;
887 let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
888 self.try_resize(raw_cap, fallibility)?;
889 } else if self.table.tag() && remaining <= self.len() {
890 // Probe sequence is too long and table is half full,
891 // resize early to reduce probing length.
892 let new_capacity = self.table.capacity() * 2;
893 self.try_resize(new_capacity, fallibility)?;
898 /// Resizes the internal vectors to a new capacity. It's your
899 /// responsibility to:
900 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
901 /// for the load factor.
902 /// 2) Ensure `new_raw_cap` is a power of two or zero.
908 fallibility: Fallibility,
909 ) -> Result<(), CollectionAllocErr> {
910 assert!(self.table.size() <= new_raw_cap);
911 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
913 let mut old_table = replace(
916 Infallible => RawTable::new(new_raw_cap),
917 Fallible => RawTable::try_new(new_raw_cap)?,
920 let old_size = old_table.size();
922 if old_table.size() == 0 {
926 let mut bucket = Bucket::head_bucket(&mut old_table);
928 // This is how the buckets might be laid out in memory:
929 // ($ marks an initialized bucket)
931 // |$$$_$$$$$$_$$$$$|
933 // But we've skipped the entire initial cluster of buckets
934 // and will continue iteration in this order:
937 // ^ wrap around once end is reached
940 // ^ exit once table.size == 0
942 bucket = match bucket.peek() {
944 let h = bucket.hash();
945 let (b, k, v) = bucket.take();
946 self.insert_hashed_ordered(h, k, v);
947 if b.table().size() == 0 {
952 Empty(b) => b.into_bucket(),
957 assert_eq!(self.table.size(), old_size);
961 /// Shrinks the capacity of the map as much as possible. It will drop
962 /// down as much as possible while maintaining the internal rules
963 /// and possibly leaving some space in accordance with the resize policy.
968 /// use std::collections::HashMap;
970 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
971 /// map.insert(1, 2);
972 /// map.insert(3, 4);
973 /// assert!(map.capacity() >= 100);
974 /// map.shrink_to_fit();
975 /// assert!(map.capacity() >= 2);
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn shrink_to_fit(&mut self) {
979 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
980 if self.raw_capacity() != new_raw_cap {
981 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
982 let old_size = old_table.size();
984 // Shrink the table. Naive algorithm for resizing:
985 for (h, k, v) in old_table.into_iter() {
986 self.insert_hashed_nocheck(h, k, v);
989 debug_assert_eq!(self.table.size(), old_size);
993 /// Shrinks the capacity of the map with a lower limit. It will drop
994 /// down no lower than the supplied limit while maintaining the internal rules
995 /// and possibly leaving some space in accordance with the resize policy.
997 /// Panics if the current capacity is smaller than the supplied
998 /// minimum capacity.
1003 /// #![feature(shrink_to)]
1004 /// use std::collections::HashMap;
1006 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1007 /// map.insert(1, 2);
1008 /// map.insert(3, 4);
1009 /// assert!(map.capacity() >= 100);
1010 /// map.shrink_to(10);
1011 /// assert!(map.capacity() >= 10);
1012 /// map.shrink_to(0);
1013 /// assert!(map.capacity() >= 2);
1015 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1016 pub fn shrink_to(&mut self, min_capacity: usize) {
1017 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1019 let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1020 if self.raw_capacity() != new_raw_cap {
1021 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1022 let old_size = old_table.size();
1024 // Shrink the table. Naive algorithm for resizing:
1025 for (h, k, v) in old_table.into_iter() {
1026 self.insert_hashed_nocheck(h, k, v);
1029 debug_assert_eq!(self.table.size(), old_size);
1033 /// Insert a pre-hashed key-value pair, without first checking
1034 /// that there's enough room in the buckets. Returns a reference to the
1035 /// newly insert value.
1037 /// If the key already exists, the hashtable will be returned untouched
1038 /// and a reference to the existing element will be returned.
1039 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1040 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1042 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1043 Some(Vacant(elem)) => {
1047 None => unreachable!(),
1051 /// An iterator visiting all keys in arbitrary order.
1052 /// The iterator element type is `&'a K`.
1057 /// use std::collections::HashMap;
1059 /// let mut map = HashMap::new();
1060 /// map.insert("a", 1);
1061 /// map.insert("b", 2);
1062 /// map.insert("c", 3);
1064 /// for key in map.keys() {
1065 /// println!("{}", key);
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn keys(&self) -> Keys<K, V> {
1070 Keys { inner: self.iter() }
1073 /// An iterator visiting all values in arbitrary order.
1074 /// The iterator element type is `&'a V`.
1079 /// use std::collections::HashMap;
1081 /// let mut map = HashMap::new();
1082 /// map.insert("a", 1);
1083 /// map.insert("b", 2);
1084 /// map.insert("c", 3);
1086 /// for val in map.values() {
1087 /// println!("{}", val);
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn values(&self) -> Values<K, V> {
1092 Values { inner: self.iter() }
1095 /// An iterator visiting all values mutably in arbitrary order.
1096 /// The iterator element type is `&'a mut V`.
1101 /// use std::collections::HashMap;
1103 /// let mut map = HashMap::new();
1105 /// map.insert("a", 1);
1106 /// map.insert("b", 2);
1107 /// map.insert("c", 3);
1109 /// for val in map.values_mut() {
1110 /// *val = *val + 10;
1113 /// for val in map.values() {
1114 /// println!("{}", val);
1117 #[stable(feature = "map_values_mut", since = "1.10.0")]
1118 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1119 ValuesMut { inner: self.iter_mut() }
1122 /// An iterator visiting all key-value pairs in arbitrary order.
1123 /// The iterator element type is `(&'a K, &'a V)`.
1128 /// use std::collections::HashMap;
1130 /// let mut map = HashMap::new();
1131 /// map.insert("a", 1);
1132 /// map.insert("b", 2);
1133 /// map.insert("c", 3);
1135 /// for (key, val) in map.iter() {
1136 /// println!("key: {} val: {}", key, val);
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn iter(&self) -> Iter<K, V> {
1141 Iter { inner: self.table.iter() }
1144 /// An iterator visiting all key-value pairs in arbitrary order,
1145 /// with mutable references to the values.
1146 /// The iterator element type is `(&'a K, &'a mut V)`.
1151 /// use std::collections::HashMap;
1153 /// let mut map = HashMap::new();
1154 /// map.insert("a", 1);
1155 /// map.insert("b", 2);
1156 /// map.insert("c", 3);
1158 /// // Update all values
1159 /// for (_, val) in map.iter_mut() {
1163 /// for (key, val) in &map {
1164 /// println!("key: {} val: {}", key, val);
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1169 IterMut { inner: self.table.iter_mut() }
1172 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1177 /// use std::collections::HashMap;
1179 /// let mut letters = HashMap::new();
1181 /// for ch in "a short treatise on fungi".chars() {
1182 /// let counter = letters.entry(ch).or_insert(0);
1186 /// assert_eq!(letters[&'s'], 2);
1187 /// assert_eq!(letters[&'t'], 3);
1188 /// assert_eq!(letters[&'u'], 1);
1189 /// assert_eq!(letters.get(&'y'), None);
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1193 // Gotta resize now.
1195 let hash = self.make_hash(&key);
1196 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1197 .into_entry(key).expect("unreachable")
1200 /// Returns the number of elements in the map.
1205 /// use std::collections::HashMap;
1207 /// let mut a = HashMap::new();
1208 /// assert_eq!(a.len(), 0);
1209 /// a.insert(1, "a");
1210 /// assert_eq!(a.len(), 1);
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn len(&self) -> usize {
1217 /// Returns `true` if the map contains no elements.
1222 /// use std::collections::HashMap;
1224 /// let mut a = HashMap::new();
1225 /// assert!(a.is_empty());
1226 /// a.insert(1, "a");
1227 /// assert!(!a.is_empty());
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub fn is_empty(&self) -> bool {
1235 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1236 /// allocated memory for reuse.
1241 /// use std::collections::HashMap;
1243 /// let mut a = HashMap::new();
1244 /// a.insert(1, "a");
1245 /// a.insert(2, "b");
1247 /// for (k, v) in a.drain().take(1) {
1248 /// assert!(k == 1 || k == 2);
1249 /// assert!(v == "a" || v == "b");
1252 /// assert!(a.is_empty());
1255 #[stable(feature = "drain", since = "1.6.0")]
1256 pub fn drain(&mut self) -> Drain<K, V> {
1257 Drain { inner: self.table.drain() }
1260 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1266 /// use std::collections::HashMap;
1268 /// let mut a = HashMap::new();
1269 /// a.insert(1, "a");
1271 /// assert!(a.is_empty());
1273 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub fn clear(&mut self) {
1279 /// Returns a reference to the value corresponding to the key.
1281 /// The key may be any borrowed form of the map's key type, but
1282 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1285 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1286 /// [`Hash`]: ../../std/hash/trait.Hash.html
1291 /// use std::collections::HashMap;
1293 /// let mut map = HashMap::new();
1294 /// map.insert(1, "a");
1295 /// assert_eq!(map.get(&1), Some(&"a"));
1296 /// assert_eq!(map.get(&2), None);
1298 #[stable(feature = "rust1", since = "1.0.0")]
1300 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1304 self.search(k).map(|bucket| bucket.into_refs().1)
1307 /// Returns the key-value pair corresponding to the supplied key.
1309 /// The supplied key may be any borrowed form of the map's key type, but
1310 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1313 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1314 /// [`Hash`]: ../../std/hash/trait.Hash.html
1319 /// #![feature(map_get_key_value)]
1320 /// use std::collections::HashMap;
1322 /// let mut map = HashMap::new();
1323 /// map.insert(1, "a");
1324 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1325 /// assert_eq!(map.get_key_value(&2), None);
1327 #[unstable(feature = "map_get_key_value", issue = "49347")]
1328 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1332 self.search(k).map(|bucket| bucket.into_refs())
1335 /// Returns `true` if the map contains a value for the specified key.
1337 /// The key may be any borrowed form of the map's key type, but
1338 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1341 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1342 /// [`Hash`]: ../../std/hash/trait.Hash.html
1347 /// use std::collections::HashMap;
1349 /// let mut map = HashMap::new();
1350 /// map.insert(1, "a");
1351 /// assert_eq!(map.contains_key(&1), true);
1352 /// assert_eq!(map.contains_key(&2), false);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1359 self.search(k).is_some()
1362 /// Returns a mutable reference to the value corresponding to the key.
1364 /// The key may be any borrowed form of the map's key type, but
1365 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1368 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1369 /// [`Hash`]: ../../std/hash/trait.Hash.html
1374 /// use std::collections::HashMap;
1376 /// let mut map = HashMap::new();
1377 /// map.insert(1, "a");
1378 /// if let Some(x) = map.get_mut(&1) {
1381 /// assert_eq!(map[&1], "b");
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1388 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1391 /// Inserts a key-value pair into the map.
1393 /// If the map did not have this key present, [`None`] is returned.
1395 /// If the map did have this key present, the value is updated, and the old
1396 /// value is returned. The key is not updated, though; this matters for
1397 /// types that can be `==` without being identical. See the [module-level
1398 /// documentation] for more.
1400 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1401 /// [module-level documentation]: index.html#insert-and-complex-keys
1406 /// use std::collections::HashMap;
1408 /// let mut map = HashMap::new();
1409 /// assert_eq!(map.insert(37, "a"), None);
1410 /// assert_eq!(map.is_empty(), false);
1412 /// map.insert(37, "b");
1413 /// assert_eq!(map.insert(37, "c"), Some("b"));
1414 /// assert_eq!(map[&37], "c");
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1418 let hash = self.make_hash(&k);
1420 self.insert_hashed_nocheck(hash, k, v)
1423 /// Removes a key from the map, returning the value at the key if the key
1424 /// was previously in the map.
1426 /// The key may be any borrowed form of the map's key type, but
1427 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1430 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1431 /// [`Hash`]: ../../std/hash/trait.Hash.html
1436 /// use std::collections::HashMap;
1438 /// let mut map = HashMap::new();
1439 /// map.insert(1, "a");
1440 /// assert_eq!(map.remove(&1), Some("a"));
1441 /// assert_eq!(map.remove(&1), None);
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1448 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1451 /// Removes a key from the map, returning the stored key and value if the
1452 /// key was previously in the map.
1454 /// The key may be any borrowed form of the map's key type, but
1455 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1458 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1459 /// [`Hash`]: ../../std/hash/trait.Hash.html
1464 /// use std::collections::HashMap;
1467 /// let mut map = HashMap::new();
1468 /// map.insert(1, "a");
1469 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1470 /// assert_eq!(map.remove(&1), None);
1473 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1474 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1480 let (k, v, _) = pop_internal(bucket);
1485 /// Retains only the elements specified by the predicate.
1487 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1492 /// use std::collections::HashMap;
1494 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1495 /// map.retain(|&k, _| k % 2 == 0);
1496 /// assert_eq!(map.len(), 4);
1498 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1499 pub fn retain<F>(&mut self, mut f: F)
1500 where F: FnMut(&K, &mut V) -> bool
1502 if self.table.size() == 0 {
1505 let mut elems_left = self.table.size();
1506 let mut bucket = Bucket::head_bucket(&mut self.table);
1508 let start_index = bucket.index();
1509 while elems_left != 0 {
1510 bucket = match bucket.peek() {
1513 let should_remove = {
1514 let (k, v) = full.read_mut();
1518 let prev_raw = full.raw();
1519 let (_, _, t) = pop_internal(full);
1520 Bucket::new_from(prev_raw, t)
1529 bucket.prev(); // reverse iteration
1530 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1535 impl<K, V, S> HashMap<K, V, S>
1539 /// Creates a raw entry builder for the HashMap.
1541 /// Raw entries provide the lowest level of control for searching and
1542 /// manipulating a map. They must be manually initialized with a hash and
1543 /// then manually searched. After this, insertions into a vacant entry
1544 /// still require an owned key to be provided.
1546 /// Raw entries are useful for such exotic situations as:
1548 /// * Hash memoization
1549 /// * Deferring the creation of an owned key until it is known to be required
1550 /// * Using a search key that doesn't work with the Borrow trait
1551 /// * Using custom comparison logic without newtype wrappers
1553 /// Because raw entries provide much more low-level control, it's much easier
1554 /// to put the HashMap into an inconsistent state which, while memory-safe,
1555 /// will cause the map to produce seemingly random results. Higher-level and
1556 /// more foolproof APIs like `entry` should be preferred when possible.
1558 /// In particular, the hash used to initialized the raw entry must still be
1559 /// consistent with the hash of the key that is ultimately stored in the entry.
1560 /// This is because implementations of HashMap may need to recompute hashes
1561 /// when resizing, at which point only the keys are available.
1563 /// Raw entries give mutable access to the keys. This must not be used
1564 /// to modify how the key would compare or hash, as the map will not re-evaluate
1565 /// where the key should go, meaning the keys may become "lost" if their
1566 /// location does not reflect their state. For instance, if you change a key
1567 /// so that the map now contains keys which compare equal, search may start
1568 /// acting erratically, with two keys randomly masking each other. Implementations
1569 /// are free to assume this doesn't happen (within the limits of memory-safety).
1571 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1572 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1574 RawEntryBuilderMut { map: self }
1577 /// Creates a raw immutable entry builder for the HashMap.
1579 /// Raw entries provide the lowest level of control for searching and
1580 /// manipulating a map. They must be manually initialized with a hash and
1581 /// then manually searched.
1583 /// This is useful for
1584 /// * Hash memoization
1585 /// * Using a search key that doesn't work with the Borrow trait
1586 /// * Using custom comparison logic without newtype wrappers
1588 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1589 /// `get` should be preferred.
1591 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1592 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1593 pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1594 RawEntryBuilder { map: self }
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<K, V, S> PartialEq for HashMap<K, V, S>
1604 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1605 if self.len() != other.len() {
1609 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<K, V, S> Eq for HashMap<K, V, S>
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<K, V, S> Debug for HashMap<K, V, S>
1623 where K: Eq + Hash + Debug,
1627 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1628 f.debug_map().entries(self.iter()).finish()
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl<K, V, S> Default for HashMap<K, V, S>
1635 S: BuildHasher + Default
1637 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1638 fn default() -> HashMap<K, V, S> {
1639 HashMap::with_hasher(Default::default())
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1645 where K: Eq + Hash + Borrow<Q>,
1651 /// Returns a reference to the value corresponding to the supplied key.
1655 /// Panics if the key is not present in the `HashMap`.
1657 fn index(&self, key: &Q) -> &V {
1658 self.get(key).expect("no entry found for key")
1662 /// An iterator over the entries of a `HashMap`.
1664 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1665 /// documentation for more.
1667 /// [`iter`]: struct.HashMap.html#method.iter
1668 /// [`HashMap`]: struct.HashMap.html
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub struct Iter<'a, K: 'a, V: 'a> {
1671 inner: table::Iter<'a, K, V>,
1674 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<'a, K, V> Clone for Iter<'a, K, V> {
1677 fn clone(&self) -> Iter<'a, K, V> {
1678 Iter { inner: self.inner.clone() }
1682 #[stable(feature = "std_debug", since = "1.16.0")]
1683 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1686 .entries(self.clone())
1691 /// A mutable iterator over the entries of a `HashMap`.
1693 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1694 /// documentation for more.
1696 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1697 /// [`HashMap`]: struct.HashMap.html
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 pub struct IterMut<'a, K: 'a, V: 'a> {
1700 inner: table::IterMut<'a, K, V>,
1703 /// An owning iterator over the entries of a `HashMap`.
1705 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1706 /// (provided by the `IntoIterator` trait). See its documentation for more.
1708 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1709 /// [`HashMap`]: struct.HashMap.html
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub struct IntoIter<K, V> {
1712 pub(super) inner: table::IntoIter<K, V>,
1715 /// An iterator over the keys of a `HashMap`.
1717 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1718 /// documentation for more.
1720 /// [`keys`]: struct.HashMap.html#method.keys
1721 /// [`HashMap`]: struct.HashMap.html
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub struct Keys<'a, K: 'a, V: 'a> {
1724 inner: Iter<'a, K, V>,
1727 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl<'a, K, V> Clone for Keys<'a, K, V> {
1730 fn clone(&self) -> Keys<'a, K, V> {
1731 Keys { inner: self.inner.clone() }
1735 #[stable(feature = "std_debug", since = "1.16.0")]
1736 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1739 .entries(self.clone())
1744 /// An iterator over the values of a `HashMap`.
1746 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1747 /// documentation for more.
1749 /// [`values`]: struct.HashMap.html#method.values
1750 /// [`HashMap`]: struct.HashMap.html
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub struct Values<'a, K: 'a, V: 'a> {
1753 inner: Iter<'a, K, V>,
1756 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a, K, V> Clone for Values<'a, K, V> {
1759 fn clone(&self) -> Values<'a, K, V> {
1760 Values { inner: self.inner.clone() }
1764 #[stable(feature = "std_debug", since = "1.16.0")]
1765 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1766 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1768 .entries(self.clone())
1773 /// A draining iterator over the entries of a `HashMap`.
1775 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1776 /// documentation for more.
1778 /// [`drain`]: struct.HashMap.html#method.drain
1779 /// [`HashMap`]: struct.HashMap.html
1780 #[stable(feature = "drain", since = "1.6.0")]
1781 pub struct Drain<'a, K: 'a, V: 'a> {
1782 pub(super) inner: table::Drain<'a, K, V>,
1785 /// A mutable iterator over the values of a `HashMap`.
1787 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1788 /// documentation for more.
1790 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1791 /// [`HashMap`]: struct.HashMap.html
1792 #[stable(feature = "map_values_mut", since = "1.10.0")]
1793 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1794 inner: IterMut<'a, K, V>,
1797 enum InternalEntry<K, V, M> {
1798 Occupied { elem: FullBucket<K, V, M> },
1801 elem: VacantEntryState<K, V, M>,
1806 impl<K, V, M> InternalEntry<K, V, M> {
1808 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1810 InternalEntry::Occupied { elem } => Some(elem),
1816 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1818 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1820 InternalEntry::Occupied { elem } => {
1821 Some(Occupied(OccupiedEntry {
1826 InternalEntry::Vacant { hash, elem } => {
1827 Some(Vacant(VacantEntry {
1833 InternalEntry::TableIsEmpty => None,
1838 /// A builder for computing where in a HashMap a key-value pair would be stored.
1840 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1842 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1844 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1845 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1846 map: &'a mut HashMap<K, V, S>,
1849 /// A view into a single entry in a map, which may either be vacant or occupied.
1851 /// This is a lower-level version of [`Entry`].
1853 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1855 /// [`HashMap`]: struct.HashMap.html
1856 /// [`Entry`]: enum.Entry.html
1857 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1858 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1859 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1860 /// An occupied entry.
1861 Occupied(RawOccupiedEntryMut<'a, K, V>),
1863 Vacant(RawVacantEntryMut<'a, K, V, S>),
1866 /// A view into an occupied entry in a `HashMap`.
1867 /// It is part of the [`RawEntryMut`] enum.
1869 /// [`RawEntryMut`]: enum.RawEntryMut.html
1870 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1871 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1872 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1875 /// A view into a vacant entry in a `HashMap`.
1876 /// It is part of the [`RawEntryMut`] enum.
1878 /// [`RawEntryMut`]: enum.RawEntryMut.html
1879 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1880 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1881 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1882 hash_builder: &'a S,
1885 /// A builder for computing where in a HashMap a key-value pair would be stored.
1887 /// See the [`HashMap::raw_entry`] docs for usage examples.
1889 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1890 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1891 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1892 map: &'a HashMap<K, V, S>,
1895 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1896 where S: BuildHasher,
1899 /// Creates a `RawEntryMut` from the given key.
1900 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1901 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1905 let mut hasher = self.map.hash_builder.build_hasher();
1906 k.hash(&mut hasher);
1907 self.from_key_hashed_nocheck(hasher.finish(), k)
1910 /// Creates a `RawEntryMut` from the given key and its hash.
1912 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1913 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1917 self.from_hash(hash, |q| q.borrow().eq(k))
1921 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> RawEntryMut<'a, K, V, S>
1922 where for<'b> F: FnMut(&'b K) -> bool,
1924 match search_hashed_nonempty_mut(&mut self.map.table,
1925 SafeHash::new(hash),
1928 InternalEntry::Occupied { elem } => {
1929 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1931 InternalEntry::Vacant { elem, .. } => {
1932 RawEntryMut::Vacant(RawVacantEntryMut {
1934 hash_builder: &self.map.hash_builder,
1937 InternalEntry::TableIsEmpty => {
1942 /// Creates 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 if unsafe { unlikely(self.map.table.size() == 0) } {
1992 match search_hashed_nonempty(&self.map.table,
1993 SafeHash::new(hash),
1996 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
1997 InternalEntry::Vacant { .. } => None,
1998 InternalEntry::TableIsEmpty => unreachable!(),
2002 /// Access an entry by hash.
2003 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2004 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2005 where F: FnMut(&K) -> bool
2007 self.search(hash, is_match, true)
2010 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2011 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2013 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2014 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2015 where F: FnMut(&K) -> bool
2017 self.search(hash, is_match, false)
2021 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2022 /// Ensures a value is in the entry by inserting the default if empty, and returns
2023 /// mutable references to the key and value in the entry.
2028 /// #![feature(hash_raw_entry)]
2029 /// use std::collections::HashMap;
2031 /// let mut map: HashMap<&str, u32> = HashMap::new();
2033 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2034 /// assert_eq!(map["poneyland"], 3);
2036 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2037 /// assert_eq!(map["poneyland"], 6);
2039 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2040 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2045 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2046 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2050 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2051 /// and returns mutable references to the key and value in the entry.
2056 /// #![feature(hash_raw_entry)]
2057 /// use std::collections::HashMap;
2059 /// let mut map: HashMap<&str, String> = HashMap::new();
2061 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2062 /// ("poneyland", "hoho".to_string())
2065 /// assert_eq!(map["poneyland"], "hoho".to_string());
2067 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2068 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2069 where F: FnOnce() -> (K, V),
2074 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2075 RawEntryMut::Vacant(entry) => {
2076 let (k, v) = default();
2082 /// Provides in-place mutable access to an occupied entry before any
2083 /// potential inserts into the map.
2088 /// #![feature(hash_raw_entry)]
2089 /// use std::collections::HashMap;
2091 /// let mut map: HashMap<&str, u32> = HashMap::new();
2093 /// map.raw_entry_mut()
2094 /// .from_key("poneyland")
2095 /// .and_modify(|_k, v| { *v += 1 })
2096 /// .or_insert("poneyland", 42);
2097 /// assert_eq!(map["poneyland"], 42);
2099 /// map.raw_entry_mut()
2100 /// .from_key("poneyland")
2101 /// .and_modify(|_k, v| { *v += 1 })
2102 /// .or_insert("poneyland", 0);
2103 /// assert_eq!(map["poneyland"], 43);
2105 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2106 pub fn and_modify<F>(self, f: F) -> Self
2107 where F: FnOnce(&mut K, &mut V)
2110 RawEntryMut::Occupied(mut entry) => {
2112 let (k, v) = entry.get_key_value_mut();
2115 RawEntryMut::Occupied(entry)
2117 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2122 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2123 /// Gets a reference to the key in the entry.
2124 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2125 pub fn key(&self) -> &K {
2129 /// Gets a mutable reference to the key in the entry.
2130 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2131 pub fn key_mut(&mut self) -> &mut K {
2132 self.elem.read_mut().0
2135 /// Converts the entry into a mutable reference to the key in the entry
2136 /// with a lifetime bound to the map itself.
2137 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2138 pub fn into_key(self) -> &'a mut K {
2139 self.elem.into_mut_refs().0
2142 /// Gets a reference to the value in the entry.
2143 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2144 pub fn get(&self) -> &V {
2148 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2149 /// with a lifetime bound to the map itself.
2150 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2151 pub fn into_mut(self) -> &'a mut V {
2152 self.elem.into_mut_refs().1
2155 /// Gets a mutable reference to the value in the entry.
2156 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2157 pub fn get_mut(&mut self) -> &mut V {
2158 self.elem.read_mut().1
2161 /// Gets a reference to the key and value in the entry.
2162 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2163 pub fn get_key_value(&mut self) -> (&K, &V) {
2167 /// Gets a mutable reference to the key and value in the entry.
2168 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2169 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2170 self.elem.read_mut()
2173 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2174 /// with a lifetime bound to the map itself.
2175 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2176 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2177 self.elem.into_mut_refs()
2180 /// Sets the value of the entry, and returns the entry's old value.
2181 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2182 pub fn insert(&mut self, value: V) -> V {
2183 mem::replace(self.get_mut(), value)
2186 /// Sets the value of the entry, and returns the entry's old value.
2187 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2188 pub fn insert_key(&mut self, key: K) -> K {
2189 mem::replace(self.key_mut(), key)
2192 /// Takes the value out of the entry, and returns it.
2193 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2194 pub fn remove(self) -> V {
2195 pop_internal(self.elem).1
2198 /// Take the ownership of the key and value from the map.
2199 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2200 pub fn remove_entry(self) -> (K, V) {
2201 let (k, v, _) = pop_internal(self.elem);
2206 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2207 /// Sets the value of the entry with the VacantEntry's key,
2208 /// and returns a mutable reference to it.
2209 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2210 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2214 let mut hasher = self.hash_builder.build_hasher();
2215 key.hash(&mut hasher);
2216 self.insert_hashed_nocheck(hasher.finish(), key, value)
2219 /// Sets the value of the entry with the VacantEntry's key,
2220 /// and returns a mutable reference to it.
2222 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2223 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2224 let hash = SafeHash::new(hash);
2225 let b = match self.elem {
2226 NeqElem(mut bucket, disp) => {
2227 if disp >= DISPLACEMENT_THRESHOLD {
2228 bucket.table_mut().set_tag(true);
2230 robin_hood(bucket, disp, hash, key, value)
2232 NoElem(mut bucket, disp) => {
2233 if disp >= DISPLACEMENT_THRESHOLD {
2234 bucket.table_mut().set_tag(true);
2236 bucket.put(hash, key, value)
2243 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2244 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2246 f.debug_struct("RawEntryBuilder")
2251 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2252 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2253 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2255 RawEntryMut::Vacant(ref v) => {
2256 f.debug_tuple("RawEntry")
2260 RawEntryMut::Occupied(ref o) => {
2261 f.debug_tuple("RawEntry")
2269 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2270 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2272 f.debug_struct("RawOccupiedEntryMut")
2273 .field("key", self.key())
2274 .field("value", self.get())
2279 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2280 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2282 f.debug_struct("RawVacantEntryMut")
2287 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2288 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2290 f.debug_struct("RawEntryBuilder")
2295 /// A view into a single entry in a map, which may either be vacant or occupied.
2297 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2299 /// [`HashMap`]: struct.HashMap.html
2300 /// [`entry`]: struct.HashMap.html#method.entry
2301 #[stable(feature = "rust1", since = "1.0.0")]
2302 pub enum Entry<'a, K: 'a, V: 'a> {
2303 /// An occupied entry.
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2306 OccupiedEntry<'a, K, V>),
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2311 VacantEntry<'a, K, V>),
2314 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2315 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2319 f.debug_tuple("Entry")
2323 Occupied(ref o) => {
2324 f.debug_tuple("Entry")
2332 /// A view into an occupied entry in a `HashMap`.
2333 /// It is part of the [`Entry`] enum.
2335 /// [`Entry`]: enum.Entry.html
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2339 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2342 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2343 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2345 f.debug_struct("OccupiedEntry")
2346 .field("key", self.key())
2347 .field("value", self.get())
2352 /// A view into a vacant entry in a `HashMap`.
2353 /// It is part of the [`Entry`] enum.
2355 /// [`Entry`]: enum.Entry.html
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2360 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2363 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2364 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2366 f.debug_tuple("VacantEntry")
2372 /// Possible states of a VacantEntry.
2373 enum VacantEntryState<K, V, M> {
2374 /// The index is occupied, but the key to insert has precedence,
2375 /// and will kick the current one out on insertion.
2376 NeqElem(FullBucket<K, V, M>, usize),
2377 /// The index is genuinely vacant.
2378 NoElem(EmptyBucket<K, V, M>, usize),
2381 #[stable(feature = "rust1", since = "1.0.0")]
2382 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2386 type Item = (&'a K, &'a V);
2387 type IntoIter = Iter<'a, K, V>;
2389 fn into_iter(self) -> Iter<'a, K, V> {
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2399 type Item = (&'a K, &'a mut V);
2400 type IntoIter = IterMut<'a, K, V>;
2402 fn into_iter(self) -> IterMut<'a, K, V> {
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2413 type IntoIter = IntoIter<K, V>;
2415 /// Creates a consuming iterator, that is, one that moves each key-value
2416 /// pair out of the map in arbitrary order. The map cannot be used after
2422 /// use std::collections::HashMap;
2424 /// let mut map = HashMap::new();
2425 /// map.insert("a", 1);
2426 /// map.insert("b", 2);
2427 /// map.insert("c", 3);
2429 /// // Not possible with .iter()
2430 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2432 fn into_iter(self) -> IntoIter<K, V> {
2433 IntoIter { inner: self.table.into_iter() }
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2439 type Item = (&'a K, &'a V);
2442 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2446 fn size_hint(&self) -> (usize, Option<usize>) {
2447 self.inner.size_hint()
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2453 fn len(&self) -> usize {
2458 #[stable(feature = "fused", since = "1.26.0")]
2459 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2463 type Item = (&'a K, &'a mut V);
2466 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2470 fn size_hint(&self) -> (usize, Option<usize>) {
2471 self.inner.size_hint()
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2477 fn len(&self) -> usize {
2481 #[stable(feature = "fused", since = "1.26.0")]
2482 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2484 #[stable(feature = "std_debug", since = "1.16.0")]
2485 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2486 where K: fmt::Debug,
2489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2491 .entries(self.inner.iter())
2496 #[stable(feature = "rust1", since = "1.0.0")]
2497 impl<K, V> Iterator for IntoIter<K, V> {
2501 fn next(&mut self) -> Option<(K, V)> {
2502 self.inner.next().map(|(_, k, v)| (k, v))
2505 fn size_hint(&self) -> (usize, Option<usize>) {
2506 self.inner.size_hint()
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2512 fn len(&self) -> usize {
2516 #[stable(feature = "fused", since = "1.26.0")]
2517 impl<K, V> FusedIterator for IntoIter<K, V> {}
2519 #[stable(feature = "std_debug", since = "1.16.0")]
2520 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2523 .entries(self.inner.iter())
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2533 fn next(&mut self) -> Option<(&'a K)> {
2534 self.inner.next().map(|(k, _)| k)
2537 fn size_hint(&self) -> (usize, Option<usize>) {
2538 self.inner.size_hint()
2541 #[stable(feature = "rust1", since = "1.0.0")]
2542 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2544 fn len(&self) -> usize {
2548 #[stable(feature = "fused", since = "1.26.0")]
2549 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 impl<'a, K, V> Iterator for Values<'a, K, V> {
2556 fn next(&mut self) -> Option<(&'a V)> {
2557 self.inner.next().map(|(_, v)| v)
2560 fn size_hint(&self) -> (usize, Option<usize>) {
2561 self.inner.size_hint()
2564 #[stable(feature = "rust1", since = "1.0.0")]
2565 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2567 fn len(&self) -> usize {
2571 #[stable(feature = "fused", since = "1.26.0")]
2572 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2574 #[stable(feature = "map_values_mut", since = "1.10.0")]
2575 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2576 type Item = &'a mut V;
2579 fn next(&mut self) -> Option<(&'a mut V)> {
2580 self.inner.next().map(|(_, v)| v)
2583 fn size_hint(&self) -> (usize, Option<usize>) {
2584 self.inner.size_hint()
2587 #[stable(feature = "map_values_mut", since = "1.10.0")]
2588 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2590 fn len(&self) -> usize {
2594 #[stable(feature = "fused", since = "1.26.0")]
2595 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2597 #[stable(feature = "std_debug", since = "1.16.0")]
2598 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2599 where K: fmt::Debug,
2602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2604 .entries(self.inner.inner.iter())
2609 #[stable(feature = "drain", since = "1.6.0")]
2610 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2614 fn next(&mut self) -> Option<(K, V)> {
2615 self.inner.next().map(|(_, k, v)| (k, v))
2618 fn size_hint(&self) -> (usize, Option<usize>) {
2619 self.inner.size_hint()
2622 #[stable(feature = "drain", since = "1.6.0")]
2623 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2625 fn len(&self) -> usize {
2629 #[stable(feature = "fused", since = "1.26.0")]
2630 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2632 #[stable(feature = "std_debug", since = "1.16.0")]
2633 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2634 where K: fmt::Debug,
2637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2639 .entries(self.inner.iter())
2644 impl<'a, K, V> Entry<'a, K, V> {
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 /// Ensures a value is in the entry by inserting the default if empty, and returns
2647 /// a mutable reference to the value in the entry.
2652 /// use std::collections::HashMap;
2654 /// let mut map: HashMap<&str, u32> = HashMap::new();
2656 /// map.entry("poneyland").or_insert(3);
2657 /// assert_eq!(map["poneyland"], 3);
2659 /// *map.entry("poneyland").or_insert(10) *= 2;
2660 /// assert_eq!(map["poneyland"], 6);
2662 pub fn or_insert(self, default: V) -> &'a mut V {
2664 Occupied(entry) => entry.into_mut(),
2665 Vacant(entry) => entry.insert(default),
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2671 /// and returns a mutable reference to the value in the entry.
2676 /// use std::collections::HashMap;
2678 /// let mut map: HashMap<&str, String> = HashMap::new();
2679 /// let s = "hoho".to_string();
2681 /// map.entry("poneyland").or_insert_with(|| s);
2683 /// assert_eq!(map["poneyland"], "hoho".to_string());
2685 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2687 Occupied(entry) => entry.into_mut(),
2688 Vacant(entry) => entry.insert(default()),
2692 /// Returns a reference to this entry's key.
2697 /// use std::collections::HashMap;
2699 /// let mut map: HashMap<&str, u32> = HashMap::new();
2700 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2702 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2703 pub fn key(&self) -> &K {
2705 Occupied(ref entry) => entry.key(),
2706 Vacant(ref entry) => entry.key(),
2710 /// Provides in-place mutable access to an occupied entry before any
2711 /// potential inserts into the map.
2716 /// use std::collections::HashMap;
2718 /// let mut map: HashMap<&str, u32> = HashMap::new();
2720 /// map.entry("poneyland")
2721 /// .and_modify(|e| { *e += 1 })
2723 /// assert_eq!(map["poneyland"], 42);
2725 /// map.entry("poneyland")
2726 /// .and_modify(|e| { *e += 1 })
2728 /// assert_eq!(map["poneyland"], 43);
2730 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2731 pub fn and_modify<F>(self, f: F) -> Self
2732 where F: FnOnce(&mut V)
2735 Occupied(mut entry) => {
2739 Vacant(entry) => Vacant(entry),
2745 impl<'a, K, V: Default> Entry<'a, K, V> {
2746 #[stable(feature = "entry_or_default", since = "1.28.0")]
2747 /// Ensures a value is in the entry by inserting the default value if empty,
2748 /// and returns a mutable reference to the value in the entry.
2754 /// use std::collections::HashMap;
2756 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2757 /// map.entry("poneyland").or_default();
2759 /// assert_eq!(map["poneyland"], None);
2762 pub fn or_default(self) -> &'a mut V {
2764 Occupied(entry) => entry.into_mut(),
2765 Vacant(entry) => entry.insert(Default::default()),
2770 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2771 /// Gets a reference to the key in the entry.
2776 /// use std::collections::HashMap;
2778 /// let mut map: HashMap<&str, u32> = HashMap::new();
2779 /// map.entry("poneyland").or_insert(12);
2780 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2782 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2783 pub fn key(&self) -> &K {
2787 /// Take the ownership of the key and value from the map.
2792 /// use std::collections::HashMap;
2793 /// use std::collections::hash_map::Entry;
2795 /// let mut map: HashMap<&str, u32> = HashMap::new();
2796 /// map.entry("poneyland").or_insert(12);
2798 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2799 /// // We delete the entry from the map.
2800 /// o.remove_entry();
2803 /// assert_eq!(map.contains_key("poneyland"), false);
2805 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2806 pub fn remove_entry(self) -> (K, V) {
2807 let (k, v, _) = pop_internal(self.elem);
2811 /// Gets a reference to the value in the entry.
2816 /// use std::collections::HashMap;
2817 /// use std::collections::hash_map::Entry;
2819 /// let mut map: HashMap<&str, u32> = HashMap::new();
2820 /// map.entry("poneyland").or_insert(12);
2822 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2823 /// assert_eq!(o.get(), &12);
2826 #[stable(feature = "rust1", since = "1.0.0")]
2827 pub fn get(&self) -> &V {
2831 /// Gets a mutable reference to the value in the entry.
2833 /// If you need a reference to the `OccupiedEntry` which may outlive the
2834 /// destruction of the `Entry` value, see [`into_mut`].
2836 /// [`into_mut`]: #method.into_mut
2841 /// use std::collections::HashMap;
2842 /// use std::collections::hash_map::Entry;
2844 /// let mut map: HashMap<&str, u32> = HashMap::new();
2845 /// map.entry("poneyland").or_insert(12);
2847 /// assert_eq!(map["poneyland"], 12);
2848 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2849 /// *o.get_mut() += 10;
2850 /// assert_eq!(*o.get(), 22);
2852 /// // We can use the same Entry multiple times.
2853 /// *o.get_mut() += 2;
2856 /// assert_eq!(map["poneyland"], 24);
2858 #[stable(feature = "rust1", since = "1.0.0")]
2859 pub fn get_mut(&mut self) -> &mut V {
2860 self.elem.read_mut().1
2863 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2864 /// with a lifetime bound to the map itself.
2866 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2868 /// [`get_mut`]: #method.get_mut
2873 /// use std::collections::HashMap;
2874 /// use std::collections::hash_map::Entry;
2876 /// let mut map: HashMap<&str, u32> = HashMap::new();
2877 /// map.entry("poneyland").or_insert(12);
2879 /// assert_eq!(map["poneyland"], 12);
2880 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2881 /// *o.into_mut() += 10;
2884 /// assert_eq!(map["poneyland"], 22);
2886 #[stable(feature = "rust1", since = "1.0.0")]
2887 pub fn into_mut(self) -> &'a mut V {
2888 self.elem.into_mut_refs().1
2891 /// Sets the value of the entry, and returns the entry's old value.
2896 /// use std::collections::HashMap;
2897 /// use std::collections::hash_map::Entry;
2899 /// let mut map: HashMap<&str, u32> = HashMap::new();
2900 /// map.entry("poneyland").or_insert(12);
2902 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2903 /// assert_eq!(o.insert(15), 12);
2906 /// assert_eq!(map["poneyland"], 15);
2908 #[stable(feature = "rust1", since = "1.0.0")]
2909 pub fn insert(&mut self, mut value: V) -> V {
2910 let old_value = self.get_mut();
2911 mem::swap(&mut value, old_value);
2915 /// Takes the value out of the entry, and returns it.
2920 /// use std::collections::HashMap;
2921 /// use std::collections::hash_map::Entry;
2923 /// let mut map: HashMap<&str, u32> = HashMap::new();
2924 /// map.entry("poneyland").or_insert(12);
2926 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2927 /// assert_eq!(o.remove(), 12);
2930 /// assert_eq!(map.contains_key("poneyland"), false);
2932 #[stable(feature = "rust1", since = "1.0.0")]
2933 pub fn remove(self) -> V {
2934 pop_internal(self.elem).1
2937 /// Returns a key that was used for search.
2939 /// The key was retained for further use.
2940 fn take_key(&mut self) -> Option<K> {
2944 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2945 /// the key used to create this entry.
2950 /// #![feature(map_entry_replace)]
2951 /// use std::collections::hash_map::{Entry, HashMap};
2952 /// use std::rc::Rc;
2954 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2955 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2957 /// let my_key = Rc::new("Stringthing".to_string());
2959 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2960 /// // Also replace the key with a handle to our other key.
2961 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2965 #[unstable(feature = "map_entry_replace", issue = "44286")]
2966 pub fn replace_entry(mut self, value: V) -> (K, V) {
2967 let (old_key, old_value) = self.elem.read_mut();
2969 let old_key = mem::replace(old_key, self.key.unwrap());
2970 let old_value = mem::replace(old_value, value);
2972 (old_key, old_value)
2975 /// Replaces the key in the hash map with the key used to create this entry.
2980 /// #![feature(map_entry_replace)]
2981 /// use std::collections::hash_map::{Entry, HashMap};
2982 /// use std::rc::Rc;
2984 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2985 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2987 /// // Initialise known strings, run program, etc.
2989 /// reclaim_memory(&mut map, &known_strings);
2991 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2992 /// for s in known_strings {
2993 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2994 /// // Replaces the entry's key with our version of it in `known_strings`.
2995 /// entry.replace_key();
3000 #[unstable(feature = "map_entry_replace", issue = "44286")]
3001 pub fn replace_key(mut self) -> K {
3002 let (old_key, _) = self.elem.read_mut();
3003 mem::replace(old_key, self.key.unwrap())
3007 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3008 /// Gets a reference to the key that would be used when inserting a value
3009 /// through the `VacantEntry`.
3014 /// use std::collections::HashMap;
3016 /// let mut map: HashMap<&str, u32> = HashMap::new();
3017 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3019 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3020 pub fn key(&self) -> &K {
3024 /// Take ownership of the key.
3029 /// use std::collections::HashMap;
3030 /// use std::collections::hash_map::Entry;
3032 /// let mut map: HashMap<&str, u32> = HashMap::new();
3034 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3038 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3039 pub fn into_key(self) -> K {
3043 /// Sets the value of the entry with the VacantEntry's key,
3044 /// and returns a mutable reference to it.
3049 /// use std::collections::HashMap;
3050 /// use std::collections::hash_map::Entry;
3052 /// let mut map: HashMap<&str, u32> = HashMap::new();
3054 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3057 /// assert_eq!(map["poneyland"], 37);
3059 #[stable(feature = "rust1", since = "1.0.0")]
3060 pub fn insert(self, value: V) -> &'a mut V {
3061 let b = match self.elem {
3062 NeqElem(mut bucket, disp) => {
3063 if disp >= DISPLACEMENT_THRESHOLD {
3064 bucket.table_mut().set_tag(true);
3066 robin_hood(bucket, disp, self.hash, self.key, value)
3068 NoElem(mut bucket, disp) => {
3069 if disp >= DISPLACEMENT_THRESHOLD {
3070 bucket.table_mut().set_tag(true);
3072 bucket.put(self.hash, self.key, value)
3079 #[stable(feature = "rust1", since = "1.0.0")]
3080 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3082 S: BuildHasher + Default
3084 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3085 let mut map = HashMap::with_hasher(Default::default());
3091 #[stable(feature = "rust1", since = "1.0.0")]
3092 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3096 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3097 // Keys may be already present or show multiple times in the iterator.
3098 // Reserve the entire hint lower bound if the map is empty.
3099 // Otherwise reserve half the hint (rounded up), so the map
3100 // will only resize twice in the worst case.
3101 let iter = iter.into_iter();
3102 let reserve = if self.is_empty() {
3105 (iter.size_hint().0 + 1) / 2
3107 self.reserve(reserve);
3108 for (k, v) in iter {
3114 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3115 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3116 where K: Eq + Hash + Copy,
3120 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3121 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3125 /// `RandomState` is the default state for [`HashMap`] types.
3127 /// A particular instance `RandomState` will create the same instances of
3128 /// [`Hasher`], but the hashers created by two different `RandomState`
3129 /// instances are unlikely to produce the same result for the same values.
3131 /// [`HashMap`]: struct.HashMap.html
3132 /// [`Hasher`]: ../../hash/trait.Hasher.html
3137 /// use std::collections::HashMap;
3138 /// use std::collections::hash_map::RandomState;
3140 /// let s = RandomState::new();
3141 /// let mut map = HashMap::with_hasher(s);
3142 /// map.insert(1, 2);
3145 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3146 pub struct RandomState {
3152 /// Constructs a new `RandomState` that is initialized with random keys.
3157 /// use std::collections::hash_map::RandomState;
3159 /// let s = RandomState::new();
3162 #[allow(deprecated)]
3164 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3165 pub fn new() -> RandomState {
3166 // Historically this function did not cache keys from the OS and instead
3167 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3168 // was discovered, however, that because we re-seed the thread-local RNG
3169 // from the OS periodically that this can cause excessive slowdown when
3170 // many hash maps are created on a thread. To solve this performance
3171 // trap we cache the first set of randomly generated keys per-thread.
3173 // Later in #36481 it was discovered that exposing a deterministic
3174 // iteration order allows a form of DOS attack. To counter that we
3175 // increment one of the seeds on every RandomState creation, giving
3176 // every corresponding HashMap a different iteration order.
3177 thread_local!(static KEYS: Cell<(u64, u64)> = {
3178 Cell::new(sys::hashmap_random_keys())
3182 let (k0, k1) = keys.get();
3183 keys.set((k0.wrapping_add(1), k1));
3184 RandomState { k0: k0, k1: k1 }
3189 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3190 impl BuildHasher for RandomState {
3191 type Hasher = DefaultHasher;
3193 #[allow(deprecated)]
3194 fn build_hasher(&self) -> DefaultHasher {
3195 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3199 /// The default [`Hasher`] used by [`RandomState`].
3201 /// The internal algorithm is not specified, and so it and its hashes should
3202 /// not be relied upon over releases.
3204 /// [`RandomState`]: struct.RandomState.html
3205 /// [`Hasher`]: ../../hash/trait.Hasher.html
3206 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3207 #[allow(deprecated)]
3208 #[derive(Clone, Debug)]
3209 pub struct DefaultHasher(SipHasher13);
3211 impl DefaultHasher {
3212 /// Creates a new `DefaultHasher`.
3214 /// This hasher is not guaranteed to be the same as all other
3215 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3216 /// instances created through `new` or `default`.
3217 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3218 #[allow(deprecated)]
3219 pub fn new() -> DefaultHasher {
3220 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3224 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3225 impl Default for DefaultHasher {
3226 /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3227 /// See its documentation for more.
3228 fn default() -> DefaultHasher {
3229 DefaultHasher::new()
3233 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3234 impl Hasher for DefaultHasher {
3236 fn write(&mut self, msg: &[u8]) {
3241 fn finish(&self) -> u64 {
3246 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3247 impl Default for RandomState {
3248 /// Constructs a new `RandomState`.
3250 fn default() -> RandomState {
3255 #[stable(feature = "std_debug", since = "1.16.0")]
3256 impl fmt::Debug for RandomState {
3257 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3258 f.pad("RandomState { .. }")
3262 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3263 where K: Eq + Hash + Borrow<Q>,
3270 fn get(&self, key: &Q) -> Option<&K> {
3271 self.search(key).map(|bucket| bucket.into_refs().0)
3274 fn take(&mut self, key: &Q) -> Option<K> {
3275 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3279 fn replace(&mut self, key: K) -> Option<K> {
3282 match self.entry(key) {
3283 Occupied(mut occupied) => {
3284 let key = occupied.take_key().unwrap();
3285 Some(mem::replace(occupied.elem.read_mut().0, key))
3296 fn assert_covariance() {
3297 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3300 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3303 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3306 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3309 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3312 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3315 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3318 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3321 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3324 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3327 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3328 -> Drain<'new, &'new str, &'new str> {
3336 use super::Entry::{Occupied, Vacant};
3337 use super::RandomState;
3339 use rand::{thread_rng, Rng};
3340 use realstd::collections::CollectionAllocErr::*;
3341 use realstd::mem::size_of;
3345 fn test_zero_capacities() {
3346 type HM = HashMap<i32, i32>;
3349 assert_eq!(m.capacity(), 0);
3351 let m = HM::default();
3352 assert_eq!(m.capacity(), 0);
3354 let m = HM::with_hasher(RandomState::new());
3355 assert_eq!(m.capacity(), 0);
3357 let m = HM::with_capacity(0);
3358 assert_eq!(m.capacity(), 0);
3360 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3361 assert_eq!(m.capacity(), 0);
3363 let mut m = HM::new();
3369 assert_eq!(m.capacity(), 0);
3371 let mut m = HM::new();
3373 assert_eq!(m.capacity(), 0);
3377 fn test_create_capacity_zero() {
3378 let mut m = HashMap::with_capacity(0);
3380 assert!(m.insert(1, 1).is_none());
3382 assert!(m.contains_key(&1));
3383 assert!(!m.contains_key(&0));
3388 let mut m = HashMap::new();
3389 assert_eq!(m.len(), 0);
3390 assert!(m.insert(1, 2).is_none());
3391 assert_eq!(m.len(), 1);
3392 assert!(m.insert(2, 4).is_none());
3393 assert_eq!(m.len(), 2);
3394 assert_eq!(*m.get(&1).unwrap(), 2);
3395 assert_eq!(*m.get(&2).unwrap(), 4);
3400 let mut m = HashMap::new();
3401 assert_eq!(m.len(), 0);
3402 assert!(m.insert(1, 2).is_none());
3403 assert_eq!(m.len(), 1);
3404 assert!(m.insert(2, 4).is_none());
3405 assert_eq!(m.len(), 2);
3407 assert_eq!(*m2.get(&1).unwrap(), 2);
3408 assert_eq!(*m2.get(&2).unwrap(), 4);
3409 assert_eq!(m2.len(), 2);
3412 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3414 #[derive(Hash, PartialEq, Eq)]
3420 fn new(k: usize) -> Droppable {
3421 DROP_VECTOR.with(|slot| {
3422 slot.borrow_mut()[k] += 1;
3429 impl Drop for Droppable {
3430 fn drop(&mut self) {
3431 DROP_VECTOR.with(|slot| {
3432 slot.borrow_mut()[self.k] -= 1;
3437 impl Clone for Droppable {
3438 fn clone(&self) -> Droppable {
3439 Droppable::new(self.k)
3445 DROP_VECTOR.with(|slot| {
3446 *slot.borrow_mut() = vec![0; 200];
3450 let mut m = HashMap::new();
3452 DROP_VECTOR.with(|v| {
3454 assert_eq!(v.borrow()[i], 0);
3459 let d1 = Droppable::new(i);
3460 let d2 = Droppable::new(i + 100);
3464 DROP_VECTOR.with(|v| {
3466 assert_eq!(v.borrow()[i], 1);
3471 let k = Droppable::new(i);
3472 let v = m.remove(&k);
3474 assert!(v.is_some());
3476 DROP_VECTOR.with(|v| {
3477 assert_eq!(v.borrow()[i], 1);
3478 assert_eq!(v.borrow()[i+100], 1);
3482 DROP_VECTOR.with(|v| {
3484 assert_eq!(v.borrow()[i], 0);
3485 assert_eq!(v.borrow()[i+100], 0);
3489 assert_eq!(v.borrow()[i], 1);
3490 assert_eq!(v.borrow()[i+100], 1);
3495 DROP_VECTOR.with(|v| {
3497 assert_eq!(v.borrow()[i], 0);
3503 fn test_into_iter_drops() {
3504 DROP_VECTOR.with(|v| {
3505 *v.borrow_mut() = vec![0; 200];
3509 let mut hm = HashMap::new();
3511 DROP_VECTOR.with(|v| {
3513 assert_eq!(v.borrow()[i], 0);
3518 let d1 = Droppable::new(i);
3519 let d2 = Droppable::new(i + 100);
3523 DROP_VECTOR.with(|v| {
3525 assert_eq!(v.borrow()[i], 1);
3532 // By the way, ensure that cloning doesn't screw up the dropping.
3536 let mut half = hm.into_iter().take(50);
3538 DROP_VECTOR.with(|v| {
3540 assert_eq!(v.borrow()[i], 1);
3544 for _ in half.by_ref() {}
3546 DROP_VECTOR.with(|v| {
3548 .filter(|&i| v.borrow()[i] == 1)
3552 .filter(|&i| v.borrow()[i + 100] == 1)
3560 DROP_VECTOR.with(|v| {
3562 assert_eq!(v.borrow()[i], 0);
3568 fn test_empty_remove() {
3569 let mut m: HashMap<i32, bool> = HashMap::new();
3570 assert_eq!(m.remove(&0), None);
3574 fn test_empty_entry() {
3575 let mut m: HashMap<i32, bool> = HashMap::new();
3577 Occupied(_) => panic!(),
3580 assert!(*m.entry(0).or_insert(true));
3581 assert_eq!(m.len(), 1);
3585 fn test_empty_iter() {
3586 let mut m: HashMap<i32, bool> = HashMap::new();
3587 assert_eq!(m.drain().next(), None);
3588 assert_eq!(m.keys().next(), None);
3589 assert_eq!(m.values().next(), None);
3590 assert_eq!(m.values_mut().next(), None);
3591 assert_eq!(m.iter().next(), None);
3592 assert_eq!(m.iter_mut().next(), None);
3593 assert_eq!(m.len(), 0);
3594 assert!(m.is_empty());
3595 assert_eq!(m.into_iter().next(), None);
3599 fn test_lots_of_insertions() {
3600 let mut m = HashMap::new();
3602 // Try this a few times to make sure we never screw up the hashmap's
3605 assert!(m.is_empty());
3608 assert!(m.insert(i, i).is_none());
3612 assert_eq!(r, Some(&j));
3615 for j in i + 1..1001 {
3617 assert_eq!(r, None);
3621 for i in 1001..2001 {
3622 assert!(!m.contains_key(&i));
3627 assert!(m.remove(&i).is_some());
3630 assert!(!m.contains_key(&j));
3633 for j in i + 1..1001 {
3634 assert!(m.contains_key(&j));
3639 assert!(!m.contains_key(&i));
3643 assert!(m.insert(i, i).is_none());
3647 for i in (1..1001).rev() {
3648 assert!(m.remove(&i).is_some());
3651 assert!(!m.contains_key(&j));
3655 assert!(m.contains_key(&j));
3662 fn test_find_mut() {
3663 let mut m = HashMap::new();
3664 assert!(m.insert(1, 12).is_none());
3665 assert!(m.insert(2, 8).is_none());
3666 assert!(m.insert(5, 14).is_none());
3668 match m.get_mut(&5) {
3670 Some(x) => *x = new,
3672 assert_eq!(m.get(&5), Some(&new));
3676 fn test_insert_overwrite() {
3677 let mut m = HashMap::new();
3678 assert!(m.insert(1, 2).is_none());
3679 assert_eq!(*m.get(&1).unwrap(), 2);
3680 assert!(!m.insert(1, 3).is_none());
3681 assert_eq!(*m.get(&1).unwrap(), 3);
3685 fn test_insert_conflicts() {
3686 let mut m = HashMap::with_capacity(4);
3687 assert!(m.insert(1, 2).is_none());
3688 assert!(m.insert(5, 3).is_none());
3689 assert!(m.insert(9, 4).is_none());
3690 assert_eq!(*m.get(&9).unwrap(), 4);
3691 assert_eq!(*m.get(&5).unwrap(), 3);
3692 assert_eq!(*m.get(&1).unwrap(), 2);
3696 fn test_conflict_remove() {
3697 let mut m = HashMap::with_capacity(4);
3698 assert!(m.insert(1, 2).is_none());
3699 assert_eq!(*m.get(&1).unwrap(), 2);
3700 assert!(m.insert(5, 3).is_none());
3701 assert_eq!(*m.get(&1).unwrap(), 2);
3702 assert_eq!(*m.get(&5).unwrap(), 3);
3703 assert!(m.insert(9, 4).is_none());
3704 assert_eq!(*m.get(&1).unwrap(), 2);
3705 assert_eq!(*m.get(&5).unwrap(), 3);
3706 assert_eq!(*m.get(&9).unwrap(), 4);
3707 assert!(m.remove(&1).is_some());
3708 assert_eq!(*m.get(&9).unwrap(), 4);
3709 assert_eq!(*m.get(&5).unwrap(), 3);
3713 fn test_is_empty() {
3714 let mut m = HashMap::with_capacity(4);
3715 assert!(m.insert(1, 2).is_none());
3716 assert!(!m.is_empty());
3717 assert!(m.remove(&1).is_some());
3718 assert!(m.is_empty());
3723 let mut m = HashMap::new();
3725 assert_eq!(m.remove(&1), Some(2));
3726 assert_eq!(m.remove(&1), None);
3730 fn test_remove_entry() {
3731 let mut m = HashMap::new();
3733 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3734 assert_eq!(m.remove(&1), None);
3739 let mut m = HashMap::with_capacity(4);
3741 assert!(m.insert(i, i*2).is_none());
3743 assert_eq!(m.len(), 32);
3745 let mut observed: u32 = 0;
3748 assert_eq!(*v, *k * 2);
3749 observed |= 1 << *k;
3751 assert_eq!(observed, 0xFFFF_FFFF);
3756 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3757 let map: HashMap<_, _> = vec.into_iter().collect();
3758 let keys: Vec<_> = map.keys().cloned().collect();
3759 assert_eq!(keys.len(), 3);
3760 assert!(keys.contains(&1));
3761 assert!(keys.contains(&2));
3762 assert!(keys.contains(&3));
3767 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3768 let map: HashMap<_, _> = vec.into_iter().collect();
3769 let values: Vec<_> = map.values().cloned().collect();
3770 assert_eq!(values.len(), 3);
3771 assert!(values.contains(&'a'));
3772 assert!(values.contains(&'b'));
3773 assert!(values.contains(&'c'));
3777 fn test_values_mut() {
3778 let vec = vec![(1, 1), (2, 2), (3, 3)];
3779 let mut map: HashMap<_, _> = vec.into_iter().collect();
3780 for value in map.values_mut() {
3781 *value = (*value) * 2
3783 let values: Vec<_> = map.values().cloned().collect();
3784 assert_eq!(values.len(), 3);
3785 assert!(values.contains(&2));
3786 assert!(values.contains(&4));
3787 assert!(values.contains(&6));
3792 let mut m = HashMap::new();
3793 assert!(m.get(&1).is_none());
3797 Some(v) => assert_eq!(*v, 2),
3803 let mut m1 = HashMap::new();
3808 let mut m2 = HashMap::new();
3821 let mut map = HashMap::new();
3822 let empty: HashMap<i32, i32> = HashMap::new();
3827 let map_str = format!("{:?}", map);
3829 assert!(map_str == "{1: 2, 3: 4}" ||
3830 map_str == "{3: 4, 1: 2}");
3831 assert_eq!(format!("{:?}", empty), "{}");
3836 let mut m = HashMap::new();
3838 assert_eq!(m.len(), 0);
3839 assert!(m.is_empty());
3842 let old_raw_cap = m.raw_capacity();
3843 while old_raw_cap == m.raw_capacity() {
3848 assert_eq!(m.len(), i);
3849 assert!(!m.is_empty());
3853 fn test_behavior_resize_policy() {
3854 let mut m = HashMap::new();
3856 assert_eq!(m.len(), 0);
3857 assert_eq!(m.raw_capacity(), 0);
3858 assert!(m.is_empty());
3862 assert!(m.is_empty());
3863 let initial_raw_cap = m.raw_capacity();
3864 m.reserve(initial_raw_cap);
3865 let raw_cap = m.raw_capacity();
3867 assert_eq!(raw_cap, initial_raw_cap * 2);
3870 for _ in 0..raw_cap * 3 / 4 {
3874 // three quarters full
3876 assert_eq!(m.len(), i);
3877 assert_eq!(m.raw_capacity(), raw_cap);
3879 for _ in 0..raw_cap / 4 {
3885 let new_raw_cap = m.raw_capacity();
3886 assert_eq!(new_raw_cap, raw_cap * 2);
3888 for _ in 0..raw_cap / 2 - 1 {
3891 assert_eq!(m.raw_capacity(), new_raw_cap);
3893 // A little more than one quarter full.
3895 assert_eq!(m.raw_capacity(), raw_cap);
3896 // again, a little more than half full
3897 for _ in 0..raw_cap / 2 - 1 {
3903 assert_eq!(m.len(), i);
3904 assert!(!m.is_empty());
3905 assert_eq!(m.raw_capacity(), initial_raw_cap);
3909 fn test_reserve_shrink_to_fit() {
3910 let mut m = HashMap::new();
3913 assert!(m.capacity() >= m.len());
3919 let usable_cap = m.capacity();
3920 for i in 128..(128 + 256) {
3922 assert_eq!(m.capacity(), usable_cap);
3925 for i in 100..(128 + 256) {
3926 assert_eq!(m.remove(&i), Some(i));
3930 assert_eq!(m.len(), 100);
3931 assert!(!m.is_empty());
3932 assert!(m.capacity() >= m.len());
3935 assert_eq!(m.remove(&i), Some(i));
3940 assert_eq!(m.len(), 1);
3941 assert!(m.capacity() >= m.len());
3942 assert_eq!(m.remove(&0), Some(0));
3946 fn test_from_iter() {
3947 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3949 let map: HashMap<_, _> = xs.iter().cloned().collect();
3951 for &(k, v) in &xs {
3952 assert_eq!(map.get(&k), Some(&v));
3957 fn test_size_hint() {
3958 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3960 let map: HashMap<_, _> = xs.iter().cloned().collect();
3962 let mut iter = map.iter();
3964 for _ in iter.by_ref().take(3) {}
3966 assert_eq!(iter.size_hint(), (3, Some(3)));
3970 fn test_iter_len() {
3971 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3973 let map: HashMap<_, _> = xs.iter().cloned().collect();
3975 let mut iter = map.iter();
3977 for _ in iter.by_ref().take(3) {}
3979 assert_eq!(iter.len(), 3);
3983 fn test_mut_size_hint() {
3984 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3986 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3988 let mut iter = map.iter_mut();
3990 for _ in iter.by_ref().take(3) {}
3992 assert_eq!(iter.size_hint(), (3, Some(3)));
3996 fn test_iter_mut_len() {
3997 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3999 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4001 let mut iter = map.iter_mut();
4003 for _ in iter.by_ref().take(3) {}
4005 assert_eq!(iter.len(), 3);
4010 let mut map = HashMap::new();
4016 assert_eq!(map[&2], 1);
4021 fn test_index_nonexistent() {
4022 let mut map = HashMap::new();
4033 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4035 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4037 // Existing key (insert)
4038 match map.entry(1) {
4039 Vacant(_) => unreachable!(),
4040 Occupied(mut view) => {
4041 assert_eq!(view.get(), &10);
4042 assert_eq!(view.insert(100), 10);
4045 assert_eq!(map.get(&1).unwrap(), &100);
4046 assert_eq!(map.len(), 6);
4049 // Existing key (update)
4050 match map.entry(2) {
4051 Vacant(_) => unreachable!(),
4052 Occupied(mut view) => {
4053 let v = view.get_mut();
4054 let new_v = (*v) * 10;
4058 assert_eq!(map.get(&2).unwrap(), &200);
4059 assert_eq!(map.len(), 6);
4061 // Existing key (take)
4062 match map.entry(3) {
4063 Vacant(_) => unreachable!(),
4065 assert_eq!(view.remove(), 30);
4068 assert_eq!(map.get(&3), None);
4069 assert_eq!(map.len(), 5);
4072 // Inexistent key (insert)
4073 match map.entry(10) {
4074 Occupied(_) => unreachable!(),
4076 assert_eq!(*view.insert(1000), 1000);
4079 assert_eq!(map.get(&10).unwrap(), &1000);
4080 assert_eq!(map.len(), 6);
4084 fn test_entry_take_doesnt_corrupt() {
4085 #![allow(deprecated)] //rand
4087 fn check(m: &HashMap<i32, ()>) {
4089 assert!(m.contains_key(k),
4090 "{} is in keys() but not in the map?", k);
4094 let mut m = HashMap::new();
4095 let mut rng = thread_rng();
4097 // Populate the map with some items.
4099 let x = rng.gen_range(-10, 10);
4104 let x = rng.gen_range(-10, 10);
4117 fn test_extend_ref() {
4118 let mut a = HashMap::new();
4120 let mut b = HashMap::new();
4122 b.insert(3, "three");
4126 assert_eq!(a.len(), 3);
4127 assert_eq!(a[&1], "one");
4128 assert_eq!(a[&2], "two");
4129 assert_eq!(a[&3], "three");
4133 fn test_capacity_not_less_than_len() {
4134 let mut a = HashMap::new();
4142 assert!(a.capacity() > a.len());
4144 let free = a.capacity() - a.len();
4150 assert_eq!(a.len(), a.capacity());
4152 // Insert at capacity should cause allocation.
4154 assert!(a.capacity() > a.len());
4158 fn test_occupied_entry_key() {
4159 let mut a = HashMap::new();
4160 let key = "hello there";
4161 let value = "value goes here";
4162 assert!(a.is_empty());
4163 a.insert(key.clone(), value.clone());
4164 assert_eq!(a.len(), 1);
4165 assert_eq!(a[key], value);
4167 match a.entry(key.clone()) {
4168 Vacant(_) => panic!(),
4169 Occupied(e) => assert_eq!(key, *e.key()),
4171 assert_eq!(a.len(), 1);
4172 assert_eq!(a[key], value);
4176 fn test_vacant_entry_key() {
4177 let mut a = HashMap::new();
4178 let key = "hello there";
4179 let value = "value goes here";
4181 assert!(a.is_empty());
4182 match a.entry(key.clone()) {
4183 Occupied(_) => panic!(),
4185 assert_eq!(key, *e.key());
4186 e.insert(value.clone());
4189 assert_eq!(a.len(), 1);
4190 assert_eq!(a[key], value);
4195 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4197 map.retain(|&k, _| k % 2 == 0);
4198 assert_eq!(map.len(), 50);
4199 assert_eq!(map[&2], 20);
4200 assert_eq!(map[&4], 40);
4201 assert_eq!(map[&6], 60);
4205 fn test_adaptive() {
4206 const TEST_LEN: usize = 5000;
4207 // by cloning we get maps with the same hasher seed
4208 let mut first = HashMap::new();
4209 let mut second = first.clone();
4210 first.extend((0..TEST_LEN).map(|i| (i, i)));
4211 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4213 for (&k, &v) in &second {
4214 let prev_cap = first.capacity();
4215 let expect_grow = first.len() == prev_cap;
4217 if !expect_grow && first.capacity() != prev_cap {
4221 panic!("Adaptive early resize failed");
4225 fn test_try_reserve() {
4227 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4229 const MAX_USIZE: usize = usize::MAX;
4231 // HashMap and RawTables use complicated size calculations
4232 // hashes_size is sizeof(HashUint) * capacity;
4233 // pairs_size is sizeof((K. V)) * capacity;
4234 // alignment_hashes_size is 8
4235 // alignment_pairs size is 4
4236 let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4237 // The following formula is used to calculate the new capacity
4238 let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4240 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4241 } else { panic!("usize::MAX should trigger an overflow!"); }
4243 if size_of::<usize>() < 8 {
4244 if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4245 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4247 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4248 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4253 fn test_raw_entry() {
4254 use super::RawEntryMut::{Occupied, Vacant};
4256 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4258 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4260 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4261 use core::hash::{BuildHasher, Hash, Hasher};
4263 let mut hasher = map.hasher().build_hasher();
4264 k.hash(&mut hasher);
4268 // Existing key (insert)
4269 match map.raw_entry_mut().from_key(&1) {
4270 Vacant(_) => unreachable!(),
4271 Occupied(mut view) => {
4272 assert_eq!(view.get(), &10);
4273 assert_eq!(view.insert(100), 10);
4276 let hash1 = compute_hash(&map, 1);
4277 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4278 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4279 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4280 assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4281 assert_eq!(map.len(), 6);
4283 // Existing key (update)
4284 match map.raw_entry_mut().from_key(&2) {
4285 Vacant(_) => unreachable!(),
4286 Occupied(mut view) => {
4287 let v = view.get_mut();
4288 let new_v = (*v) * 10;
4292 let hash2 = compute_hash(&map, 2);
4293 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4294 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4295 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4296 assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4297 assert_eq!(map.len(), 6);
4299 // Existing key (take)
4300 let hash3 = compute_hash(&map, 3);
4301 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4302 Vacant(_) => unreachable!(),
4304 assert_eq!(view.remove_entry(), (3, 30));
4307 assert_eq!(map.raw_entry().from_key(&3), None);
4308 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4309 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4310 assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4311 assert_eq!(map.len(), 5);
4314 // Nonexistent key (insert)
4315 match map.raw_entry_mut().from_key(&10) {
4316 Occupied(_) => unreachable!(),
4318 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4321 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4322 assert_eq!(map.len(), 6);
4324 // Ensure all lookup methods produce equivalent results.
4326 let hash = compute_hash(&map, k);
4327 let v = map.get(&k).cloned();
4328 let kv = v.as_ref().map(|v| (&k, v));
4330 assert_eq!(map.raw_entry().from_key(&k), kv);
4331 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4332 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4333 assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4335 match map.raw_entry_mut().from_key(&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_key_hashed_nocheck(hash, &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().from_hash(hash, |q| *q == k) {
4344 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4345 Vacant(_) => assert_eq!(v, None),
4347 match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4348 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4349 Vacant(_) => assert_eq!(v, None),