1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use self::VacantEntryState::*;
14 use collections::CollectionAllocErr;
18 use fmt::{self, Debug};
20 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
21 use iter::{FromIterator, FusedIterator};
22 use mem::{self, replace};
23 use ops::{Deref, DerefMut, Index};
26 use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
28 use super::table::BucketState::{Empty, Full};
29 use super::table::Fallibility::{Fallible, Infallible};
31 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
33 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
35 struct DefaultResizePolicy;
37 impl DefaultResizePolicy {
39 fn new() -> DefaultResizePolicy {
43 /// A hash map's "capacity" is the number of elements it can hold without
44 /// being resized. Its "raw capacity" is the number of slots required to
45 /// provide that capacity, accounting for maximum loading. The raw capacity
46 /// is always zero or a power of two.
48 fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
52 // 1. Account for loading: `raw_capacity >= len * 1.1`.
53 // 2. Ensure it is a power of two.
54 // 3. Ensure it is at least the minimum size.
55 let mut raw_cap = len.checked_mul(11)
57 .and_then(|l| l.checked_next_power_of_two())
58 .ok_or(CollectionAllocErr::CapacityOverflow)?;
60 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
66 fn raw_capacity(&self, len: usize) -> usize {
67 self.try_raw_capacity(len).expect("raw_capacity overflow")
70 /// The capacity of the given raw capacity.
72 fn capacity(&self, raw_cap: usize) -> usize {
73 // This doesn't have to be checked for overflow since allocation size
74 // in bytes will overflow earlier than multiplication by 10.
76 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
77 // to be: (raw_cap * den + den - 1) / num
78 (raw_cap * 10 + 10 - 1) / 11
82 // The main performance trick in this hashmap is called Robin Hood Hashing.
83 // It gains its excellent performance from one essential operation:
85 // If an insertion collides with an existing element, and that element's
86 // "probe distance" (how far away the element is from its ideal location)
87 // is higher than how far we've already probed, swap the elements.
89 // This massively lowers variance in probe distance, and allows us to get very
90 // high load factors with good performance. The 90% load factor I use is rather
93 // > Why a load factor of approximately 90%?
95 // In general, all the distances to initial buckets will converge on the mean.
96 // At a load factor of α, the odds of finding the target bucket after k
97 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
98 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
99 // this down to make the math easier on the CPU and avoid its FPU.
100 // Since on average we start the probing in the middle of a cache line, this
101 // strategy pulls in two cache lines of hashes on every lookup. I think that's
102 // pretty good, but if you want to trade off some space, it could go down to one
103 // cache line on average with an α of 0.84.
105 // > Wait, what? Where did you get 1-α^k from?
107 // On the first probe, your odds of a collision with an existing element is α.
108 // The odds of doing this twice in a row is approximately α^2. For three times,
109 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
110 // colliding after k tries is 1-α^k.
112 // The paper from 1986 cited below mentions an implementation which keeps track
113 // of the distance-to-initial-bucket histogram. This approach is not suitable
114 // for modern architectures because it requires maintaining an internal data
115 // structure. This allows very good first guesses, but we are most concerned
116 // with guessing entire cache lines, not individual indexes. Furthermore, array
117 // accesses are no longer linear and in one direction, as we have now. There
118 // is also memory and cache pressure that this would entail that would be very
119 // difficult to properly see in a microbenchmark.
121 // ## Future Improvements (FIXME!)
123 // Allow the load factor to be changed dynamically and/or at initialization.
125 // Also, would it be possible for us to reuse storage when growing the
126 // underlying table? This is exactly the use case for 'realloc', and may
127 // be worth exploring.
129 // ## Future Optimizations (FIXME!)
131 // Another possible design choice that I made without any real reason is
132 // parameterizing the raw table over keys and values. Technically, all we need
133 // is the size and alignment of keys and values, and the code should be just as
134 // efficient (well, we might need one for power-of-two size and one for not...).
135 // This has the potential to reduce code bloat in rust executables, without
136 // really losing anything except 4 words (key size, key alignment, val size,
137 // val alignment) which can be passed in to every call of a `RawTable` function.
138 // This would definitely be an avenue worth exploring if people start complaining
139 // about the size of rust executables.
141 // Annotate exceedingly likely branches in `table::make_hash`
142 // and `search_hashed` to reduce instruction cache pressure
143 // and mispredictions once it becomes possible (blocked on issue #11092).
145 // Shrinking the table could simply reallocate in place after moving buckets
146 // to the first half.
148 // The growth algorithm (fragment of the Proof of Correctness)
149 // --------------------
151 // The growth algorithm is basically a fast path of the naive reinsertion-
152 // during-resize algorithm. Other paths should never be taken.
154 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
155 // by allocating a new table of capacity `2n`, and then individually reinsert
156 // each element in the old table into the new one. This guarantees that the
157 // new table is a valid robin hood hashtable with all the desired statistical
158 // properties. Remark that the order we reinsert the elements in should not
159 // matter. For simplicity and efficiency, we will consider only linear
160 // reinsertions, which consist of reinserting all elements in the old table
161 // into the new one by increasing order of index. However we will not be
162 // starting our reinsertions from index 0 in general. If we start from index
163 // i, for the purpose of reinsertion we will consider all elements with real
164 // index j < i to have virtual index n + j.
166 // Our hash generation scheme consists of generating a 64-bit hash and
167 // truncating the most significant bits. When moving to the new table, we
168 // simply introduce a new bit to the front of the hash. Therefore, if an
169 // elements has ideal index i in the old table, it can have one of two ideal
170 // locations in the new table. If the new bit is 0, then the new ideal index
171 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
172 // we are producing two independent tables of size n, and for each element we
173 // independently choose which table to insert it into with equal probability.
174 // However the rather than wrapping around themselves on overflowing their
175 // indexes, the first table overflows into the first, and the first into the
176 // second. Visually, our new table will look something like:
178 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
180 // Where x's are elements inserted into the first table, y's are elements
181 // inserted into the second, and _'s are empty sections. We now define a few
182 // key concepts that we will use later. Note that this is a very abstract
183 // perspective of the table. A real resized table would be at least half
186 // Theorem: A linear robin hood reinsertion from the first ideal element
187 // produces identical results to a linear naive reinsertion from the same
190 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
192 // Adaptive early resizing
193 // ----------------------
194 // To protect against degenerate performance scenarios (including DOS attacks),
195 // the implementation includes an adaptive behavior that can resize the map
196 // early (before its capacity is exceeded) when suspiciously long probe sequences
199 // With this algorithm in place it would be possible to turn a CPU attack into
200 // a memory attack due to the aggressive resizing. To prevent that the
201 // adaptive behavior only triggers when the map is at least half full.
202 // This reduces the effectiveness of the algorithm but also makes it completely safe.
204 // The previous safety measure also prevents degenerate interactions with
205 // really bad quality hash algorithms that can make normal inputs look like a
208 const DISPLACEMENT_THRESHOLD: usize = 128;
210 // The threshold of 128 is chosen to minimize the chance of exceeding it.
211 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
212 // For displacement, the smallest constant that fits our needs is 90,
213 // so we round that up to 128.
215 // At a load factor of α, the odds of finding the target bucket after exactly n
216 // unsuccessful probes[1] are
218 // Pr_α{displacement = n} =
219 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
221 // We use this formula to find the probability of triggering the adaptive behavior
223 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
225 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
226 // hashing with buckets.
228 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
230 /// By default, `HashMap` uses a hashing algorithm selected to provide
231 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
232 /// reasonable best-effort is made to generate this seed from a high quality,
233 /// secure source of randomness provided by the host without blocking the
234 /// program. Because of this, the randomness of the seed depends on the output
235 /// quality of the system's random number generator when the seed is created.
236 /// In particular, seeds generated when the system's entropy pool is abnormally
237 /// low such as during system boot may be of a lower quality.
239 /// The default hashing algorithm is currently SipHash 1-3, though this is
240 /// subject to change at any point in the future. While its performance is very
241 /// competitive for medium sized keys, other hashing algorithms will outperform
242 /// it for small keys such as integers as well as large keys such as long
243 /// strings, though those algorithms will typically *not* protect against
244 /// attacks such as HashDoS.
246 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
247 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
248 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
250 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
251 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
252 /// If you implement these yourself, it is important that the following
256 /// k1 == k2 -> hash(k1) == hash(k2)
259 /// In other words, if two keys are equal, their hashes must be equal.
261 /// It is a logic error for a key to be modified in such a way that the key's
262 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
263 /// the [`Eq`] trait, changes while it is in the map. This is normally only
264 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
266 /// Relevant papers/articles:
268 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
269 /// 2. Emmanuel Goossaert. ["Robin Hood
270 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
271 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
272 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
277 /// use std::collections::HashMap;
279 /// // Type inference lets us omit an explicit type signature (which
280 /// // would be `HashMap<String, String>` in this example).
281 /// let mut book_reviews = HashMap::new();
283 /// // Review some books.
284 /// book_reviews.insert(
285 /// "Adventures of Huckleberry Finn".to_string(),
286 /// "My favorite book.".to_string(),
288 /// book_reviews.insert(
289 /// "Grimms' Fairy Tales".to_string(),
290 /// "Masterpiece.".to_string(),
292 /// book_reviews.insert(
293 /// "Pride and Prejudice".to_string(),
294 /// "Very enjoyable.".to_string(),
296 /// book_reviews.insert(
297 /// "The Adventures of Sherlock Holmes".to_string(),
298 /// "Eye lyked it alot.".to_string(),
301 /// // Check for a specific one.
302 /// // When collections store owned values (String), they can still be
303 /// // queried using references (&str).
304 /// if !book_reviews.contains_key("Les Misérables") {
305 /// println!("We've got {} reviews, but Les Misérables ain't one.",
306 /// book_reviews.len());
309 /// // oops, this review has a lot of spelling mistakes, let's delete it.
310 /// book_reviews.remove("The Adventures of Sherlock Holmes");
312 /// // Look up the values associated with some keys.
313 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
314 /// for &book in &to_find {
315 /// match book_reviews.get(book) {
316 /// Some(review) => println!("{}: {}", book, review),
317 /// None => println!("{} is unreviewed.", book)
321 /// // Iterate over everything.
322 /// for (book, review) in &book_reviews {
323 /// println!("{}: \"{}\"", book, review);
327 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
328 /// for more complex methods of getting, setting, updating and removing keys and
332 /// use std::collections::HashMap;
334 /// // type inference lets us omit an explicit type signature (which
335 /// // would be `HashMap<&str, u8>` in this example).
336 /// let mut player_stats = HashMap::new();
338 /// fn random_stat_buff() -> u8 {
339 /// // could actually return some random value here - let's just return
340 /// // some fixed value for now
344 /// // insert a key only if it doesn't already exist
345 /// player_stats.entry("health").or_insert(100);
347 /// // insert a key using a function that provides a new value only if it
348 /// // doesn't already exist
349 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
351 /// // update a key, guarding against the key possibly not being set
352 /// let stat = player_stats.entry("attack").or_insert(100);
353 /// *stat += random_stat_buff();
356 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
357 /// We must also derive [`PartialEq`].
359 /// [`Eq`]: ../../std/cmp/trait.Eq.html
360 /// [`Hash`]: ../../std/hash/trait.Hash.html
361 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
362 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
363 /// [`Cell`]: ../../std/cell/struct.Cell.html
364 /// [`default`]: #method.default
365 /// [`with_hasher`]: #method.with_hasher
366 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
367 /// [`fnv`]: https://crates.io/crates/fnv
370 /// use std::collections::HashMap;
372 /// #[derive(Hash, Eq, PartialEq, Debug)]
379 /// /// Create a new Viking.
380 /// fn new(name: &str, country: &str) -> Viking {
381 /// Viking { name: name.to_string(), country: country.to_string() }
385 /// // Use a HashMap to store the vikings' health points.
386 /// let mut vikings = HashMap::new();
388 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
389 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
390 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
392 /// // Use derived implementation to print the status of the vikings.
393 /// for (viking, health) in &vikings {
394 /// println!("{:?} has {} hp", viking, health);
398 /// A `HashMap` with fixed list of elements can be initialized from an array:
401 /// use std::collections::HashMap;
404 /// let timber_resources: HashMap<&str, i32> =
405 /// [("Norway", 100),
408 /// .iter().cloned().collect();
409 /// // use the values stored in map
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub struct HashMap<K, V, S = RandomState> {
416 // All hashes are keyed on these values, to prevent hash collision attacks.
419 table: RawTable<K, V>,
421 resize_policy: DefaultResizePolicy,
424 /// Search for a pre-hashed key.
425 /// If you don't already know the hash, use search or search_mut instead
427 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
428 where M: Deref<Target = RawTable<K, V>>,
431 // This is the only function where capacity can be zero. To avoid
432 // undefined behavior when Bucket::new gets the raw bucket in this
433 // case, immediately return the appropriate search result.
434 if table.capacity() == 0 {
435 return InternalEntry::TableIsEmpty;
438 search_hashed_nonempty(table, hash, is_match)
441 /// Search for a pre-hashed key.
442 /// If you don't already know the hash, use search or search_mut instead
444 fn search_hashed_mut<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
445 where M: DerefMut<Target = RawTable<K, V>>,
448 // This is the only function where capacity can be zero. To avoid
449 // undefined behavior when Bucket::new gets the raw bucket in this
450 // case, immediately return the appropriate search result.
451 if table.capacity() == 0 {
452 return InternalEntry::TableIsEmpty;
455 search_hashed_nonempty_mut(table, hash, is_match)
458 /// Search for a pre-hashed key when the hash map is known to be non-empty.
460 fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F)
461 -> InternalEntry<K, V, M>
462 where M: Deref<Target = RawTable<K, V>>,
465 // Do not check the capacity as an extra branch could slow the lookup.
467 let size = table.size();
468 let mut probe = Bucket::new(table, hash);
469 let mut displacement = 0;
472 let full = match probe.peek() {
475 return InternalEntry::Vacant {
477 elem: NoElem(bucket, displacement),
480 Full(bucket) => bucket,
483 let probe_displacement = full.displacement();
485 if probe_displacement < displacement {
486 // Found a luckier bucket than me.
487 // We can finish the search early if we hit any bucket
488 // with a lower distance to initial bucket than we've probed.
489 return InternalEntry::Vacant {
491 elem: NeqElem(full, probe_displacement),
495 // If the hash doesn't match, it can't be this one..
496 if hash == full.hash() {
497 // If the key doesn't match, it can't be this one..
498 if is_match(full.read().0) {
499 return InternalEntry::Occupied { elem: full };
504 debug_assert!(displacement <= size);
508 /// Search for a pre-hashed key when the hash map is known to be non-empty.
510 fn search_hashed_nonempty_mut<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F)
511 -> InternalEntry<K, V, M>
512 where M: DerefMut<Target = RawTable<K, V>>,
515 // Do not check the capacity as an extra branch could slow the lookup.
517 let size = table.size();
518 let mut probe = Bucket::new(table, hash);
519 let mut displacement = 0;
522 let mut full = match probe.peek() {
525 return InternalEntry::Vacant {
527 elem: NoElem(bucket, displacement),
530 Full(bucket) => bucket,
533 let probe_displacement = full.displacement();
535 if probe_displacement < displacement {
536 // Found a luckier bucket than me.
537 // We can finish the search early if we hit any bucket
538 // with a lower distance to initial bucket than we've probed.
539 return InternalEntry::Vacant {
541 elem: NeqElem(full, probe_displacement),
545 // If the hash doesn't match, it can't be this one..
546 if hash == full.hash() {
547 // If the key doesn't match, it can't be this one..
548 if is_match(full.read_mut().0) {
549 return InternalEntry::Occupied { elem: full };
554 debug_assert!(displacement <= size);
558 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
559 -> (K, V, &mut RawTable<K, V>)
561 let (empty, retkey, retval) = starting_bucket.take();
562 let mut gap = match empty.gap_peek() {
564 Err(b) => return (retkey, retval, b.into_table()),
567 while gap.full().displacement() != 0 {
568 gap = match gap.shift() {
571 return (retkey, retval, b.into_table());
576 // Now we've done all our shifting. Return the value we grabbed earlier.
577 (retkey, retval, gap.into_table())
580 /// Perform robin hood bucket stealing at the given `bucket`. You must
581 /// also pass that bucket's displacement so we don't have to recalculate it.
583 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
584 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
585 mut displacement: usize,
589 -> FullBucketMut<'a, K, V> {
590 let size = bucket.table().size();
591 let raw_capacity = bucket.table().capacity();
592 // There can be at most `size - dib` buckets to displace, because
593 // in the worst case, there are `size` elements and we already are
594 // `displacement` buckets away from the initial one.
595 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
596 // Save the *starting point*.
597 let mut bucket = bucket.stash();
600 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
607 let probe = bucket.next();
608 debug_assert!(probe.index() != idx_end);
610 let full_bucket = match probe.peek() {
613 let bucket = bucket.put(hash, key, val);
614 // Now that it's stolen, just read the value's pointer
615 // right out of the table! Go back to the *starting point*.
617 // This use of `into_table` is misleading. It turns the
618 // bucket, which is a FullBucket on top of a
619 // FullBucketMut, into just one FullBucketMut. The "table"
620 // refers to the inner FullBucketMut in this context.
621 return bucket.into_table();
623 Full(bucket) => bucket,
626 let probe_displacement = full_bucket.displacement();
628 bucket = full_bucket;
630 // Robin hood! Steal the spot.
631 if probe_displacement < displacement {
632 displacement = probe_displacement;
639 impl<K, V, S> HashMap<K, V, S>
643 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
646 table::make_hash(&self.hash_builder, x)
649 /// Search for a key, yielding the index if it's found in the hashtable.
650 /// If you already have the hash for the key lying around, or if you need an
651 /// InternalEntry, use search_hashed or search_hashed_nonempty.
653 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
654 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
662 let hash = self.make_hash(q);
663 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()))
664 .into_occupied_bucket()
668 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
669 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
677 let hash = self.make_hash(q);
678 search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()))
679 .into_occupied_bucket()
682 // The caller should ensure that invariants by Robin Hood Hashing hold
683 // and that there's space in the underlying table.
684 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
685 let mut buckets = Bucket::new(&mut self.table, hash);
686 let start_index = buckets.index();
689 // We don't need to compare hashes for value swap.
690 // Not even DIBs for Robin Hood.
691 buckets = match buckets.peek() {
693 empty.put(hash, k, v);
696 Full(b) => b.into_bucket(),
699 debug_assert!(buckets.index() != start_index);
704 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
705 /// Creates an empty `HashMap`.
707 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
708 /// is first inserted into.
713 /// use std::collections::HashMap;
714 /// let mut map: HashMap<&str, i32> = HashMap::new();
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn new() -> HashMap<K, V, RandomState> {
722 /// Creates an empty `HashMap` with the specified capacity.
724 /// The hash map will be able to hold at least `capacity` elements without
725 /// reallocating. If `capacity` is 0, the hash map will not allocate.
730 /// use std::collections::HashMap;
731 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
736 HashMap::with_capacity_and_hasher(capacity, Default::default())
740 impl<K, V, S> HashMap<K, V, S>
744 /// Creates an empty `HashMap` which will use the given hash builder to hash
747 /// The created map has the default initial capacity.
749 /// Warning: `hash_builder` is normally randomly generated, and
750 /// is designed to allow HashMaps to be resistant to attacks that
751 /// cause many collisions and very poor performance. Setting it
752 /// manually using this function can expose a DoS attack vector.
757 /// use std::collections::HashMap;
758 /// use std::collections::hash_map::RandomState;
760 /// let s = RandomState::new();
761 /// let mut map = HashMap::with_hasher(s);
762 /// map.insert(1, 2);
765 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
766 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
769 resize_policy: DefaultResizePolicy::new(),
770 table: RawTable::new(0),
774 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
775 /// to hash the keys.
777 /// The hash map will be able to hold at least `capacity` elements without
778 /// reallocating. If `capacity` is 0, the hash map will not allocate.
780 /// Warning: `hash_builder` is normally randomly generated, and
781 /// is designed to allow HashMaps to be resistant to attacks that
782 /// cause many collisions and very poor performance. Setting it
783 /// manually using this function can expose a DoS attack vector.
788 /// use std::collections::HashMap;
789 /// use std::collections::hash_map::RandomState;
791 /// let s = RandomState::new();
792 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
793 /// map.insert(1, 2);
796 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
797 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
798 let resize_policy = DefaultResizePolicy::new();
799 let raw_cap = resize_policy.raw_capacity(capacity);
803 table: RawTable::new(raw_cap),
807 /// Returns a reference to the map's [`BuildHasher`].
809 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
814 /// use std::collections::HashMap;
815 /// use std::collections::hash_map::RandomState;
817 /// let hasher = RandomState::new();
818 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
819 /// let hasher: &RandomState = map.hasher();
821 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
822 pub fn hasher(&self) -> &S {
826 /// Returns the number of elements the map can hold without reallocating.
828 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
829 /// more, but is guaranteed to be able to hold at least this many.
834 /// use std::collections::HashMap;
835 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
836 /// assert!(map.capacity() >= 100);
839 #[stable(feature = "rust1", since = "1.0.0")]
840 pub fn capacity(&self) -> usize {
841 self.resize_policy.capacity(self.raw_capacity())
844 /// Returns the hash map's raw capacity.
846 fn raw_capacity(&self) -> usize {
847 self.table.capacity()
850 /// Reserves capacity for at least `additional` more elements to be inserted
851 /// in the `HashMap`. The collection may reserve more space to avoid
852 /// frequent reallocations.
856 /// Panics if the new allocation size overflows [`usize`].
858 /// [`usize`]: ../../std/primitive.usize.html
863 /// use std::collections::HashMap;
864 /// let mut map: HashMap<&str, i32> = HashMap::new();
867 #[stable(feature = "rust1", since = "1.0.0")]
868 pub fn reserve(&mut self, additional: usize) {
869 match self.reserve_internal(additional, Infallible) {
870 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
871 Err(CollectionAllocErr::AllocErr) => unreachable!(),
872 Ok(()) => { /* yay */ }
876 /// Tries to reserve capacity for at least `additional` more elements to be inserted
877 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
878 /// frequent reallocations.
882 /// If the capacity overflows, or the allocator reports a failure, then an error
888 /// #![feature(try_reserve)]
889 /// use std::collections::HashMap;
890 /// let mut map: HashMap<&str, isize> = HashMap::new();
891 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
893 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
894 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
895 self.reserve_internal(additional, Fallible)
898 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
899 -> Result<(), CollectionAllocErr> {
901 let remaining = self.capacity() - self.len(); // this can't overflow
902 if remaining < additional {
903 let min_cap = self.len()
904 .checked_add(additional)
905 .ok_or(CollectionAllocErr::CapacityOverflow)?;
906 let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
907 self.try_resize(raw_cap, fallibility)?;
908 } else if self.table.tag() && remaining <= self.len() {
909 // Probe sequence is too long and table is half full,
910 // resize early to reduce probing length.
911 let new_capacity = self.table.capacity() * 2;
912 self.try_resize(new_capacity, fallibility)?;
917 /// Resizes the internal vectors to a new capacity. It's your
918 /// responsibility to:
919 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
920 /// for the load factor.
921 /// 2) Ensure `new_raw_cap` is a power of two or zero.
927 fallibility: Fallibility,
928 ) -> Result<(), CollectionAllocErr> {
929 assert!(self.table.size() <= new_raw_cap);
930 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
932 let mut old_table = replace(
935 Infallible => RawTable::new(new_raw_cap),
936 Fallible => RawTable::try_new(new_raw_cap)?,
939 let old_size = old_table.size();
941 if old_table.size() == 0 {
945 let mut bucket = Bucket::head_bucket(&mut old_table);
947 // This is how the buckets might be laid out in memory:
948 // ($ marks an initialized bucket)
950 // |$$$_$$$$$$_$$$$$|
952 // But we've skipped the entire initial cluster of buckets
953 // and will continue iteration in this order:
956 // ^ wrap around once end is reached
959 // ^ exit once table.size == 0
961 bucket = match bucket.peek() {
963 let h = bucket.hash();
964 let (b, k, v) = bucket.take();
965 self.insert_hashed_ordered(h, k, v);
966 if b.table().size() == 0 {
971 Empty(b) => b.into_bucket(),
976 assert_eq!(self.table.size(), old_size);
980 /// Shrinks the capacity of the map as much as possible. It will drop
981 /// down as much as possible while maintaining the internal rules
982 /// and possibly leaving some space in accordance with the resize policy.
987 /// use std::collections::HashMap;
989 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
990 /// map.insert(1, 2);
991 /// map.insert(3, 4);
992 /// assert!(map.capacity() >= 100);
993 /// map.shrink_to_fit();
994 /// assert!(map.capacity() >= 2);
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn shrink_to_fit(&mut self) {
998 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
999 if self.raw_capacity() != new_raw_cap {
1000 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1001 let old_size = old_table.size();
1003 // Shrink the table. Naive algorithm for resizing:
1004 for (h, k, v) in old_table.into_iter() {
1005 self.insert_hashed_nocheck(h, k, v);
1008 debug_assert_eq!(self.table.size(), old_size);
1012 /// Shrinks the capacity of the map with a lower limit. It will drop
1013 /// down no lower than the supplied limit while maintaining the internal rules
1014 /// and possibly leaving some space in accordance with the resize policy.
1016 /// Panics if the current capacity is smaller than the supplied
1017 /// minimum capacity.
1022 /// #![feature(shrink_to)]
1023 /// use std::collections::HashMap;
1025 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1026 /// map.insert(1, 2);
1027 /// map.insert(3, 4);
1028 /// assert!(map.capacity() >= 100);
1029 /// map.shrink_to(10);
1030 /// assert!(map.capacity() >= 10);
1031 /// map.shrink_to(0);
1032 /// assert!(map.capacity() >= 2);
1034 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
1035 pub fn shrink_to(&mut self, min_capacity: usize) {
1036 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1038 let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1039 if self.raw_capacity() != new_raw_cap {
1040 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1041 let old_size = old_table.size();
1043 // Shrink the table. Naive algorithm for resizing:
1044 for (h, k, v) in old_table.into_iter() {
1045 self.insert_hashed_nocheck(h, k, v);
1048 debug_assert_eq!(self.table.size(), old_size);
1052 /// Insert a pre-hashed key-value pair, without first checking
1053 /// that there's enough room in the buckets. Returns a reference to the
1054 /// newly insert value.
1056 /// If the key already exists, the hashtable will be returned untouched
1057 /// and a reference to the existing element will be returned.
1058 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1059 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1061 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1062 Some(Vacant(elem)) => {
1066 None => unreachable!(),
1070 /// An iterator visiting all keys in arbitrary order.
1071 /// The iterator element type is `&'a K`.
1076 /// use std::collections::HashMap;
1078 /// let mut map = HashMap::new();
1079 /// map.insert("a", 1);
1080 /// map.insert("b", 2);
1081 /// map.insert("c", 3);
1083 /// for key in map.keys() {
1084 /// println!("{}", key);
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub fn keys(&self) -> Keys<K, V> {
1089 Keys { inner: self.iter() }
1092 /// An iterator visiting all values in arbitrary order.
1093 /// The iterator element type is `&'a V`.
1098 /// use std::collections::HashMap;
1100 /// let mut map = HashMap::new();
1101 /// map.insert("a", 1);
1102 /// map.insert("b", 2);
1103 /// map.insert("c", 3);
1105 /// for val in map.values() {
1106 /// println!("{}", val);
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub fn values(&self) -> Values<K, V> {
1111 Values { inner: self.iter() }
1114 /// An iterator visiting all values mutably in arbitrary order.
1115 /// The iterator element type is `&'a mut V`.
1120 /// use std::collections::HashMap;
1122 /// let mut map = HashMap::new();
1124 /// map.insert("a", 1);
1125 /// map.insert("b", 2);
1126 /// map.insert("c", 3);
1128 /// for val in map.values_mut() {
1129 /// *val = *val + 10;
1132 /// for val in map.values() {
1133 /// println!("{}", val);
1136 #[stable(feature = "map_values_mut", since = "1.10.0")]
1137 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1138 ValuesMut { inner: self.iter_mut() }
1141 /// An iterator visiting all key-value pairs in arbitrary order.
1142 /// The iterator element type is `(&'a K, &'a V)`.
1147 /// use std::collections::HashMap;
1149 /// let mut map = HashMap::new();
1150 /// map.insert("a", 1);
1151 /// map.insert("b", 2);
1152 /// map.insert("c", 3);
1154 /// for (key, val) in map.iter() {
1155 /// println!("key: {} val: {}", key, val);
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn iter(&self) -> Iter<K, V> {
1160 Iter { inner: self.table.iter() }
1163 /// An iterator visiting all key-value pairs in arbitrary order,
1164 /// with mutable references to the values.
1165 /// The iterator element type is `(&'a K, &'a mut V)`.
1170 /// use std::collections::HashMap;
1172 /// let mut map = HashMap::new();
1173 /// map.insert("a", 1);
1174 /// map.insert("b", 2);
1175 /// map.insert("c", 3);
1177 /// // Update all values
1178 /// for (_, val) in map.iter_mut() {
1182 /// for (key, val) in &map {
1183 /// println!("key: {} val: {}", key, val);
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1188 IterMut { inner: self.table.iter_mut() }
1191 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1196 /// use std::collections::HashMap;
1198 /// let mut letters = HashMap::new();
1200 /// for ch in "a short treatise on fungi".chars() {
1201 /// let counter = letters.entry(ch).or_insert(0);
1205 /// assert_eq!(letters[&'s'], 2);
1206 /// assert_eq!(letters[&'t'], 3);
1207 /// assert_eq!(letters[&'u'], 1);
1208 /// assert_eq!(letters.get(&'y'), None);
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1212 // Gotta resize now.
1214 let hash = self.make_hash(&key);
1215 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1216 .into_entry(key).expect("unreachable")
1219 /// Returns the number of elements in the map.
1224 /// use std::collections::HashMap;
1226 /// let mut a = HashMap::new();
1227 /// assert_eq!(a.len(), 0);
1228 /// a.insert(1, "a");
1229 /// assert_eq!(a.len(), 1);
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn len(&self) -> usize {
1236 /// Returns true if the map contains no elements.
1241 /// use std::collections::HashMap;
1243 /// let mut a = HashMap::new();
1244 /// assert!(a.is_empty());
1245 /// a.insert(1, "a");
1246 /// assert!(!a.is_empty());
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn is_empty(&self) -> bool {
1254 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1255 /// allocated memory for reuse.
1260 /// use std::collections::HashMap;
1262 /// let mut a = HashMap::new();
1263 /// a.insert(1, "a");
1264 /// a.insert(2, "b");
1266 /// for (k, v) in a.drain().take(1) {
1267 /// assert!(k == 1 || k == 2);
1268 /// assert!(v == "a" || v == "b");
1271 /// assert!(a.is_empty());
1274 #[stable(feature = "drain", since = "1.6.0")]
1275 pub fn drain(&mut self) -> Drain<K, V> {
1276 Drain { inner: self.table.drain() }
1279 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1285 /// use std::collections::HashMap;
1287 /// let mut a = HashMap::new();
1288 /// a.insert(1, "a");
1290 /// assert!(a.is_empty());
1292 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub fn clear(&mut self) {
1298 /// Returns a reference to the value corresponding to the key.
1300 /// The key may be any borrowed form of the map's key type, but
1301 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1304 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1305 /// [`Hash`]: ../../std/hash/trait.Hash.html
1310 /// use std::collections::HashMap;
1312 /// let mut map = HashMap::new();
1313 /// map.insert(1, "a");
1314 /// assert_eq!(map.get(&1), Some(&"a"));
1315 /// assert_eq!(map.get(&2), None);
1317 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1323 self.search(k).map(|bucket| bucket.into_refs().1)
1326 /// Returns the key-value pair corresponding to the supplied key.
1328 /// The supplied key may be any borrowed form of the map's key type, but
1329 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1332 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1333 /// [`Hash`]: ../../std/hash/trait.Hash.html
1338 /// #![feature(map_get_key_value)]
1339 /// use std::collections::HashMap;
1341 /// let mut map = HashMap::new();
1342 /// map.insert(1, "a");
1343 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1344 /// assert_eq!(map.get_key_value(&2), None);
1346 #[unstable(feature = "map_get_key_value", issue = "49347")]
1347 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1351 self.search(k).map(|bucket| bucket.into_refs())
1354 /// Returns true if the map contains a value for the specified key.
1356 /// The key may be any borrowed form of the map's key type, but
1357 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1360 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1361 /// [`Hash`]: ../../std/hash/trait.Hash.html
1366 /// use std::collections::HashMap;
1368 /// let mut map = HashMap::new();
1369 /// map.insert(1, "a");
1370 /// assert_eq!(map.contains_key(&1), true);
1371 /// assert_eq!(map.contains_key(&2), false);
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1378 self.search(k).is_some()
1381 /// Returns a mutable reference to the value corresponding to the key.
1383 /// The key may be any borrowed form of the map's key type, but
1384 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1387 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1388 /// [`Hash`]: ../../std/hash/trait.Hash.html
1393 /// use std::collections::HashMap;
1395 /// let mut map = HashMap::new();
1396 /// map.insert(1, "a");
1397 /// if let Some(x) = map.get_mut(&1) {
1400 /// assert_eq!(map[&1], "b");
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1407 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1410 /// Inserts a key-value pair into the map.
1412 /// If the map did not have this key present, [`None`] is returned.
1414 /// If the map did have this key present, the value is updated, and the old
1415 /// value is returned. The key is not updated, though; this matters for
1416 /// types that can be `==` without being identical. See the [module-level
1417 /// documentation] for more.
1419 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1420 /// [module-level documentation]: index.html#insert-and-complex-keys
1425 /// use std::collections::HashMap;
1427 /// let mut map = HashMap::new();
1428 /// assert_eq!(map.insert(37, "a"), None);
1429 /// assert_eq!(map.is_empty(), false);
1431 /// map.insert(37, "b");
1432 /// assert_eq!(map.insert(37, "c"), Some("b"));
1433 /// assert_eq!(map[&37], "c");
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1437 let hash = self.make_hash(&k);
1439 self.insert_hashed_nocheck(hash, k, v)
1442 /// Removes a key from the map, returning the value at the key if the key
1443 /// was previously in the map.
1445 /// The key may be any borrowed form of the map's key type, but
1446 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1449 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1450 /// [`Hash`]: ../../std/hash/trait.Hash.html
1455 /// use std::collections::HashMap;
1457 /// let mut map = HashMap::new();
1458 /// map.insert(1, "a");
1459 /// assert_eq!(map.remove(&1), Some("a"));
1460 /// assert_eq!(map.remove(&1), None);
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1467 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1470 /// Removes a key from the map, returning the stored key and value if the
1471 /// key was previously in the map.
1473 /// The key may be any borrowed form of the map's key type, but
1474 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1477 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1478 /// [`Hash`]: ../../std/hash/trait.Hash.html
1483 /// use std::collections::HashMap;
1486 /// let mut map = HashMap::new();
1487 /// map.insert(1, "a");
1488 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1489 /// assert_eq!(map.remove(&1), None);
1492 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1493 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1499 let (k, v, _) = pop_internal(bucket);
1504 /// Retains only the elements specified by the predicate.
1506 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1511 /// use std::collections::HashMap;
1513 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1514 /// map.retain(|&k, _| k % 2 == 0);
1515 /// assert_eq!(map.len(), 4);
1517 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1518 pub fn retain<F>(&mut self, mut f: F)
1519 where F: FnMut(&K, &mut V) -> bool
1521 if self.table.size() == 0 {
1524 let mut elems_left = self.table.size();
1525 let mut bucket = Bucket::head_bucket(&mut self.table);
1527 let start_index = bucket.index();
1528 while elems_left != 0 {
1529 bucket = match bucket.peek() {
1532 let should_remove = {
1533 let (k, v) = full.read_mut();
1537 let prev_raw = full.raw();
1538 let (_, _, t) = pop_internal(full);
1539 Bucket::new_from(prev_raw, t)
1548 bucket.prev(); // reverse iteration
1549 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1554 impl<K, V, S> HashMap<K, V, S>
1558 /// Creates a raw entry builder for the HashMap.
1560 /// Raw entries provide the lowest level of control for searching and
1561 /// manipulating a map. They must be manually initialized with a hash and
1562 /// then manually searched. After this, insertions into a vacant entry
1563 /// still require an owned key to be provided.
1565 /// Raw entries are useful for such exotic situations as:
1567 /// * Hash memoization
1568 /// * Deferring the creation of an owned key until it is known to be required
1569 /// * Using a search key that doesn't work with the Borrow trait
1570 /// * Using custom comparison logic without newtype wrappers
1572 /// Because raw entries provide much more low-level control, it's much easier
1573 /// to put the HashMap into an inconsistent state which, while memory-safe,
1574 /// will cause the map to produce seemingly random results. Higher-level and
1575 /// more foolproof APIs like `entry` should be preferred when possible.
1577 /// In particular, the hash used to initialized the raw entry must still be
1578 /// consistent with the hash of the key that is ultimately stored in the entry.
1579 /// This is because implementations of HashMap may need to recompute hashes
1580 /// when resizing, at which point only the keys are available.
1582 /// Raw entries give mutable access to the keys. This must not be used
1583 /// to modify how the key would compare or hash, as the map will not re-evaluate
1584 /// where the key should go, meaning the keys may become "lost" if their
1585 /// location does not reflect their state. For instance, if you change a key
1586 /// so that the map now contains keys which compare equal, search may start
1587 /// acting eratically, with two keys randomly masking eachother. Implementations
1588 /// are free to assume this doesn't happen (within the limits of memory-safety).
1593 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1594 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1596 RawEntryBuilderMut { map: self }
1599 /// Creates a raw immutable entry builder for the HashMap.
1601 /// Raw entries provide the lowest level of control for searching and
1602 /// manipulating a map. They must be manually initialized with a hash and
1603 /// then manually searched.
1605 /// This is useful for
1606 /// * Hash memoization
1607 /// * Using a search key that doesn't work with the Borrow trait
1608 /// * Using custom comparison logic without newtype wrappers
1610 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1611 /// `get` should be preferred.
1613 /// Immutable raw entries have very limited use; you might instead want `raw_entry`.
1614 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1615 pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1616 RawEntryBuilder { map: self }
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<K, V, S> PartialEq for HashMap<K, V, S>
1626 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1627 if self.len() != other.len() {
1631 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<K, V, S> Eq for HashMap<K, V, S>
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<K, V, S> Debug for HashMap<K, V, S>
1645 where K: Eq + Hash + Debug,
1649 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1650 f.debug_map().entries(self.iter()).finish()
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<K, V, S> Default for HashMap<K, V, S>
1657 S: BuildHasher + Default
1659 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1660 fn default() -> HashMap<K, V, S> {
1661 HashMap::with_hasher(Default::default())
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1667 where K: Eq + Hash + Borrow<Q>,
1673 /// Returns a reference to the value corresponding to the supplied key.
1677 /// Panics if the key is not present in the `HashMap`.
1679 fn index(&self, key: &Q) -> &V {
1680 self.get(key).expect("no entry found for key")
1684 /// An iterator over the entries of a `HashMap`.
1686 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1687 /// documentation for more.
1689 /// [`iter`]: struct.HashMap.html#method.iter
1690 /// [`HashMap`]: struct.HashMap.html
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 pub struct Iter<'a, K: 'a, V: 'a> {
1693 inner: table::Iter<'a, K, V>,
1696 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<'a, K, V> Clone for Iter<'a, K, V> {
1699 fn clone(&self) -> Iter<'a, K, V> {
1700 Iter { inner: self.inner.clone() }
1704 #[stable(feature = "std_debug", since = "1.16.0")]
1705 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1708 .entries(self.clone())
1713 /// A mutable iterator over the entries of a `HashMap`.
1715 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1716 /// documentation for more.
1718 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1719 /// [`HashMap`]: struct.HashMap.html
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub struct IterMut<'a, K: 'a, V: 'a> {
1722 inner: table::IterMut<'a, K, V>,
1725 /// An owning iterator over the entries of a `HashMap`.
1727 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1728 /// (provided by the `IntoIterator` trait). See its documentation for more.
1730 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1731 /// [`HashMap`]: struct.HashMap.html
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 pub struct IntoIter<K, V> {
1734 pub(super) inner: table::IntoIter<K, V>,
1737 /// An iterator over the keys of a `HashMap`.
1739 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1740 /// documentation for more.
1742 /// [`keys`]: struct.HashMap.html#method.keys
1743 /// [`HashMap`]: struct.HashMap.html
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub struct Keys<'a, K: 'a, V: 'a> {
1746 inner: Iter<'a, K, V>,
1749 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<'a, K, V> Clone for Keys<'a, K, V> {
1752 fn clone(&self) -> Keys<'a, K, V> {
1753 Keys { inner: self.inner.clone() }
1757 #[stable(feature = "std_debug", since = "1.16.0")]
1758 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1761 .entries(self.clone())
1766 /// An iterator over the values of a `HashMap`.
1768 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1769 /// documentation for more.
1771 /// [`values`]: struct.HashMap.html#method.values
1772 /// [`HashMap`]: struct.HashMap.html
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 pub struct Values<'a, K: 'a, V: 'a> {
1775 inner: Iter<'a, K, V>,
1778 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1779 #[stable(feature = "rust1", since = "1.0.0")]
1780 impl<'a, K, V> Clone for Values<'a, K, V> {
1781 fn clone(&self) -> Values<'a, K, V> {
1782 Values { inner: self.inner.clone() }
1786 #[stable(feature = "std_debug", since = "1.16.0")]
1787 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1790 .entries(self.clone())
1795 /// A draining iterator over the entries of a `HashMap`.
1797 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1798 /// documentation for more.
1800 /// [`drain`]: struct.HashMap.html#method.drain
1801 /// [`HashMap`]: struct.HashMap.html
1802 #[stable(feature = "drain", since = "1.6.0")]
1803 pub struct Drain<'a, K: 'a, V: 'a> {
1804 pub(super) inner: table::Drain<'a, K, V>,
1807 /// A mutable iterator over the values of a `HashMap`.
1809 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1810 /// documentation for more.
1812 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1813 /// [`HashMap`]: struct.HashMap.html
1814 #[stable(feature = "map_values_mut", since = "1.10.0")]
1815 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1816 inner: IterMut<'a, K, V>,
1819 enum InternalEntry<K, V, M> {
1820 Occupied { elem: FullBucket<K, V, M> },
1823 elem: VacantEntryState<K, V, M>,
1828 impl<K, V, M> InternalEntry<K, V, M> {
1830 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1832 InternalEntry::Occupied { elem } => Some(elem),
1838 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1840 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1842 InternalEntry::Occupied { elem } => {
1843 Some(Occupied(OccupiedEntry {
1848 InternalEntry::Vacant { hash, elem } => {
1849 Some(Vacant(VacantEntry {
1855 InternalEntry::TableIsEmpty => None,
1860 /// A builder for computing where in a HashMap a key-value pair would be stored.
1862 /// See the [`HashMap::raw_entry_mut`][] docs for usage examples.
1863 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1864 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1865 map: &'a mut HashMap<K, V, S>,
1868 /// A view into a single entry in a map, which may either be vacant or occupied.
1870 /// This is a lower-level version of [`Entry`].
1872 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1874 /// [`HashMap`]: struct.HashMap.html
1875 /// [`Entry`]: struct.Entry.html
1876 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1877 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1878 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1879 /// An occupied entry.
1880 Occupied(RawOccupiedEntryMut<'a, K, V>),
1882 Vacant(RawVacantEntryMut<'a, K, V, S>),
1885 /// A view into an occupied entry in a `HashMap`.
1886 /// It is part of the [`RawEntryMut`] enum.
1888 /// [`RawEntryMut`]: enum.RawEntryMut.html
1889 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1890 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1891 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1894 /// A view into a vacant entry in a `HashMap`.
1895 /// It is part of the [`RawEntryMut`] enum.
1897 /// [`RawEntryMut`]: enum.RawEntryMut.html
1898 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1899 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1900 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1901 hash_builder: &'a S,
1904 /// A builder for computing where in a HashMap a key-value pair would be stored.
1906 /// See the [`HashMap::raw_entry`][] docs for usage examples.
1907 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1908 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1909 map: &'a HashMap<K, V, S>,
1912 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1913 where S: BuildHasher,
1916 /// Create a `RawEntryMut` from the given key.
1917 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1918 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1922 let mut hasher = self.map.hash_builder.build_hasher();
1923 k.hash(&mut hasher);
1924 self.from_key_hashed_nocheck(hasher.finish(), k)
1927 /// Create a `RawEntryMut` from the given key and its hash.
1928 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1929 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1933 self.from_hash(hash, |q| q.borrow().eq(k))
1936 /// Create a `RawEntryMut` from the given hash.
1937 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1938 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1939 where for<'b> F: FnMut(&'b K) -> bool,
1941 match search_hashed_mut(&mut self.map.table, SafeHash::new(hash), is_match) {
1942 InternalEntry::Occupied { elem } => {
1943 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1945 InternalEntry::Vacant { elem, .. } => {
1946 RawEntryMut::Vacant(RawVacantEntryMut {
1948 hash_builder: &self.map.hash_builder,
1951 InternalEntry::TableIsEmpty => {
1957 /// Create a `RawEntryMut` by examining the elements of a hash bucket until `is_match` returns
1958 /// true for one of them.
1959 #[unstable(feature = "hash_raw_entry", issue = "42069")]
1960 pub fn from_bucket<F>(self, hash_bucket: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S>
1961 where for<'b> F: FnMut(&'b K) -> bool,
1963 let hash = SafeHash::new(hash_bucket);
1965 let size = self.map.table.size();
1966 let mut probe = Bucket::new(&mut self.map.table, hash);
1967 let mut displacement = 0;
1970 let full = match probe.peek() {
1973 return RawEntryMut::Vacant(RawVacantEntryMut {
1974 elem: NoElem(bucket, displacement),
1975 hash_builder: &self.map.hash_builder,
1978 Full(bucket) => bucket,
1981 let probe_displacement = full.displacement();
1983 if probe_displacement < displacement {
1984 // Found a luckier bucket than me.
1985 // We can finish the search early if we hit any bucket
1986 // with a lower distance to initial bucket than we've probed.
1987 return RawEntryMut::Vacant(RawVacantEntryMut {
1988 elem: NeqElem(full, probe_displacement),
1989 hash_builder: &self.map.hash_builder,
1993 // Call is_match even if hash doesn't match hash_bucket.
1994 if is_match(full.read().0) {
1995 return RawEntryMut::Occupied(RawOccupiedEntryMut { elem: full });
1999 probe = full.next();
2000 debug_assert!(displacement <= size);
2005 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
2006 where S: BuildHasher,
2008 /// Access an entry by key.
2009 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2010 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
2014 let mut hasher = self.map.hash_builder.build_hasher();
2015 k.hash(&mut hasher);
2016 self.from_key_hashed_nocheck(hasher.finish(), k)
2019 /// Access an entry by a key and its hash.
2020 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2021 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
2026 self.from_hash(hash, |q| q.borrow().eq(k))
2029 /// Access an entry by hash.
2030 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2031 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2032 where F: FnMut(&K) -> bool
2034 match search_hashed(&self.map.table, SafeHash::new(hash), is_match) {
2035 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
2036 InternalEntry::Vacant { .. } => None,
2037 InternalEntry::TableIsEmpty => unreachable!(),
2042 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2043 /// Ensures a value is in the entry by inserting the default if empty, and returns
2044 /// mutable references to the key and value in the entry.
2049 /// use std::collections::HashMap;
2051 /// let mut map: HashMap<&str, u32> = HashMap::new();
2052 /// map.raw_entry().search_by("poneyland").or_insert("poneyland", 12);
2054 /// assert_eq!(map["poneyland"], 12);
2056 /// *map.raw_entry().search_by("poneyland").or_insert("poneyland", 12).1 += 10;
2057 /// assert_eq!(map["poneyland"], 22);
2059 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2060 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2065 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2066 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2070 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2071 /// and returns mutable references to the key and value in the entry.
2076 /// use std::collections::HashMap;
2078 /// let mut map: HashMap<&str, String> = HashMap::new();
2080 /// map.raw_entry().search_by("poneyland").or_insert_with(|| {
2081 /// ("poneyland".to_string(), "hoho".to_string())
2084 /// assert_eq!(map["poneyland"], "hoho".to_string());
2086 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2087 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2088 where F: FnOnce() -> (K, V),
2093 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2094 RawEntryMut::Vacant(entry) => {
2095 let (k, v) = default();
2101 /// Provides in-place mutable access to an occupied entry before any
2102 /// potential inserts into the map.
2107 /// use std::collections::HashMap;
2109 /// let mut map: HashMap<&str, u32> = HashMap::new();
2112 /// .search_by("poneyland")
2113 /// .and_modify(|_k, v| { *v += 1 })
2114 /// .or_insert("poneyland", 42);
2115 /// assert_eq!(map["poneyland"], 42);
2118 /// .search_by("poneyland")
2119 /// .and_modify(|_k, v| { *v += 1 })
2120 /// .or_insert("poneyland", 42);
2121 /// assert_eq!(map["poneyland"], 43);
2123 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2124 pub fn and_modify<F>(self, f: F) -> Self
2125 where F: FnOnce(&mut K, &mut V)
2128 RawEntryMut::Occupied(mut entry) => {
2130 let (k, v) = entry.get_key_value_mut();
2133 RawEntryMut::Occupied(entry)
2135 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2140 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2141 /// Gets a reference to the key in the entry.
2142 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2143 pub fn key(&self) -> &K {
2147 /// Gets a mutable reference to the key in the entry.
2148 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2149 pub fn key_mut(&mut self) -> &mut K {
2150 self.elem.read_mut().0
2153 /// Converts the entry into a mutable reference to the key in the entry
2154 /// with a lifetime bound to the map itself.
2155 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2156 pub fn into_key(self) -> &'a mut K {
2157 self.elem.into_mut_refs().0
2160 /// Gets a reference to the value in the entry.
2161 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2162 pub fn get(&self) -> &V {
2166 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2167 /// with a lifetime bound to the map itself.
2168 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2169 pub fn into_mut(self) -> &'a mut V {
2170 self.elem.into_mut_refs().1
2173 /// Gets a mutable reference to the value in the entry.
2174 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2175 pub fn get_mut(&mut self) -> &mut V {
2176 self.elem.read_mut().1
2179 /// Gets a reference to the key and value in the entry.
2180 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2181 pub fn get_key_value(&mut self) -> (&K, &V) {
2185 /// Gets a mutable reference to the key and value in the entry.
2186 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2187 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2188 self.elem.read_mut()
2191 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2192 /// with a lifetime bound to the map itself.
2193 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2194 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2195 self.elem.into_mut_refs()
2198 /// Sets the value of the entry, and returns the entry's old value.
2199 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2200 pub fn insert(&mut self, value: V) -> V {
2201 mem::replace(self.get_mut(), value)
2204 /// Sets the value of the entry, and returns the entry's old value.
2205 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2206 pub fn insert_key(&mut self, key: K) -> K {
2207 mem::replace(self.key_mut(), key)
2210 /// Takes the value out of the entry, and returns it.
2211 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2212 pub fn remove(self) -> V {
2213 pop_internal(self.elem).1
2217 /// Take the ownership of the key and value from the map.
2218 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2219 pub fn remove_entry(self) -> (K, V) {
2220 let (k, v, _) = pop_internal(self.elem);
2225 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2226 /// Sets the value of the entry with the VacantEntry's key,
2227 /// and returns a mutable reference to it.
2228 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2229 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2233 let mut hasher = self.hash_builder.build_hasher();
2234 key.hash(&mut hasher);
2235 self.insert_hashed_nocheck(hasher.finish(), key, value)
2238 /// Sets the value of the entry with the VacantEntry's key,
2239 /// and returns a mutable reference to it.
2240 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2241 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2242 let hash = SafeHash::new(hash);
2243 let b = match self.elem {
2244 NeqElem(mut bucket, disp) => {
2245 if disp >= DISPLACEMENT_THRESHOLD {
2246 bucket.table_mut().set_tag(true);
2248 robin_hood(bucket, disp, hash, key, value)
2250 NoElem(mut bucket, disp) => {
2251 if disp >= DISPLACEMENT_THRESHOLD {
2252 bucket.table_mut().set_tag(true);
2254 bucket.put(hash, key, value)
2261 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2262 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2264 f.debug_struct("RawEntryBuilder")
2269 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2270 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2273 RawEntryMut::Vacant(ref v) => {
2274 f.debug_tuple("RawEntry")
2278 RawEntryMut::Occupied(ref o) => {
2279 f.debug_tuple("RawEntry")
2287 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2288 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2290 f.debug_struct("RawOccupiedEntryMut")
2291 .field("key", self.key())
2292 .field("value", self.get())
2297 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2298 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2300 f.debug_struct("RawVacantEntryMut")
2305 #[unstable(feature = "hash_raw_entry", issue = "42069")]
2306 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2308 f.debug_struct("RawEntryBuilder")
2313 /// A view into a single entry in a map, which may either be vacant or occupied.
2315 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2317 /// [`HashMap`]: struct.HashMap.html
2318 /// [`entry`]: struct.HashMap.html#method.entry
2319 #[stable(feature = "rust1", since = "1.0.0")]
2320 pub enum Entry<'a, K: 'a, V: 'a> {
2321 /// An occupied entry.
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2324 OccupiedEntry<'a, K, V>),
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2329 VacantEntry<'a, K, V>),
2332 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2333 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2337 f.debug_tuple("Entry")
2341 Occupied(ref o) => {
2342 f.debug_tuple("Entry")
2350 /// A view into an occupied entry in a `HashMap`.
2351 /// It is part of the [`Entry`] enum.
2353 /// [`Entry`]: enum.Entry.html
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2357 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2360 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2361 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2363 f.debug_struct("OccupiedEntry")
2364 .field("key", self.key())
2365 .field("value", self.get())
2370 /// A view into a vacant entry in a `HashMap`.
2371 /// It is part of the [`Entry`] enum.
2373 /// [`Entry`]: enum.Entry.html
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2378 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2381 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2382 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2384 f.debug_tuple("VacantEntry")
2390 /// Possible states of a VacantEntry.
2391 enum VacantEntryState<K, V, M> {
2392 /// The index is occupied, but the key to insert has precedence,
2393 /// and will kick the current one out on insertion.
2394 NeqElem(FullBucket<K, V, M>, usize),
2395 /// The index is genuinely vacant.
2396 NoElem(EmptyBucket<K, V, M>, usize),
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2404 type Item = (&'a K, &'a V);
2405 type IntoIter = Iter<'a, K, V>;
2407 fn into_iter(self) -> Iter<'a, K, V> {
2412 #[stable(feature = "rust1", since = "1.0.0")]
2413 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2417 type Item = (&'a K, &'a mut V);
2418 type IntoIter = IterMut<'a, K, V>;
2420 fn into_iter(self) -> IterMut<'a, K, V> {
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2431 type IntoIter = IntoIter<K, V>;
2433 /// Creates a consuming iterator, that is, one that moves each key-value
2434 /// pair out of the map in arbitrary order. The map cannot be used after
2440 /// use std::collections::HashMap;
2442 /// let mut map = HashMap::new();
2443 /// map.insert("a", 1);
2444 /// map.insert("b", 2);
2445 /// map.insert("c", 3);
2447 /// // Not possible with .iter()
2448 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2450 fn into_iter(self) -> IntoIter<K, V> {
2451 IntoIter { inner: self.table.into_iter() }
2455 #[stable(feature = "rust1", since = "1.0.0")]
2456 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2457 type Item = (&'a K, &'a V);
2460 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2464 fn size_hint(&self) -> (usize, Option<usize>) {
2465 self.inner.size_hint()
2468 #[stable(feature = "rust1", since = "1.0.0")]
2469 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2471 fn len(&self) -> usize {
2476 #[stable(feature = "fused", since = "1.26.0")]
2477 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2479 #[stable(feature = "rust1", since = "1.0.0")]
2480 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2481 type Item = (&'a K, &'a mut V);
2484 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2488 fn size_hint(&self) -> (usize, Option<usize>) {
2489 self.inner.size_hint()
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2495 fn len(&self) -> usize {
2499 #[stable(feature = "fused", since = "1.26.0")]
2500 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2502 #[stable(feature = "std_debug", since = "1.16.0")]
2503 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2504 where K: fmt::Debug,
2507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2509 .entries(self.inner.iter())
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 impl<K, V> Iterator for IntoIter<K, V> {
2519 fn next(&mut self) -> Option<(K, V)> {
2520 self.inner.next().map(|(_, k, v)| (k, v))
2523 fn size_hint(&self) -> (usize, Option<usize>) {
2524 self.inner.size_hint()
2527 #[stable(feature = "rust1", since = "1.0.0")]
2528 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2530 fn len(&self) -> usize {
2534 #[stable(feature = "fused", since = "1.26.0")]
2535 impl<K, V> FusedIterator for IntoIter<K, V> {}
2537 #[stable(feature = "std_debug", since = "1.16.0")]
2538 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2541 .entries(self.inner.iter())
2546 #[stable(feature = "rust1", since = "1.0.0")]
2547 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2551 fn next(&mut self) -> Option<(&'a K)> {
2552 self.inner.next().map(|(k, _)| k)
2555 fn size_hint(&self) -> (usize, Option<usize>) {
2556 self.inner.size_hint()
2559 #[stable(feature = "rust1", since = "1.0.0")]
2560 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2562 fn len(&self) -> usize {
2566 #[stable(feature = "fused", since = "1.26.0")]
2567 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2569 #[stable(feature = "rust1", since = "1.0.0")]
2570 impl<'a, K, V> Iterator for Values<'a, K, V> {
2574 fn next(&mut self) -> Option<(&'a V)> {
2575 self.inner.next().map(|(_, v)| v)
2578 fn size_hint(&self) -> (usize, Option<usize>) {
2579 self.inner.size_hint()
2582 #[stable(feature = "rust1", since = "1.0.0")]
2583 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2585 fn len(&self) -> usize {
2589 #[stable(feature = "fused", since = "1.26.0")]
2590 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2592 #[stable(feature = "map_values_mut", since = "1.10.0")]
2593 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2594 type Item = &'a mut V;
2597 fn next(&mut self) -> Option<(&'a mut V)> {
2598 self.inner.next().map(|(_, v)| v)
2601 fn size_hint(&self) -> (usize, Option<usize>) {
2602 self.inner.size_hint()
2605 #[stable(feature = "map_values_mut", since = "1.10.0")]
2606 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2608 fn len(&self) -> usize {
2612 #[stable(feature = "fused", since = "1.26.0")]
2613 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2615 #[stable(feature = "std_debug", since = "1.16.0")]
2616 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2617 where K: fmt::Debug,
2620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2622 .entries(self.inner.inner.iter())
2627 #[stable(feature = "drain", since = "1.6.0")]
2628 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2632 fn next(&mut self) -> Option<(K, V)> {
2633 self.inner.next().map(|(_, k, v)| (k, v))
2636 fn size_hint(&self) -> (usize, Option<usize>) {
2637 self.inner.size_hint()
2640 #[stable(feature = "drain", since = "1.6.0")]
2641 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2643 fn len(&self) -> usize {
2647 #[stable(feature = "fused", since = "1.26.0")]
2648 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2650 #[stable(feature = "std_debug", since = "1.16.0")]
2651 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2652 where K: fmt::Debug,
2655 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2657 .entries(self.inner.iter())
2662 impl<'a, K, V> Entry<'a, K, V> {
2663 #[stable(feature = "rust1", since = "1.0.0")]
2664 /// Ensures a value is in the entry by inserting the default if empty, and returns
2665 /// a mutable reference to the value in the entry.
2670 /// use std::collections::HashMap;
2672 /// let mut map: HashMap<&str, u32> = HashMap::new();
2673 /// map.entry("poneyland").or_insert(12);
2675 /// assert_eq!(map["poneyland"], 12);
2677 /// *map.entry("poneyland").or_insert(12) += 10;
2678 /// assert_eq!(map["poneyland"], 22);
2680 pub fn or_insert(self, default: V) -> &'a mut V {
2682 Occupied(entry) => entry.into_mut(),
2683 Vacant(entry) => entry.insert(default),
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2689 /// and returns a mutable reference to the value in the entry.
2694 /// use std::collections::HashMap;
2696 /// let mut map: HashMap<&str, String> = HashMap::new();
2697 /// let s = "hoho".to_string();
2699 /// map.entry("poneyland").or_insert_with(|| s);
2701 /// assert_eq!(map["poneyland"], "hoho".to_string());
2703 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2705 Occupied(entry) => entry.into_mut(),
2706 Vacant(entry) => entry.insert(default()),
2710 /// Returns a reference to this entry's key.
2715 /// use std::collections::HashMap;
2717 /// let mut map: HashMap<&str, u32> = HashMap::new();
2718 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2720 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2721 pub fn key(&self) -> &K {
2723 Occupied(ref entry) => entry.key(),
2724 Vacant(ref entry) => entry.key(),
2728 /// Provides in-place mutable access to an occupied entry before any
2729 /// potential inserts into the map.
2734 /// use std::collections::HashMap;
2736 /// let mut map: HashMap<&str, u32> = HashMap::new();
2738 /// map.entry("poneyland")
2739 /// .and_modify(|e| { *e += 1 })
2741 /// assert_eq!(map["poneyland"], 42);
2743 /// map.entry("poneyland")
2744 /// .and_modify(|e| { *e += 1 })
2746 /// assert_eq!(map["poneyland"], 43);
2748 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2749 pub fn and_modify<F>(self, f: F) -> Self
2750 where F: FnOnce(&mut V)
2753 Occupied(mut entry) => {
2757 Vacant(entry) => Vacant(entry),
2763 impl<'a, K, V: Default> Entry<'a, K, V> {
2764 #[stable(feature = "entry_or_default", since = "1.28.0")]
2765 /// Ensures a value is in the entry by inserting the default value if empty,
2766 /// and returns a mutable reference to the value in the entry.
2772 /// use std::collections::HashMap;
2774 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2775 /// map.entry("poneyland").or_default();
2777 /// assert_eq!(map["poneyland"], None);
2780 pub fn or_default(self) -> &'a mut V {
2782 Occupied(entry) => entry.into_mut(),
2783 Vacant(entry) => entry.insert(Default::default()),
2788 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2789 /// Gets a reference to the key in the entry.
2794 /// use std::collections::HashMap;
2796 /// let mut map: HashMap<&str, u32> = HashMap::new();
2797 /// map.entry("poneyland").or_insert(12);
2798 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2800 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2801 pub fn key(&self) -> &K {
2805 /// Take the ownership of the key and value from the map.
2810 /// use std::collections::HashMap;
2811 /// use std::collections::hash_map::Entry;
2813 /// let mut map: HashMap<&str, u32> = HashMap::new();
2814 /// map.entry("poneyland").or_insert(12);
2816 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2817 /// // We delete the entry from the map.
2818 /// o.remove_entry();
2821 /// assert_eq!(map.contains_key("poneyland"), false);
2823 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2824 pub fn remove_entry(self) -> (K, V) {
2825 let (k, v, _) = pop_internal(self.elem);
2829 /// Gets a reference to the value in the entry.
2834 /// use std::collections::HashMap;
2835 /// use std::collections::hash_map::Entry;
2837 /// let mut map: HashMap<&str, u32> = HashMap::new();
2838 /// map.entry("poneyland").or_insert(12);
2840 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2841 /// assert_eq!(o.get(), &12);
2844 #[stable(feature = "rust1", since = "1.0.0")]
2845 pub fn get(&self) -> &V {
2849 /// Gets a mutable reference to the value in the entry.
2851 /// If you need a reference to the `OccupiedEntry` which may outlive the
2852 /// destruction of the `Entry` value, see [`into_mut`].
2854 /// [`into_mut`]: #method.into_mut
2859 /// use std::collections::HashMap;
2860 /// use std::collections::hash_map::Entry;
2862 /// let mut map: HashMap<&str, u32> = HashMap::new();
2863 /// map.entry("poneyland").or_insert(12);
2865 /// assert_eq!(map["poneyland"], 12);
2866 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2867 /// *o.get_mut() += 10;
2868 /// assert_eq!(*o.get(), 22);
2870 /// // We can use the same Entry multiple times.
2871 /// *o.get_mut() += 2;
2874 /// assert_eq!(map["poneyland"], 24);
2876 #[stable(feature = "rust1", since = "1.0.0")]
2877 pub fn get_mut(&mut self) -> &mut V {
2878 self.elem.read_mut().1
2881 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2882 /// with a lifetime bound to the map itself.
2884 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2886 /// [`get_mut`]: #method.get_mut
2891 /// use std::collections::HashMap;
2892 /// use std::collections::hash_map::Entry;
2894 /// let mut map: HashMap<&str, u32> = HashMap::new();
2895 /// map.entry("poneyland").or_insert(12);
2897 /// assert_eq!(map["poneyland"], 12);
2898 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2899 /// *o.into_mut() += 10;
2902 /// assert_eq!(map["poneyland"], 22);
2904 #[stable(feature = "rust1", since = "1.0.0")]
2905 pub fn into_mut(self) -> &'a mut V {
2906 self.elem.into_mut_refs().1
2909 /// Sets the value of the entry, and returns the entry's old value.
2914 /// use std::collections::HashMap;
2915 /// use std::collections::hash_map::Entry;
2917 /// let mut map: HashMap<&str, u32> = HashMap::new();
2918 /// map.entry("poneyland").or_insert(12);
2920 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2921 /// assert_eq!(o.insert(15), 12);
2924 /// assert_eq!(map["poneyland"], 15);
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 pub fn insert(&mut self, mut value: V) -> V {
2928 let old_value = self.get_mut();
2929 mem::swap(&mut value, old_value);
2933 /// Takes the value out of the entry, and returns it.
2938 /// use std::collections::HashMap;
2939 /// use std::collections::hash_map::Entry;
2941 /// let mut map: HashMap<&str, u32> = HashMap::new();
2942 /// map.entry("poneyland").or_insert(12);
2944 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2945 /// assert_eq!(o.remove(), 12);
2948 /// assert_eq!(map.contains_key("poneyland"), false);
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 pub fn remove(self) -> V {
2952 pop_internal(self.elem).1
2955 /// Returns a key that was used for search.
2957 /// The key was retained for further use.
2958 fn take_key(&mut self) -> Option<K> {
2962 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2963 /// the key used to create this entry.
2968 /// #![feature(map_entry_replace)]
2969 /// use std::collections::hash_map::{Entry, HashMap};
2970 /// use std::rc::Rc;
2972 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2973 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2975 /// let my_key = Rc::new("Stringthing".to_string());
2977 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2978 /// // Also replace the key with a handle to our other key.
2979 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2983 #[unstable(feature = "map_entry_replace", issue = "44286")]
2984 pub fn replace_entry(mut self, value: V) -> (K, V) {
2985 let (old_key, old_value) = self.elem.read_mut();
2987 let old_key = mem::replace(old_key, self.key.unwrap());
2988 let old_value = mem::replace(old_value, value);
2990 (old_key, old_value)
2993 /// Replaces the key in the hash map with the key used to create this entry.
2998 /// #![feature(map_entry_replace)]
2999 /// use std::collections::hash_map::{Entry, HashMap};
3000 /// use std::rc::Rc;
3002 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
3003 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
3005 /// // Initialise known strings, run program, etc.
3007 /// reclaim_memory(&mut map, &known_strings);
3009 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
3010 /// for s in known_strings {
3011 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
3012 /// // Replaces the entry's key with our version of it in `known_strings`.
3013 /// entry.replace_key();
3018 #[unstable(feature = "map_entry_replace", issue = "44286")]
3019 pub fn replace_key(mut self) -> K {
3020 let (old_key, _) = self.elem.read_mut();
3021 mem::replace(old_key, self.key.unwrap())
3025 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3026 /// Gets a reference to the key that would be used when inserting a value
3027 /// through the `VacantEntry`.
3032 /// use std::collections::HashMap;
3034 /// let mut map: HashMap<&str, u32> = HashMap::new();
3035 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3037 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3038 pub fn key(&self) -> &K {
3042 /// Take ownership of the key.
3047 /// use std::collections::HashMap;
3048 /// use std::collections::hash_map::Entry;
3050 /// let mut map: HashMap<&str, u32> = HashMap::new();
3052 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3056 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3057 pub fn into_key(self) -> K {
3061 /// Sets the value of the entry with the VacantEntry's key,
3062 /// and returns a mutable reference to it.
3067 /// use std::collections::HashMap;
3068 /// use std::collections::hash_map::Entry;
3070 /// let mut map: HashMap<&str, u32> = HashMap::new();
3072 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3075 /// assert_eq!(map["poneyland"], 37);
3077 #[stable(feature = "rust1", since = "1.0.0")]
3078 pub fn insert(self, value: V) -> &'a mut V {
3079 let b = match self.elem {
3080 NeqElem(mut bucket, disp) => {
3081 if disp >= DISPLACEMENT_THRESHOLD {
3082 bucket.table_mut().set_tag(true);
3084 robin_hood(bucket, disp, self.hash, self.key, value)
3086 NoElem(mut bucket, disp) => {
3087 if disp >= DISPLACEMENT_THRESHOLD {
3088 bucket.table_mut().set_tag(true);
3090 bucket.put(self.hash, self.key, value)
3097 #[stable(feature = "rust1", since = "1.0.0")]
3098 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3100 S: BuildHasher + Default
3102 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3103 let mut map = HashMap::with_hasher(Default::default());
3109 #[stable(feature = "rust1", since = "1.0.0")]
3110 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3114 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3115 // Keys may be already present or show multiple times in the iterator.
3116 // Reserve the entire hint lower bound if the map is empty.
3117 // Otherwise reserve half the hint (rounded up), so the map
3118 // will only resize twice in the worst case.
3119 let iter = iter.into_iter();
3120 let reserve = if self.is_empty() {
3123 (iter.size_hint().0 + 1) / 2
3125 self.reserve(reserve);
3126 for (k, v) in iter {
3132 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3133 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3134 where K: Eq + Hash + Copy,
3138 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3139 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3143 /// `RandomState` is the default state for [`HashMap`] types.
3145 /// A particular instance `RandomState` will create the same instances of
3146 /// [`Hasher`], but the hashers created by two different `RandomState`
3147 /// instances are unlikely to produce the same result for the same values.
3149 /// [`HashMap`]: struct.HashMap.html
3150 /// [`Hasher`]: ../../hash/trait.Hasher.html
3155 /// use std::collections::HashMap;
3156 /// use std::collections::hash_map::RandomState;
3158 /// let s = RandomState::new();
3159 /// let mut map = HashMap::with_hasher(s);
3160 /// map.insert(1, 2);
3163 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3164 pub struct RandomState {
3170 /// Constructs a new `RandomState` that is initialized with random keys.
3175 /// use std::collections::hash_map::RandomState;
3177 /// let s = RandomState::new();
3180 #[allow(deprecated)]
3182 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3183 pub fn new() -> RandomState {
3184 // Historically this function did not cache keys from the OS and instead
3185 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3186 // was discovered, however, that because we re-seed the thread-local RNG
3187 // from the OS periodically that this can cause excessive slowdown when
3188 // many hash maps are created on a thread. To solve this performance
3189 // trap we cache the first set of randomly generated keys per-thread.
3191 // Later in #36481 it was discovered that exposing a deterministic
3192 // iteration order allows a form of DOS attack. To counter that we
3193 // increment one of the seeds on every RandomState creation, giving
3194 // every corresponding HashMap a different iteration order.
3195 thread_local!(static KEYS: Cell<(u64, u64)> = {
3196 Cell::new(sys::hashmap_random_keys())
3200 let (k0, k1) = keys.get();
3201 keys.set((k0.wrapping_add(1), k1));
3202 RandomState { k0: k0, k1: k1 }
3207 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3208 impl BuildHasher for RandomState {
3209 type Hasher = DefaultHasher;
3211 #[allow(deprecated)]
3212 fn build_hasher(&self) -> DefaultHasher {
3213 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3217 /// The default [`Hasher`] used by [`RandomState`].
3219 /// The internal algorithm is not specified, and so it and its hashes should
3220 /// not be relied upon over releases.
3222 /// [`RandomState`]: struct.RandomState.html
3223 /// [`Hasher`]: ../../hash/trait.Hasher.html
3224 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3225 #[allow(deprecated)]
3226 #[derive(Clone, Debug)]
3227 pub struct DefaultHasher(SipHasher13);
3229 impl DefaultHasher {
3230 /// Creates a new `DefaultHasher`.
3232 /// This hasher is not guaranteed to be the same as all other
3233 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3234 /// instances created through `new` or `default`.
3235 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3236 #[allow(deprecated)]
3237 pub fn new() -> DefaultHasher {
3238 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3242 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3243 impl Default for DefaultHasher {
3244 /// Creates a new `DefaultHasher` using [`new`]. See its documentation for more.
3246 /// [`new`]: #method.new
3247 fn default() -> DefaultHasher {
3248 DefaultHasher::new()
3252 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3253 impl Hasher for DefaultHasher {
3255 fn write(&mut self, msg: &[u8]) {
3260 fn finish(&self) -> u64 {
3265 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3266 impl Default for RandomState {
3267 /// Constructs a new `RandomState`.
3269 fn default() -> RandomState {
3274 #[stable(feature = "std_debug", since = "1.16.0")]
3275 impl fmt::Debug for RandomState {
3276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3277 f.pad("RandomState { .. }")
3281 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3282 where K: Eq + Hash + Borrow<Q>,
3289 fn get(&self, key: &Q) -> Option<&K> {
3290 self.search(key).map(|bucket| bucket.into_refs().0)
3293 fn take(&mut self, key: &Q) -> Option<K> {
3294 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3298 fn replace(&mut self, key: K) -> Option<K> {
3301 match self.entry(key) {
3302 Occupied(mut occupied) => {
3303 let key = occupied.take_key().unwrap();
3304 Some(mem::replace(occupied.elem.read_mut().0, key))
3315 fn assert_covariance() {
3316 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3319 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3322 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3325 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3328 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3331 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3334 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3337 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3340 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3343 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3346 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3347 -> Drain<'new, &'new str, &'new str> {
3355 use super::Entry::{Occupied, Vacant};
3356 use super::RandomState;
3358 use rand::{thread_rng, Rng};
3359 use realstd::collections::CollectionAllocErr::*;
3360 use realstd::mem::size_of;
3364 fn test_zero_capacities() {
3365 type HM = HashMap<i32, i32>;
3368 assert_eq!(m.capacity(), 0);
3370 let m = HM::default();
3371 assert_eq!(m.capacity(), 0);
3373 let m = HM::with_hasher(RandomState::new());
3374 assert_eq!(m.capacity(), 0);
3376 let m = HM::with_capacity(0);
3377 assert_eq!(m.capacity(), 0);
3379 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3380 assert_eq!(m.capacity(), 0);
3382 let mut m = HM::new();
3388 assert_eq!(m.capacity(), 0);
3390 let mut m = HM::new();
3392 assert_eq!(m.capacity(), 0);
3396 fn test_create_capacity_zero() {
3397 let mut m = HashMap::with_capacity(0);
3399 assert!(m.insert(1, 1).is_none());
3401 assert!(m.contains_key(&1));
3402 assert!(!m.contains_key(&0));
3407 let mut m = HashMap::new();
3408 assert_eq!(m.len(), 0);
3409 assert!(m.insert(1, 2).is_none());
3410 assert_eq!(m.len(), 1);
3411 assert!(m.insert(2, 4).is_none());
3412 assert_eq!(m.len(), 2);
3413 assert_eq!(*m.get(&1).unwrap(), 2);
3414 assert_eq!(*m.get(&2).unwrap(), 4);
3419 let mut m = HashMap::new();
3420 assert_eq!(m.len(), 0);
3421 assert!(m.insert(1, 2).is_none());
3422 assert_eq!(m.len(), 1);
3423 assert!(m.insert(2, 4).is_none());
3424 assert_eq!(m.len(), 2);
3426 assert_eq!(*m2.get(&1).unwrap(), 2);
3427 assert_eq!(*m2.get(&2).unwrap(), 4);
3428 assert_eq!(m2.len(), 2);
3431 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3433 #[derive(Hash, PartialEq, Eq)]
3439 fn new(k: usize) -> Droppable {
3440 DROP_VECTOR.with(|slot| {
3441 slot.borrow_mut()[k] += 1;
3448 impl Drop for Droppable {
3449 fn drop(&mut self) {
3450 DROP_VECTOR.with(|slot| {
3451 slot.borrow_mut()[self.k] -= 1;
3456 impl Clone for Droppable {
3457 fn clone(&self) -> Droppable {
3458 Droppable::new(self.k)
3464 DROP_VECTOR.with(|slot| {
3465 *slot.borrow_mut() = vec![0; 200];
3469 let mut m = HashMap::new();
3471 DROP_VECTOR.with(|v| {
3473 assert_eq!(v.borrow()[i], 0);
3478 let d1 = Droppable::new(i);
3479 let d2 = Droppable::new(i + 100);
3483 DROP_VECTOR.with(|v| {
3485 assert_eq!(v.borrow()[i], 1);
3490 let k = Droppable::new(i);
3491 let v = m.remove(&k);
3493 assert!(v.is_some());
3495 DROP_VECTOR.with(|v| {
3496 assert_eq!(v.borrow()[i], 1);
3497 assert_eq!(v.borrow()[i+100], 1);
3501 DROP_VECTOR.with(|v| {
3503 assert_eq!(v.borrow()[i], 0);
3504 assert_eq!(v.borrow()[i+100], 0);
3508 assert_eq!(v.borrow()[i], 1);
3509 assert_eq!(v.borrow()[i+100], 1);
3514 DROP_VECTOR.with(|v| {
3516 assert_eq!(v.borrow()[i], 0);
3522 fn test_into_iter_drops() {
3523 DROP_VECTOR.with(|v| {
3524 *v.borrow_mut() = vec![0; 200];
3528 let mut hm = HashMap::new();
3530 DROP_VECTOR.with(|v| {
3532 assert_eq!(v.borrow()[i], 0);
3537 let d1 = Droppable::new(i);
3538 let d2 = Droppable::new(i + 100);
3542 DROP_VECTOR.with(|v| {
3544 assert_eq!(v.borrow()[i], 1);
3551 // By the way, ensure that cloning doesn't screw up the dropping.
3555 let mut half = hm.into_iter().take(50);
3557 DROP_VECTOR.with(|v| {
3559 assert_eq!(v.borrow()[i], 1);
3563 for _ in half.by_ref() {}
3565 DROP_VECTOR.with(|v| {
3567 .filter(|&i| v.borrow()[i] == 1)
3571 .filter(|&i| v.borrow()[i + 100] == 1)
3579 DROP_VECTOR.with(|v| {
3581 assert_eq!(v.borrow()[i], 0);
3587 fn test_empty_remove() {
3588 let mut m: HashMap<i32, bool> = HashMap::new();
3589 assert_eq!(m.remove(&0), None);
3593 fn test_empty_entry() {
3594 let mut m: HashMap<i32, bool> = HashMap::new();
3596 Occupied(_) => panic!(),
3599 assert!(*m.entry(0).or_insert(true));
3600 assert_eq!(m.len(), 1);
3604 fn test_empty_iter() {
3605 let mut m: HashMap<i32, bool> = HashMap::new();
3606 assert_eq!(m.drain().next(), None);
3607 assert_eq!(m.keys().next(), None);
3608 assert_eq!(m.values().next(), None);
3609 assert_eq!(m.values_mut().next(), None);
3610 assert_eq!(m.iter().next(), None);
3611 assert_eq!(m.iter_mut().next(), None);
3612 assert_eq!(m.len(), 0);
3613 assert!(m.is_empty());
3614 assert_eq!(m.into_iter().next(), None);
3618 fn test_lots_of_insertions() {
3619 let mut m = HashMap::new();
3621 // Try this a few times to make sure we never screw up the hashmap's
3624 assert!(m.is_empty());
3627 assert!(m.insert(i, i).is_none());
3631 assert_eq!(r, Some(&j));
3634 for j in i + 1..1001 {
3636 assert_eq!(r, None);
3640 for i in 1001..2001 {
3641 assert!(!m.contains_key(&i));
3646 assert!(m.remove(&i).is_some());
3649 assert!(!m.contains_key(&j));
3652 for j in i + 1..1001 {
3653 assert!(m.contains_key(&j));
3658 assert!(!m.contains_key(&i));
3662 assert!(m.insert(i, i).is_none());
3666 for i in (1..1001).rev() {
3667 assert!(m.remove(&i).is_some());
3670 assert!(!m.contains_key(&j));
3674 assert!(m.contains_key(&j));
3681 fn test_find_mut() {
3682 let mut m = HashMap::new();
3683 assert!(m.insert(1, 12).is_none());
3684 assert!(m.insert(2, 8).is_none());
3685 assert!(m.insert(5, 14).is_none());
3687 match m.get_mut(&5) {
3689 Some(x) => *x = new,
3691 assert_eq!(m.get(&5), Some(&new));
3695 fn test_insert_overwrite() {
3696 let mut m = HashMap::new();
3697 assert!(m.insert(1, 2).is_none());
3698 assert_eq!(*m.get(&1).unwrap(), 2);
3699 assert!(!m.insert(1, 3).is_none());
3700 assert_eq!(*m.get(&1).unwrap(), 3);
3704 fn test_insert_conflicts() {
3705 let mut m = HashMap::with_capacity(4);
3706 assert!(m.insert(1, 2).is_none());
3707 assert!(m.insert(5, 3).is_none());
3708 assert!(m.insert(9, 4).is_none());
3709 assert_eq!(*m.get(&9).unwrap(), 4);
3710 assert_eq!(*m.get(&5).unwrap(), 3);
3711 assert_eq!(*m.get(&1).unwrap(), 2);
3715 fn test_conflict_remove() {
3716 let mut m = HashMap::with_capacity(4);
3717 assert!(m.insert(1, 2).is_none());
3718 assert_eq!(*m.get(&1).unwrap(), 2);
3719 assert!(m.insert(5, 3).is_none());
3720 assert_eq!(*m.get(&1).unwrap(), 2);
3721 assert_eq!(*m.get(&5).unwrap(), 3);
3722 assert!(m.insert(9, 4).is_none());
3723 assert_eq!(*m.get(&1).unwrap(), 2);
3724 assert_eq!(*m.get(&5).unwrap(), 3);
3725 assert_eq!(*m.get(&9).unwrap(), 4);
3726 assert!(m.remove(&1).is_some());
3727 assert_eq!(*m.get(&9).unwrap(), 4);
3728 assert_eq!(*m.get(&5).unwrap(), 3);
3732 fn test_is_empty() {
3733 let mut m = HashMap::with_capacity(4);
3734 assert!(m.insert(1, 2).is_none());
3735 assert!(!m.is_empty());
3736 assert!(m.remove(&1).is_some());
3737 assert!(m.is_empty());
3742 let mut m = HashMap::new();
3744 assert_eq!(m.remove(&1), Some(2));
3745 assert_eq!(m.remove(&1), None);
3749 fn test_remove_entry() {
3750 let mut m = HashMap::new();
3752 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3753 assert_eq!(m.remove(&1), None);
3758 let mut m = HashMap::with_capacity(4);
3760 assert!(m.insert(i, i*2).is_none());
3762 assert_eq!(m.len(), 32);
3764 let mut observed: u32 = 0;
3767 assert_eq!(*v, *k * 2);
3768 observed |= 1 << *k;
3770 assert_eq!(observed, 0xFFFF_FFFF);
3775 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3776 let map: HashMap<_, _> = vec.into_iter().collect();
3777 let keys: Vec<_> = map.keys().cloned().collect();
3778 assert_eq!(keys.len(), 3);
3779 assert!(keys.contains(&1));
3780 assert!(keys.contains(&2));
3781 assert!(keys.contains(&3));
3786 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3787 let map: HashMap<_, _> = vec.into_iter().collect();
3788 let values: Vec<_> = map.values().cloned().collect();
3789 assert_eq!(values.len(), 3);
3790 assert!(values.contains(&'a'));
3791 assert!(values.contains(&'b'));
3792 assert!(values.contains(&'c'));
3796 fn test_values_mut() {
3797 let vec = vec![(1, 1), (2, 2), (3, 3)];
3798 let mut map: HashMap<_, _> = vec.into_iter().collect();
3799 for value in map.values_mut() {
3800 *value = (*value) * 2
3802 let values: Vec<_> = map.values().cloned().collect();
3803 assert_eq!(values.len(), 3);
3804 assert!(values.contains(&2));
3805 assert!(values.contains(&4));
3806 assert!(values.contains(&6));
3811 let mut m = HashMap::new();
3812 assert!(m.get(&1).is_none());
3816 Some(v) => assert_eq!(*v, 2),
3822 let mut m1 = HashMap::new();
3827 let mut m2 = HashMap::new();
3840 let mut map = HashMap::new();
3841 let empty: HashMap<i32, i32> = HashMap::new();
3846 let map_str = format!("{:?}", map);
3848 assert!(map_str == "{1: 2, 3: 4}" ||
3849 map_str == "{3: 4, 1: 2}");
3850 assert_eq!(format!("{:?}", empty), "{}");
3855 let mut m = HashMap::new();
3857 assert_eq!(m.len(), 0);
3858 assert!(m.is_empty());
3861 let old_raw_cap = m.raw_capacity();
3862 while old_raw_cap == m.raw_capacity() {
3867 assert_eq!(m.len(), i);
3868 assert!(!m.is_empty());
3872 fn test_behavior_resize_policy() {
3873 let mut m = HashMap::new();
3875 assert_eq!(m.len(), 0);
3876 assert_eq!(m.raw_capacity(), 0);
3877 assert!(m.is_empty());
3881 assert!(m.is_empty());
3882 let initial_raw_cap = m.raw_capacity();
3883 m.reserve(initial_raw_cap);
3884 let raw_cap = m.raw_capacity();
3886 assert_eq!(raw_cap, initial_raw_cap * 2);
3889 for _ in 0..raw_cap * 3 / 4 {
3893 // three quarters full
3895 assert_eq!(m.len(), i);
3896 assert_eq!(m.raw_capacity(), raw_cap);
3898 for _ in 0..raw_cap / 4 {
3904 let new_raw_cap = m.raw_capacity();
3905 assert_eq!(new_raw_cap, raw_cap * 2);
3907 for _ in 0..raw_cap / 2 - 1 {
3910 assert_eq!(m.raw_capacity(), new_raw_cap);
3912 // A little more than one quarter full.
3914 assert_eq!(m.raw_capacity(), raw_cap);
3915 // again, a little more than half full
3916 for _ in 0..raw_cap / 2 - 1 {
3922 assert_eq!(m.len(), i);
3923 assert!(!m.is_empty());
3924 assert_eq!(m.raw_capacity(), initial_raw_cap);
3928 fn test_reserve_shrink_to_fit() {
3929 let mut m = HashMap::new();
3932 assert!(m.capacity() >= m.len());
3938 let usable_cap = m.capacity();
3939 for i in 128..(128 + 256) {
3941 assert_eq!(m.capacity(), usable_cap);
3944 for i in 100..(128 + 256) {
3945 assert_eq!(m.remove(&i), Some(i));
3949 assert_eq!(m.len(), 100);
3950 assert!(!m.is_empty());
3951 assert!(m.capacity() >= m.len());
3954 assert_eq!(m.remove(&i), Some(i));
3959 assert_eq!(m.len(), 1);
3960 assert!(m.capacity() >= m.len());
3961 assert_eq!(m.remove(&0), Some(0));
3965 fn test_from_iter() {
3966 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3968 let map: HashMap<_, _> = xs.iter().cloned().collect();
3970 for &(k, v) in &xs {
3971 assert_eq!(map.get(&k), Some(&v));
3976 fn test_size_hint() {
3977 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3979 let map: HashMap<_, _> = xs.iter().cloned().collect();
3981 let mut iter = map.iter();
3983 for _ in iter.by_ref().take(3) {}
3985 assert_eq!(iter.size_hint(), (3, Some(3)));
3989 fn test_iter_len() {
3990 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3992 let map: HashMap<_, _> = xs.iter().cloned().collect();
3994 let mut iter = map.iter();
3996 for _ in iter.by_ref().take(3) {}
3998 assert_eq!(iter.len(), 3);
4002 fn test_mut_size_hint() {
4003 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
4005 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4007 let mut iter = map.iter_mut();
4009 for _ in iter.by_ref().take(3) {}
4011 assert_eq!(iter.size_hint(), (3, Some(3)));
4015 fn test_iter_mut_len() {
4016 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
4018 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4020 let mut iter = map.iter_mut();
4022 for _ in iter.by_ref().take(3) {}
4024 assert_eq!(iter.len(), 3);
4029 let mut map = HashMap::new();
4035 assert_eq!(map[&2], 1);
4040 fn test_index_nonexistent() {
4041 let mut map = HashMap::new();
4052 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4054 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4056 // Existing key (insert)
4057 match map.entry(1) {
4058 Vacant(_) => unreachable!(),
4059 Occupied(mut view) => {
4060 assert_eq!(view.get(), &10);
4061 assert_eq!(view.insert(100), 10);
4064 assert_eq!(map.get(&1).unwrap(), &100);
4065 assert_eq!(map.len(), 6);
4068 // Existing key (update)
4069 match map.entry(2) {
4070 Vacant(_) => unreachable!(),
4071 Occupied(mut view) => {
4072 let v = view.get_mut();
4073 let new_v = (*v) * 10;
4077 assert_eq!(map.get(&2).unwrap(), &200);
4078 assert_eq!(map.len(), 6);
4080 // Existing key (take)
4081 match map.entry(3) {
4082 Vacant(_) => unreachable!(),
4084 assert_eq!(view.remove(), 30);
4087 assert_eq!(map.get(&3), None);
4088 assert_eq!(map.len(), 5);
4091 // Inexistent key (insert)
4092 match map.entry(10) {
4093 Occupied(_) => unreachable!(),
4095 assert_eq!(*view.insert(1000), 1000);
4098 assert_eq!(map.get(&10).unwrap(), &1000);
4099 assert_eq!(map.len(), 6);
4103 fn test_entry_take_doesnt_corrupt() {
4104 #![allow(deprecated)] //rand
4106 fn check(m: &HashMap<i32, ()>) {
4108 assert!(m.contains_key(k),
4109 "{} is in keys() but not in the map?", k);
4113 let mut m = HashMap::new();
4114 let mut rng = thread_rng();
4116 // Populate the map with some items.
4118 let x = rng.gen_range(-10, 10);
4123 let x = rng.gen_range(-10, 10);
4127 println!("{}: remove {}", i, x);
4137 fn test_extend_ref() {
4138 let mut a = HashMap::new();
4140 let mut b = HashMap::new();
4142 b.insert(3, "three");
4146 assert_eq!(a.len(), 3);
4147 assert_eq!(a[&1], "one");
4148 assert_eq!(a[&2], "two");
4149 assert_eq!(a[&3], "three");
4153 fn test_capacity_not_less_than_len() {
4154 let mut a = HashMap::new();
4162 assert!(a.capacity() > a.len());
4164 let free = a.capacity() - a.len();
4170 assert_eq!(a.len(), a.capacity());
4172 // Insert at capacity should cause allocation.
4174 assert!(a.capacity() > a.len());
4178 fn test_occupied_entry_key() {
4179 let mut a = HashMap::new();
4180 let key = "hello there";
4181 let value = "value goes here";
4182 assert!(a.is_empty());
4183 a.insert(key.clone(), value.clone());
4184 assert_eq!(a.len(), 1);
4185 assert_eq!(a[key], value);
4187 match a.entry(key.clone()) {
4188 Vacant(_) => panic!(),
4189 Occupied(e) => assert_eq!(key, *e.key()),
4191 assert_eq!(a.len(), 1);
4192 assert_eq!(a[key], value);
4196 fn test_vacant_entry_key() {
4197 let mut a = HashMap::new();
4198 let key = "hello there";
4199 let value = "value goes here";
4201 assert!(a.is_empty());
4202 match a.entry(key.clone()) {
4203 Occupied(_) => panic!(),
4205 assert_eq!(key, *e.key());
4206 e.insert(value.clone());
4209 assert_eq!(a.len(), 1);
4210 assert_eq!(a[key], value);
4215 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4217 map.retain(|&k, _| k % 2 == 0);
4218 assert_eq!(map.len(), 50);
4219 assert_eq!(map[&2], 20);
4220 assert_eq!(map[&4], 40);
4221 assert_eq!(map[&6], 60);
4225 fn test_adaptive() {
4226 const TEST_LEN: usize = 5000;
4227 // by cloning we get maps with the same hasher seed
4228 let mut first = HashMap::new();
4229 let mut second = first.clone();
4230 first.extend((0..TEST_LEN).map(|i| (i, i)));
4231 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4233 for (&k, &v) in &second {
4234 let prev_cap = first.capacity();
4235 let expect_grow = first.len() == prev_cap;
4237 if !expect_grow && first.capacity() != prev_cap {
4241 panic!("Adaptive early resize failed");
4245 fn test_try_reserve() {
4247 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4249 const MAX_USIZE: usize = usize::MAX;
4251 // HashMap and RawTables use complicated size calculations
4252 // hashes_size is sizeof(HashUint) * capacity;
4253 // pairs_size is sizeof((K. V)) * capacity;
4254 // alignment_hashes_size is 8
4255 // alignment_pairs size is 4
4256 let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4257 // The following formula is used to calculate the new capacity
4258 let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4260 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4261 } else { panic!("usize::MAX should trigger an overflow!"); }
4263 if size_of::<usize>() < 8 {
4264 if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4265 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4267 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4268 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4273 fn test_raw_entry() {
4274 use super::RawEntry::{Occupied, Vacant};
4276 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4278 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4280 // Existing key (insert)
4281 match map.raw_entry().search_by(&1) {
4282 Vacant(_) => unreachable!(),
4283 Occupied(mut view) => {
4284 assert_eq!(view.get(), &10);
4285 assert_eq!(view.insert(100), 10);
4288 assert_eq!(map.raw_entry_immut().hash_with(|mut h| {
4291 }).search_with(|k| *k == 1)
4292 .unwrap(), (&10, &100));
4293 assert_eq!(map.len(), 6);
4296 // Existing key (update)
4297 match map.raw_entry().hash_by(&2).search_by(&2) {
4298 Vacant(_) => unreachable!(),
4299 Occupied(mut view) => {
4300 let v = view.get_mut();
4301 let new_v = (*v) * 10;
4305 assert_eq!(map.raw_entry_immut().search_by(&2).unwrap(), (&2, &200));
4306 assert_eq!(map.len(), 6);
4308 // Existing key (take)
4309 match map.raw_entry().hash_with(|mut h| {
4312 }).search_with(|k| *k == 3) {
4313 Vacant(_) => unreachable!(),
4315 assert_eq!(view.remove_key_value(), (3, 30));
4318 assert_eq!(map.raw_entry_immut().search_by(&3), None);
4319 assert_eq!(map.len(), 5);
4322 // Inexistent key (insert)
4323 match map.raw_entry().search_by(&10) {
4324 Occupied(_) => unreachable!(),
4326 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4329 assert_eq!(map.raw_entry_immut().hash_by(&10).search_by(&10).unwrap(), (&10, &1000));
4330 assert_eq!(map.len(), 6);