1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use self::VacantEntryState::*;
17 use fmt::{self, Debug};
19 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
20 use iter::{FromIterator, FusedIterator};
21 use mem::{self, replace};
22 use ops::{Deref, Index, InPlace, Place, Placer};
26 use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash};
27 use super::table::BucketState::{Empty, Full};
29 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
31 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
33 struct DefaultResizePolicy;
35 impl DefaultResizePolicy {
36 fn new() -> DefaultResizePolicy {
40 /// A hash map's "capacity" is the number of elements it can hold without
41 /// being resized. Its "raw capacity" is the number of slots required to
42 /// provide that capacity, accounting for maximum loading. The raw capacity
43 /// is always zero or a power of two.
45 fn raw_capacity(&self, len: usize) -> usize {
49 // 1. Account for loading: `raw_capacity >= len * 1.1`.
50 // 2. Ensure it is a power of two.
51 // 3. Ensure it is at least the minimum size.
52 let mut raw_cap = len * 11 / 10;
53 assert!(raw_cap >= len, "raw_cap overflow");
54 raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow");
55 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
60 /// The capacity of the given raw capacity.
62 fn capacity(&self, raw_cap: usize) -> usize {
63 // This doesn't have to be checked for overflow since allocation size
64 // in bytes will overflow earlier than multiplication by 10.
66 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
67 // to be: (raw_cap * den + den - 1) / num
68 (raw_cap * 10 + 10 - 1) / 11
72 // The main performance trick in this hashmap is called Robin Hood Hashing.
73 // It gains its excellent performance from one essential operation:
75 // If an insertion collides with an existing element, and that element's
76 // "probe distance" (how far away the element is from its ideal location)
77 // is higher than how far we've already probed, swap the elements.
79 // This massively lowers variance in probe distance, and allows us to get very
80 // high load factors with good performance. The 90% load factor I use is rather
83 // > Why a load factor of approximately 90%?
85 // In general, all the distances to initial buckets will converge on the mean.
86 // At a load factor of α, the odds of finding the target bucket after k
87 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
88 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
89 // this down to make the math easier on the CPU and avoid its FPU.
90 // Since on average we start the probing in the middle of a cache line, this
91 // strategy pulls in two cache lines of hashes on every lookup. I think that's
92 // pretty good, but if you want to trade off some space, it could go down to one
93 // cache line on average with an α of 0.84.
95 // > Wait, what? Where did you get 1-α^k from?
97 // On the first probe, your odds of a collision with an existing element is α.
98 // The odds of doing this twice in a row is approximately α^2. For three times,
99 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
100 // colliding after k tries is 1-α^k.
102 // The paper from 1986 cited below mentions an implementation which keeps track
103 // of the distance-to-initial-bucket histogram. This approach is not suitable
104 // for modern architectures because it requires maintaining an internal data
105 // structure. This allows very good first guesses, but we are most concerned
106 // with guessing entire cache lines, not individual indexes. Furthermore, array
107 // accesses are no longer linear and in one direction, as we have now. There
108 // is also memory and cache pressure that this would entail that would be very
109 // difficult to properly see in a microbenchmark.
111 // ## Future Improvements (FIXME!)
113 // Allow the load factor to be changed dynamically and/or at initialization.
115 // Also, would it be possible for us to reuse storage when growing the
116 // underlying table? This is exactly the use case for 'realloc', and may
117 // be worth exploring.
119 // ## Future Optimizations (FIXME!)
121 // Another possible design choice that I made without any real reason is
122 // parameterizing the raw table over keys and values. Technically, all we need
123 // is the size and alignment of keys and values, and the code should be just as
124 // efficient (well, we might need one for power-of-two size and one for not...).
125 // This has the potential to reduce code bloat in rust executables, without
126 // really losing anything except 4 words (key size, key alignment, val size,
127 // val alignment) which can be passed in to every call of a `RawTable` function.
128 // This would definitely be an avenue worth exploring if people start complaining
129 // about the size of rust executables.
131 // Annotate exceedingly likely branches in `table::make_hash`
132 // and `search_hashed` to reduce instruction cache pressure
133 // and mispredictions once it becomes possible (blocked on issue #11092).
135 // Shrinking the table could simply reallocate in place after moving buckets
136 // to the first half.
138 // The growth algorithm (fragment of the Proof of Correctness)
139 // --------------------
141 // The growth algorithm is basically a fast path of the naive reinsertion-
142 // during-resize algorithm. Other paths should never be taken.
144 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
145 // by allocating a new table of capacity `2n`, and then individually reinsert
146 // each element in the old table into the new one. This guarantees that the
147 // new table is a valid robin hood hashtable with all the desired statistical
148 // properties. Remark that the order we reinsert the elements in should not
149 // matter. For simplicity and efficiency, we will consider only linear
150 // reinsertions, which consist of reinserting all elements in the old table
151 // into the new one by increasing order of index. However we will not be
152 // starting our reinsertions from index 0 in general. If we start from index
153 // i, for the purpose of reinsertion we will consider all elements with real
154 // index j < i to have virtual index n + j.
156 // Our hash generation scheme consists of generating a 64-bit hash and
157 // truncating the most significant bits. When moving to the new table, we
158 // simply introduce a new bit to the front of the hash. Therefore, if an
159 // elements has ideal index i in the old table, it can have one of two ideal
160 // locations in the new table. If the new bit is 0, then the new ideal index
161 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
162 // we are producing two independent tables of size n, and for each element we
163 // independently choose which table to insert it into with equal probability.
164 // However the rather than wrapping around themselves on overflowing their
165 // indexes, the first table overflows into the first, and the first into the
166 // second. Visually, our new table will look something like:
168 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
170 // Where x's are elements inserted into the first table, y's are elements
171 // inserted into the second, and _'s are empty sections. We now define a few
172 // key concepts that we will use later. Note that this is a very abstract
173 // perspective of the table. A real resized table would be at least half
176 // Theorem: A linear robin hood reinsertion from the first ideal element
177 // produces identical results to a linear naive reinsertion from the same
180 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
182 // Adaptive early resizing
183 // ----------------------
184 // To protect against degenerate performance scenarios (including DOS attacks),
185 // the implementation includes an adaptive behavior that can resize the map
186 // early (before its capacity is exceeded) when suspiciously long probe sequences
189 // With this algorithm in place it would be possible to turn a CPU attack into
190 // a memory attack due to the aggressive resizing. To prevent that the
191 // adaptive behavior only triggers when the map is at least half full.
192 // This reduces the effectiveness of the algorithm but also makes it completely safe.
194 // The previous safety measure also prevents degenerate interactions with
195 // really bad quality hash algorithms that can make normal inputs look like a
198 const DISPLACEMENT_THRESHOLD: usize = 128;
200 // The threshold of 128 is chosen to minimize the chance of exceeding it.
201 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
202 // For displacement, the smallest constant that fits our needs is 90,
203 // so we round that up to 128.
205 // At a load factor of α, the odds of finding the target bucket after exactly n
206 // unsuccessful probes[1] are
208 // Pr_α{displacement = n} =
209 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
211 // We use this formula to find the probability of triggering the adaptive behavior
213 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
215 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
216 // hashing with buckets.
218 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
220 /// By default, `HashMap` uses a hashing algorithm selected to provide
221 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
222 /// reasonable best-effort is made to generate this seed from a high quality,
223 /// secure source of randomness provided by the host without blocking the
224 /// program. Because of this, the randomness of the seed depends on the output
225 /// quality of the system's random number generator when the seed is created.
226 /// In particular, seeds generated when the system's entropy pool is abnormally
227 /// low such as during system boot may be of a lower quality.
229 /// The default hashing algorithm is currently SipHash 1-3, though this is
230 /// subject to change at any point in the future. While its performance is very
231 /// competitive for medium sized keys, other hashing algorithms will outperform
232 /// it for small keys such as integers as well as large keys such as long
233 /// strings, though those algorithms will typically *not* protect against
234 /// attacks such as HashDoS.
236 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
237 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
238 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
240 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
241 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
242 /// If you implement these yourself, it is important that the following
246 /// k1 == k2 -> hash(k1) == hash(k2)
249 /// In other words, if two keys are equal, their hashes must be equal.
251 /// It is a logic error for a key to be modified in such a way that the key's
252 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
253 /// the [`Eq`] trait, changes while it is in the map. This is normally only
254 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
256 /// Relevant papers/articles:
258 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
259 /// 2. Emmanuel Goossaert. ["Robin Hood
260 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
261 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
262 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
267 /// use std::collections::HashMap;
269 /// // type inference lets us omit an explicit type signature (which
270 /// // would be `HashMap<&str, &str>` in this example).
271 /// let mut book_reviews = HashMap::new();
273 /// // review some books.
274 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
275 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
276 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
277 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
279 /// // check for a specific one.
280 /// if !book_reviews.contains_key("Les Misérables") {
281 /// println!("We've got {} reviews, but Les Misérables ain't one.",
282 /// book_reviews.len());
285 /// // oops, this review has a lot of spelling mistakes, let's delete it.
286 /// book_reviews.remove("The Adventures of Sherlock Holmes");
288 /// // look up the values associated with some keys.
289 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
290 /// for book in &to_find {
291 /// match book_reviews.get(book) {
292 /// Some(review) => println!("{}: {}", book, review),
293 /// None => println!("{} is unreviewed.", book)
297 /// // iterate over everything.
298 /// for (book, review) in &book_reviews {
299 /// println!("{}: \"{}\"", book, review);
303 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
304 /// for more complex methods of getting, setting, updating and removing keys and
308 /// use std::collections::HashMap;
310 /// // type inference lets us omit an explicit type signature (which
311 /// // would be `HashMap<&str, u8>` in this example).
312 /// let mut player_stats = HashMap::new();
314 /// fn random_stat_buff() -> u8 {
315 /// // could actually return some random value here - let's just return
316 /// // some fixed value for now
320 /// // insert a key only if it doesn't already exist
321 /// player_stats.entry("health").or_insert(100);
323 /// // insert a key using a function that provides a new value only if it
324 /// // doesn't already exist
325 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
327 /// // update a key, guarding against the key possibly not being set
328 /// let stat = player_stats.entry("attack").or_insert(100);
329 /// *stat += random_stat_buff();
332 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
333 /// We must also derive [`PartialEq`].
335 /// [`Eq`]: ../../std/cmp/trait.Eq.html
336 /// [`Hash`]: ../../std/hash/trait.Hash.html
337 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
338 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
339 /// [`Cell`]: ../../std/cell/struct.Cell.html
340 /// [`default`]: #method.default
341 /// [`with_hasher`]: #method.with_hasher
342 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
343 /// [`fnv`]: https://crates.io/crates/fnv
346 /// use std::collections::HashMap;
348 /// #[derive(Hash, Eq, PartialEq, Debug)]
355 /// /// Create a new Viking.
356 /// fn new(name: &str, country: &str) -> Viking {
357 /// Viking { name: name.to_string(), country: country.to_string() }
361 /// // Use a HashMap to store the vikings' health points.
362 /// let mut vikings = HashMap::new();
364 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
365 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
366 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
368 /// // Use derived implementation to print the status of the vikings.
369 /// for (viking, health) in &vikings {
370 /// println!("{:?} has {} hp", viking, health);
374 /// A `HashMap` with fixed list of elements can be initialized from an array:
377 /// use std::collections::HashMap;
380 /// let timber_resources: HashMap<&str, i32> =
381 /// [("Norway", 100),
384 /// .iter().cloned().collect();
385 /// // use the values stored in map
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub struct HashMap<K, V, S = RandomState> {
392 // All hashes are keyed on these values, to prevent hash collision attacks.
395 table: RawTable<K, V>,
397 resize_policy: DefaultResizePolicy,
400 /// Search for a pre-hashed key.
401 /// If you don't already know the hash, use search or search_mut instead
403 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
404 where M: Deref<Target = RawTable<K, V>>,
407 // This is the only function where capacity can be zero. To avoid
408 // undefined behavior when Bucket::new gets the raw bucket in this
409 // case, immediately return the appropriate search result.
410 if table.capacity() == 0 {
411 return InternalEntry::TableIsEmpty;
414 search_hashed_nonempty(table, hash, is_match)
417 /// Search for a pre-hashed key when the hash map is known to be non-empty.
419 fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F)
420 -> InternalEntry<K, V, M>
421 where M: Deref<Target = RawTable<K, V>>,
424 // Do not check the capacity as an extra branch could slow the lookup.
426 let size = table.size();
427 let mut probe = Bucket::new(table, hash);
428 let mut displacement = 0;
431 let full = match probe.peek() {
434 return InternalEntry::Vacant {
436 elem: NoElem(bucket, displacement),
439 Full(bucket) => bucket,
442 let probe_displacement = full.displacement();
444 if probe_displacement < displacement {
445 // Found a luckier bucket than me.
446 // We can finish the search early if we hit any bucket
447 // with a lower distance to initial bucket than we've probed.
448 return InternalEntry::Vacant {
450 elem: NeqElem(full, probe_displacement),
454 // If the hash doesn't match, it can't be this one..
455 if hash == full.hash() {
456 // If the key doesn't match, it can't be this one..
457 if is_match(full.read().0) {
458 return InternalEntry::Occupied { elem: full };
463 debug_assert!(displacement <= size);
467 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
468 -> (K, V, &mut RawTable<K, V>)
470 let (empty, retkey, retval) = starting_bucket.take();
471 let mut gap = match empty.gap_peek() {
473 Err(b) => return (retkey, retval, b.into_table()),
476 while gap.full().displacement() != 0 {
477 gap = match gap.shift() {
480 return (retkey, retval, b.into_table());
485 // Now we've done all our shifting. Return the value we grabbed earlier.
486 (retkey, retval, gap.into_table())
489 /// Perform robin hood bucket stealing at the given `bucket`. You must
490 /// also pass that bucket's displacement so we don't have to recalculate it.
492 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
493 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
494 mut displacement: usize,
498 -> FullBucketMut<'a, K, V> {
499 let size = bucket.table().size();
500 let raw_capacity = bucket.table().capacity();
501 // There can be at most `size - dib` buckets to displace, because
502 // in the worst case, there are `size` elements and we already are
503 // `displacement` buckets away from the initial one.
504 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
505 // Save the *starting point*.
506 let mut bucket = bucket.stash();
509 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
516 let probe = bucket.next();
517 debug_assert!(probe.index() != idx_end);
519 let full_bucket = match probe.peek() {
522 let bucket = bucket.put(hash, key, val);
523 // Now that it's stolen, just read the value's pointer
524 // right out of the table! Go back to the *starting point*.
526 // This use of `into_table` is misleading. It turns the
527 // bucket, which is a FullBucket on top of a
528 // FullBucketMut, into just one FullBucketMut. The "table"
529 // refers to the inner FullBucketMut in this context.
530 return bucket.into_table();
532 Full(bucket) => bucket,
535 let probe_displacement = full_bucket.displacement();
537 bucket = full_bucket;
539 // Robin hood! Steal the spot.
540 if probe_displacement < displacement {
541 displacement = probe_displacement;
548 impl<K, V, S> HashMap<K, V, S>
552 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
555 table::make_hash(&self.hash_builder, x)
558 /// Search for a key, yielding the index if it's found in the hashtable.
559 /// If you already have the hash for the key lying around, or if you need an
560 /// InternalEntry, use search_hashed or search_hashed_nonempty.
562 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
563 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
571 let hash = self.make_hash(q);
572 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()))
573 .into_occupied_bucket()
577 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
578 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
586 let hash = self.make_hash(q);
587 search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()))
588 .into_occupied_bucket()
591 // The caller should ensure that invariants by Robin Hood Hashing hold
592 // and that there's space in the underlying table.
593 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
594 let mut buckets = Bucket::new(&mut self.table, hash);
595 let start_index = buckets.index();
598 // We don't need to compare hashes for value swap.
599 // Not even DIBs for Robin Hood.
600 buckets = match buckets.peek() {
602 empty.put(hash, k, v);
605 Full(b) => b.into_bucket(),
608 debug_assert!(buckets.index() != start_index);
613 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
614 /// Creates an empty `HashMap`.
616 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
617 /// is first inserted into.
622 /// use std::collections::HashMap;
623 /// let mut map: HashMap<&str, isize> = HashMap::new();
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn new() -> HashMap<K, V, RandomState> {
631 /// Creates an empty `HashMap` with the specified capacity.
633 /// The hash map will be able to hold at least `capacity` elements without
634 /// reallocating. If `capacity` is 0, the hash map will not allocate.
639 /// use std::collections::HashMap;
640 /// let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
645 HashMap::with_capacity_and_hasher(capacity, Default::default())
649 impl<K, V, S> HashMap<K, V, S>
653 /// Creates an empty `HashMap` which will use the given hash builder to hash
656 /// The created map has the default initial capacity.
658 /// Warning: `hash_builder` is normally randomly generated, and
659 /// is designed to allow HashMaps to be resistant to attacks that
660 /// cause many collisions and very poor performance. Setting it
661 /// manually using this function can expose a DoS attack vector.
666 /// use std::collections::HashMap;
667 /// use std::collections::hash_map::RandomState;
669 /// let s = RandomState::new();
670 /// let mut map = HashMap::with_hasher(s);
671 /// map.insert(1, 2);
674 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
675 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
678 resize_policy: DefaultResizePolicy::new(),
679 table: RawTable::new(0),
683 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
684 /// to hash the keys.
686 /// The hash map will be able to hold at least `capacity` elements without
687 /// reallocating. If `capacity` is 0, the hash map will not allocate.
689 /// Warning: `hash_builder` is normally randomly generated, and
690 /// is designed to allow HashMaps to be resistant to attacks that
691 /// cause many collisions and very poor performance. Setting it
692 /// manually using this function can expose a DoS attack vector.
697 /// use std::collections::HashMap;
698 /// use std::collections::hash_map::RandomState;
700 /// let s = RandomState::new();
701 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
702 /// map.insert(1, 2);
705 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
706 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
707 let resize_policy = DefaultResizePolicy::new();
708 let raw_cap = resize_policy.raw_capacity(capacity);
712 table: RawTable::new(raw_cap),
716 /// Returns a reference to the map's [`BuildHasher`].
718 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
723 /// use std::collections::HashMap;
724 /// use std::collections::hash_map::RandomState;
726 /// let hasher = RandomState::new();
727 /// let map: HashMap<isize, isize> = HashMap::with_hasher(hasher);
728 /// let hasher: &RandomState = map.hasher();
730 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
731 pub fn hasher(&self) -> &S {
735 /// Returns the number of elements the map can hold without reallocating.
737 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
738 /// more, but is guaranteed to be able to hold at least this many.
743 /// use std::collections::HashMap;
744 /// let map: HashMap<isize, isize> = HashMap::with_capacity(100);
745 /// assert!(map.capacity() >= 100);
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn capacity(&self) -> usize {
750 self.resize_policy.capacity(self.raw_capacity())
753 /// Returns the hash map's raw capacity.
755 fn raw_capacity(&self) -> usize {
756 self.table.capacity()
759 /// Reserves capacity for at least `additional` more elements to be inserted
760 /// in the `HashMap`. The collection may reserve more space to avoid
761 /// frequent reallocations.
765 /// Panics if the new allocation size overflows [`usize`].
767 /// [`usize`]: ../../std/primitive.usize.html
772 /// use std::collections::HashMap;
773 /// let mut map: HashMap<&str, isize> = HashMap::new();
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn reserve(&mut self, additional: usize) {
778 let remaining = self.capacity() - self.len(); // this can't overflow
779 if remaining < additional {
780 let min_cap = self.len().checked_add(additional).expect("reserve overflow");
781 let raw_cap = self.resize_policy.raw_capacity(min_cap);
782 self.resize(raw_cap);
783 } else if self.table.tag() && remaining <= self.len() {
784 // Probe sequence is too long and table is half full,
785 // resize early to reduce probing length.
786 let new_capacity = self.table.capacity() * 2;
787 self.resize(new_capacity);
791 /// Resizes the internal vectors to a new capacity. It's your
792 /// responsibility to:
793 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
794 /// for the load factor.
795 /// 2) Ensure `new_raw_cap` is a power of two or zero.
798 fn resize(&mut self, new_raw_cap: usize) {
799 assert!(self.table.size() <= new_raw_cap);
800 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
802 let mut old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
803 let old_size = old_table.size();
805 if old_table.size() == 0 {
809 let mut bucket = Bucket::head_bucket(&mut old_table);
811 // This is how the buckets might be laid out in memory:
812 // ($ marks an initialized bucket)
814 // |$$$_$$$$$$_$$$$$|
816 // But we've skipped the entire initial cluster of buckets
817 // and will continue iteration in this order:
820 // ^ wrap around once end is reached
823 // ^ exit once table.size == 0
825 bucket = match bucket.peek() {
827 let h = bucket.hash();
828 let (b, k, v) = bucket.take();
829 self.insert_hashed_ordered(h, k, v);
830 if b.table().size() == 0 {
835 Empty(b) => b.into_bucket(),
840 assert_eq!(self.table.size(), old_size);
843 /// Shrinks the capacity of the map as much as possible. It will drop
844 /// down as much as possible while maintaining the internal rules
845 /// and possibly leaving some space in accordance with the resize policy.
850 /// use std::collections::HashMap;
852 /// let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
853 /// map.insert(1, 2);
854 /// map.insert(3, 4);
855 /// assert!(map.capacity() >= 100);
856 /// map.shrink_to_fit();
857 /// assert!(map.capacity() >= 2);
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn shrink_to_fit(&mut self) {
861 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
862 if self.raw_capacity() != new_raw_cap {
863 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
864 let old_size = old_table.size();
866 // Shrink the table. Naive algorithm for resizing:
867 for (h, k, v) in old_table.into_iter() {
868 self.insert_hashed_nocheck(h, k, v);
871 debug_assert_eq!(self.table.size(), old_size);
875 /// Insert a pre-hashed key-value pair, without first checking
876 /// that there's enough room in the buckets. Returns a reference to the
877 /// newly insert value.
879 /// If the key already exists, the hashtable will be returned untouched
880 /// and a reference to the existing element will be returned.
881 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
882 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
884 Some(Occupied(mut elem)) => Some(elem.insert(v)),
885 Some(Vacant(elem)) => {
889 None => unreachable!(),
893 /// An iterator visiting all keys in arbitrary order.
894 /// The iterator element type is `&'a K`.
899 /// use std::collections::HashMap;
901 /// let mut map = HashMap::new();
902 /// map.insert("a", 1);
903 /// map.insert("b", 2);
904 /// map.insert("c", 3);
906 /// for key in map.keys() {
907 /// println!("{}", key);
910 #[stable(feature = "rust1", since = "1.0.0")]
911 pub fn keys(&self) -> Keys<K, V> {
912 Keys { inner: self.iter() }
915 /// An iterator visiting all values in arbitrary order.
916 /// The iterator element type is `&'a V`.
921 /// use std::collections::HashMap;
923 /// let mut map = HashMap::new();
924 /// map.insert("a", 1);
925 /// map.insert("b", 2);
926 /// map.insert("c", 3);
928 /// for val in map.values() {
929 /// println!("{}", val);
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn values(&self) -> Values<K, V> {
934 Values { inner: self.iter() }
937 /// An iterator visiting all values mutably in arbitrary order.
938 /// The iterator element type is `&'a mut V`.
943 /// use std::collections::HashMap;
945 /// let mut map = HashMap::new();
947 /// map.insert("a", 1);
948 /// map.insert("b", 2);
949 /// map.insert("c", 3);
951 /// for val in map.values_mut() {
952 /// *val = *val + 10;
955 /// for val in map.values() {
956 /// println!("{}", val);
959 #[stable(feature = "map_values_mut", since = "1.10.0")]
960 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
961 ValuesMut { inner: self.iter_mut() }
964 /// An iterator visiting all key-value pairs in arbitrary order.
965 /// The iterator element type is `(&'a K, &'a V)`.
970 /// use std::collections::HashMap;
972 /// let mut map = HashMap::new();
973 /// map.insert("a", 1);
974 /// map.insert("b", 2);
975 /// map.insert("c", 3);
977 /// for (key, val) in map.iter() {
978 /// println!("key: {} val: {}", key, val);
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn iter(&self) -> Iter<K, V> {
983 Iter { inner: self.table.iter() }
986 /// An iterator visiting all key-value pairs in arbitrary order,
987 /// with mutable references to the values.
988 /// The iterator element type is `(&'a K, &'a mut V)`.
993 /// use std::collections::HashMap;
995 /// let mut map = HashMap::new();
996 /// map.insert("a", 1);
997 /// map.insert("b", 2);
998 /// map.insert("c", 3);
1000 /// // Update all values
1001 /// for (_, val) in map.iter_mut() {
1005 /// for (key, val) in &map {
1006 /// println!("key: {} val: {}", key, val);
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1011 IterMut { inner: self.table.iter_mut() }
1014 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1019 /// use std::collections::HashMap;
1021 /// let mut letters = HashMap::new();
1023 /// for ch in "a short treatise on fungi".chars() {
1024 /// let counter = letters.entry(ch).or_insert(0);
1028 /// assert_eq!(letters[&'s'], 2);
1029 /// assert_eq!(letters[&'t'], 3);
1030 /// assert_eq!(letters[&'u'], 1);
1031 /// assert_eq!(letters.get(&'y'), None);
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1035 // Gotta resize now.
1037 let hash = self.make_hash(&key);
1038 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1039 .into_entry(key).expect("unreachable")
1042 /// Returns the number of elements in the map.
1047 /// use std::collections::HashMap;
1049 /// let mut a = HashMap::new();
1050 /// assert_eq!(a.len(), 0);
1051 /// a.insert(1, "a");
1052 /// assert_eq!(a.len(), 1);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn len(&self) -> usize {
1059 /// Returns true if the map contains no elements.
1064 /// use std::collections::HashMap;
1066 /// let mut a = HashMap::new();
1067 /// assert!(a.is_empty());
1068 /// a.insert(1, "a");
1069 /// assert!(!a.is_empty());
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn is_empty(&self) -> bool {
1077 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1078 /// allocated memory for reuse.
1083 /// use std::collections::HashMap;
1085 /// let mut a = HashMap::new();
1086 /// a.insert(1, "a");
1087 /// a.insert(2, "b");
1089 /// for (k, v) in a.drain().take(1) {
1090 /// assert!(k == 1 || k == 2);
1091 /// assert!(v == "a" || v == "b");
1094 /// assert!(a.is_empty());
1097 #[stable(feature = "drain", since = "1.6.0")]
1098 pub fn drain(&mut self) -> Drain<K, V> {
1099 Drain { inner: self.table.drain() }
1102 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1108 /// use std::collections::HashMap;
1110 /// let mut a = HashMap::new();
1111 /// a.insert(1, "a");
1113 /// assert!(a.is_empty());
1115 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub fn clear(&mut self) {
1121 /// Returns a reference to the value corresponding to the key.
1123 /// The key may be any borrowed form of the map's key type, but
1124 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1127 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1128 /// [`Hash`]: ../../std/hash/trait.Hash.html
1133 /// use std::collections::HashMap;
1135 /// let mut map = HashMap::new();
1136 /// map.insert(1, "a");
1137 /// assert_eq!(map.get(&1), Some(&"a"));
1138 /// assert_eq!(map.get(&2), None);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1146 self.search(k).map(|bucket| bucket.into_refs().1)
1149 /// Returns true if the map contains a value for the specified key.
1151 /// The key may be any borrowed form of the map's key type, but
1152 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1155 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1156 /// [`Hash`]: ../../std/hash/trait.Hash.html
1161 /// use std::collections::HashMap;
1163 /// let mut map = HashMap::new();
1164 /// map.insert(1, "a");
1165 /// assert_eq!(map.contains_key(&1), true);
1166 /// assert_eq!(map.contains_key(&2), false);
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1173 self.search(k).is_some()
1176 /// Returns a mutable reference to the value corresponding to the key.
1178 /// The key may be any borrowed form of the map's key type, but
1179 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1182 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1183 /// [`Hash`]: ../../std/hash/trait.Hash.html
1188 /// use std::collections::HashMap;
1190 /// let mut map = HashMap::new();
1191 /// map.insert(1, "a");
1192 /// if let Some(x) = map.get_mut(&1) {
1195 /// assert_eq!(map[&1], "b");
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1202 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1205 /// Inserts a key-value pair into the map.
1207 /// If the map did not have this key present, [`None`] is returned.
1209 /// If the map did have this key present, the value is updated, and the old
1210 /// value is returned. The key is not updated, though; this matters for
1211 /// types that can be `==` without being identical. See the [module-level
1212 /// documentation] for more.
1214 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1215 /// [module-level documentation]: index.html#insert-and-complex-keys
1220 /// use std::collections::HashMap;
1222 /// let mut map = HashMap::new();
1223 /// assert_eq!(map.insert(37, "a"), None);
1224 /// assert_eq!(map.is_empty(), false);
1226 /// map.insert(37, "b");
1227 /// assert_eq!(map.insert(37, "c"), Some("b"));
1228 /// assert_eq!(map[&37], "c");
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1232 let hash = self.make_hash(&k);
1234 self.insert_hashed_nocheck(hash, k, v)
1237 /// Removes a key from the map, returning the value at the key if the key
1238 /// was previously in the map.
1240 /// The key may be any borrowed form of the map's key type, but
1241 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1244 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1245 /// [`Hash`]: ../../std/hash/trait.Hash.html
1250 /// use std::collections::HashMap;
1252 /// let mut map = HashMap::new();
1253 /// map.insert(1, "a");
1254 /// assert_eq!(map.remove(&1), Some("a"));
1255 /// assert_eq!(map.remove(&1), None);
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1262 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1265 /// Removes a key from the map, returning the stored key and value if the
1266 /// key was previously in the map.
1268 /// The key may be any borrowed form of the map's key type, but
1269 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1272 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1273 /// [`Hash`]: ../../std/hash/trait.Hash.html
1278 /// #![feature(hash_map_remove_entry)]
1279 /// use std::collections::HashMap;
1282 /// let mut map = HashMap::new();
1283 /// map.insert(1, "a");
1284 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1285 /// assert_eq!(map.remove(&1), None);
1288 #[unstable(feature = "hash_map_remove_entry", issue = "46344")]
1289 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1295 let (k, v, _) = pop_internal(bucket);
1300 /// Retains only the elements specified by the predicate.
1302 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1307 /// use std::collections::HashMap;
1309 /// let mut map: HashMap<isize, isize> = (0..8).map(|x|(x, x*10)).collect();
1310 /// map.retain(|&k, _| k % 2 == 0);
1311 /// assert_eq!(map.len(), 4);
1313 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1314 pub fn retain<F>(&mut self, mut f: F)
1315 where F: FnMut(&K, &mut V) -> bool
1317 if self.table.size() == 0 {
1320 let mut elems_left = self.table.size();
1321 let mut bucket = Bucket::head_bucket(&mut self.table);
1323 let start_index = bucket.index();
1324 while elems_left != 0 {
1325 bucket = match bucket.peek() {
1328 let should_remove = {
1329 let (k, v) = full.read_mut();
1333 let prev_raw = full.raw();
1334 let (_, _, t) = pop_internal(full);
1335 Bucket::new_from(prev_raw, t)
1344 bucket.prev(); // reverse iteration
1345 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<K, V, S> PartialEq for HashMap<K, V, S>
1356 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1357 if self.len() != other.len() {
1361 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<K, V, S> Eq for HashMap<K, V, S>
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<K, V, S> Debug for HashMap<K, V, S>
1375 where K: Eq + Hash + Debug,
1379 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380 f.debug_map().entries(self.iter()).finish()
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<K, V, S> Default for HashMap<K, V, S>
1387 S: BuildHasher + Default
1389 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1390 fn default() -> HashMap<K, V, S> {
1391 HashMap::with_hasher(Default::default())
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1397 where K: Eq + Hash + Borrow<Q>,
1403 /// Returns a reference to the value corresponding to the supplied key.
1407 /// Panics if the key is not present in the `HashMap`.
1409 fn index(&self, key: &Q) -> &V {
1410 self.get(key).expect("no entry found for key")
1414 /// An iterator over the entries of a `HashMap`.
1416 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1417 /// documentation for more.
1419 /// [`iter`]: struct.HashMap.html#method.iter
1420 /// [`HashMap`]: struct.HashMap.html
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub struct Iter<'a, K: 'a, V: 'a> {
1423 inner: table::Iter<'a, K, V>,
1426 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<'a, K, V> Clone for Iter<'a, K, V> {
1429 fn clone(&self) -> Iter<'a, K, V> {
1430 Iter { inner: self.inner.clone() }
1434 #[stable(feature = "std_debug", since = "1.16.0")]
1435 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1436 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1438 .entries(self.clone())
1443 /// A mutable iterator over the entries of a `HashMap`.
1445 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1446 /// documentation for more.
1448 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1449 /// [`HashMap`]: struct.HashMap.html
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 pub struct IterMut<'a, K: 'a, V: 'a> {
1452 inner: table::IterMut<'a, K, V>,
1455 /// An owning iterator over the entries of a `HashMap`.
1457 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1458 /// (provided by the `IntoIterator` trait). See its documentation for more.
1460 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1461 /// [`HashMap`]: struct.HashMap.html
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 pub struct IntoIter<K, V> {
1464 pub(super) inner: table::IntoIter<K, V>,
1467 /// An iterator over the keys of a `HashMap`.
1469 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1470 /// documentation for more.
1472 /// [`keys`]: struct.HashMap.html#method.keys
1473 /// [`HashMap`]: struct.HashMap.html
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub struct Keys<'a, K: 'a, V: 'a> {
1476 inner: Iter<'a, K, V>,
1479 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl<'a, K, V> Clone for Keys<'a, K, V> {
1482 fn clone(&self) -> Keys<'a, K, V> {
1483 Keys { inner: self.inner.clone() }
1487 #[stable(feature = "std_debug", since = "1.16.0")]
1488 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491 .entries(self.clone())
1496 /// An iterator over the values of a `HashMap`.
1498 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1499 /// documentation for more.
1501 /// [`values`]: struct.HashMap.html#method.values
1502 /// [`HashMap`]: struct.HashMap.html
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub struct Values<'a, K: 'a, V: 'a> {
1505 inner: Iter<'a, K, V>,
1508 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<'a, K, V> Clone for Values<'a, K, V> {
1511 fn clone(&self) -> Values<'a, K, V> {
1512 Values { inner: self.inner.clone() }
1516 #[stable(feature = "std_debug", since = "1.16.0")]
1517 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1520 .entries(self.clone())
1525 /// A draining iterator over the entries of a `HashMap`.
1527 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1528 /// documentation for more.
1530 /// [`drain`]: struct.HashMap.html#method.drain
1531 /// [`HashMap`]: struct.HashMap.html
1532 #[stable(feature = "drain", since = "1.6.0")]
1533 pub struct Drain<'a, K: 'a, V: 'a> {
1534 pub(super) inner: table::Drain<'a, K, V>,
1537 /// A mutable iterator over the values of a `HashMap`.
1539 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1540 /// documentation for more.
1542 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1543 /// [`HashMap`]: struct.HashMap.html
1544 #[stable(feature = "map_values_mut", since = "1.10.0")]
1545 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1546 inner: IterMut<'a, K, V>,
1549 enum InternalEntry<K, V, M> {
1550 Occupied { elem: FullBucket<K, V, M> },
1553 elem: VacantEntryState<K, V, M>,
1558 impl<K, V, M> InternalEntry<K, V, M> {
1560 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1562 InternalEntry::Occupied { elem } => Some(elem),
1568 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1570 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1572 InternalEntry::Occupied { elem } => {
1573 Some(Occupied(OccupiedEntry {
1578 InternalEntry::Vacant { hash, elem } => {
1579 Some(Vacant(VacantEntry {
1585 InternalEntry::TableIsEmpty => None,
1590 /// A view into a single entry in a map, which may either be vacant or occupied.
1592 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1594 /// [`HashMap`]: struct.HashMap.html
1595 /// [`entry`]: struct.HashMap.html#method.entry
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 pub enum Entry<'a, K: 'a, V: 'a> {
1598 /// An occupied entry.
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
1601 OccupiedEntry<'a, K, V>),
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
1606 VacantEntry<'a, K, V>),
1609 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1610 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
1611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1614 f.debug_tuple("Entry")
1618 Occupied(ref o) => {
1619 f.debug_tuple("Entry")
1627 /// A view into an occupied entry in a `HashMap`.
1628 /// It is part of the [`Entry`] enum.
1630 /// [`Entry`]: enum.Entry.html
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1634 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1637 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1638 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
1639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1640 f.debug_struct("OccupiedEntry")
1641 .field("key", self.key())
1642 .field("value", self.get())
1647 /// A view into a vacant entry in a `HashMap`.
1648 /// It is part of the [`Entry`] enum.
1650 /// [`Entry`]: enum.Entry.html
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1655 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1658 #[stable(feature= "debug_hash_map", since = "1.12.0")]
1659 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
1660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1661 f.debug_tuple("VacantEntry")
1667 /// Possible states of a VacantEntry.
1668 enum VacantEntryState<K, V, M> {
1669 /// The index is occupied, but the key to insert has precedence,
1670 /// and will kick the current one out on insertion.
1671 NeqElem(FullBucket<K, V, M>, usize),
1672 /// The index is genuinely vacant.
1673 NoElem(EmptyBucket<K, V, M>, usize),
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1681 type Item = (&'a K, &'a V);
1682 type IntoIter = Iter<'a, K, V>;
1684 fn into_iter(self) -> Iter<'a, K, V> {
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1694 type Item = (&'a K, &'a mut V);
1695 type IntoIter = IterMut<'a, K, V>;
1697 fn into_iter(self) -> IterMut<'a, K, V> {
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1708 type IntoIter = IntoIter<K, V>;
1710 /// Creates a consuming iterator, that is, one that moves each key-value
1711 /// pair out of the map in arbitrary order. The map cannot be used after
1717 /// use std::collections::HashMap;
1719 /// let mut map = HashMap::new();
1720 /// map.insert("a", 1);
1721 /// map.insert("b", 2);
1722 /// map.insert("c", 3);
1724 /// // Not possible with .iter()
1725 /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
1727 fn into_iter(self) -> IntoIter<K, V> {
1728 IntoIter { inner: self.table.into_iter() }
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1734 type Item = (&'a K, &'a V);
1737 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1741 fn size_hint(&self) -> (usize, Option<usize>) {
1742 self.inner.size_hint()
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1748 fn len(&self) -> usize {
1753 #[stable(feature = "fused", since = "1.26.0")]
1754 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1758 type Item = (&'a K, &'a mut V);
1761 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1765 fn size_hint(&self) -> (usize, Option<usize>) {
1766 self.inner.size_hint()
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1772 fn len(&self) -> usize {
1776 #[stable(feature = "fused", since = "1.26.0")]
1777 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1779 #[stable(feature = "std_debug", since = "1.16.0")]
1780 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
1781 where K: fmt::Debug,
1784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1786 .entries(self.inner.iter())
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 impl<K, V> Iterator for IntoIter<K, V> {
1796 fn next(&mut self) -> Option<(K, V)> {
1797 self.inner.next().map(|(_, k, v)| (k, v))
1800 fn size_hint(&self) -> (usize, Option<usize>) {
1801 self.inner.size_hint()
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1807 fn len(&self) -> usize {
1811 #[stable(feature = "fused", since = "1.26.0")]
1812 impl<K, V> FusedIterator for IntoIter<K, V> {}
1814 #[stable(feature = "std_debug", since = "1.16.0")]
1815 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1816 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1818 .entries(self.inner.iter())
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1828 fn next(&mut self) -> Option<(&'a K)> {
1829 self.inner.next().map(|(k, _)| k)
1832 fn size_hint(&self) -> (usize, Option<usize>) {
1833 self.inner.size_hint()
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1839 fn len(&self) -> usize {
1843 #[stable(feature = "fused", since = "1.26.0")]
1844 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 impl<'a, K, V> Iterator for Values<'a, K, V> {
1851 fn next(&mut self) -> Option<(&'a V)> {
1852 self.inner.next().map(|(_, v)| v)
1855 fn size_hint(&self) -> (usize, Option<usize>) {
1856 self.inner.size_hint()
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1862 fn len(&self) -> usize {
1866 #[stable(feature = "fused", since = "1.26.0")]
1867 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1869 #[stable(feature = "map_values_mut", since = "1.10.0")]
1870 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1871 type Item = &'a mut V;
1874 fn next(&mut self) -> Option<(&'a mut V)> {
1875 self.inner.next().map(|(_, v)| v)
1878 fn size_hint(&self) -> (usize, Option<usize>) {
1879 self.inner.size_hint()
1882 #[stable(feature = "map_values_mut", since = "1.10.0")]
1883 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1885 fn len(&self) -> usize {
1889 #[stable(feature = "fused", since = "1.26.0")]
1890 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1892 #[stable(feature = "std_debug", since = "1.16.0")]
1893 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
1894 where K: fmt::Debug,
1897 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1899 .entries(self.inner.inner.iter())
1904 #[stable(feature = "drain", since = "1.6.0")]
1905 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1909 fn next(&mut self) -> Option<(K, V)> {
1910 self.inner.next().map(|(_, k, v)| (k, v))
1913 fn size_hint(&self) -> (usize, Option<usize>) {
1914 self.inner.size_hint()
1917 #[stable(feature = "drain", since = "1.6.0")]
1918 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1920 fn len(&self) -> usize {
1924 #[stable(feature = "fused", since = "1.26.0")]
1925 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1927 #[stable(feature = "std_debug", since = "1.16.0")]
1928 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
1929 where K: fmt::Debug,
1932 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1934 .entries(self.inner.iter())
1939 /// A place for insertion to a `Entry`.
1941 /// See [`HashMap::entry`](struct.HashMap.html#method.entry) for details.
1942 #[must_use = "places do nothing unless written to with `<-` syntax"]
1943 #[unstable(feature = "collection_placement",
1944 reason = "struct name and placement protocol is subject to change",
1946 pub struct EntryPlace<'a, K: 'a, V: 'a> {
1947 bucket: FullBucketMut<'a, K, V>,
1950 #[unstable(feature = "collection_placement",
1951 reason = "struct name and placement protocol is subject to change",
1953 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for EntryPlace<'a, K, V> {
1954 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1955 f.debug_struct("EntryPlace")
1956 .field("key", self.bucket.read().0)
1957 .field("value", self.bucket.read().1)
1962 #[unstable(feature = "collection_placement",
1963 reason = "struct name and placement protocol is subject to change",
1965 impl<'a, K, V> Drop for EntryPlace<'a, K, V> {
1966 fn drop(&mut self) {
1967 // Inplacement insertion failed. Only key need to drop.
1968 // The value is failed to insert into map.
1969 unsafe { self.bucket.remove_key() };
1973 #[unstable(feature = "collection_placement",
1974 reason = "placement protocol is subject to change",
1976 impl<'a, K, V> Placer<V> for Entry<'a, K, V> {
1977 type Place = EntryPlace<'a, K, V>;
1979 fn make_place(self) -> EntryPlace<'a, K, V> {
1980 let b = match self {
1981 Occupied(mut o) => {
1982 unsafe { ptr::drop_in_place(o.elem.read_mut().1); }
1986 unsafe { v.insert_key() }
1989 EntryPlace { bucket: b }
1993 #[unstable(feature = "collection_placement",
1994 reason = "placement protocol is subject to change",
1996 unsafe impl<'a, K, V> Place<V> for EntryPlace<'a, K, V> {
1997 fn pointer(&mut self) -> *mut V {
1998 self.bucket.read_mut().1
2002 #[unstable(feature = "collection_placement",
2003 reason = "placement protocol is subject to change",
2005 impl<'a, K, V> InPlace<V> for EntryPlace<'a, K, V> {
2008 unsafe fn finalize(self) {
2013 impl<'a, K, V> Entry<'a, K, V> {
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 /// Ensures a value is in the entry by inserting the default if empty, and returns
2016 /// a mutable reference to the value in the entry.
2021 /// use std::collections::HashMap;
2023 /// let mut map: HashMap<&str, u32> = HashMap::new();
2024 /// map.entry("poneyland").or_insert(12);
2026 /// assert_eq!(map["poneyland"], 12);
2028 /// *map.entry("poneyland").or_insert(12) += 10;
2029 /// assert_eq!(map["poneyland"], 22);
2031 pub fn or_insert(self, default: V) -> &'a mut V {
2033 Occupied(entry) => entry.into_mut(),
2034 Vacant(entry) => entry.insert(default),
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2040 /// and returns a mutable reference to the value in the entry.
2045 /// use std::collections::HashMap;
2047 /// let mut map: HashMap<&str, String> = HashMap::new();
2048 /// let s = "hoho".to_string();
2050 /// map.entry("poneyland").or_insert_with(|| s);
2052 /// assert_eq!(map["poneyland"], "hoho".to_string());
2054 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2056 Occupied(entry) => entry.into_mut(),
2057 Vacant(entry) => entry.insert(default()),
2061 /// Returns a reference to this entry's key.
2066 /// use std::collections::HashMap;
2068 /// let mut map: HashMap<&str, u32> = HashMap::new();
2069 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2071 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2072 pub fn key(&self) -> &K {
2074 Occupied(ref entry) => entry.key(),
2075 Vacant(ref entry) => entry.key(),
2079 /// Provides in-place mutable access to an occupied entry before any
2080 /// potential inserts into the map.
2085 /// use std::collections::HashMap;
2087 /// let mut map: HashMap<&str, u32> = HashMap::new();
2089 /// map.entry("poneyland")
2090 /// .and_modify(|e| { *e += 1 })
2092 /// assert_eq!(map["poneyland"], 42);
2094 /// map.entry("poneyland")
2095 /// .and_modify(|e| { *e += 1 })
2097 /// assert_eq!(map["poneyland"], 43);
2099 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2100 pub fn and_modify<F>(self, mut f: F) -> Self
2101 where F: FnMut(&mut V)
2104 Occupied(mut entry) => {
2108 Vacant(entry) => Vacant(entry),
2114 impl<'a, K, V: Default> Entry<'a, K, V> {
2115 #[unstable(feature = "entry_or_default", issue = "44324")]
2116 /// Ensures a value is in the entry by inserting the default value if empty,
2117 /// and returns a mutable reference to the value in the entry.
2122 /// #![feature(entry_or_default)]
2124 /// use std::collections::HashMap;
2126 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2127 /// map.entry("poneyland").or_default();
2129 /// assert_eq!(map["poneyland"], None);
2132 pub fn or_default(self) -> &'a mut V {
2134 Occupied(entry) => entry.into_mut(),
2135 Vacant(entry) => entry.insert(Default::default()),
2141 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2142 /// Gets a reference to the key in the entry.
2147 /// use std::collections::HashMap;
2149 /// let mut map: HashMap<&str, u32> = HashMap::new();
2150 /// map.entry("poneyland").or_insert(12);
2151 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2153 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2154 pub fn key(&self) -> &K {
2158 /// Take the ownership of the key and value from the map.
2163 /// use std::collections::HashMap;
2164 /// use std::collections::hash_map::Entry;
2166 /// let mut map: HashMap<&str, u32> = HashMap::new();
2167 /// map.entry("poneyland").or_insert(12);
2169 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2170 /// // We delete the entry from the map.
2171 /// o.remove_entry();
2174 /// assert_eq!(map.contains_key("poneyland"), false);
2176 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2177 pub fn remove_entry(self) -> (K, V) {
2178 let (k, v, _) = pop_internal(self.elem);
2182 /// Gets a reference to the value in the entry.
2187 /// use std::collections::HashMap;
2188 /// use std::collections::hash_map::Entry;
2190 /// let mut map: HashMap<&str, u32> = HashMap::new();
2191 /// map.entry("poneyland").or_insert(12);
2193 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2194 /// assert_eq!(o.get(), &12);
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 pub fn get(&self) -> &V {
2202 /// Gets a mutable reference to the value in the entry.
2207 /// use std::collections::HashMap;
2208 /// use std::collections::hash_map::Entry;
2210 /// let mut map: HashMap<&str, u32> = HashMap::new();
2211 /// map.entry("poneyland").or_insert(12);
2213 /// assert_eq!(map["poneyland"], 12);
2214 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2215 /// *o.get_mut() += 10;
2218 /// assert_eq!(map["poneyland"], 22);
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 pub fn get_mut(&mut self) -> &mut V {
2222 self.elem.read_mut().1
2225 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2226 /// with a lifetime bound to the map itself.
2231 /// use std::collections::HashMap;
2232 /// use std::collections::hash_map::Entry;
2234 /// let mut map: HashMap<&str, u32> = HashMap::new();
2235 /// map.entry("poneyland").or_insert(12);
2237 /// assert_eq!(map["poneyland"], 12);
2238 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2239 /// *o.into_mut() += 10;
2242 /// assert_eq!(map["poneyland"], 22);
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 pub fn into_mut(self) -> &'a mut V {
2246 self.elem.into_mut_refs().1
2249 /// Sets the value of the entry, and returns the entry's old value.
2254 /// use std::collections::HashMap;
2255 /// use std::collections::hash_map::Entry;
2257 /// let mut map: HashMap<&str, u32> = HashMap::new();
2258 /// map.entry("poneyland").or_insert(12);
2260 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2261 /// assert_eq!(o.insert(15), 12);
2264 /// assert_eq!(map["poneyland"], 15);
2266 #[stable(feature = "rust1", since = "1.0.0")]
2267 pub fn insert(&mut self, mut value: V) -> V {
2268 let old_value = self.get_mut();
2269 mem::swap(&mut value, old_value);
2273 /// Takes the value out of the entry, and returns it.
2278 /// use std::collections::HashMap;
2279 /// use std::collections::hash_map::Entry;
2281 /// let mut map: HashMap<&str, u32> = HashMap::new();
2282 /// map.entry("poneyland").or_insert(12);
2284 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2285 /// assert_eq!(o.remove(), 12);
2288 /// assert_eq!(map.contains_key("poneyland"), false);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn remove(self) -> V {
2292 pop_internal(self.elem).1
2295 /// Returns a key that was used for search.
2297 /// The key was retained for further use.
2298 fn take_key(&mut self) -> Option<K> {
2302 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2303 /// the key used to create this entry.
2308 /// #![feature(map_entry_replace)]
2309 /// use std::collections::hash_map::{Entry, HashMap};
2310 /// use std::rc::Rc;
2312 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2313 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2315 /// let my_key = Rc::new("Stringthing".to_string());
2317 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2318 /// // Also replace the key with a handle to our other key.
2319 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2323 #[unstable(feature = "map_entry_replace", issue = "44286")]
2324 pub fn replace_entry(mut self, value: V) -> (K, V) {
2325 let (old_key, old_value) = self.elem.read_mut();
2327 let old_key = mem::replace(old_key, self.key.unwrap());
2328 let old_value = mem::replace(old_value, value);
2330 (old_key, old_value)
2333 /// Replaces the key in the hash map with the key used to create this entry.
2338 /// #![feature(map_entry_replace)]
2339 /// use std::collections::hash_map::{Entry, HashMap};
2340 /// use std::rc::Rc;
2342 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2343 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2345 /// // Initialise known strings, run program, etc.
2347 /// reclaim_memory(&mut map, &known_strings);
2349 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2350 /// for s in known_strings {
2351 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2352 /// // Replaces the entry's key with our version of it in `known_strings`.
2353 /// entry.replace_key();
2358 #[unstable(feature = "map_entry_replace", issue = "44286")]
2359 pub fn replace_key(mut self) -> K {
2360 let (old_key, _) = self.elem.read_mut();
2361 mem::replace(old_key, self.key.unwrap())
2365 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2366 /// Gets a reference to the key that would be used when inserting a value
2367 /// through the `VacantEntry`.
2372 /// use std::collections::HashMap;
2374 /// let mut map: HashMap<&str, u32> = HashMap::new();
2375 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2377 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2378 pub fn key(&self) -> &K {
2382 /// Take ownership of the key.
2387 /// use std::collections::HashMap;
2388 /// use std::collections::hash_map::Entry;
2390 /// let mut map: HashMap<&str, u32> = HashMap::new();
2392 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2396 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2397 pub fn into_key(self) -> K {
2401 /// Sets the value of the entry with the VacantEntry's key,
2402 /// and returns a mutable reference to it.
2407 /// use std::collections::HashMap;
2408 /// use std::collections::hash_map::Entry;
2410 /// let mut map: HashMap<&str, u32> = HashMap::new();
2412 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2415 /// assert_eq!(map["poneyland"], 37);
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 pub fn insert(self, value: V) -> &'a mut V {
2419 let b = match self.elem {
2420 NeqElem(mut bucket, disp) => {
2421 if disp >= DISPLACEMENT_THRESHOLD {
2422 bucket.table_mut().set_tag(true);
2424 robin_hood(bucket, disp, self.hash, self.key, value)
2426 NoElem(mut bucket, disp) => {
2427 if disp >= DISPLACEMENT_THRESHOLD {
2428 bucket.table_mut().set_tag(true);
2430 bucket.put(self.hash, self.key, value)
2436 // Only used for InPlacement insert. Avoid unnecessary value copy.
2437 // The value remains uninitialized.
2438 unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2440 NeqElem(mut bucket, disp) => {
2441 if disp >= DISPLACEMENT_THRESHOLD {
2442 bucket.table_mut().set_tag(true);
2444 let uninit = mem::uninitialized();
2445 robin_hood(bucket, disp, self.hash, self.key, uninit)
2447 NoElem(mut bucket, disp) => {
2448 if disp >= DISPLACEMENT_THRESHOLD {
2449 bucket.table_mut().set_tag(true);
2451 bucket.put_key(self.hash, self.key)
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2460 S: BuildHasher + Default
2462 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2463 let mut map = HashMap::with_hasher(Default::default());
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2474 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2475 // Keys may be already present or show multiple times in the iterator.
2476 // Reserve the entire hint lower bound if the map is empty.
2477 // Otherwise reserve half the hint (rounded up), so the map
2478 // will only resize twice in the worst case.
2479 let iter = iter.into_iter();
2480 let reserve = if self.is_empty() {
2483 (iter.size_hint().0 + 1) / 2
2485 self.reserve(reserve);
2486 for (k, v) in iter {
2492 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2493 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2494 where K: Eq + Hash + Copy,
2498 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2499 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2503 /// `RandomState` is the default state for [`HashMap`] types.
2505 /// A particular instance `RandomState` will create the same instances of
2506 /// [`Hasher`], but the hashers created by two different `RandomState`
2507 /// instances are unlikely to produce the same result for the same values.
2509 /// [`HashMap`]: struct.HashMap.html
2510 /// [`Hasher`]: ../../hash/trait.Hasher.html
2515 /// use std::collections::HashMap;
2516 /// use std::collections::hash_map::RandomState;
2518 /// let s = RandomState::new();
2519 /// let mut map = HashMap::with_hasher(s);
2520 /// map.insert(1, 2);
2523 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2524 pub struct RandomState {
2530 /// Constructs a new `RandomState` that is initialized with random keys.
2535 /// use std::collections::hash_map::RandomState;
2537 /// let s = RandomState::new();
2540 #[allow(deprecated)]
2542 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2543 pub fn new() -> RandomState {
2544 // Historically this function did not cache keys from the OS and instead
2545 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2546 // was discovered, however, that because we re-seed the thread-local RNG
2547 // from the OS periodically that this can cause excessive slowdown when
2548 // many hash maps are created on a thread. To solve this performance
2549 // trap we cache the first set of randomly generated keys per-thread.
2551 // Later in #36481 it was discovered that exposing a deterministic
2552 // iteration order allows a form of DOS attack. To counter that we
2553 // increment one of the seeds on every RandomState creation, giving
2554 // every corresponding HashMap a different iteration order.
2555 thread_local!(static KEYS: Cell<(u64, u64)> = {
2556 Cell::new(sys::hashmap_random_keys())
2560 let (k0, k1) = keys.get();
2561 keys.set((k0.wrapping_add(1), k1));
2562 RandomState { k0: k0, k1: k1 }
2567 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2568 impl BuildHasher for RandomState {
2569 type Hasher = DefaultHasher;
2571 #[allow(deprecated)]
2572 fn build_hasher(&self) -> DefaultHasher {
2573 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2577 /// The default [`Hasher`] used by [`RandomState`].
2579 /// The internal algorithm is not specified, and so it and its hashes should
2580 /// not be relied upon over releases.
2582 /// [`RandomState`]: struct.RandomState.html
2583 /// [`Hasher`]: ../../hash/trait.Hasher.html
2584 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2585 #[allow(deprecated)]
2586 #[derive(Clone, Debug)]
2587 pub struct DefaultHasher(SipHasher13);
2589 impl DefaultHasher {
2590 /// Creates a new `DefaultHasher`.
2592 /// This hasher is not guaranteed to be the same as all other
2593 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2594 /// instances created through `new` or `default`.
2595 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2596 #[allow(deprecated)]
2597 pub fn new() -> DefaultHasher {
2598 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2602 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2603 impl Default for DefaultHasher {
2604 /// Creates a new `DefaultHasher` using [`new`]. See its documentation for more.
2606 /// [`new`]: #method.new
2607 fn default() -> DefaultHasher {
2608 DefaultHasher::new()
2612 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2613 impl Hasher for DefaultHasher {
2615 fn write(&mut self, msg: &[u8]) {
2620 fn finish(&self) -> u64 {
2625 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2626 impl Default for RandomState {
2627 /// Constructs a new `RandomState`.
2629 fn default() -> RandomState {
2634 #[stable(feature = "std_debug", since = "1.16.0")]
2635 impl fmt::Debug for RandomState {
2636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2637 f.pad("RandomState { .. }")
2641 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2642 where K: Eq + Hash + Borrow<Q>,
2649 fn get(&self, key: &Q) -> Option<&K> {
2650 self.search(key).map(|bucket| bucket.into_refs().0)
2653 fn take(&mut self, key: &Q) -> Option<K> {
2654 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
2658 fn replace(&mut self, key: K) -> Option<K> {
2661 match self.entry(key) {
2662 Occupied(mut occupied) => {
2663 let key = occupied.take_key().unwrap();
2664 Some(mem::replace(occupied.elem.read_mut().0, key))
2675 fn assert_covariance() {
2676 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2679 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2682 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2685 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2688 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2691 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2694 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2697 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2700 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2703 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2706 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2707 -> Drain<'new, &'new str, &'new str> {
2715 use super::Entry::{Occupied, Vacant};
2716 use super::RandomState;
2718 use rand::{thread_rng, Rng};
2722 fn test_zero_capacities() {
2723 type HM = HashMap<i32, i32>;
2726 assert_eq!(m.capacity(), 0);
2728 let m = HM::default();
2729 assert_eq!(m.capacity(), 0);
2731 let m = HM::with_hasher(RandomState::new());
2732 assert_eq!(m.capacity(), 0);
2734 let m = HM::with_capacity(0);
2735 assert_eq!(m.capacity(), 0);
2737 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2738 assert_eq!(m.capacity(), 0);
2740 let mut m = HM::new();
2746 assert_eq!(m.capacity(), 0);
2748 let mut m = HM::new();
2750 assert_eq!(m.capacity(), 0);
2754 fn test_create_capacity_zero() {
2755 let mut m = HashMap::with_capacity(0);
2757 assert!(m.insert(1, 1).is_none());
2759 assert!(m.contains_key(&1));
2760 assert!(!m.contains_key(&0));
2765 let mut m = HashMap::new();
2766 assert_eq!(m.len(), 0);
2767 assert!(m.insert(1, 2).is_none());
2768 assert_eq!(m.len(), 1);
2769 assert!(m.insert(2, 4).is_none());
2770 assert_eq!(m.len(), 2);
2771 assert_eq!(*m.get(&1).unwrap(), 2);
2772 assert_eq!(*m.get(&2).unwrap(), 4);
2777 let mut m = HashMap::new();
2778 assert_eq!(m.len(), 0);
2779 assert!(m.insert(1, 2).is_none());
2780 assert_eq!(m.len(), 1);
2781 assert!(m.insert(2, 4).is_none());
2782 assert_eq!(m.len(), 2);
2784 assert_eq!(*m2.get(&1).unwrap(), 2);
2785 assert_eq!(*m2.get(&2).unwrap(), 4);
2786 assert_eq!(m2.len(), 2);
2789 thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2791 #[derive(Hash, PartialEq, Eq)]
2797 fn new(k: usize) -> Dropable {
2798 DROP_VECTOR.with(|slot| {
2799 slot.borrow_mut()[k] += 1;
2806 impl Drop for Dropable {
2807 fn drop(&mut self) {
2808 DROP_VECTOR.with(|slot| {
2809 slot.borrow_mut()[self.k] -= 1;
2814 impl Clone for Dropable {
2815 fn clone(&self) -> Dropable {
2816 Dropable::new(self.k)
2822 DROP_VECTOR.with(|slot| {
2823 *slot.borrow_mut() = vec![0; 200];
2827 let mut m = HashMap::new();
2829 DROP_VECTOR.with(|v| {
2831 assert_eq!(v.borrow()[i], 0);
2836 let d1 = Dropable::new(i);
2837 let d2 = Dropable::new(i + 100);
2841 DROP_VECTOR.with(|v| {
2843 assert_eq!(v.borrow()[i], 1);
2848 let k = Dropable::new(i);
2849 let v = m.remove(&k);
2851 assert!(v.is_some());
2853 DROP_VECTOR.with(|v| {
2854 assert_eq!(v.borrow()[i], 1);
2855 assert_eq!(v.borrow()[i+100], 1);
2859 DROP_VECTOR.with(|v| {
2861 assert_eq!(v.borrow()[i], 0);
2862 assert_eq!(v.borrow()[i+100], 0);
2866 assert_eq!(v.borrow()[i], 1);
2867 assert_eq!(v.borrow()[i+100], 1);
2872 DROP_VECTOR.with(|v| {
2874 assert_eq!(v.borrow()[i], 0);
2880 fn test_into_iter_drops() {
2881 DROP_VECTOR.with(|v| {
2882 *v.borrow_mut() = vec![0; 200];
2886 let mut hm = HashMap::new();
2888 DROP_VECTOR.with(|v| {
2890 assert_eq!(v.borrow()[i], 0);
2895 let d1 = Dropable::new(i);
2896 let d2 = Dropable::new(i + 100);
2900 DROP_VECTOR.with(|v| {
2902 assert_eq!(v.borrow()[i], 1);
2909 // By the way, ensure that cloning doesn't screw up the dropping.
2913 let mut half = hm.into_iter().take(50);
2915 DROP_VECTOR.with(|v| {
2917 assert_eq!(v.borrow()[i], 1);
2921 for _ in half.by_ref() {}
2923 DROP_VECTOR.with(|v| {
2925 .filter(|&i| v.borrow()[i] == 1)
2929 .filter(|&i| v.borrow()[i + 100] == 1)
2937 DROP_VECTOR.with(|v| {
2939 assert_eq!(v.borrow()[i], 0);
2945 fn test_empty_remove() {
2946 let mut m: HashMap<isize, bool> = HashMap::new();
2947 assert_eq!(m.remove(&0), None);
2951 fn test_empty_entry() {
2952 let mut m: HashMap<isize, bool> = HashMap::new();
2954 Occupied(_) => panic!(),
2957 assert!(*m.entry(0).or_insert(true));
2958 assert_eq!(m.len(), 1);
2962 fn test_empty_iter() {
2963 let mut m: HashMap<isize, bool> = HashMap::new();
2964 assert_eq!(m.drain().next(), None);
2965 assert_eq!(m.keys().next(), None);
2966 assert_eq!(m.values().next(), None);
2967 assert_eq!(m.values_mut().next(), None);
2968 assert_eq!(m.iter().next(), None);
2969 assert_eq!(m.iter_mut().next(), None);
2970 assert_eq!(m.len(), 0);
2971 assert!(m.is_empty());
2972 assert_eq!(m.into_iter().next(), None);
2976 fn test_lots_of_insertions() {
2977 let mut m = HashMap::new();
2979 // Try this a few times to make sure we never screw up the hashmap's
2982 assert!(m.is_empty());
2985 assert!(m.insert(i, i).is_none());
2989 assert_eq!(r, Some(&j));
2992 for j in i + 1..1001 {
2994 assert_eq!(r, None);
2998 for i in 1001..2001 {
2999 assert!(!m.contains_key(&i));
3004 assert!(m.remove(&i).is_some());
3007 assert!(!m.contains_key(&j));
3010 for j in i + 1..1001 {
3011 assert!(m.contains_key(&j));
3016 assert!(!m.contains_key(&i));
3020 assert!(m.insert(i, i).is_none());
3024 for i in (1..1001).rev() {
3025 assert!(m.remove(&i).is_some());
3028 assert!(!m.contains_key(&j));
3032 assert!(m.contains_key(&j));
3039 fn test_find_mut() {
3040 let mut m = HashMap::new();
3041 assert!(m.insert(1, 12).is_none());
3042 assert!(m.insert(2, 8).is_none());
3043 assert!(m.insert(5, 14).is_none());
3045 match m.get_mut(&5) {
3047 Some(x) => *x = new,
3049 assert_eq!(m.get(&5), Some(&new));
3053 fn test_insert_overwrite() {
3054 let mut m = HashMap::new();
3055 assert!(m.insert(1, 2).is_none());
3056 assert_eq!(*m.get(&1).unwrap(), 2);
3057 assert!(!m.insert(1, 3).is_none());
3058 assert_eq!(*m.get(&1).unwrap(), 3);
3062 fn test_insert_conflicts() {
3063 let mut m = HashMap::with_capacity(4);
3064 assert!(m.insert(1, 2).is_none());
3065 assert!(m.insert(5, 3).is_none());
3066 assert!(m.insert(9, 4).is_none());
3067 assert_eq!(*m.get(&9).unwrap(), 4);
3068 assert_eq!(*m.get(&5).unwrap(), 3);
3069 assert_eq!(*m.get(&1).unwrap(), 2);
3073 fn test_conflict_remove() {
3074 let mut m = HashMap::with_capacity(4);
3075 assert!(m.insert(1, 2).is_none());
3076 assert_eq!(*m.get(&1).unwrap(), 2);
3077 assert!(m.insert(5, 3).is_none());
3078 assert_eq!(*m.get(&1).unwrap(), 2);
3079 assert_eq!(*m.get(&5).unwrap(), 3);
3080 assert!(m.insert(9, 4).is_none());
3081 assert_eq!(*m.get(&1).unwrap(), 2);
3082 assert_eq!(*m.get(&5).unwrap(), 3);
3083 assert_eq!(*m.get(&9).unwrap(), 4);
3084 assert!(m.remove(&1).is_some());
3085 assert_eq!(*m.get(&9).unwrap(), 4);
3086 assert_eq!(*m.get(&5).unwrap(), 3);
3090 fn test_is_empty() {
3091 let mut m = HashMap::with_capacity(4);
3092 assert!(m.insert(1, 2).is_none());
3093 assert!(!m.is_empty());
3094 assert!(m.remove(&1).is_some());
3095 assert!(m.is_empty());
3100 let mut m = HashMap::new();
3102 assert_eq!(m.remove(&1), Some(2));
3103 assert_eq!(m.remove(&1), None);
3107 fn test_remove_entry() {
3108 let mut m = HashMap::new();
3110 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3111 assert_eq!(m.remove(&1), None);
3116 let mut m = HashMap::with_capacity(4);
3118 assert!(m.insert(i, i*2).is_none());
3120 assert_eq!(m.len(), 32);
3122 let mut observed: u32 = 0;
3125 assert_eq!(*v, *k * 2);
3126 observed |= 1 << *k;
3128 assert_eq!(observed, 0xFFFF_FFFF);
3133 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3134 let map: HashMap<_, _> = vec.into_iter().collect();
3135 let keys: Vec<_> = map.keys().cloned().collect();
3136 assert_eq!(keys.len(), 3);
3137 assert!(keys.contains(&1));
3138 assert!(keys.contains(&2));
3139 assert!(keys.contains(&3));
3144 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3145 let map: HashMap<_, _> = vec.into_iter().collect();
3146 let values: Vec<_> = map.values().cloned().collect();
3147 assert_eq!(values.len(), 3);
3148 assert!(values.contains(&'a'));
3149 assert!(values.contains(&'b'));
3150 assert!(values.contains(&'c'));
3154 fn test_values_mut() {
3155 let vec = vec![(1, 1), (2, 2), (3, 3)];
3156 let mut map: HashMap<_, _> = vec.into_iter().collect();
3157 for value in map.values_mut() {
3158 *value = (*value) * 2
3160 let values: Vec<_> = map.values().cloned().collect();
3161 assert_eq!(values.len(), 3);
3162 assert!(values.contains(&2));
3163 assert!(values.contains(&4));
3164 assert!(values.contains(&6));
3169 let mut m = HashMap::new();
3170 assert!(m.get(&1).is_none());
3174 Some(v) => assert_eq!(*v, 2),
3180 let mut m1 = HashMap::new();
3185 let mut m2 = HashMap::new();
3198 let mut map = HashMap::new();
3199 let empty: HashMap<i32, i32> = HashMap::new();
3204 let map_str = format!("{:?}", map);
3206 assert!(map_str == "{1: 2, 3: 4}" ||
3207 map_str == "{3: 4, 1: 2}");
3208 assert_eq!(format!("{:?}", empty), "{}");
3213 let mut m = HashMap::new();
3215 assert_eq!(m.len(), 0);
3216 assert!(m.is_empty());
3219 let old_raw_cap = m.raw_capacity();
3220 while old_raw_cap == m.raw_capacity() {
3225 assert_eq!(m.len(), i);
3226 assert!(!m.is_empty());
3230 fn test_behavior_resize_policy() {
3231 let mut m = HashMap::new();
3233 assert_eq!(m.len(), 0);
3234 assert_eq!(m.raw_capacity(), 0);
3235 assert!(m.is_empty());
3239 assert!(m.is_empty());
3240 let initial_raw_cap = m.raw_capacity();
3241 m.reserve(initial_raw_cap);
3242 let raw_cap = m.raw_capacity();
3244 assert_eq!(raw_cap, initial_raw_cap * 2);
3247 for _ in 0..raw_cap * 3 / 4 {
3251 // three quarters full
3253 assert_eq!(m.len(), i);
3254 assert_eq!(m.raw_capacity(), raw_cap);
3256 for _ in 0..raw_cap / 4 {
3262 let new_raw_cap = m.raw_capacity();
3263 assert_eq!(new_raw_cap, raw_cap * 2);
3265 for _ in 0..raw_cap / 2 - 1 {
3268 assert_eq!(m.raw_capacity(), new_raw_cap);
3270 // A little more than one quarter full.
3272 assert_eq!(m.raw_capacity(), raw_cap);
3273 // again, a little more than half full
3274 for _ in 0..raw_cap / 2 - 1 {
3280 assert_eq!(m.len(), i);
3281 assert!(!m.is_empty());
3282 assert_eq!(m.raw_capacity(), initial_raw_cap);
3286 fn test_reserve_shrink_to_fit() {
3287 let mut m = HashMap::new();
3290 assert!(m.capacity() >= m.len());
3296 let usable_cap = m.capacity();
3297 for i in 128..(128 + 256) {
3299 assert_eq!(m.capacity(), usable_cap);
3302 for i in 100..(128 + 256) {
3303 assert_eq!(m.remove(&i), Some(i));
3307 assert_eq!(m.len(), 100);
3308 assert!(!m.is_empty());
3309 assert!(m.capacity() >= m.len());
3312 assert_eq!(m.remove(&i), Some(i));
3317 assert_eq!(m.len(), 1);
3318 assert!(m.capacity() >= m.len());
3319 assert_eq!(m.remove(&0), Some(0));
3323 fn test_from_iter() {
3324 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3326 let map: HashMap<_, _> = xs.iter().cloned().collect();
3328 for &(k, v) in &xs {
3329 assert_eq!(map.get(&k), Some(&v));
3334 fn test_size_hint() {
3335 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3337 let map: HashMap<_, _> = xs.iter().cloned().collect();
3339 let mut iter = map.iter();
3341 for _ in iter.by_ref().take(3) {}
3343 assert_eq!(iter.size_hint(), (3, Some(3)));
3347 fn test_iter_len() {
3348 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3350 let map: HashMap<_, _> = xs.iter().cloned().collect();
3352 let mut iter = map.iter();
3354 for _ in iter.by_ref().take(3) {}
3356 assert_eq!(iter.len(), 3);
3360 fn test_mut_size_hint() {
3361 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3363 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3365 let mut iter = map.iter_mut();
3367 for _ in iter.by_ref().take(3) {}
3369 assert_eq!(iter.size_hint(), (3, Some(3)));
3373 fn test_iter_mut_len() {
3374 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3376 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3378 let mut iter = map.iter_mut();
3380 for _ in iter.by_ref().take(3) {}
3382 assert_eq!(iter.len(), 3);
3387 let mut map = HashMap::new();
3393 assert_eq!(map[&2], 1);
3398 fn test_index_nonexistent() {
3399 let mut map = HashMap::new();
3410 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3412 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3414 // Existing key (insert)
3415 match map.entry(1) {
3416 Vacant(_) => unreachable!(),
3417 Occupied(mut view) => {
3418 assert_eq!(view.get(), &10);
3419 assert_eq!(view.insert(100), 10);
3422 assert_eq!(map.get(&1).unwrap(), &100);
3423 assert_eq!(map.len(), 6);
3426 // Existing key (update)
3427 match map.entry(2) {
3428 Vacant(_) => unreachable!(),
3429 Occupied(mut view) => {
3430 let v = view.get_mut();
3431 let new_v = (*v) * 10;
3435 assert_eq!(map.get(&2).unwrap(), &200);
3436 assert_eq!(map.len(), 6);
3438 // Existing key (take)
3439 match map.entry(3) {
3440 Vacant(_) => unreachable!(),
3442 assert_eq!(view.remove(), 30);
3445 assert_eq!(map.get(&3), None);
3446 assert_eq!(map.len(), 5);
3449 // Inexistent key (insert)
3450 match map.entry(10) {
3451 Occupied(_) => unreachable!(),
3453 assert_eq!(*view.insert(1000), 1000);
3456 assert_eq!(map.get(&10).unwrap(), &1000);
3457 assert_eq!(map.len(), 6);
3461 fn test_entry_take_doesnt_corrupt() {
3462 #![allow(deprecated)] //rand
3464 fn check(m: &HashMap<isize, ()>) {
3466 assert!(m.contains_key(k),
3467 "{} is in keys() but not in the map?", k);
3471 let mut m = HashMap::new();
3472 let mut rng = thread_rng();
3474 // Populate the map with some items.
3476 let x = rng.gen_range(-10, 10);
3481 let x = rng.gen_range(-10, 10);
3485 println!("{}: remove {}", i, x);
3495 fn test_extend_ref() {
3496 let mut a = HashMap::new();
3498 let mut b = HashMap::new();
3500 b.insert(3, "three");
3504 assert_eq!(a.len(), 3);
3505 assert_eq!(a[&1], "one");
3506 assert_eq!(a[&2], "two");
3507 assert_eq!(a[&3], "three");
3511 fn test_capacity_not_less_than_len() {
3512 let mut a = HashMap::new();
3520 assert!(a.capacity() > a.len());
3522 let free = a.capacity() - a.len();
3528 assert_eq!(a.len(), a.capacity());
3530 // Insert at capacity should cause allocation.
3532 assert!(a.capacity() > a.len());
3536 fn test_occupied_entry_key() {
3537 let mut a = HashMap::new();
3538 let key = "hello there";
3539 let value = "value goes here";
3540 assert!(a.is_empty());
3541 a.insert(key.clone(), value.clone());
3542 assert_eq!(a.len(), 1);
3543 assert_eq!(a[key], value);
3545 match a.entry(key.clone()) {
3546 Vacant(_) => panic!(),
3547 Occupied(e) => assert_eq!(key, *e.key()),
3549 assert_eq!(a.len(), 1);
3550 assert_eq!(a[key], value);
3554 fn test_vacant_entry_key() {
3555 let mut a = HashMap::new();
3556 let key = "hello there";
3557 let value = "value goes here";
3559 assert!(a.is_empty());
3560 match a.entry(key.clone()) {
3561 Occupied(_) => panic!(),
3563 assert_eq!(key, *e.key());
3564 e.insert(value.clone());
3567 assert_eq!(a.len(), 1);
3568 assert_eq!(a[key], value);
3573 let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3575 map.retain(|&k, _| k % 2 == 0);
3576 assert_eq!(map.len(), 50);
3577 assert_eq!(map[&2], 20);
3578 assert_eq!(map[&4], 40);
3579 assert_eq!(map[&6], 60);
3583 fn test_adaptive() {
3584 const TEST_LEN: usize = 5000;
3585 // by cloning we get maps with the same hasher seed
3586 let mut first = HashMap::new();
3587 let mut second = first.clone();
3588 first.extend((0..TEST_LEN).map(|i| (i, i)));
3589 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3591 for (&k, &v) in &second {
3592 let prev_cap = first.capacity();
3593 let expect_grow = first.len() == prev_cap;
3595 if !expect_grow && first.capacity() != prev_cap {
3599 panic!("Adaptive early resize failed");
3603 fn test_placement_in() {
3604 let mut map = HashMap::new();
3605 map.extend((0..10).map(|i| (i, i)));
3607 map.entry(100) <- 100;
3608 assert_eq!(map[&100], 100);
3611 assert_eq!(map[&0], 10);
3613 assert_eq!(map.len(), 11);
3617 fn test_placement_panic() {
3618 let mut map = HashMap::new();
3619 map.extend((0..10).map(|i| (i, i)));
3621 fn mkpanic() -> usize { panic!() }
3623 // modify existing key
3624 // when panic happens, previous key is removed.
3625 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3626 assert_eq!(map.len(), 9);
3627 assert!(!map.contains_key(&0));
3630 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3631 assert_eq!(map.len(), 9);
3632 assert!(!map.contains_key(&100));
3636 fn test_placement_drop() {
3638 struct TestV<'a>(&'a mut bool);
3639 impl<'a> Drop for TestV<'a> {
3640 fn drop(&mut self) {
3641 if !*self.0 { panic!("value double drop!"); } // no double drop
3646 fn makepanic<'a>() -> TestV<'a> { panic!() }
3648 let mut can_drop = true;
3649 let mut hm = HashMap::new();
3650 hm.insert(0, TestV(&mut can_drop));
3651 let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3652 assert_eq!(hm.len(), 0);