2 use self::VacantEntryState
::*;
4 use intrinsics
::unlikely
;
5 use collections
::CollectionAllocErr
;
9 use fmt
::{self, Debug}
;
11 use hash
::{Hash, Hasher, BuildHasher, SipHasher13}
;
12 use iter
::{FromIterator, FusedIterator}
;
13 use mem
::{self, replace}
;
14 use ops
::{Deref, DerefMut, Index}
;
17 use super::table
::{self, Bucket
, EmptyBucket
, Fallibility
, FullBucket
, FullBucketMut
, RawTable
,
19 use super::table
::BucketState
::{Empty, Full}
;
20 use super::table
::Fallibility
::{Fallible, Infallible}
;
22 const MIN_NONZERO_RAW_CAPACITY
: usize = 32; // must be a power of two
24 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
26 struct DefaultResizePolicy
;
28 impl DefaultResizePolicy
{
30 fn new() -> DefaultResizePolicy
{
34 /// A hash map's "capacity" is the number of elements it can hold without
35 /// being resized. Its "raw capacity" is the number of slots required to
36 /// provide that capacity, accounting for maximum loading. The raw capacity
37 /// is always zero or a power of two.
39 fn try_raw_capacity(&self, len
: usize) -> Result
<usize, CollectionAllocErr
> {
43 // 1. Account for loading: `raw_capacity >= len * 1.1`.
44 // 2. Ensure it is a power of two.
45 // 3. Ensure it is at least the minimum size.
46 let mut raw_cap
= len
.checked_mul(11)
48 .and_then(|l
| l
.checked_next_power_of_two())
49 .ok_or(CollectionAllocErr
::CapacityOverflow
)?
;
51 raw_cap
= max(MIN_NONZERO_RAW_CAPACITY
, raw_cap
);
57 fn raw_capacity(&self, len
: usize) -> usize {
58 self.try_raw_capacity(len
).expect("raw_capacity overflow")
61 /// The capacity of the given raw capacity.
63 fn capacity(&self, raw_cap
: usize) -> usize {
64 // This doesn't have to be checked for overflow since allocation size
65 // in bytes will overflow earlier than multiplication by 10.
67 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
68 // to be: (raw_cap * den + den - 1) / num
69 (raw_cap
* 10 + 10 - 1) / 11
73 // The main performance trick in this hashmap is called Robin Hood Hashing.
74 // It gains its excellent performance from one essential operation:
76 // If an insertion collides with an existing element, and that element's
77 // "probe distance" (how far away the element is from its ideal location)
78 // is higher than how far we've already probed, swap the elements.
80 // This massively lowers variance in probe distance, and allows us to get very
81 // high load factors with good performance. The 90% load factor I use is rather
84 // > Why a load factor of approximately 90%?
86 // In general, all the distances to initial buckets will converge on the mean.
87 // At a load factor of α, the odds of finding the target bucket after k
88 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
89 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
90 // this down to make the math easier on the CPU and avoid its FPU.
91 // Since on average we start the probing in the middle of a cache line, this
92 // strategy pulls in two cache lines of hashes on every lookup. I think that's
93 // pretty good, but if you want to trade off some space, it could go down to one
94 // cache line on average with an α of 0.84.
96 // > Wait, what? Where did you get 1-α^k from?
98 // On the first probe, your odds of a collision with an existing element is α.
99 // The odds of doing this twice in a row is approximately α^2. For three times,
100 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
101 // colliding after k tries is 1-α^k.
103 // The paper from 1986 cited below mentions an implementation which keeps track
104 // of the distance-to-initial-bucket histogram. This approach is not suitable
105 // for modern architectures because it requires maintaining an internal data
106 // structure. This allows very good first guesses, but we are most concerned
107 // with guessing entire cache lines, not individual indexes. Furthermore, array
108 // accesses are no longer linear and in one direction, as we have now. There
109 // is also memory and cache pressure that this would entail that would be very
110 // difficult to properly see in a microbenchmark.
112 // ## Future Improvements (FIXME!)
114 // Allow the load factor to be changed dynamically and/or at initialization.
116 // Also, would it be possible for us to reuse storage when growing the
117 // underlying table? This is exactly the use case for 'realloc', and may
118 // be worth exploring.
120 // ## Future Optimizations (FIXME!)
122 // Another possible design choice that I made without any real reason is
123 // parameterizing the raw table over keys and values. Technically, all we need
124 // is the size and alignment of keys and values, and the code should be just as
125 // efficient (well, we might need one for power-of-two size and one for not...).
126 // This has the potential to reduce code bloat in rust executables, without
127 // really losing anything except 4 words (key size, key alignment, val size,
128 // val alignment) which can be passed in to every call of a `RawTable` function.
129 // This would definitely be an avenue worth exploring if people start complaining
130 // about the size of rust executables.
132 // Annotate exceedingly likely branches in `table::make_hash`
133 // and `search_hashed` to reduce instruction cache pressure
134 // and mispredictions once it becomes possible (blocked on issue #11092).
136 // Shrinking the table could simply reallocate in place after moving buckets
137 // to the first half.
139 // The growth algorithm (fragment of the Proof of Correctness)
140 // --------------------
142 // The growth algorithm is basically a fast path of the naive reinsertion-
143 // during-resize algorithm. Other paths should never be taken.
145 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
146 // by allocating a new table of capacity `2n`, and then individually reinsert
147 // each element in the old table into the new one. This guarantees that the
148 // new table is a valid robin hood hashtable with all the desired statistical
149 // properties. Remark that the order we reinsert the elements in should not
150 // matter. For simplicity and efficiency, we will consider only linear
151 // reinsertions, which consist of reinserting all elements in the old table
152 // into the new one by increasing order of index. However we will not be
153 // starting our reinsertions from index 0 in general. If we start from index
154 // i, for the purpose of reinsertion we will consider all elements with real
155 // index j < i to have virtual index n + j.
157 // Our hash generation scheme consists of generating a 64-bit hash and
158 // truncating the most significant bits. When moving to the new table, we
159 // simply introduce a new bit to the front of the hash. Therefore, if an
160 // element has ideal index i in the old table, it can have one of two ideal
161 // locations in the new table. If the new bit is 0, then the new ideal index
162 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
163 // we are producing two independent tables of size n, and for each element we
164 // independently choose which table to insert it into with equal probability.
165 // However, rather than wrapping around themselves on overflowing their
166 // indexes, the first table overflows into the second, and the second into the
167 // first. Visually, our new table will look something like:
169 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
171 // Where x's are elements inserted into the first table, y's are elements
172 // inserted into the second, and _'s are empty sections. We now define a few
173 // key concepts that we will use later. Note that this is a very abstract
174 // perspective of the table. A real resized table would be at least half
177 // Theorem: A linear robin hood reinsertion from the first ideal element
178 // produces identical results to a linear naive reinsertion from the same
181 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
183 // Adaptive early resizing
184 // ----------------------
185 // To protect against degenerate performance scenarios (including DOS attacks),
186 // the implementation includes an adaptive behavior that can resize the map
187 // early (before its capacity is exceeded) when suspiciously long probe sequences
190 // With this algorithm in place it would be possible to turn a CPU attack into
191 // a memory attack due to the aggressive resizing. To prevent that the
192 // adaptive behavior only triggers when the map is at least half full.
193 // This reduces the effectiveness of the algorithm but also makes it completely safe.
195 // The previous safety measure also prevents degenerate interactions with
196 // really bad quality hash algorithms that can make normal inputs look like a
199 const DISPLACEMENT_THRESHOLD
: usize = 128;
201 // The threshold of 128 is chosen to minimize the chance of exceeding it.
202 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
203 // For displacement, the smallest constant that fits our needs is 90,
204 // so we round that up to 128.
206 // At a load factor of α, the odds of finding the target bucket after exactly n
207 // unsuccessful probes[1] are
209 // Pr_α{displacement = n} =
210 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
212 // We use this formula to find the probability of triggering the adaptive behavior
214 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
216 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
217 // hashing with buckets.
219 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
221 /// By default, `HashMap` uses a hashing algorithm selected to provide
222 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
223 /// reasonable best-effort is made to generate this seed from a high quality,
224 /// secure source of randomness provided by the host without blocking the
225 /// program. Because of this, the randomness of the seed depends on the output
226 /// quality of the system's random number generator when the seed is created.
227 /// In particular, seeds generated when the system's entropy pool is abnormally
228 /// low such as during system boot may be of a lower quality.
230 /// The default hashing algorithm is currently SipHash 1-3, though this is
231 /// subject to change at any point in the future. While its performance is very
232 /// competitive for medium sized keys, other hashing algorithms will outperform
233 /// it for small keys such as integers as well as large keys such as long
234 /// strings, though those algorithms will typically *not* protect against
235 /// attacks such as HashDoS.
237 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
238 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
239 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
241 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
242 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
243 /// If you implement these yourself, it is important that the following
247 /// k1 == k2 -> hash(k1) == hash(k2)
250 /// In other words, if two keys are equal, their hashes must be equal.
252 /// It is a logic error for a key to be modified in such a way that the key's
253 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
254 /// the [`Eq`] trait, changes while it is in the map. This is normally only
255 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
257 /// Relevant papers/articles:
259 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
260 /// 2. Emmanuel Goossaert. ["Robin Hood
261 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
262 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
263 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
268 /// use std::collections::HashMap;
270 /// // Type inference lets us omit an explicit type signature (which
271 /// // would be `HashMap<String, String>` in this example).
272 /// let mut book_reviews = HashMap::new();
274 /// // Review some books.
275 /// book_reviews.insert(
276 /// "Adventures of Huckleberry Finn".to_string(),
277 /// "My favorite book.".to_string(),
279 /// book_reviews.insert(
280 /// "Grimms' Fairy Tales".to_string(),
281 /// "Masterpiece.".to_string(),
283 /// book_reviews.insert(
284 /// "Pride and Prejudice".to_string(),
285 /// "Very enjoyable.".to_string(),
287 /// book_reviews.insert(
288 /// "The Adventures of Sherlock Holmes".to_string(),
289 /// "Eye lyked it alot.".to_string(),
292 /// // Check for a specific one.
293 /// // When collections store owned values (String), they can still be
294 /// // queried using references (&str).
295 /// if !book_reviews.contains_key("Les Misérables") {
296 /// println!("We've got {} reviews, but Les Misérables ain't one.",
297 /// book_reviews.len());
300 /// // oops, this review has a lot of spelling mistakes, let's delete it.
301 /// book_reviews.remove("The Adventures of Sherlock Holmes");
303 /// // Look up the values associated with some keys.
304 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
305 /// for &book in &to_find {
306 /// match book_reviews.get(book) {
307 /// Some(review) => println!("{}: {}", book, review),
308 /// None => println!("{} is unreviewed.", book)
312 /// // Look up the value for a key (will panic if the key is not found).
313 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
315 /// // Iterate over everything.
316 /// for (book, review) in &book_reviews {
317 /// println!("{}: \"{}\"", book, review);
321 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
322 /// for more complex methods of getting, setting, updating and removing keys and
326 /// use std::collections::HashMap;
328 /// // type inference lets us omit an explicit type signature (which
329 /// // would be `HashMap<&str, u8>` in this example).
330 /// let mut player_stats = HashMap::new();
332 /// fn random_stat_buff() -> u8 {
333 /// // could actually return some random value here - let's just return
334 /// // some fixed value for now
338 /// // insert a key only if it doesn't already exist
339 /// player_stats.entry("health").or_insert(100);
341 /// // insert a key using a function that provides a new value only if it
342 /// // doesn't already exist
343 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
345 /// // update a key, guarding against the key possibly not being set
346 /// let stat = player_stats.entry("attack").or_insert(100);
347 /// *stat += random_stat_buff();
350 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
351 /// We must also derive [`PartialEq`].
353 /// [`Eq`]: ../../std/cmp/trait.Eq.html
354 /// [`Hash`]: ../../std/hash/trait.Hash.html
355 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
356 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
357 /// [`Cell`]: ../../std/cell/struct.Cell.html
358 /// [`default`]: #method.default
359 /// [`with_hasher`]: #method.with_hasher
360 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
361 /// [`fnv`]: https://crates.io/crates/fnv
364 /// use std::collections::HashMap;
366 /// #[derive(Hash, Eq, PartialEq, Debug)]
373 /// /// Creates a new Viking.
374 /// fn new(name: &str, country: &str) -> Viking {
375 /// Viking { name: name.to_string(), country: country.to_string() }
379 /// // Use a HashMap to store the vikings' health points.
380 /// let mut vikings = HashMap::new();
382 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
383 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
384 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
386 /// // Use derived implementation to print the status of the vikings.
387 /// for (viking, health) in &vikings {
388 /// println!("{:?} has {} hp", viking, health);
392 /// A `HashMap` with fixed list of elements can be initialized from an array:
395 /// use std::collections::HashMap;
398 /// let timber_resources: HashMap<&str, i32> =
399 /// [("Norway", 100),
402 /// .iter().cloned().collect();
403 /// // use the values stored in map
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub struct HashMap
<K
, V
, S
= RandomState
> {
410 // All hashes are keyed on these values, to prevent hash collision attacks.
413 table
: RawTable
<K
, V
>,
415 resize_policy
: DefaultResizePolicy
,
418 /// Search for a pre-hashed key.
419 /// If you don't already know the hash, use search or search_mut instead
421 fn search_hashed
<K
, V
, M
, F
>(table
: M
, hash
: SafeHash
, is_match
: F
) -> InternalEntry
<K
, V
, M
>
422 where M
: Deref
<Target
= RawTable
<K
, V
>>,
425 // This is the only function where capacity can be zero. To avoid
426 // undefined behavior when Bucket::new gets the raw bucket in this
427 // case, immediately return the appropriate search result.
428 if table
.capacity() == 0 {
429 return InternalEntry
::TableIsEmpty
;
432 search_hashed_nonempty(table
, hash
, is_match
, true)
435 /// Search for a pre-hashed key when the hash map is known to be non-empty.
437 fn search_hashed_nonempty
<K
, V
, M
, F
>(table
: M
, hash
: SafeHash
, mut is_match
: F
,
438 compare_hashes
: bool
)
439 -> InternalEntry
<K
, V
, M
>
440 where M
: Deref
<Target
= RawTable
<K
, V
>>,
443 // Do not check the capacity as an extra branch could slow the lookup.
445 let size
= table
.size();
446 let mut probe
= Bucket
::new(table
, hash
);
447 let mut displacement
= 0;
450 let full
= match probe
.peek() {
453 return InternalEntry
::Vacant
{
455 elem
: NoElem(bucket
, displacement
),
458 Full(bucket
) => bucket
,
461 let probe_displacement
= full
.displacement();
463 if probe_displacement
< displacement
{
464 // Found a luckier bucket than me.
465 // We can finish the search early if we hit any bucket
466 // with a lower distance to initial bucket than we've probed.
467 return InternalEntry
::Vacant
{
469 elem
: NeqElem(full
, probe_displacement
),
473 // If the hash doesn't match, it can't be this one..
474 if !compare_hashes
|| hash
== full
.hash() {
475 // If the key doesn't match, it can't be this one..
476 if is_match(full
.read().0) {
477 return InternalEntry
::Occupied { elem: full }
;
482 debug_assert
!(displacement
<= size
);
486 /// Same as `search_hashed_nonempty` but for mutable access.
488 fn search_hashed_nonempty_mut
<K
, V
, M
, F
>(table
: M
, hash
: SafeHash
, mut is_match
: F
,
489 compare_hashes
: bool
)
490 -> InternalEntry
<K
, V
, M
>
491 where M
: DerefMut
<Target
= RawTable
<K
, V
>>,
494 // Do not check the capacity as an extra branch could slow the lookup.
496 let size
= table
.size();
497 let mut probe
= Bucket
::new(table
, hash
);
498 let mut displacement
= 0;
501 let mut full
= match probe
.peek() {
504 return InternalEntry
::Vacant
{
506 elem
: NoElem(bucket
, displacement
),
509 Full(bucket
) => bucket
,
512 let probe_displacement
= full
.displacement();
514 if probe_displacement
< displacement
{
515 // Found a luckier bucket than me.
516 // We can finish the search early if we hit any bucket
517 // with a lower distance to initial bucket than we've probed.
518 return InternalEntry
::Vacant
{
520 elem
: NeqElem(full
, probe_displacement
),
524 // If the hash doesn't match, it can't be this one..
525 if hash
== full
.hash() || !compare_hashes
{
526 // If the key doesn't match, it can't be this one..
527 if is_match(full
.read_mut().0) {
528 return InternalEntry
::Occupied { elem: full }
;
533 debug_assert
!(displacement
<= size
);
537 fn pop_internal
<K
, V
>(starting_bucket
: FullBucketMut
<K
, V
>)
538 -> (K
, V
, &mut RawTable
<K
, V
>)
540 let (empty
, retkey
, retval
) = starting_bucket
.take();
541 let mut gap
= match empty
.gap_peek() {
543 Err(b
) => return (retkey
, retval
, b
.into_table()),
546 while gap
.full().displacement() != 0 {
547 gap
= match gap
.shift() {
550 return (retkey
, retval
, b
.into_table());
555 // Now we've done all our shifting. Return the value we grabbed earlier.
556 (retkey
, retval
, gap
.into_table())
559 /// Performs robin hood bucket stealing at the given `bucket`. You must
560 /// also pass that bucket's displacement so we don't have to recalculate it.
562 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
563 fn robin_hood
<'a
, K
: 'a
, V
: 'a
>(bucket
: FullBucketMut
<'a
, K
, V
>,
564 mut displacement
: usize,
568 -> FullBucketMut
<'a
, K
, V
> {
569 let size
= bucket
.table().size();
570 let raw_capacity
= bucket
.table().capacity();
571 // There can be at most `size - dib` buckets to displace, because
572 // in the worst case, there are `size` elements and we already are
573 // `displacement` buckets away from the initial one.
574 let idx_end
= (bucket
.index() + size
- bucket
.displacement()) % raw_capacity
;
575 // Save the *starting point*.
576 let mut bucket
= bucket
.stash();
579 let (old_hash
, old_key
, old_val
) = bucket
.replace(hash
, key
, val
);
586 let probe
= bucket
.next();
587 debug_assert
!(probe
.index() != idx_end
);
589 let full_bucket
= match probe
.peek() {
592 let bucket
= bucket
.put(hash
, key
, val
);
593 // Now that it's stolen, just read the value's pointer
594 // right out of the table! Go back to the *starting point*.
596 // This use of `into_table` is misleading. It turns the
597 // bucket, which is a FullBucket on top of a
598 // FullBucketMut, into just one FullBucketMut. The "table"
599 // refers to the inner FullBucketMut in this context.
600 return bucket
.into_table();
602 Full(bucket
) => bucket
,
605 let probe_displacement
= full_bucket
.displacement();
607 bucket
= full_bucket
;
609 // Robin hood! Steal the spot.
610 if probe_displacement
< displacement
{
611 displacement
= probe_displacement
;
618 impl<K
, V
, S
> HashMap
<K
, V
, S
>
622 fn make_hash
<X
: ?Sized
>(&self, x
: &X
) -> SafeHash
625 table
::make_hash(&self.hash_builder
, x
)
628 /// Search for a key, yielding the index if it's found in the hashtable.
629 /// If you already have the hash for the key lying around, or if you need an
630 /// InternalEntry, use search_hashed or search_hashed_nonempty.
632 fn search
<'a
, Q
: ?Sized
>(&'a
self, q
: &Q
)
633 -> Option
<FullBucket
<K
, V
, &'a RawTable
<K
, V
>>>
641 let hash
= self.make_hash(q
);
642 search_hashed_nonempty(&self.table
, hash
, |k
| q
.eq(k
.borrow()), true)
643 .into_occupied_bucket()
647 fn search_mut
<'a
, Q
: ?Sized
>(&'a
mut self, q
: &Q
)
648 -> Option
<FullBucket
<K
, V
, &'a
mut RawTable
<K
, V
>>>
656 let hash
= self.make_hash(q
);
657 search_hashed_nonempty(&mut self.table
, hash
, |k
| q
.eq(k
.borrow()), true)
658 .into_occupied_bucket()
661 // The caller should ensure that invariants by Robin Hood Hashing hold
662 // and that there's space in the underlying table.
663 fn insert_hashed_ordered(&mut self, hash
: SafeHash
, k
: K
, v
: V
) {
664 let mut buckets
= Bucket
::new(&mut self.table
, hash
);
665 let start_index
= buckets
.index();
668 // We don't need to compare hashes for value swap.
669 // Not even DIBs for Robin Hood.
670 buckets
= match buckets
.peek() {
672 empty
.put(hash
, k
, v
);
675 Full(b
) => b
.into_bucket(),
678 debug_assert
!(buckets
.index() != start_index
);
683 impl<K
: Hash
+ Eq
, V
> HashMap
<K
, V
, RandomState
> {
684 /// Creates an empty `HashMap`.
686 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
687 /// is first inserted into.
692 /// use std::collections::HashMap;
693 /// let mut map: HashMap<&str, i32> = HashMap::new();
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn new() -> HashMap
<K
, V
, RandomState
> {
701 /// Creates an empty `HashMap` with the specified capacity.
703 /// The hash map will be able to hold at least `capacity` elements without
704 /// reallocating. If `capacity` is 0, the hash map will not allocate.
709 /// use std::collections::HashMap;
710 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn with_capacity(capacity
: usize) -> HashMap
<K
, V
, RandomState
> {
715 HashMap
::with_capacity_and_hasher(capacity
, Default
::default())
719 impl<K
, V
, S
> HashMap
<K
, V
, S
> {
720 /// Returns the number of elements the map can hold without reallocating.
722 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
723 /// more, but is guaranteed to be able to hold at least this many.
728 /// use std::collections::HashMap;
729 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
730 /// assert!(map.capacity() >= 100);
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn capacity(&self) -> usize {
735 self.resize_policy
.capacity(self.raw_capacity())
738 /// Returns the hash map's raw capacity.
740 fn raw_capacity(&self) -> usize {
741 self.table
.capacity()
744 /// An iterator visiting all keys in arbitrary order.
745 /// The iterator element type is `&'a K`.
750 /// use std::collections::HashMap;
752 /// let mut map = HashMap::new();
753 /// map.insert("a", 1);
754 /// map.insert("b", 2);
755 /// map.insert("c", 3);
757 /// for key in map.keys() {
758 /// println!("{}", key);
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn keys(&self) -> Keys
<K
, V
> {
763 Keys { inner: self.iter() }
766 /// An iterator visiting all values in arbitrary order.
767 /// The iterator element type is `&'a V`.
772 /// use std::collections::HashMap;
774 /// let mut map = HashMap::new();
775 /// map.insert("a", 1);
776 /// map.insert("b", 2);
777 /// map.insert("c", 3);
779 /// for val in map.values() {
780 /// println!("{}", val);
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn values(&self) -> Values
<K
, V
> {
785 Values { inner: self.iter() }
788 /// An iterator visiting all values mutably in arbitrary order.
789 /// The iterator element type is `&'a mut V`.
794 /// use std::collections::HashMap;
796 /// let mut map = HashMap::new();
798 /// map.insert("a", 1);
799 /// map.insert("b", 2);
800 /// map.insert("c", 3);
802 /// for val in map.values_mut() {
803 /// *val = *val + 10;
806 /// for val in map.values() {
807 /// println!("{}", val);
810 #[stable(feature = "map_values_mut", since = "1.10.0")]
811 pub fn values_mut(&mut self) -> ValuesMut
<K
, V
> {
812 ValuesMut { inner: self.iter_mut() }
815 /// An iterator visiting all key-value pairs in arbitrary order.
816 /// The iterator element type is `(&'a K, &'a V)`.
821 /// use std::collections::HashMap;
823 /// let mut map = HashMap::new();
824 /// map.insert("a", 1);
825 /// map.insert("b", 2);
826 /// map.insert("c", 3);
828 /// for (key, val) in map.iter() {
829 /// println!("key: {} val: {}", key, val);
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub fn iter(&self) -> Iter
<K
, V
> {
834 Iter { inner: self.table.iter() }
837 /// An iterator visiting all key-value pairs in arbitrary order,
838 /// with mutable references to the values.
839 /// The iterator element type is `(&'a K, &'a mut V)`.
844 /// use std::collections::HashMap;
846 /// let mut map = HashMap::new();
847 /// map.insert("a", 1);
848 /// map.insert("b", 2);
849 /// map.insert("c", 3);
851 /// // Update all values
852 /// for (_, val) in map.iter_mut() {
856 /// for (key, val) in &map {
857 /// println!("key: {} val: {}", key, val);
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn iter_mut(&mut self) -> IterMut
<K
, V
> {
862 IterMut { inner: self.table.iter_mut() }
865 /// Returns the number of elements in the map.
870 /// use std::collections::HashMap;
872 /// let mut a = HashMap::new();
873 /// assert_eq!(a.len(), 0);
874 /// a.insert(1, "a");
875 /// assert_eq!(a.len(), 1);
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn len(&self) -> usize {
882 /// Returns `true` if the map contains no elements.
887 /// use std::collections::HashMap;
889 /// let mut a = HashMap::new();
890 /// assert!(a.is_empty());
891 /// a.insert(1, "a");
892 /// assert!(!a.is_empty());
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn is_empty(&self) -> bool
{
900 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
901 /// allocated memory for reuse.
906 /// use std::collections::HashMap;
908 /// let mut a = HashMap::new();
909 /// a.insert(1, "a");
910 /// a.insert(2, "b");
912 /// for (k, v) in a.drain().take(1) {
913 /// assert!(k == 1 || k == 2);
914 /// assert!(v == "a" || v == "b");
917 /// assert!(a.is_empty());
920 #[stable(feature = "drain", since = "1.6.0")]
921 pub fn drain(&mut self) -> Drain
<K
, V
> {
922 Drain { inner: self.table.drain() }
925 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
931 /// use std::collections::HashMap;
933 /// let mut a = HashMap::new();
934 /// a.insert(1, "a");
936 /// assert!(a.is_empty());
938 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn clear(&mut self) {
945 impl<K
, V
, S
> HashMap
<K
, V
, S
>
949 /// Creates an empty `HashMap` which will use the given hash builder to hash
952 /// The created map has the default initial capacity.
954 /// Warning: `hash_builder` is normally randomly generated, and
955 /// is designed to allow HashMaps to be resistant to attacks that
956 /// cause many collisions and very poor performance. Setting it
957 /// manually using this function can expose a DoS attack vector.
962 /// use std::collections::HashMap;
963 /// use std::collections::hash_map::RandomState;
965 /// let s = RandomState::new();
966 /// let mut map = HashMap::with_hasher(s);
967 /// map.insert(1, 2);
970 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
971 pub fn with_hasher(hash_builder
: S
) -> HashMap
<K
, V
, S
> {
974 resize_policy
: DefaultResizePolicy
::new(),
975 table
: RawTable
::new(0),
979 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
980 /// to hash the keys.
982 /// The hash map will be able to hold at least `capacity` elements without
983 /// reallocating. If `capacity` is 0, the hash map will not allocate.
985 /// Warning: `hash_builder` is normally randomly generated, and
986 /// is designed to allow HashMaps to be resistant to attacks that
987 /// cause many collisions and very poor performance. Setting it
988 /// manually using this function can expose a DoS attack vector.
993 /// use std::collections::HashMap;
994 /// use std::collections::hash_map::RandomState;
996 /// let s = RandomState::new();
997 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
998 /// map.insert(1, 2);
1001 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1002 pub fn with_capacity_and_hasher(capacity
: usize, hash_builder
: S
) -> HashMap
<K
, V
, S
> {
1003 let resize_policy
= DefaultResizePolicy
::new();
1004 let raw_cap
= resize_policy
.raw_capacity(capacity
);
1008 table
: RawTable
::new(raw_cap
),
1012 /// Returns a reference to the map's [`BuildHasher`].
1014 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
1019 /// use std::collections::HashMap;
1020 /// use std::collections::hash_map::RandomState;
1022 /// let hasher = RandomState::new();
1023 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
1024 /// let hasher: &RandomState = map.hasher();
1026 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
1027 pub fn hasher(&self) -> &S
{
1031 /// Reserves capacity for at least `additional` more elements to be inserted
1032 /// in the `HashMap`. The collection may reserve more space to avoid
1033 /// frequent reallocations.
1037 /// Panics if the new allocation size overflows [`usize`].
1039 /// [`usize`]: ../../std/primitive.usize.html
1044 /// use std::collections::HashMap;
1045 /// let mut map: HashMap<&str, i32> = HashMap::new();
1046 /// map.reserve(10);
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn reserve(&mut self, additional
: usize) {
1051 match self.reserve_internal(additional
, Infallible
) {
1052 Err(CollectionAllocErr
::CapacityOverflow
) => panic
!("capacity overflow"),
1053 Err(CollectionAllocErr
::AllocErr
) => unreachable
!(),
1054 Ok(()) => { /* yay */ }
1058 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1059 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1060 /// frequent reallocations.
1064 /// If the capacity overflows, or the allocator reports a failure, then an error
1070 /// #![feature(try_reserve)]
1071 /// use std::collections::HashMap;
1072 /// let mut map: HashMap<&str, isize> = HashMap::new();
1073 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1075 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
1076 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), CollectionAllocErr
> {
1077 self.reserve_internal(additional
, Fallible
)
1081 fn reserve_internal(&mut self, additional
: usize, fallibility
: Fallibility
)
1082 -> Result
<(), CollectionAllocErr
> {
1084 let remaining
= self.capacity() - self.len(); // this can't overflow
1085 if remaining
< additional
{
1086 let min_cap
= self.len()
1087 .checked_add(additional
)
1088 .ok_or(CollectionAllocErr
::CapacityOverflow
)?
;
1089 let raw_cap
= self.resize_policy
.try_raw_capacity(min_cap
)?
;
1090 self.try_resize(raw_cap
, fallibility
)?
;
1091 } else if self.table
.tag() && remaining
<= self.len() {
1092 // Probe sequence is too long and table is half full,
1093 // resize early to reduce probing length.
1094 let new_capacity
= self.table
.capacity() * 2;
1095 self.try_resize(new_capacity
, fallibility
)?
;
1100 /// Resizes the internal vectors to a new capacity. It's your
1101 /// responsibility to:
1102 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
1103 /// for the load factor.
1104 /// 2) Ensure `new_raw_cap` is a power of two or zero.
1110 fallibility
: Fallibility
,
1111 ) -> Result
<(), CollectionAllocErr
> {
1112 assert
!(self.table
.size() <= new_raw_cap
);
1113 assert
!(new_raw_cap
.is_power_of_two() || new_raw_cap
== 0);
1115 let mut old_table
= replace(
1118 Infallible
=> RawTable
::new(new_raw_cap
),
1119 Fallible
=> RawTable
::try_new(new_raw_cap
)?
,
1122 let old_size
= old_table
.size();
1124 if old_table
.size() == 0 {
1128 let mut bucket
= Bucket
::head_bucket(&mut old_table
);
1130 // This is how the buckets might be laid out in memory:
1131 // ($ marks an initialized bucket)
1133 // |$$$_$$$$$$_$$$$$|
1135 // But we've skipped the entire initial cluster of buckets
1136 // and will continue iteration in this order:
1139 // ^ wrap around once end is reached
1141 // $$$_____________|
1142 // ^ exit once table.size == 0
1144 bucket
= match bucket
.peek() {
1146 let h
= bucket
.hash();
1147 let (b
, k
, v
) = bucket
.take();
1148 self.insert_hashed_ordered(h
, k
, v
);
1149 if b
.table().size() == 0 {
1154 Empty(b
) => b
.into_bucket(),
1159 assert_eq
!(self.table
.size(), old_size
);
1163 /// Shrinks the capacity of the map as much as possible. It will drop
1164 /// down as much as possible while maintaining the internal rules
1165 /// and possibly leaving some space in accordance with the resize policy.
1170 /// use std::collections::HashMap;
1172 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1173 /// map.insert(1, 2);
1174 /// map.insert(3, 4);
1175 /// assert!(map.capacity() >= 100);
1176 /// map.shrink_to_fit();
1177 /// assert!(map.capacity() >= 2);
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub fn shrink_to_fit(&mut self) {
1181 let new_raw_cap
= self.resize_policy
.raw_capacity(self.len());
1182 if self.raw_capacity() != new_raw_cap
{
1183 let old_table
= replace(&mut self.table
, RawTable
::new(new_raw_cap
));
1184 let old_size
= old_table
.size();
1186 // Shrink the table. Naive algorithm for resizing:
1187 for (h
, k
, v
) in old_table
.into_iter() {
1188 self.insert_hashed_nocheck(h
, k
, v
);
1191 debug_assert_eq
!(self.table
.size(), old_size
);
1195 /// Shrinks the capacity of the map with a lower limit. It will drop
1196 /// down no lower than the supplied limit while maintaining the internal rules
1197 /// and possibly leaving some space in accordance with the resize policy.
1199 /// Panics if the current capacity is smaller than the supplied
1200 /// minimum capacity.
1205 /// #![feature(shrink_to)]
1206 /// use std::collections::HashMap;
1208 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1209 /// map.insert(1, 2);
1210 /// map.insert(3, 4);
1211 /// assert!(map.capacity() >= 100);
1212 /// map.shrink_to(10);
1213 /// assert!(map.capacity() >= 10);
1214 /// map.shrink_to(0);
1215 /// assert!(map.capacity() >= 2);
1217 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1218 pub fn shrink_to(&mut self, min_capacity
: usize) {
1219 assert
!(self.capacity() >= min_capacity
, "Tried to shrink to a larger capacity");
1221 let new_raw_cap
= self.resize_policy
.raw_capacity(max(self.len(), min_capacity
));
1222 if self.raw_capacity() != new_raw_cap
{
1223 let old_table
= replace(&mut self.table
, RawTable
::new(new_raw_cap
));
1224 let old_size
= old_table
.size();
1226 // Shrink the table. Naive algorithm for resizing:
1227 for (h
, k
, v
) in old_table
.into_iter() {
1228 self.insert_hashed_nocheck(h
, k
, v
);
1231 debug_assert_eq
!(self.table
.size(), old_size
);
1235 /// Insert a pre-hashed key-value pair, without first checking
1236 /// that there's enough room in the buckets. Returns a reference to the
1237 /// newly insert value.
1239 /// If the key already exists, the hashtable will be returned untouched
1240 /// and a reference to the existing element will be returned.
1241 fn insert_hashed_nocheck(&mut self, hash
: SafeHash
, k
: K
, v
: V
) -> Option
<V
> {
1242 let entry
= search_hashed(&mut self.table
, hash
, |key
| *key
== k
).into_entry(k
);
1244 Some(Occupied(mut elem
)) => Some(elem
.insert(v
)),
1245 Some(Vacant(elem
)) => {
1249 None
=> unreachable
!(),
1253 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1258 /// use std::collections::HashMap;
1260 /// let mut letters = HashMap::new();
1262 /// for ch in "a short treatise on fungi".chars() {
1263 /// let counter = letters.entry(ch).or_insert(0);
1267 /// assert_eq!(letters[&'s'], 2);
1268 /// assert_eq!(letters[&'t'], 3);
1269 /// assert_eq!(letters[&'u'], 1);
1270 /// assert_eq!(letters.get(&'y'), None);
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 pub fn entry(&mut self, key
: K
) -> Entry
<K
, V
> {
1274 // Gotta resize now.
1276 let hash
= self.make_hash(&key
);
1277 search_hashed(&mut self.table
, hash
, |q
| q
.eq(&key
))
1278 .into_entry(key
).expect("unreachable")
1281 /// Returns a reference to the value corresponding to the key.
1283 /// The key may be any borrowed form of the map's key type, but
1284 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1287 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1288 /// [`Hash`]: ../../std/hash/trait.Hash.html
1293 /// use std::collections::HashMap;
1295 /// let mut map = HashMap::new();
1296 /// map.insert(1, "a");
1297 /// assert_eq!(map.get(&1), Some(&"a"));
1298 /// assert_eq!(map.get(&2), None);
1300 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&V
>
1306 self.search(k
).map(|bucket
| bucket
.into_refs().1)
1309 /// Returns the key-value pair corresponding to the supplied key.
1311 /// The supplied key may be any borrowed form of the map's key type, but
1312 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1315 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1316 /// [`Hash`]: ../../std/hash/trait.Hash.html
1321 /// #![feature(map_get_key_value)]
1322 /// use std::collections::HashMap;
1324 /// let mut map = HashMap::new();
1325 /// map.insert(1, "a");
1326 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1327 /// assert_eq!(map.get_key_value(&2), None);
1329 #[unstable(feature = "map_get_key_value", issue = "49347")]
1330 pub fn get_key_value
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<(&K
, &V
)>
1334 self.search(k
).map(|bucket
| bucket
.into_refs())
1337 /// Returns `true` if the map contains a value for the specified key.
1339 /// The key may be any borrowed form of the map's key type, but
1340 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1343 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1344 /// [`Hash`]: ../../std/hash/trait.Hash.html
1349 /// use std::collections::HashMap;
1351 /// let mut map = HashMap::new();
1352 /// map.insert(1, "a");
1353 /// assert_eq!(map.contains_key(&1), true);
1354 /// assert_eq!(map.contains_key(&2), false);
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
1361 self.search(k
).is_some()
1364 /// Returns a mutable reference to the value corresponding to the key.
1366 /// The key may be any borrowed form of the map's key type, but
1367 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1370 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1371 /// [`Hash`]: ../../std/hash/trait.Hash.html
1376 /// use std::collections::HashMap;
1378 /// let mut map = HashMap::new();
1379 /// map.insert(1, "a");
1380 /// if let Some(x) = map.get_mut(&1) {
1383 /// assert_eq!(map[&1], "b");
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut V
>
1390 self.search_mut(k
).map(|bucket
| bucket
.into_mut_refs().1)
1393 /// Inserts a key-value pair into the map.
1395 /// If the map did not have this key present, [`None`] is returned.
1397 /// If the map did have this key present, the value is updated, and the old
1398 /// value is returned. The key is not updated, though; this matters for
1399 /// types that can be `==` without being identical. See the [module-level
1400 /// documentation] for more.
1402 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1403 /// [module-level documentation]: index.html#insert-and-complex-keys
1408 /// use std::collections::HashMap;
1410 /// let mut map = HashMap::new();
1411 /// assert_eq!(map.insert(37, "a"), None);
1412 /// assert_eq!(map.is_empty(), false);
1414 /// map.insert(37, "b");
1415 /// assert_eq!(map.insert(37, "c"), Some("b"));
1416 /// assert_eq!(map[&37], "c");
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 pub fn insert(&mut self, k
: K
, v
: V
) -> Option
<V
> {
1420 let hash
= self.make_hash(&k
);
1422 self.insert_hashed_nocheck(hash
, k
, v
)
1425 /// Removes a key from the map, returning the value at the key if the key
1426 /// was previously in the map.
1428 /// The key may be any borrowed form of the map's key type, but
1429 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1432 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1433 /// [`Hash`]: ../../std/hash/trait.Hash.html
1438 /// use std::collections::HashMap;
1440 /// let mut map = HashMap::new();
1441 /// map.insert(1, "a");
1442 /// assert_eq!(map.remove(&1), Some("a"));
1443 /// assert_eq!(map.remove(&1), None);
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<V
>
1450 self.search_mut(k
).map(|bucket
| pop_internal(bucket
).1)
1453 /// Removes a key from the map, returning the stored key and value if the
1454 /// key was previously in the map.
1456 /// The key may be any borrowed form of the map's key type, but
1457 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1460 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1461 /// [`Hash`]: ../../std/hash/trait.Hash.html
1466 /// use std::collections::HashMap;
1469 /// let mut map = HashMap::new();
1470 /// map.insert(1, "a");
1471 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1472 /// assert_eq!(map.remove(&1), None);
1475 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1476 pub fn remove_entry
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<(K
, V
)>
1482 let (k
, v
, _
) = pop_internal(bucket
);
1487 /// Retains only the elements specified by the predicate.
1489 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1494 /// use std::collections::HashMap;
1496 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1497 /// map.retain(|&k, _| k % 2 == 0);
1498 /// assert_eq!(map.len(), 4);
1500 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1501 pub fn retain
<F
>(&mut self, mut f
: F
)
1502 where F
: FnMut(&K
, &mut V
) -> bool
1504 if self.table
.size() == 0 {
1507 let mut elems_left
= self.table
.size();
1508 let mut bucket
= Bucket
::head_bucket(&mut self.table
);
1510 let start_index
= bucket
.index();
1511 while elems_left
!= 0 {
1512 bucket
= match bucket
.peek() {
1515 let should_remove
= {
1516 let (k
, v
) = full
.read_mut();
1520 let prev_raw
= full
.raw();
1521 let (_
, _
, t
) = pop_internal(full
);
1522 Bucket
::new_from(prev_raw
, t
)
1531 bucket
.prev(); // reverse iteration
1532 debug_assert
!(elems_left
== 0 || bucket
.index() != start_index
);
1537 impl<K
, V
, S
> HashMap
<K
, V
, S
>
1541 /// Creates a raw entry builder for the HashMap.
1543 /// Raw entries provide the lowest level of control for searching and
1544 /// manipulating a map. They must be manually initialized with a hash and
1545 /// then manually searched. After this, insertions into a vacant entry
1546 /// still require an owned key to be provided.
1548 /// Raw entries are useful for such exotic situations as:
1550 /// * Hash memoization
1551 /// * Deferring the creation of an owned key until it is known to be required
1552 /// * Using a search key that doesn't work with the Borrow trait
1553 /// * Using custom comparison logic without newtype wrappers
1555 /// Because raw entries provide much more low-level control, it's much easier
1556 /// to put the HashMap into an inconsistent state which, while memory-safe,
1557 /// will cause the map to produce seemingly random results. Higher-level and
1558 /// more foolproof APIs like `entry` should be preferred when possible.
1560 /// In particular, the hash used to initialized the raw entry must still be
1561 /// consistent with the hash of the key that is ultimately stored in the entry.
1562 /// This is because implementations of HashMap may need to recompute hashes
1563 /// when resizing, at which point only the keys are available.
1565 /// Raw entries give mutable access to the keys. This must not be used
1566 /// to modify how the key would compare or hash, as the map will not re-evaluate
1567 /// where the key should go, meaning the keys may become "lost" if their
1568 /// location does not reflect their state. For instance, if you change a key
1569 /// so that the map now contains keys which compare equal, search may start
1570 /// acting erratically, with two keys randomly masking each other. Implementations
1571 /// are free to assume this doesn't happen (within the limits of memory-safety).
1573 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1574 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut
<K
, V
, S
> {
1576 RawEntryBuilderMut { map: self }
1579 /// Creates a raw immutable entry builder for the HashMap.
1581 /// Raw entries provide the lowest level of control for searching and
1582 /// manipulating a map. They must be manually initialized with a hash and
1583 /// then manually searched.
1585 /// This is useful for
1586 /// * Hash memoization
1587 /// * Using a search key that doesn't work with the Borrow trait
1588 /// * Using custom comparison logic without newtype wrappers
1590 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1591 /// `get` should be preferred.
1593 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1594 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1595 pub fn raw_entry(&self) -> RawEntryBuilder
<K
, V
, S
> {
1596 RawEntryBuilder { map: self }
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<K
, V
, S
> PartialEq
for HashMap
<K
, V
, S
>
1606 fn eq(&self, other
: &HashMap
<K
, V
, S
>) -> bool
{
1607 if self.len() != other
.len() {
1611 self.iter().all(|(key
, value
)| other
.get(key
).map_or(false, |v
| *value
== *v
))
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<K
, V
, S
> Eq
for HashMap
<K
, V
, S
>
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<K
, V
, S
> Debug
for HashMap
<K
, V
, S
>
1625 where K
: Eq
+ Hash
+ Debug
,
1629 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1630 f
.debug_map().entries(self.iter()).finish()
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<K
, V
, S
> Default
for HashMap
<K
, V
, S
>
1637 S
: BuildHasher
+ Default
1639 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1640 fn default() -> HashMap
<K
, V
, S
> {
1641 HashMap
::with_hasher(Default
::default())
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 impl<K
, Q
: ?Sized
, V
, S
> Index
<&Q
> for HashMap
<K
, V
, S
>
1647 where K
: Eq
+ Hash
+ Borrow
<Q
>,
1653 /// Returns a reference to the value corresponding to the supplied key.
1657 /// Panics if the key is not present in the `HashMap`.
1659 fn index(&self, key
: &Q
) -> &V
{
1660 self.get(key
).expect("no entry found for key")
1664 /// An iterator over the entries of a `HashMap`.
1666 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1667 /// documentation for more.
1669 /// [`iter`]: struct.HashMap.html#method.iter
1670 /// [`HashMap`]: struct.HashMap.html
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub struct Iter
<'a
, K
: 'a
, V
: 'a
> {
1673 inner
: table
::Iter
<'a
, K
, V
>,
1676 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<K
, V
> Clone
for Iter
<'_
, K
, V
> {
1679 fn clone(&self) -> Self {
1680 Iter { inner: self.inner.clone() }
1684 #[stable(feature = "std_debug", since = "1.16.0")]
1685 impl<K
: Debug
, V
: Debug
> fmt
::Debug
for Iter
<'_
, K
, V
> {
1686 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1688 .entries(self.clone())
1693 /// A mutable iterator over the entries of a `HashMap`.
1695 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1696 /// documentation for more.
1698 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1699 /// [`HashMap`]: struct.HashMap.html
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 pub struct IterMut
<'a
, K
: 'a
, V
: 'a
> {
1702 inner
: table
::IterMut
<'a
, K
, V
>,
1705 /// An owning iterator over the entries of a `HashMap`.
1707 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1708 /// (provided by the `IntoIterator` trait). See its documentation for more.
1710 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1711 /// [`HashMap`]: struct.HashMap.html
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 pub struct IntoIter
<K
, V
> {
1714 pub(super) inner
: table
::IntoIter
<K
, V
>,
1717 /// An iterator over the keys of a `HashMap`.
1719 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1720 /// documentation for more.
1722 /// [`keys`]: struct.HashMap.html#method.keys
1723 /// [`HashMap`]: struct.HashMap.html
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 pub struct Keys
<'a
, K
: 'a
, V
: 'a
> {
1726 inner
: Iter
<'a
, K
, V
>,
1729 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<K
, V
> Clone
for Keys
<'_
, K
, V
> {
1732 fn clone(&self) -> Self {
1733 Keys { inner: self.inner.clone() }
1737 #[stable(feature = "std_debug", since = "1.16.0")]
1738 impl<K
: Debug
, V
> fmt
::Debug
for Keys
<'_
, K
, V
> {
1739 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1741 .entries(self.clone())
1746 /// An iterator over the values of a `HashMap`.
1748 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1749 /// documentation for more.
1751 /// [`values`]: struct.HashMap.html#method.values
1752 /// [`HashMap`]: struct.HashMap.html
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub struct Values
<'a
, K
: 'a
, V
: 'a
> {
1755 inner
: Iter
<'a
, K
, V
>,
1758 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<K
, V
> Clone
for Values
<'_
, K
, V
> {
1761 fn clone(&self) -> Self {
1762 Values { inner: self.inner.clone() }
1766 #[stable(feature = "std_debug", since = "1.16.0")]
1767 impl<K
, V
: Debug
> fmt
::Debug
for Values
<'_
, K
, V
> {
1768 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1770 .entries(self.clone())
1775 /// A draining iterator over the entries of a `HashMap`.
1777 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1778 /// documentation for more.
1780 /// [`drain`]: struct.HashMap.html#method.drain
1781 /// [`HashMap`]: struct.HashMap.html
1782 #[stable(feature = "drain", since = "1.6.0")]
1783 pub struct Drain
<'a
, K
: 'a
, V
: 'a
> {
1784 pub(super) inner
: table
::Drain
<'a
, K
, V
>,
1787 /// A mutable iterator over the values of a `HashMap`.
1789 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1790 /// documentation for more.
1792 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1793 /// [`HashMap`]: struct.HashMap.html
1794 #[stable(feature = "map_values_mut", since = "1.10.0")]
1795 pub struct ValuesMut
<'a
, K
: 'a
, V
: 'a
> {
1796 inner
: IterMut
<'a
, K
, V
>,
1799 enum InternalEntry
<K
, V
, M
> {
1800 Occupied { elem: FullBucket<K, V, M> }
,
1803 elem
: VacantEntryState
<K
, V
, M
>,
1808 impl<K
, V
, M
> InternalEntry
<K
, V
, M
> {
1810 fn into_occupied_bucket(self) -> Option
<FullBucket
<K
, V
, M
>> {
1812 InternalEntry
::Occupied { elem }
=> Some(elem
),
1818 impl<'a
, K
, V
> InternalEntry
<K
, V
, &'a
mut RawTable
<K
, V
>> {
1820 fn into_entry(self, key
: K
) -> Option
<Entry
<'a
, K
, V
>> {
1822 InternalEntry
::Occupied { elem }
=> {
1823 Some(Occupied(OccupiedEntry
{
1828 InternalEntry
::Vacant { hash, elem }
=> {
1829 Some(Vacant(VacantEntry
{
1835 InternalEntry
::TableIsEmpty
=> None
,
1840 /// A builder for computing where in a HashMap a key-value pair would be stored.
1842 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1844 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1846 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1847 pub struct RawEntryBuilderMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1848 map
: &'a
mut HashMap
<K
, V
, S
>,
1851 /// A view into a single entry in a map, which may either be vacant or occupied.
1853 /// This is a lower-level version of [`Entry`].
1855 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1857 /// [`HashMap`]: struct.HashMap.html
1858 /// [`Entry`]: enum.Entry.html
1859 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1860 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1861 pub enum RawEntryMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1862 /// An occupied entry.
1863 Occupied(RawOccupiedEntryMut
<'a
, K
, V
>),
1865 Vacant(RawVacantEntryMut
<'a
, K
, V
, S
>),
1868 /// A view into an occupied entry in a `HashMap`.
1869 /// It is part of the [`RawEntryMut`] enum.
1871 /// [`RawEntryMut`]: enum.RawEntryMut.html
1872 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1873 pub struct RawOccupiedEntryMut
<'a
, K
: 'a
, V
: 'a
> {
1874 elem
: FullBucket
<K
, V
, &'a
mut RawTable
<K
, V
>>,
1877 /// A view into a vacant entry in a `HashMap`.
1878 /// It is part of the [`RawEntryMut`] enum.
1880 /// [`RawEntryMut`]: enum.RawEntryMut.html
1881 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1882 pub struct RawVacantEntryMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1883 elem
: VacantEntryState
<K
, V
, &'a
mut RawTable
<K
, V
>>,
1884 hash_builder
: &'a S
,
1887 /// A builder for computing where in a HashMap a key-value pair would be stored.
1889 /// See the [`HashMap::raw_entry`] docs for usage examples.
1891 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1892 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1893 pub struct RawEntryBuilder
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1894 map
: &'a HashMap
<K
, V
, S
>,
1897 impl<'a
, K
, V
, S
> RawEntryBuilderMut
<'a
, K
, V
, S
>
1898 where S
: BuildHasher
,
1901 /// Creates a `RawEntryMut` from the given key.
1902 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1903 pub fn from_key
<Q
: ?Sized
>(self, k
: &Q
) -> RawEntryMut
<'a
, K
, V
, S
>
1907 let mut hasher
= self.map
.hash_builder
.build_hasher();
1908 k
.hash(&mut hasher
);
1909 self.from_key_hashed_nocheck(hasher
.finish(), k
)
1912 /// Creates a `RawEntryMut` from the given key and its hash.
1914 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1915 pub fn from_key_hashed_nocheck
<Q
: ?Sized
>(self, hash
: u64, k
: &Q
) -> RawEntryMut
<'a
, K
, V
, S
>
1919 self.from_hash(hash
, |q
| q
.borrow().eq(k
))
1923 fn search
<F
>(self, hash
: u64, is_match
: F
, compare_hashes
: bool
) -> RawEntryMut
<'a
, K
, V
, S
>
1924 where for<'b
> F
: FnMut(&'b K
) -> bool
,
1926 match search_hashed_nonempty_mut(&mut self.map
.table
,
1927 SafeHash
::new(hash
),
1930 InternalEntry
::Occupied { elem }
=> {
1931 RawEntryMut
::Occupied(RawOccupiedEntryMut { elem }
)
1933 InternalEntry
::Vacant { elem, .. }
=> {
1934 RawEntryMut
::Vacant(RawVacantEntryMut
{
1936 hash_builder
: &self.map
.hash_builder
,
1939 InternalEntry
::TableIsEmpty
=> {
1944 /// Creates a `RawEntryMut` from the given hash.
1946 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1947 pub fn from_hash
<F
>(self, hash
: u64, is_match
: F
) -> RawEntryMut
<'a
, K
, V
, S
>
1948 where for<'b
> F
: FnMut(&'b K
) -> bool
,
1950 self.search(hash
, is_match
, true)
1953 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1954 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1956 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1957 pub fn search_bucket
<F
>(self, hash
: u64, is_match
: F
) -> RawEntryMut
<'a
, K
, V
, S
>
1958 where for<'b
> F
: FnMut(&'b K
) -> bool
,
1960 self.search(hash
, is_match
, false)
1964 impl<'a
, K
, V
, S
> RawEntryBuilder
<'a
, K
, V
, S
>
1965 where S
: BuildHasher
,
1967 /// Access an entry by key.
1968 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1969 pub fn from_key
<Q
: ?Sized
>(self, k
: &Q
) -> Option
<(&'a K
, &'a V
)>
1973 let mut hasher
= self.map
.hash_builder
.build_hasher();
1974 k
.hash(&mut hasher
);
1975 self.from_key_hashed_nocheck(hasher
.finish(), k
)
1978 /// Access an entry by a key and its hash.
1979 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1980 pub fn from_key_hashed_nocheck
<Q
: ?Sized
>(self, hash
: u64, k
: &Q
) -> Option
<(&'a K
, &'a V
)>
1985 self.from_hash(hash
, |q
| q
.borrow().eq(k
))
1988 fn search
<F
>(self, hash
: u64, is_match
: F
, compare_hashes
: bool
) -> Option
<(&'a K
, &'a V
)>
1989 where F
: FnMut(&K
) -> bool
1991 if unsafe { unlikely(self.map.table.size() == 0) }
{
1994 match search_hashed_nonempty(&self.map
.table
,
1995 SafeHash
::new(hash
),
1998 InternalEntry
::Occupied { elem }
=> Some(elem
.into_refs()),
1999 InternalEntry
::Vacant { .. }
=> None
,
2000 InternalEntry
::TableIsEmpty
=> unreachable
!(),
2004 /// Access an entry by hash.
2005 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2006 pub fn from_hash
<F
>(self, hash
: u64, is_match
: F
) -> Option
<(&'a K
, &'a V
)>
2007 where F
: FnMut(&K
) -> bool
2009 self.search(hash
, is_match
, true)
2012 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2013 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2015 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2016 pub fn search_bucket
<F
>(self, hash
: u64, is_match
: F
) -> Option
<(&'a K
, &'a V
)>
2017 where F
: FnMut(&K
) -> bool
2019 self.search(hash
, is_match
, false)
2023 impl<'a
, K
, V
, S
> RawEntryMut
<'a
, K
, V
, S
> {
2024 /// Ensures a value is in the entry by inserting the default if empty, and returns
2025 /// mutable references to the key and value in the entry.
2030 /// #![feature(hash_raw_entry)]
2031 /// use std::collections::HashMap;
2033 /// let mut map: HashMap<&str, u32> = HashMap::new();
2035 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2036 /// assert_eq!(map["poneyland"], 3);
2038 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2039 /// assert_eq!(map["poneyland"], 6);
2041 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2042 pub fn or_insert(self, default_key
: K
, default_val
: V
) -> (&'a
mut K
, &'a
mut V
)
2047 RawEntryMut
::Occupied(entry
) => entry
.into_key_value(),
2048 RawEntryMut
::Vacant(entry
) => entry
.insert(default_key
, default_val
),
2052 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2053 /// and returns mutable references to the key and value in the entry.
2058 /// #![feature(hash_raw_entry)]
2059 /// use std::collections::HashMap;
2061 /// let mut map: HashMap<&str, String> = HashMap::new();
2063 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2064 /// ("poneyland", "hoho".to_string())
2067 /// assert_eq!(map["poneyland"], "hoho".to_string());
2069 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2070 pub fn or_insert_with
<F
>(self, default: F
) -> (&'a
mut K
, &'a
mut V
)
2071 where F
: FnOnce() -> (K
, V
),
2076 RawEntryMut
::Occupied(entry
) => entry
.into_key_value(),
2077 RawEntryMut
::Vacant(entry
) => {
2078 let (k
, v
) = default();
2084 /// Provides in-place mutable access to an occupied entry before any
2085 /// potential inserts into the map.
2090 /// #![feature(hash_raw_entry)]
2091 /// use std::collections::HashMap;
2093 /// let mut map: HashMap<&str, u32> = HashMap::new();
2095 /// map.raw_entry_mut()
2096 /// .from_key("poneyland")
2097 /// .and_modify(|_k, v| { *v += 1 })
2098 /// .or_insert("poneyland", 42);
2099 /// assert_eq!(map["poneyland"], 42);
2101 /// map.raw_entry_mut()
2102 /// .from_key("poneyland")
2103 /// .and_modify(|_k, v| { *v += 1 })
2104 /// .or_insert("poneyland", 0);
2105 /// assert_eq!(map["poneyland"], 43);
2107 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2108 pub fn and_modify
<F
>(self, f
: F
) -> Self
2109 where F
: FnOnce(&mut K
, &mut V
)
2112 RawEntryMut
::Occupied(mut entry
) => {
2114 let (k
, v
) = entry
.get_key_value_mut();
2117 RawEntryMut
::Occupied(entry
)
2119 RawEntryMut
::Vacant(entry
) => RawEntryMut
::Vacant(entry
),
2124 impl<'a
, K
, V
> RawOccupiedEntryMut
<'a
, K
, V
> {
2125 /// Gets a reference to the key in the entry.
2126 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2127 pub fn key(&self) -> &K
{
2131 /// Gets a mutable reference to the key in the entry.
2132 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2133 pub fn key_mut(&mut self) -> &mut K
{
2134 self.elem
.read_mut().0
2137 /// Converts the entry into a mutable reference to the key in the entry
2138 /// with a lifetime bound to the map itself.
2139 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2140 pub fn into_key(self) -> &'a
mut K
{
2141 self.elem
.into_mut_refs().0
2144 /// Gets a reference to the value in the entry.
2145 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2146 pub fn get(&self) -> &V
{
2150 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2151 /// with a lifetime bound to the map itself.
2152 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2153 pub fn into_mut(self) -> &'a
mut V
{
2154 self.elem
.into_mut_refs().1
2157 /// Gets a mutable reference to the value in the entry.
2158 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2159 pub fn get_mut(&mut self) -> &mut V
{
2160 self.elem
.read_mut().1
2163 /// Gets a reference to the key and value in the entry.
2164 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2165 pub fn get_key_value(&mut self) -> (&K
, &V
) {
2169 /// Gets a mutable reference to the key and value in the entry.
2170 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2171 pub fn get_key_value_mut(&mut self) -> (&mut K
, &mut V
) {
2172 self.elem
.read_mut()
2175 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2176 /// with a lifetime bound to the map itself.
2177 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2178 pub fn into_key_value(self) -> (&'a
mut K
, &'a
mut V
) {
2179 self.elem
.into_mut_refs()
2182 /// Sets the value of the entry, and returns the entry's old value.
2183 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2184 pub fn insert(&mut self, value
: V
) -> V
{
2185 mem
::replace(self.get_mut(), value
)
2188 /// Sets the value of the entry, and returns the entry's old value.
2189 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2190 pub fn insert_key(&mut self, key
: K
) -> K
{
2191 mem
::replace(self.key_mut(), key
)
2194 /// Takes the value out of the entry, and returns it.
2195 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2196 pub fn remove(self) -> V
{
2197 pop_internal(self.elem
).1
2200 /// Take the ownership of the key and value from the map.
2201 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2202 pub fn remove_entry(self) -> (K
, V
) {
2203 let (k
, v
, _
) = pop_internal(self.elem
);
2208 impl<'a
, K
, V
, S
> RawVacantEntryMut
<'a
, K
, V
, S
> {
2209 /// Sets the value of the entry with the VacantEntry's key,
2210 /// and returns a mutable reference to it.
2211 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2212 pub fn insert(self, key
: K
, value
: V
) -> (&'a
mut K
, &'a
mut V
)
2216 let mut hasher
= self.hash_builder
.build_hasher();
2217 key
.hash(&mut hasher
);
2218 self.insert_hashed_nocheck(hasher
.finish(), key
, value
)
2221 /// Sets the value of the entry with the VacantEntry's key,
2222 /// and returns a mutable reference to it.
2224 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2225 pub fn insert_hashed_nocheck(self, hash
: u64, key
: K
, value
: V
) -> (&'a
mut K
, &'a
mut V
) {
2226 let hash
= SafeHash
::new(hash
);
2227 let b
= match self.elem
{
2228 NeqElem(mut bucket
, disp
) => {
2229 if disp
>= DISPLACEMENT_THRESHOLD
{
2230 bucket
.table_mut().set_tag(true);
2232 robin_hood(bucket
, disp
, hash
, key
, value
)
2234 NoElem(mut bucket
, disp
) => {
2235 if disp
>= DISPLACEMENT_THRESHOLD
{
2236 bucket
.table_mut().set_tag(true);
2238 bucket
.put(hash
, key
, value
)
2245 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2246 impl<K
, V
, S
> Debug
for RawEntryBuilderMut
<'_
, K
, V
, S
> {
2247 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2248 f
.debug_struct("RawEntryBuilder")
2253 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2254 impl<K
: Debug
, V
: Debug
, S
> Debug
for RawEntryMut
<'_
, K
, V
, S
> {
2255 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2257 RawEntryMut
::Vacant(ref v
) => {
2258 f
.debug_tuple("RawEntry")
2262 RawEntryMut
::Occupied(ref o
) => {
2263 f
.debug_tuple("RawEntry")
2271 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2272 impl<K
: Debug
, V
: Debug
> Debug
for RawOccupiedEntryMut
<'_
, K
, V
> {
2273 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2274 f
.debug_struct("RawOccupiedEntryMut")
2275 .field("key", self.key())
2276 .field("value", self.get())
2281 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2282 impl<K
, V
, S
> Debug
for RawVacantEntryMut
<'_
, K
, V
, S
> {
2283 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2284 f
.debug_struct("RawVacantEntryMut")
2289 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2290 impl<K
, V
, S
> Debug
for RawEntryBuilder
<'_
, K
, V
, S
> {
2291 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2292 f
.debug_struct("RawEntryBuilder")
2297 /// A view into a single entry in a map, which may either be vacant or occupied.
2299 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2301 /// [`HashMap`]: struct.HashMap.html
2302 /// [`entry`]: struct.HashMap.html#method.entry
2303 #[stable(feature = "rust1", since = "1.0.0")]
2304 pub enum Entry
<'a
, K
: 'a
, V
: 'a
> {
2305 /// An occupied entry.
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2308 OccupiedEntry
<'a
, K
, V
>),
2311 #[stable(feature = "rust1", since = "1.0.0")]
2312 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2313 VacantEntry
<'a
, K
, V
>),
2316 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2317 impl<K
: Debug
, V
: Debug
> Debug
for Entry
<'_
, K
, V
> {
2318 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2321 f
.debug_tuple("Entry")
2325 Occupied(ref o
) => {
2326 f
.debug_tuple("Entry")
2334 /// A view into an occupied entry in a `HashMap`.
2335 /// It is part of the [`Entry`] enum.
2337 /// [`Entry`]: enum.Entry.html
2338 #[stable(feature = "rust1", since = "1.0.0")]
2339 pub struct OccupiedEntry
<'a
, K
: 'a
, V
: 'a
> {
2341 elem
: FullBucket
<K
, V
, &'a
mut RawTable
<K
, V
>>,
2344 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2345 impl<K
: Debug
, V
: Debug
> Debug
for OccupiedEntry
<'_
, K
, V
> {
2346 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2347 f
.debug_struct("OccupiedEntry")
2348 .field("key", self.key())
2349 .field("value", self.get())
2354 /// A view into a vacant entry in a `HashMap`.
2355 /// It is part of the [`Entry`] enum.
2357 /// [`Entry`]: enum.Entry.html
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 pub struct VacantEntry
<'a
, K
: 'a
, V
: 'a
> {
2362 elem
: VacantEntryState
<K
, V
, &'a
mut RawTable
<K
, V
>>,
2365 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2366 impl<K
: Debug
, V
> Debug
for VacantEntry
<'_
, K
, V
> {
2367 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2368 f
.debug_tuple("VacantEntry")
2374 /// Possible states of a VacantEntry.
2375 enum VacantEntryState
<K
, V
, M
> {
2376 /// The index is occupied, but the key to insert has precedence,
2377 /// and will kick the current one out on insertion.
2378 NeqElem(FullBucket
<K
, V
, M
>, usize),
2379 /// The index is genuinely vacant.
2380 NoElem(EmptyBucket
<K
, V
, M
>, usize),
2383 #[stable(feature = "rust1", since = "1.0.0")]
2384 impl<'a
, K
, V
, S
> IntoIterator
for &'a HashMap
<K
, V
, S
> {
2385 type Item
= (&'a K
, &'a V
);
2386 type IntoIter
= Iter
<'a
, K
, V
>;
2388 fn into_iter(self) -> Iter
<'a
, K
, V
> {
2393 #[stable(feature = "rust1", since = "1.0.0")]
2394 impl<'a
, K
, V
, S
> IntoIterator
for &'a
mut HashMap
<K
, V
, S
> {
2395 type Item
= (&'a K
, &'a
mut V
);
2396 type IntoIter
= IterMut
<'a
, K
, V
>;
2398 fn into_iter(self) -> IterMut
<'a
, K
, V
> {
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl<K
, V
, S
> IntoIterator
for HashMap
<K
, V
, S
> {
2406 type IntoIter
= IntoIter
<K
, V
>;
2408 /// Creates a consuming iterator, that is, one that moves each key-value
2409 /// pair out of the map in arbitrary order. The map cannot be used after
2415 /// use std::collections::HashMap;
2417 /// let mut map = HashMap::new();
2418 /// map.insert("a", 1);
2419 /// map.insert("b", 2);
2420 /// map.insert("c", 3);
2422 /// // Not possible with .iter()
2423 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2425 fn into_iter(self) -> IntoIter
<K
, V
> {
2426 IntoIter { inner: self.table.into_iter() }
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 impl<'a
, K
, V
> Iterator
for Iter
<'a
, K
, V
> {
2432 type Item
= (&'a K
, &'a V
);
2435 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
2439 fn size_hint(&self) -> (usize, Option
<usize>) {
2440 self.inner
.size_hint()
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 impl<K
, V
> ExactSizeIterator
for Iter
<'_
, K
, V
> {
2446 fn len(&self) -> usize {
2451 #[stable(feature = "fused", since = "1.26.0")]
2452 impl<K
, V
> FusedIterator
for Iter
<'_
, K
, V
> {}
2454 #[stable(feature = "rust1", since = "1.0.0")]
2455 impl<'a
, K
, V
> Iterator
for IterMut
<'a
, K
, V
> {
2456 type Item
= (&'a K
, &'a
mut V
);
2459 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
2463 fn size_hint(&self) -> (usize, Option
<usize>) {
2464 self.inner
.size_hint()
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl<K
, V
> ExactSizeIterator
for IterMut
<'_
, K
, V
> {
2470 fn len(&self) -> usize {
2474 #[stable(feature = "fused", since = "1.26.0")]
2475 impl<K
, V
> FusedIterator
for IterMut
<'_
, K
, V
> {}
2477 #[stable(feature = "std_debug", since = "1.16.0")]
2478 impl<K
, V
> fmt
::Debug
for IterMut
<'_
, K
, V
>
2479 where K
: fmt
::Debug
,
2482 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2484 .entries(self.inner
.iter())
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<K
, V
> Iterator
for IntoIter
<K
, V
> {
2494 fn next(&mut self) -> Option
<(K
, V
)> {
2495 self.inner
.next().map(|(_
, k
, v
)| (k
, v
))
2498 fn size_hint(&self) -> (usize, Option
<usize>) {
2499 self.inner
.size_hint()
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl<K
, V
> ExactSizeIterator
for IntoIter
<K
, V
> {
2505 fn len(&self) -> usize {
2509 #[stable(feature = "fused", since = "1.26.0")]
2510 impl<K
, V
> FusedIterator
for IntoIter
<K
, V
> {}
2512 #[stable(feature = "std_debug", since = "1.16.0")]
2513 impl<K
: Debug
, V
: Debug
> fmt
::Debug
for IntoIter
<K
, V
> {
2514 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2516 .entries(self.inner
.iter())
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<'a
, K
, V
> Iterator
for Keys
<'a
, K
, V
> {
2526 fn next(&mut self) -> Option
<(&'a K
)> {
2527 self.inner
.next().map(|(k
, _
)| k
)
2530 fn size_hint(&self) -> (usize, Option
<usize>) {
2531 self.inner
.size_hint()
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 impl<K
, V
> ExactSizeIterator
for Keys
<'_
, K
, V
> {
2537 fn len(&self) -> usize {
2541 #[stable(feature = "fused", since = "1.26.0")]
2542 impl<K
, V
> FusedIterator
for Keys
<'_
, K
, V
> {}
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<'a
, K
, V
> Iterator
for Values
<'a
, K
, V
> {
2549 fn next(&mut self) -> Option
<(&'a V
)> {
2550 self.inner
.next().map(|(_
, v
)| v
)
2553 fn size_hint(&self) -> (usize, Option
<usize>) {
2554 self.inner
.size_hint()
2557 #[stable(feature = "rust1", since = "1.0.0")]
2558 impl<K
, V
> ExactSizeIterator
for Values
<'_
, K
, V
> {
2560 fn len(&self) -> usize {
2564 #[stable(feature = "fused", since = "1.26.0")]
2565 impl<K
, V
> FusedIterator
for Values
<'_
, K
, V
> {}
2567 #[stable(feature = "map_values_mut", since = "1.10.0")]
2568 impl<'a
, K
, V
> Iterator
for ValuesMut
<'a
, K
, V
> {
2569 type Item
= &'a
mut V
;
2572 fn next(&mut self) -> Option
<(&'a
mut V
)> {
2573 self.inner
.next().map(|(_
, v
)| v
)
2576 fn size_hint(&self) -> (usize, Option
<usize>) {
2577 self.inner
.size_hint()
2580 #[stable(feature = "map_values_mut", since = "1.10.0")]
2581 impl<K
, V
> ExactSizeIterator
for ValuesMut
<'_
, K
, V
> {
2583 fn len(&self) -> usize {
2587 #[stable(feature = "fused", since = "1.26.0")]
2588 impl<K
, V
> FusedIterator
for ValuesMut
<'_
, K
, V
> {}
2590 #[stable(feature = "std_debug", since = "1.16.0")]
2591 impl<K
, V
> fmt
::Debug
for ValuesMut
<'_
, K
, V
>
2592 where K
: fmt
::Debug
,
2595 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2597 .entries(self.inner
.inner
.iter())
2602 #[stable(feature = "drain", since = "1.6.0")]
2603 impl<'a
, K
, V
> Iterator
for Drain
<'a
, K
, V
> {
2607 fn next(&mut self) -> Option
<(K
, V
)> {
2608 self.inner
.next().map(|(_
, k
, v
)| (k
, v
))
2611 fn size_hint(&self) -> (usize, Option
<usize>) {
2612 self.inner
.size_hint()
2615 #[stable(feature = "drain", since = "1.6.0")]
2616 impl<K
, V
> ExactSizeIterator
for Drain
<'_
, K
, V
> {
2618 fn len(&self) -> usize {
2622 #[stable(feature = "fused", since = "1.26.0")]
2623 impl<K
, V
> FusedIterator
for Drain
<'_
, K
, V
> {}
2625 #[stable(feature = "std_debug", since = "1.16.0")]
2626 impl<K
, V
> fmt
::Debug
for Drain
<'_
, K
, V
>
2627 where K
: fmt
::Debug
,
2630 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2632 .entries(self.inner
.iter())
2637 impl<'a
, K
, V
> Entry
<'a
, K
, V
> {
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 /// Ensures a value is in the entry by inserting the default if empty, and returns
2640 /// a mutable reference to the value in the entry.
2645 /// use std::collections::HashMap;
2647 /// let mut map: HashMap<&str, u32> = HashMap::new();
2649 /// map.entry("poneyland").or_insert(3);
2650 /// assert_eq!(map["poneyland"], 3);
2652 /// *map.entry("poneyland").or_insert(10) *= 2;
2653 /// assert_eq!(map["poneyland"], 6);
2655 pub fn or_insert(self, default: V
) -> &'a
mut V
{
2657 Occupied(entry
) => entry
.into_mut(),
2658 Vacant(entry
) => entry
.insert(default),
2662 #[stable(feature = "rust1", since = "1.0.0")]
2663 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2664 /// and returns a mutable reference to the value in the entry.
2669 /// use std::collections::HashMap;
2671 /// let mut map: HashMap<&str, String> = HashMap::new();
2672 /// let s = "hoho".to_string();
2674 /// map.entry("poneyland").or_insert_with(|| s);
2676 /// assert_eq!(map["poneyland"], "hoho".to_string());
2678 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
2680 Occupied(entry
) => entry
.into_mut(),
2681 Vacant(entry
) => entry
.insert(default()),
2685 /// Returns a reference to this entry's key.
2690 /// use std::collections::HashMap;
2692 /// let mut map: HashMap<&str, u32> = HashMap::new();
2693 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2695 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2696 pub fn key(&self) -> &K
{
2698 Occupied(ref entry
) => entry
.key(),
2699 Vacant(ref entry
) => entry
.key(),
2703 /// Provides in-place mutable access to an occupied entry before any
2704 /// potential inserts into the map.
2709 /// use std::collections::HashMap;
2711 /// let mut map: HashMap<&str, u32> = HashMap::new();
2713 /// map.entry("poneyland")
2714 /// .and_modify(|e| { *e += 1 })
2716 /// assert_eq!(map["poneyland"], 42);
2718 /// map.entry("poneyland")
2719 /// .and_modify(|e| { *e += 1 })
2721 /// assert_eq!(map["poneyland"], 43);
2723 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2724 pub fn and_modify
<F
>(self, f
: F
) -> Self
2725 where F
: FnOnce(&mut V
)
2728 Occupied(mut entry
) => {
2732 Vacant(entry
) => Vacant(entry
),
2738 impl<'a
, K
, V
: Default
> Entry
<'a
, K
, V
> {
2739 #[stable(feature = "entry_or_default", since = "1.28.0")]
2740 /// Ensures a value is in the entry by inserting the default value if empty,
2741 /// and returns a mutable reference to the value in the entry.
2747 /// use std::collections::HashMap;
2749 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2750 /// map.entry("poneyland").or_default();
2752 /// assert_eq!(map["poneyland"], None);
2755 pub fn or_default(self) -> &'a
mut V
{
2757 Occupied(entry
) => entry
.into_mut(),
2758 Vacant(entry
) => entry
.insert(Default
::default()),
2763 impl<'a
, K
, V
> OccupiedEntry
<'a
, K
, V
> {
2764 /// Gets a reference to the key in the entry.
2769 /// use std::collections::HashMap;
2771 /// let mut map: HashMap<&str, u32> = HashMap::new();
2772 /// map.entry("poneyland").or_insert(12);
2773 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2775 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2776 pub fn key(&self) -> &K
{
2780 /// Take the ownership of the key and value from the map.
2785 /// use std::collections::HashMap;
2786 /// use std::collections::hash_map::Entry;
2788 /// let mut map: HashMap<&str, u32> = HashMap::new();
2789 /// map.entry("poneyland").or_insert(12);
2791 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2792 /// // We delete the entry from the map.
2793 /// o.remove_entry();
2796 /// assert_eq!(map.contains_key("poneyland"), false);
2798 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2799 pub fn remove_entry(self) -> (K
, V
) {
2800 let (k
, v
, _
) = pop_internal(self.elem
);
2804 /// Gets a reference to the value in the entry.
2809 /// use std::collections::HashMap;
2810 /// use std::collections::hash_map::Entry;
2812 /// let mut map: HashMap<&str, u32> = HashMap::new();
2813 /// map.entry("poneyland").or_insert(12);
2815 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2816 /// assert_eq!(o.get(), &12);
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 pub fn get(&self) -> &V
{
2824 /// Gets a mutable reference to the value in the entry.
2826 /// If you need a reference to the `OccupiedEntry` which may outlive the
2827 /// destruction of the `Entry` value, see [`into_mut`].
2829 /// [`into_mut`]: #method.into_mut
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 /// assert_eq!(map["poneyland"], 12);
2841 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2842 /// *o.get_mut() += 10;
2843 /// assert_eq!(*o.get(), 22);
2845 /// // We can use the same Entry multiple times.
2846 /// *o.get_mut() += 2;
2849 /// assert_eq!(map["poneyland"], 24);
2851 #[stable(feature = "rust1", since = "1.0.0")]
2852 pub fn get_mut(&mut self) -> &mut V
{
2853 self.elem
.read_mut().1
2856 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2857 /// with a lifetime bound to the map itself.
2859 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2861 /// [`get_mut`]: #method.get_mut
2866 /// use std::collections::HashMap;
2867 /// use std::collections::hash_map::Entry;
2869 /// let mut map: HashMap<&str, u32> = HashMap::new();
2870 /// map.entry("poneyland").or_insert(12);
2872 /// assert_eq!(map["poneyland"], 12);
2873 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2874 /// *o.into_mut() += 10;
2877 /// assert_eq!(map["poneyland"], 22);
2879 #[stable(feature = "rust1", since = "1.0.0")]
2880 pub fn into_mut(self) -> &'a
mut V
{
2881 self.elem
.into_mut_refs().1
2884 /// Sets the value of the entry, and returns the entry's old value.
2889 /// use std::collections::HashMap;
2890 /// use std::collections::hash_map::Entry;
2892 /// let mut map: HashMap<&str, u32> = HashMap::new();
2893 /// map.entry("poneyland").or_insert(12);
2895 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2896 /// assert_eq!(o.insert(15), 12);
2899 /// assert_eq!(map["poneyland"], 15);
2901 #[stable(feature = "rust1", since = "1.0.0")]
2902 pub fn insert(&mut self, mut value
: V
) -> V
{
2903 let old_value
= self.get_mut();
2904 mem
::swap(&mut value
, old_value
);
2908 /// Takes the value out of the entry, and returns it.
2913 /// use std::collections::HashMap;
2914 /// use std::collections::hash_map::Entry;
2916 /// let mut map: HashMap<&str, u32> = HashMap::new();
2917 /// map.entry("poneyland").or_insert(12);
2919 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2920 /// assert_eq!(o.remove(), 12);
2923 /// assert_eq!(map.contains_key("poneyland"), false);
2925 #[stable(feature = "rust1", since = "1.0.0")]
2926 pub fn remove(self) -> V
{
2927 pop_internal(self.elem
).1
2930 /// Returns a key that was used for search.
2932 /// The key was retained for further use.
2933 fn take_key(&mut self) -> Option
<K
> {
2937 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2938 /// the key used to create this entry.
2943 /// #![feature(map_entry_replace)]
2944 /// use std::collections::hash_map::{Entry, HashMap};
2945 /// use std::rc::Rc;
2947 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2948 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2950 /// let my_key = Rc::new("Stringthing".to_string());
2952 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2953 /// // Also replace the key with a handle to our other key.
2954 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2958 #[unstable(feature = "map_entry_replace", issue = "44286")]
2959 pub fn replace_entry(mut self, value
: V
) -> (K
, V
) {
2960 let (old_key
, old_value
) = self.elem
.read_mut();
2962 let old_key
= mem
::replace(old_key
, self.key
.unwrap());
2963 let old_value
= mem
::replace(old_value
, value
);
2965 (old_key
, old_value
)
2968 /// Replaces the key in the hash map with the key used to create this entry.
2973 /// #![feature(map_entry_replace)]
2974 /// use std::collections::hash_map::{Entry, HashMap};
2975 /// use std::rc::Rc;
2977 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2978 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2980 /// // Initialise known strings, run program, etc.
2982 /// reclaim_memory(&mut map, &known_strings);
2984 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2985 /// for s in known_strings {
2986 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2987 /// // Replaces the entry's key with our version of it in `known_strings`.
2988 /// entry.replace_key();
2993 #[unstable(feature = "map_entry_replace", issue = "44286")]
2994 pub fn replace_key(mut self) -> K
{
2995 let (old_key
, _
) = self.elem
.read_mut();
2996 mem
::replace(old_key
, self.key
.unwrap())
3000 impl<'a
, K
: 'a
, V
: 'a
> VacantEntry
<'a
, K
, V
> {
3001 /// Gets a reference to the key that would be used when inserting a value
3002 /// through the `VacantEntry`.
3007 /// use std::collections::HashMap;
3009 /// let mut map: HashMap<&str, u32> = HashMap::new();
3010 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3012 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3013 pub fn key(&self) -> &K
{
3017 /// Take ownership of the key.
3022 /// use std::collections::HashMap;
3023 /// use std::collections::hash_map::Entry;
3025 /// let mut map: HashMap<&str, u32> = HashMap::new();
3027 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3031 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3032 pub fn into_key(self) -> K
{
3036 /// Sets the value of the entry with the VacantEntry's key,
3037 /// and returns a mutable reference to it.
3042 /// use std::collections::HashMap;
3043 /// use std::collections::hash_map::Entry;
3045 /// let mut map: HashMap<&str, u32> = HashMap::new();
3047 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3050 /// assert_eq!(map["poneyland"], 37);
3052 #[stable(feature = "rust1", since = "1.0.0")]
3053 pub fn insert(self, value
: V
) -> &'a
mut V
{
3054 let b
= match self.elem
{
3055 NeqElem(mut bucket
, disp
) => {
3056 if disp
>= DISPLACEMENT_THRESHOLD
{
3057 bucket
.table_mut().set_tag(true);
3059 robin_hood(bucket
, disp
, self.hash
, self.key
, value
)
3061 NoElem(mut bucket
, disp
) => {
3062 if disp
>= DISPLACEMENT_THRESHOLD
{
3063 bucket
.table_mut().set_tag(true);
3065 bucket
.put(self.hash
, self.key
, value
)
3072 #[stable(feature = "rust1", since = "1.0.0")]
3073 impl<K
, V
, S
> FromIterator
<(K
, V
)> for HashMap
<K
, V
, S
>
3075 S
: BuildHasher
+ Default
3077 fn from_iter
<T
: IntoIterator
<Item
= (K
, V
)>>(iter
: T
) -> HashMap
<K
, V
, S
> {
3078 let mut map
= HashMap
::with_hasher(Default
::default());
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 impl<K
, V
, S
> Extend
<(K
, V
)> for HashMap
<K
, V
, S
>
3089 fn extend
<T
: IntoIterator
<Item
= (K
, V
)>>(&mut self, iter
: T
) {
3090 // Keys may be already present or show multiple times in the iterator.
3091 // Reserve the entire hint lower bound if the map is empty.
3092 // Otherwise reserve half the hint (rounded up), so the map
3093 // will only resize twice in the worst case.
3094 let iter
= iter
.into_iter();
3095 let reserve
= if self.is_empty() {
3098 (iter
.size_hint().0 + 1) / 2
3100 self.reserve(reserve
);
3101 for (k
, v
) in iter
{
3107 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3108 impl<'a
, K
, V
, S
> Extend
<(&'a K
, &'a V
)> for HashMap
<K
, V
, S
>
3109 where K
: Eq
+ Hash
+ Copy
,
3113 fn extend
<T
: IntoIterator
<Item
= (&'a K
, &'a V
)>>(&mut self, iter
: T
) {
3114 self.extend(iter
.into_iter().map(|(&key
, &value
)| (key
, value
)));
3118 /// `RandomState` is the default state for [`HashMap`] types.
3120 /// A particular instance `RandomState` will create the same instances of
3121 /// [`Hasher`], but the hashers created by two different `RandomState`
3122 /// instances are unlikely to produce the same result for the same values.
3124 /// [`HashMap`]: struct.HashMap.html
3125 /// [`Hasher`]: ../../hash/trait.Hasher.html
3130 /// use std::collections::HashMap;
3131 /// use std::collections::hash_map::RandomState;
3133 /// let s = RandomState::new();
3134 /// let mut map = HashMap::with_hasher(s);
3135 /// map.insert(1, 2);
3138 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3139 pub struct RandomState
{
3145 /// Constructs a new `RandomState` that is initialized with random keys.
3150 /// use std::collections::hash_map::RandomState;
3152 /// let s = RandomState::new();
3155 #[allow(deprecated)]
3157 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3158 pub fn new() -> RandomState
{
3159 // Historically this function did not cache keys from the OS and instead
3160 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3161 // was discovered, however, that because we re-seed the thread-local RNG
3162 // from the OS periodically that this can cause excessive slowdown when
3163 // many hash maps are created on a thread. To solve this performance
3164 // trap we cache the first set of randomly generated keys per-thread.
3166 // Later in #36481 it was discovered that exposing a deterministic
3167 // iteration order allows a form of DOS attack. To counter that we
3168 // increment one of the seeds on every RandomState creation, giving
3169 // every corresponding HashMap a different iteration order.
3170 thread_local
!(static KEYS
: Cell
<(u64, u64)> = {
3171 Cell
::new(sys
::hashmap_random_keys())
3175 let (k0
, k1
) = keys
.get();
3176 keys
.set((k0
.wrapping_add(1), k1
));
3177 RandomState { k0: k0, k1: k1 }
3182 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3183 impl BuildHasher
for RandomState
{
3184 type Hasher
= DefaultHasher
;
3186 #[allow(deprecated)]
3187 fn build_hasher(&self) -> DefaultHasher
{
3188 DefaultHasher(SipHasher13
::new_with_keys(self.k0
, self.k1
))
3192 /// The default [`Hasher`] used by [`RandomState`].
3194 /// The internal algorithm is not specified, and so it and its hashes should
3195 /// not be relied upon over releases.
3197 /// [`RandomState`]: struct.RandomState.html
3198 /// [`Hasher`]: ../../hash/trait.Hasher.html
3199 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3200 #[allow(deprecated)]
3201 #[derive(Clone, Debug)]
3202 pub struct DefaultHasher(SipHasher13
);
3204 impl DefaultHasher
{
3205 /// Creates a new `DefaultHasher`.
3207 /// This hasher is not guaranteed to be the same as all other
3208 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3209 /// instances created through `new` or `default`.
3210 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3211 #[allow(deprecated)]
3212 pub fn new() -> DefaultHasher
{
3213 DefaultHasher(SipHasher13
::new_with_keys(0, 0))
3217 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3218 impl Default
for DefaultHasher
{
3219 /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3220 /// See its documentation for more.
3221 fn default() -> DefaultHasher
{
3222 DefaultHasher
::new()
3226 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3227 impl Hasher
for DefaultHasher
{
3229 fn write(&mut self, msg
: &[u8]) {
3234 fn finish(&self) -> u64 {
3239 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3240 impl Default
for RandomState
{
3241 /// Constructs a new `RandomState`.
3243 fn default() -> RandomState
{
3248 #[stable(feature = "std_debug", since = "1.16.0")]
3249 impl fmt
::Debug
for RandomState
{
3250 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
3251 f
.pad("RandomState { .. }")
3255 impl<K
, S
, Q
: ?Sized
> super::Recover
<Q
> for HashMap
<K
, (), S
>
3256 where K
: Eq
+ Hash
+ Borrow
<Q
>,
3263 fn get(&self, key
: &Q
) -> Option
<&K
> {
3264 self.search(key
).map(|bucket
| bucket
.into_refs().0)
3267 fn take(&mut self, key
: &Q
) -> Option
<K
> {
3268 self.search_mut(key
).map(|bucket
| pop_internal(bucket
).0)
3272 fn replace(&mut self, key
: K
) -> Option
<K
> {
3275 match self.entry(key
) {
3276 Occupied(mut occupied
) => {
3277 let key
= occupied
.take_key().unwrap();
3278 Some(mem
::replace(occupied
.elem
.read_mut().0, key
))
3289 fn assert_covariance() {
3290 fn map_key
<'new
>(v
: HashMap
<&'
static str, u8>) -> HashMap
<&'new
str, u8> {
3293 fn map_val
<'new
>(v
: HashMap
<u8, &'
static str>) -> HashMap
<u8, &'new
str> {
3296 fn iter_key
<'a
, 'new
>(v
: Iter
<'a
, &'
static str, u8>) -> Iter
<'a
, &'new
str, u8> {
3299 fn iter_val
<'a
, 'new
>(v
: Iter
<'a
, u8, &'
static str>) -> Iter
<'a
, u8, &'new
str> {
3302 fn into_iter_key
<'new
>(v
: IntoIter
<&'
static str, u8>) -> IntoIter
<&'new
str, u8> {
3305 fn into_iter_val
<'new
>(v
: IntoIter
<u8, &'
static str>) -> IntoIter
<u8, &'new
str> {
3308 fn keys_key
<'a
, 'new
>(v
: Keys
<'a
, &'
static str, u8>) -> Keys
<'a
, &'new
str, u8> {
3311 fn keys_val
<'a
, 'new
>(v
: Keys
<'a
, u8, &'
static str>) -> Keys
<'a
, u8, &'new
str> {
3314 fn values_key
<'a
, 'new
>(v
: Values
<'a
, &'
static str, u8>) -> Values
<'a
, &'new
str, u8> {
3317 fn values_val
<'a
, 'new
>(v
: Values
<'a
, u8, &'
static str>) -> Values
<'a
, u8, &'new
str> {
3320 fn drain
<'new
>(d
: Drain
<'
static, &'
static str, &'
static str>)
3321 -> Drain
<'new
, &'new
str, &'new
str> {
3329 use super::Entry
::{Occupied, Vacant}
;
3330 use super::RandomState
;
3332 use rand
::{thread_rng, Rng}
;
3333 use realstd
::collections
::CollectionAllocErr
::*;
3334 use realstd
::mem
::size_of
;
3338 fn test_zero_capacities() {
3339 type HM
= HashMap
<i32, i32>;
3342 assert_eq
!(m
.capacity(), 0);
3344 let m
= HM
::default();
3345 assert_eq
!(m
.capacity(), 0);
3347 let m
= HM
::with_hasher(RandomState
::new());
3348 assert_eq
!(m
.capacity(), 0);
3350 let m
= HM
::with_capacity(0);
3351 assert_eq
!(m
.capacity(), 0);
3353 let m
= HM
::with_capacity_and_hasher(0, RandomState
::new());
3354 assert_eq
!(m
.capacity(), 0);
3356 let mut m
= HM
::new();
3362 assert_eq
!(m
.capacity(), 0);
3364 let mut m
= HM
::new();
3366 assert_eq
!(m
.capacity(), 0);
3370 fn test_create_capacity_zero() {
3371 let mut m
= HashMap
::with_capacity(0);
3373 assert
!(m
.insert(1, 1).is_none());
3375 assert
!(m
.contains_key(&1));
3376 assert
!(!m
.contains_key(&0));
3381 let mut m
= HashMap
::new();
3382 assert_eq
!(m
.len(), 0);
3383 assert
!(m
.insert(1, 2).is_none());
3384 assert_eq
!(m
.len(), 1);
3385 assert
!(m
.insert(2, 4).is_none());
3386 assert_eq
!(m
.len(), 2);
3387 assert_eq
!(*m
.get(&1).unwrap(), 2);
3388 assert_eq
!(*m
.get(&2).unwrap(), 4);
3393 let mut m
= HashMap
::new();
3394 assert_eq
!(m
.len(), 0);
3395 assert
!(m
.insert(1, 2).is_none());
3396 assert_eq
!(m
.len(), 1);
3397 assert
!(m
.insert(2, 4).is_none());
3398 assert_eq
!(m
.len(), 2);
3400 assert_eq
!(*m2
.get(&1).unwrap(), 2);
3401 assert_eq
!(*m2
.get(&2).unwrap(), 4);
3402 assert_eq
!(m2
.len(), 2);
3405 thread_local
! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3407 #[derive(Hash, PartialEq, Eq)]
3413 fn new(k
: usize) -> Droppable
{
3414 DROP_VECTOR
.with(|slot
| {
3415 slot
.borrow_mut()[k
] += 1;
3422 impl Drop
for Droppable
{
3423 fn drop(&mut self) {
3424 DROP_VECTOR
.with(|slot
| {
3425 slot
.borrow_mut()[self.k
] -= 1;
3430 impl Clone
for Droppable
{
3431 fn clone(&self) -> Droppable
{
3432 Droppable
::new(self.k
)
3438 DROP_VECTOR
.with(|slot
| {
3439 *slot
.borrow_mut() = vec
![0; 200];
3443 let mut m
= HashMap
::new();
3445 DROP_VECTOR
.with(|v
| {
3447 assert_eq
!(v
.borrow()[i
], 0);
3452 let d1
= Droppable
::new(i
);
3453 let d2
= Droppable
::new(i
+ 100);
3457 DROP_VECTOR
.with(|v
| {
3459 assert_eq
!(v
.borrow()[i
], 1);
3464 let k
= Droppable
::new(i
);
3465 let v
= m
.remove(&k
);
3467 assert
!(v
.is_some());
3469 DROP_VECTOR
.with(|v
| {
3470 assert_eq
!(v
.borrow()[i
], 1);
3471 assert_eq
!(v
.borrow()[i
+100], 1);
3475 DROP_VECTOR
.with(|v
| {
3477 assert_eq
!(v
.borrow()[i
], 0);
3478 assert_eq
!(v
.borrow()[i
+100], 0);
3482 assert_eq
!(v
.borrow()[i
], 1);
3483 assert_eq
!(v
.borrow()[i
+100], 1);
3488 DROP_VECTOR
.with(|v
| {
3490 assert_eq
!(v
.borrow()[i
], 0);
3496 fn test_into_iter_drops() {
3497 DROP_VECTOR
.with(|v
| {
3498 *v
.borrow_mut() = vec
![0; 200];
3502 let mut hm
= HashMap
::new();
3504 DROP_VECTOR
.with(|v
| {
3506 assert_eq
!(v
.borrow()[i
], 0);
3511 let d1
= Droppable
::new(i
);
3512 let d2
= Droppable
::new(i
+ 100);
3516 DROP_VECTOR
.with(|v
| {
3518 assert_eq
!(v
.borrow()[i
], 1);
3525 // By the way, ensure that cloning doesn't screw up the dropping.
3529 let mut half
= hm
.into_iter().take(50);
3531 DROP_VECTOR
.with(|v
| {
3533 assert_eq
!(v
.borrow()[i
], 1);
3537 for _
in half
.by_ref() {}
3539 DROP_VECTOR
.with(|v
| {
3541 .filter(|&i
| v
.borrow()[i
] == 1)
3545 .filter(|&i
| v
.borrow()[i
+ 100] == 1)
3553 DROP_VECTOR
.with(|v
| {
3555 assert_eq
!(v
.borrow()[i
], 0);
3561 fn test_empty_remove() {
3562 let mut m
: HashMap
<i32, bool
> = HashMap
::new();
3563 assert_eq
!(m
.remove(&0), None
);
3567 fn test_empty_entry() {
3568 let mut m
: HashMap
<i32, bool
> = HashMap
::new();
3570 Occupied(_
) => panic
!(),
3573 assert
!(*m
.entry(0).or_insert(true));
3574 assert_eq
!(m
.len(), 1);
3578 fn test_empty_iter() {
3579 let mut m
: HashMap
<i32, bool
> = HashMap
::new();
3580 assert_eq
!(m
.drain().next(), None
);
3581 assert_eq
!(m
.keys().next(), None
);
3582 assert_eq
!(m
.values().next(), None
);
3583 assert_eq
!(m
.values_mut().next(), None
);
3584 assert_eq
!(m
.iter().next(), None
);
3585 assert_eq
!(m
.iter_mut().next(), None
);
3586 assert_eq
!(m
.len(), 0);
3587 assert
!(m
.is_empty());
3588 assert_eq
!(m
.into_iter().next(), None
);
3592 fn test_lots_of_insertions() {
3593 let mut m
= HashMap
::new();
3595 // Try this a few times to make sure we never screw up the hashmap's
3598 assert
!(m
.is_empty());
3601 assert
!(m
.insert(i
, i
).is_none());
3605 assert_eq
!(r
, Some(&j
));
3608 for j
in i
+ 1..1001 {
3610 assert_eq
!(r
, None
);
3614 for i
in 1001..2001 {
3615 assert
!(!m
.contains_key(&i
));
3620 assert
!(m
.remove(&i
).is_some());
3623 assert
!(!m
.contains_key(&j
));
3626 for j
in i
+ 1..1001 {
3627 assert
!(m
.contains_key(&j
));
3632 assert
!(!m
.contains_key(&i
));
3636 assert
!(m
.insert(i
, i
).is_none());
3640 for i
in (1..1001).rev() {
3641 assert
!(m
.remove(&i
).is_some());
3644 assert
!(!m
.contains_key(&j
));
3648 assert
!(m
.contains_key(&j
));
3655 fn test_find_mut() {
3656 let mut m
= HashMap
::new();
3657 assert
!(m
.insert(1, 12).is_none());
3658 assert
!(m
.insert(2, 8).is_none());
3659 assert
!(m
.insert(5, 14).is_none());
3661 match m
.get_mut(&5) {
3663 Some(x
) => *x
= new
,
3665 assert_eq
!(m
.get(&5), Some(&new
));
3669 fn test_insert_overwrite() {
3670 let mut m
= HashMap
::new();
3671 assert
!(m
.insert(1, 2).is_none());
3672 assert_eq
!(*m
.get(&1).unwrap(), 2);
3673 assert
!(!m
.insert(1, 3).is_none());
3674 assert_eq
!(*m
.get(&1).unwrap(), 3);
3678 fn test_insert_conflicts() {
3679 let mut m
= HashMap
::with_capacity(4);
3680 assert
!(m
.insert(1, 2).is_none());
3681 assert
!(m
.insert(5, 3).is_none());
3682 assert
!(m
.insert(9, 4).is_none());
3683 assert_eq
!(*m
.get(&9).unwrap(), 4);
3684 assert_eq
!(*m
.get(&5).unwrap(), 3);
3685 assert_eq
!(*m
.get(&1).unwrap(), 2);
3689 fn test_conflict_remove() {
3690 let mut m
= HashMap
::with_capacity(4);
3691 assert
!(m
.insert(1, 2).is_none());
3692 assert_eq
!(*m
.get(&1).unwrap(), 2);
3693 assert
!(m
.insert(5, 3).is_none());
3694 assert_eq
!(*m
.get(&1).unwrap(), 2);
3695 assert_eq
!(*m
.get(&5).unwrap(), 3);
3696 assert
!(m
.insert(9, 4).is_none());
3697 assert_eq
!(*m
.get(&1).unwrap(), 2);
3698 assert_eq
!(*m
.get(&5).unwrap(), 3);
3699 assert_eq
!(*m
.get(&9).unwrap(), 4);
3700 assert
!(m
.remove(&1).is_some());
3701 assert_eq
!(*m
.get(&9).unwrap(), 4);
3702 assert_eq
!(*m
.get(&5).unwrap(), 3);
3706 fn test_is_empty() {
3707 let mut m
= HashMap
::with_capacity(4);
3708 assert
!(m
.insert(1, 2).is_none());
3709 assert
!(!m
.is_empty());
3710 assert
!(m
.remove(&1).is_some());
3711 assert
!(m
.is_empty());
3716 let mut m
= HashMap
::new();
3718 assert_eq
!(m
.remove(&1), Some(2));
3719 assert_eq
!(m
.remove(&1), None
);
3723 fn test_remove_entry() {
3724 let mut m
= HashMap
::new();
3726 assert_eq
!(m
.remove_entry(&1), Some((1, 2)));
3727 assert_eq
!(m
.remove(&1), None
);
3732 let mut m
= HashMap
::with_capacity(4);
3734 assert
!(m
.insert(i
, i
*2).is_none());
3736 assert_eq
!(m
.len(), 32);
3738 let mut observed
: u32 = 0;
3741 assert_eq
!(*v
, *k
* 2);
3742 observed
|= 1 << *k
;
3744 assert_eq
!(observed
, 0xFFFF_FFFF);
3749 let vec
= vec
![(1, 'a'
), (2, 'b'
), (3, 'c'
)];
3750 let map
: HashMap
<_
, _
> = vec
.into_iter().collect();
3751 let keys
: Vec
<_
> = map
.keys().cloned().collect();
3752 assert_eq
!(keys
.len(), 3);
3753 assert
!(keys
.contains(&1));
3754 assert
!(keys
.contains(&2));
3755 assert
!(keys
.contains(&3));
3760 let vec
= vec
![(1, 'a'
), (2, 'b'
), (3, 'c'
)];
3761 let map
: HashMap
<_
, _
> = vec
.into_iter().collect();
3762 let values
: Vec
<_
> = map
.values().cloned().collect();
3763 assert_eq
!(values
.len(), 3);
3764 assert
!(values
.contains(&'a'
));
3765 assert
!(values
.contains(&'b'
));
3766 assert
!(values
.contains(&'c'
));
3770 fn test_values_mut() {
3771 let vec
= vec
![(1, 1), (2, 2), (3, 3)];
3772 let mut map
: HashMap
<_
, _
> = vec
.into_iter().collect();
3773 for value
in map
.values_mut() {
3774 *value
= (*value
) * 2
3776 let values
: Vec
<_
> = map
.values().cloned().collect();
3777 assert_eq
!(values
.len(), 3);
3778 assert
!(values
.contains(&2));
3779 assert
!(values
.contains(&4));
3780 assert
!(values
.contains(&6));
3785 let mut m
= HashMap
::new();
3786 assert
!(m
.get(&1).is_none());
3790 Some(v
) => assert_eq
!(*v
, 2),
3796 let mut m1
= HashMap
::new();
3801 let mut m2
= HashMap
::new();
3814 let mut map
= HashMap
::new();
3815 let empty
: HashMap
<i32, i32> = HashMap
::new();
3820 let map_str
= format
!("{:?}", map
);
3822 assert
!(map_str
== "{1: 2, 3: 4}" ||
3823 map_str
== "{3: 4, 1: 2}");
3824 assert_eq
!(format
!("{:?}", empty
), "{}");
3829 let mut m
= HashMap
::new();
3831 assert_eq
!(m
.len(), 0);
3832 assert
!(m
.is_empty());
3835 let old_raw_cap
= m
.raw_capacity();
3836 while old_raw_cap
== m
.raw_capacity() {
3841 assert_eq
!(m
.len(), i
);
3842 assert
!(!m
.is_empty());
3846 fn test_behavior_resize_policy() {
3847 let mut m
= HashMap
::new();
3849 assert_eq
!(m
.len(), 0);
3850 assert_eq
!(m
.raw_capacity(), 0);
3851 assert
!(m
.is_empty());
3855 assert
!(m
.is_empty());
3856 let initial_raw_cap
= m
.raw_capacity();
3857 m
.reserve(initial_raw_cap
);
3858 let raw_cap
= m
.raw_capacity();
3860 assert_eq
!(raw_cap
, initial_raw_cap
* 2);
3863 for _
in 0..raw_cap
* 3 / 4 {
3867 // three quarters full
3869 assert_eq
!(m
.len(), i
);
3870 assert_eq
!(m
.raw_capacity(), raw_cap
);
3872 for _
in 0..raw_cap
/ 4 {
3878 let new_raw_cap
= m
.raw_capacity();
3879 assert_eq
!(new_raw_cap
, raw_cap
* 2);
3881 for _
in 0..raw_cap
/ 2 - 1 {
3884 assert_eq
!(m
.raw_capacity(), new_raw_cap
);
3886 // A little more than one quarter full.
3888 assert_eq
!(m
.raw_capacity(), raw_cap
);
3889 // again, a little more than half full
3890 for _
in 0..raw_cap
/ 2 - 1 {
3896 assert_eq
!(m
.len(), i
);
3897 assert
!(!m
.is_empty());
3898 assert_eq
!(m
.raw_capacity(), initial_raw_cap
);
3902 fn test_reserve_shrink_to_fit() {
3903 let mut m
= HashMap
::new();
3906 assert
!(m
.capacity() >= m
.len());
3912 let usable_cap
= m
.capacity();
3913 for i
in 128..(128 + 256) {
3915 assert_eq
!(m
.capacity(), usable_cap
);
3918 for i
in 100..(128 + 256) {
3919 assert_eq
!(m
.remove(&i
), Some(i
));
3923 assert_eq
!(m
.len(), 100);
3924 assert
!(!m
.is_empty());
3925 assert
!(m
.capacity() >= m
.len());
3928 assert_eq
!(m
.remove(&i
), Some(i
));
3933 assert_eq
!(m
.len(), 1);
3934 assert
!(m
.capacity() >= m
.len());
3935 assert_eq
!(m
.remove(&0), Some(0));
3939 fn test_from_iter() {
3940 let xs
= [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3942 let map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
3944 for &(k
, v
) in &xs
{
3945 assert_eq
!(map
.get(&k
), Some(&v
));
3950 fn test_size_hint() {
3951 let xs
= [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3953 let map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
3955 let mut iter
= map
.iter();
3957 for _
in iter
.by_ref().take(3) {}
3959 assert_eq
!(iter
.size_hint(), (3, Some(3)));
3963 fn test_iter_len() {
3964 let xs
= [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3966 let map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
3968 let mut iter
= map
.iter();
3970 for _
in iter
.by_ref().take(3) {}
3972 assert_eq
!(iter
.len(), 3);
3976 fn test_mut_size_hint() {
3977 let xs
= [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3979 let mut map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
3981 let mut iter
= map
.iter_mut();
3983 for _
in iter
.by_ref().take(3) {}
3985 assert_eq
!(iter
.size_hint(), (3, Some(3)));
3989 fn test_iter_mut_len() {
3990 let xs
= [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3992 let mut map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
3994 let mut iter
= map
.iter_mut();
3996 for _
in iter
.by_ref().take(3) {}
3998 assert_eq
!(iter
.len(), 3);
4003 let mut map
= HashMap
::new();
4009 assert_eq
!(map
[&2], 1);
4014 fn test_index_nonexistent() {
4015 let mut map
= HashMap
::new();
4026 let xs
= [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4028 let mut map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
4030 // Existing key (insert)
4031 match map
.entry(1) {
4032 Vacant(_
) => unreachable
!(),
4033 Occupied(mut view
) => {
4034 assert_eq
!(view
.get(), &10);
4035 assert_eq
!(view
.insert(100), 10);
4038 assert_eq
!(map
.get(&1).unwrap(), &100);
4039 assert_eq
!(map
.len(), 6);
4042 // Existing key (update)
4043 match map
.entry(2) {
4044 Vacant(_
) => unreachable
!(),
4045 Occupied(mut view
) => {
4046 let v
= view
.get_mut();
4047 let new_v
= (*v
) * 10;
4051 assert_eq
!(map
.get(&2).unwrap(), &200);
4052 assert_eq
!(map
.len(), 6);
4054 // Existing key (take)
4055 match map
.entry(3) {
4056 Vacant(_
) => unreachable
!(),
4058 assert_eq
!(view
.remove(), 30);
4061 assert_eq
!(map
.get(&3), None
);
4062 assert_eq
!(map
.len(), 5);
4065 // Inexistent key (insert)
4066 match map
.entry(10) {
4067 Occupied(_
) => unreachable
!(),
4069 assert_eq
!(*view
.insert(1000), 1000);
4072 assert_eq
!(map
.get(&10).unwrap(), &1000);
4073 assert_eq
!(map
.len(), 6);
4077 fn test_entry_take_doesnt_corrupt() {
4078 #![allow(deprecated)] //rand
4080 fn check(m
: &HashMap
<i32, ()>) {
4082 assert
!(m
.contains_key(k
),
4083 "{} is in keys() but not in the map?", k
);
4087 let mut m
= HashMap
::new();
4088 let mut rng
= thread_rng();
4090 // Populate the map with some items.
4092 let x
= rng
.gen_range(-10, 10);
4097 let x
= rng
.gen_range(-10, 10);
4110 fn test_extend_ref() {
4111 let mut a
= HashMap
::new();
4113 let mut b
= HashMap
::new();
4115 b
.insert(3, "three");
4119 assert_eq
!(a
.len(), 3);
4120 assert_eq
!(a
[&1], "one");
4121 assert_eq
!(a
[&2], "two");
4122 assert_eq
!(a
[&3], "three");
4126 fn test_capacity_not_less_than_len() {
4127 let mut a
= HashMap
::new();
4135 assert
!(a
.capacity() > a
.len());
4137 let free
= a
.capacity() - a
.len();
4143 assert_eq
!(a
.len(), a
.capacity());
4145 // Insert at capacity should cause allocation.
4147 assert
!(a
.capacity() > a
.len());
4151 fn test_occupied_entry_key() {
4152 let mut a
= HashMap
::new();
4153 let key
= "hello there";
4154 let value
= "value goes here";
4155 assert
!(a
.is_empty());
4156 a
.insert(key
.clone(), value
.clone());
4157 assert_eq
!(a
.len(), 1);
4158 assert_eq
!(a
[key
], value
);
4160 match a
.entry(key
.clone()) {
4161 Vacant(_
) => panic
!(),
4162 Occupied(e
) => assert_eq
!(key
, *e
.key()),
4164 assert_eq
!(a
.len(), 1);
4165 assert_eq
!(a
[key
], value
);
4169 fn test_vacant_entry_key() {
4170 let mut a
= HashMap
::new();
4171 let key
= "hello there";
4172 let value
= "value goes here";
4174 assert
!(a
.is_empty());
4175 match a
.entry(key
.clone()) {
4176 Occupied(_
) => panic
!(),
4178 assert_eq
!(key
, *e
.key());
4179 e
.insert(value
.clone());
4182 assert_eq
!(a
.len(), 1);
4183 assert_eq
!(a
[key
], value
);
4188 let mut map
: HashMap
<i32, i32> = (0..100).map(|x
|(x
, x
*10)).collect();
4190 map
.retain(|&k
, _
| k
% 2 == 0);
4191 assert_eq
!(map
.len(), 50);
4192 assert_eq
!(map
[&2], 20);
4193 assert_eq
!(map
[&4], 40);
4194 assert_eq
!(map
[&6], 60);
4198 fn test_adaptive() {
4199 const TEST_LEN
: usize = 5000;
4200 // by cloning we get maps with the same hasher seed
4201 let mut first
= HashMap
::new();
4202 let mut second
= first
.clone();
4203 first
.extend((0..TEST_LEN
).map(|i
| (i
, i
)));
4204 second
.extend((TEST_LEN
..TEST_LEN
* 2).map(|i
| (i
, i
)));
4206 for (&k
, &v
) in &second
{
4207 let prev_cap
= first
.capacity();
4208 let expect_grow
= first
.len() == prev_cap
;
4210 if !expect_grow
&& first
.capacity() != prev_cap
{
4214 panic
!("Adaptive early resize failed");
4218 fn test_try_reserve() {
4220 let mut empty_bytes
: HashMap
<u8,u8> = HashMap
::new();
4222 const MAX_USIZE
: usize = usize::MAX
;
4224 // HashMap and RawTables use complicated size calculations
4225 // hashes_size is sizeof(HashUint) * capacity;
4226 // pairs_size is sizeof((K. V)) * capacity;
4227 // alignment_hashes_size is 8
4228 // alignment_pairs size is 4
4229 let size_of_multiplier
= (size_of
::<usize>() + size_of
::<(u8, u8)>()).next_power_of_two();
4230 // The following formula is used to calculate the new capacity
4231 let max_no_ovf
= ((MAX_USIZE
/ 11) * 10) / size_of_multiplier
- 1;
4233 if let Err(CapacityOverflow
) = empty_bytes
.try_reserve(MAX_USIZE
) {
4234 } else { panic!("usize::MAX should trigger an overflow!"); }
4236 if size_of
::<usize>() < 8 {
4237 if let Err(CapacityOverflow
) = empty_bytes
.try_reserve(max_no_ovf
) {
4238 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4240 if let Err(AllocErr
) = empty_bytes
.try_reserve(max_no_ovf
) {
4241 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4246 fn test_raw_entry() {
4247 use super::RawEntryMut
::{Occupied, Vacant}
;
4249 let xs
= [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4251 let mut map
: HashMap
<_
, _
> = xs
.iter().cloned().collect();
4253 let compute_hash
= |map
: &HashMap
<i32, i32>, k
: i32| -> u64 {
4254 use core
::hash
::{BuildHasher, Hash, Hasher}
;
4256 let mut hasher
= map
.hasher().build_hasher();
4257 k
.hash(&mut hasher
);
4261 // Existing key (insert)
4262 match map
.raw_entry_mut().from_key(&1) {
4263 Vacant(_
) => unreachable
!(),
4264 Occupied(mut view
) => {
4265 assert_eq
!(view
.get(), &10);
4266 assert_eq
!(view
.insert(100), 10);
4269 let hash1
= compute_hash(&map
, 1);
4270 assert_eq
!(map
.raw_entry().from_key(&1).unwrap(), (&1, &100));
4271 assert_eq
!(map
.raw_entry().from_hash(hash1
, |k
| *k
== 1).unwrap(), (&1, &100));
4272 assert_eq
!(map
.raw_entry().from_key_hashed_nocheck(hash1
, &1).unwrap(), (&1, &100));
4273 assert_eq
!(map
.raw_entry().search_bucket(hash1
, |k
| *k
== 1).unwrap(), (&1, &100));
4274 assert_eq
!(map
.len(), 6);
4276 // Existing key (update)
4277 match map
.raw_entry_mut().from_key(&2) {
4278 Vacant(_
) => unreachable
!(),
4279 Occupied(mut view
) => {
4280 let v
= view
.get_mut();
4281 let new_v
= (*v
) * 10;
4285 let hash2
= compute_hash(&map
, 2);
4286 assert_eq
!(map
.raw_entry().from_key(&2).unwrap(), (&2, &200));
4287 assert_eq
!(map
.raw_entry().from_hash(hash2
, |k
| *k
== 2).unwrap(), (&2, &200));
4288 assert_eq
!(map
.raw_entry().from_key_hashed_nocheck(hash2
, &2).unwrap(), (&2, &200));
4289 assert_eq
!(map
.raw_entry().search_bucket(hash2
, |k
| *k
== 2).unwrap(), (&2, &200));
4290 assert_eq
!(map
.len(), 6);
4292 // Existing key (take)
4293 let hash3
= compute_hash(&map
, 3);
4294 match map
.raw_entry_mut().from_key_hashed_nocheck(hash3
, &3) {
4295 Vacant(_
) => unreachable
!(),
4297 assert_eq
!(view
.remove_entry(), (3, 30));
4300 assert_eq
!(map
.raw_entry().from_key(&3), None
);
4301 assert_eq
!(map
.raw_entry().from_hash(hash3
, |k
| *k
== 3), None
);
4302 assert_eq
!(map
.raw_entry().from_key_hashed_nocheck(hash3
, &3), None
);
4303 assert_eq
!(map
.raw_entry().search_bucket(hash3
, |k
| *k
== 3), None
);
4304 assert_eq
!(map
.len(), 5);
4307 // Nonexistent key (insert)
4308 match map
.raw_entry_mut().from_key(&10) {
4309 Occupied(_
) => unreachable
!(),
4311 assert_eq
!(view
.insert(10, 1000), (&mut 10, &mut 1000));
4314 assert_eq
!(map
.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4315 assert_eq
!(map
.len(), 6);
4317 // Ensure all lookup methods produce equivalent results.
4319 let hash
= compute_hash(&map
, k
);
4320 let v
= map
.get(&k
).cloned();
4321 let kv
= v
.as_ref().map(|v
| (&k
, v
));
4323 assert_eq
!(map
.raw_entry().from_key(&k
), kv
);
4324 assert_eq
!(map
.raw_entry().from_hash(hash
, |q
| *q
== k
), kv
);
4325 assert_eq
!(map
.raw_entry().from_key_hashed_nocheck(hash
, &k
), kv
);
4326 assert_eq
!(map
.raw_entry().search_bucket(hash
, |q
| *q
== k
), kv
);
4328 match map
.raw_entry_mut().from_key(&k
) {
4329 Occupied(mut o
) => assert_eq
!(Some(o
.get_key_value()), kv
),
4330 Vacant(_
) => assert_eq
!(v
, None
),
4332 match map
.raw_entry_mut().from_key_hashed_nocheck(hash
, &k
) {
4333 Occupied(mut o
) => assert_eq
!(Some(o
.get_key_value()), kv
),
4334 Vacant(_
) => assert_eq
!(v
, None
),
4336 match map
.raw_entry_mut().from_hash(hash
, |q
| *q
== k
) {
4337 Occupied(mut o
) => assert_eq
!(Some(o
.get_key_value()), kv
),
4338 Vacant(_
) => assert_eq
!(v
, None
),
4340 match map
.raw_entry_mut().search_bucket(hash
, |q
| *q
== k
) {
4341 Occupied(mut o
) => assert_eq
!(Some(o
.get_key_value()), kv
),
4342 Vacant(_
) => assert_eq
!(v
, None
),