]> git.proxmox.com Git - rustc.git/blob - src/libstd/collections/hash/map.rs
New upstream version 1.34.2+dfsg1
[rustc.git] / src / libstd / collections / hash / map.rs
1 use self::Entry::*;
2 use self::VacantEntryState::*;
3
4 use intrinsics::unlikely;
5 use collections::CollectionAllocErr;
6 use cell::Cell;
7 use borrow::Borrow;
8 use cmp::max;
9 use fmt::{self, Debug};
10 #[allow(deprecated)]
11 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
12 use iter::{FromIterator, FusedIterator};
13 use mem::{self, replace};
14 use ops::{Deref, DerefMut, Index};
15 use sys;
16
17 use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
18 SafeHash};
19 use super::table::BucketState::{Empty, Full};
20 use super::table::Fallibility::{Fallible, Infallible};
21
22 const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
23
24 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
25 #[derive(Clone)]
26 struct DefaultResizePolicy;
27
28 impl DefaultResizePolicy {
29 #[inline]
30 fn new() -> DefaultResizePolicy {
31 DefaultResizePolicy
32 }
33
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.
38 #[inline]
39 fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
40 if len == 0 {
41 Ok(0)
42 } else {
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)
47 .map(|l| l / 10)
48 .and_then(|l| l.checked_next_power_of_two())
49 .ok_or(CollectionAllocErr::CapacityOverflow)?;
50
51 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
52 Ok(raw_cap)
53 }
54 }
55
56 #[inline]
57 fn raw_capacity(&self, len: usize) -> usize {
58 self.try_raw_capacity(len).expect("raw_capacity overflow")
59 }
60
61 /// The capacity of the given raw capacity.
62 #[inline]
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.
66 //
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
70 }
71 }
72
73 // The main performance trick in this hashmap is called Robin Hood Hashing.
74 // It gains its excellent performance from one essential operation:
75 //
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.
79 //
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
82 // conservative.
83 //
84 // > Why a load factor of approximately 90%?
85 //
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.
95 //
96 // > Wait, what? Where did you get 1-α^k from?
97 //
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.
102 //
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.
111 //
112 // ## Future Improvements (FIXME!)
113 //
114 // Allow the load factor to be changed dynamically and/or at initialization.
115 //
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.
119 //
120 // ## Future Optimizations (FIXME!)
121 //
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.
131 //
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).
135 //
136 // Shrinking the table could simply reallocate in place after moving buckets
137 // to the first half.
138 //
139 // The growth algorithm (fragment of the Proof of Correctness)
140 // --------------------
141 //
142 // The growth algorithm is basically a fast path of the naive reinsertion-
143 // during-resize algorithm. Other paths should never be taken.
144 //
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.
156 //
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:
168 //
169 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
170 //
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
175 // empty.
176 //
177 // Theorem: A linear robin hood reinsertion from the first ideal element
178 // produces identical results to a linear naive reinsertion from the same
179 // element.
180 //
181 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
182 //
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
188 // are encountered.
189 //
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.
194 //
195 // The previous safety measure also prevents degenerate interactions with
196 // really bad quality hash algorithms that can make normal inputs look like a
197 // DOS attack.
198 //
199 const DISPLACEMENT_THRESHOLD: usize = 128;
200 //
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.
205 //
206 // At a load factor of α, the odds of finding the target bucket after exactly n
207 // unsuccessful probes[1] are
208 //
209 // Pr_α{displacement = n} =
210 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
211 //
212 // We use this formula to find the probability of triggering the adaptive behavior
213 //
214 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
215 //
216 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
217 // hashing with buckets.
218
219 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
220 ///
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.
229 ///
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.
236 ///
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.
240 ///
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
244 /// property holds:
245 ///
246 /// ```text
247 /// k1 == k2 -> hash(k1) == hash(k2)
248 /// ```
249 ///
250 /// In other words, if two keys are equal, their hashes must be equal.
251 ///
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.
256 ///
257 /// Relevant papers/articles:
258 ///
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/)
264 ///
265 /// # Examples
266 ///
267 /// ```
268 /// use std::collections::HashMap;
269 ///
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();
273 ///
274 /// // Review some books.
275 /// book_reviews.insert(
276 /// "Adventures of Huckleberry Finn".to_string(),
277 /// "My favorite book.".to_string(),
278 /// );
279 /// book_reviews.insert(
280 /// "Grimms' Fairy Tales".to_string(),
281 /// "Masterpiece.".to_string(),
282 /// );
283 /// book_reviews.insert(
284 /// "Pride and Prejudice".to_string(),
285 /// "Very enjoyable.".to_string(),
286 /// );
287 /// book_reviews.insert(
288 /// "The Adventures of Sherlock Holmes".to_string(),
289 /// "Eye lyked it alot.".to_string(),
290 /// );
291 ///
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());
298 /// }
299 ///
300 /// // oops, this review has a lot of spelling mistakes, let's delete it.
301 /// book_reviews.remove("The Adventures of Sherlock Holmes");
302 ///
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)
309 /// }
310 /// }
311 ///
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"]);
314 ///
315 /// // Iterate over everything.
316 /// for (book, review) in &book_reviews {
317 /// println!("{}: \"{}\"", book, review);
318 /// }
319 /// ```
320 ///
321 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
322 /// for more complex methods of getting, setting, updating and removing keys and
323 /// their values:
324 ///
325 /// ```
326 /// use std::collections::HashMap;
327 ///
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();
331 ///
332 /// fn random_stat_buff() -> u8 {
333 /// // could actually return some random value here - let's just return
334 /// // some fixed value for now
335 /// 42
336 /// }
337 ///
338 /// // insert a key only if it doesn't already exist
339 /// player_stats.entry("health").or_insert(100);
340 ///
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);
344 ///
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();
348 /// ```
349 ///
350 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
351 /// We must also derive [`PartialEq`].
352 ///
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
362 ///
363 /// ```
364 /// use std::collections::HashMap;
365 ///
366 /// #[derive(Hash, Eq, PartialEq, Debug)]
367 /// struct Viking {
368 /// name: String,
369 /// country: String,
370 /// }
371 ///
372 /// impl Viking {
373 /// /// Creates a new Viking.
374 /// fn new(name: &str, country: &str) -> Viking {
375 /// Viking { name: name.to_string(), country: country.to_string() }
376 /// }
377 /// }
378 ///
379 /// // Use a HashMap to store the vikings' health points.
380 /// let mut vikings = HashMap::new();
381 ///
382 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
383 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
384 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
385 ///
386 /// // Use derived implementation to print the status of the vikings.
387 /// for (viking, health) in &vikings {
388 /// println!("{:?} has {} hp", viking, health);
389 /// }
390 /// ```
391 ///
392 /// A `HashMap` with fixed list of elements can be initialized from an array:
393 ///
394 /// ```
395 /// use std::collections::HashMap;
396 ///
397 /// fn main() {
398 /// let timber_resources: HashMap<&str, i32> =
399 /// [("Norway", 100),
400 /// ("Denmark", 50),
401 /// ("Iceland", 10)]
402 /// .iter().cloned().collect();
403 /// // use the values stored in map
404 /// }
405 /// ```
406
407 #[derive(Clone)]
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.
411 hash_builder: S,
412
413 table: RawTable<K, V>,
414
415 resize_policy: DefaultResizePolicy,
416 }
417
418 /// Search for a pre-hashed key.
419 /// If you don't already know the hash, use search or search_mut instead
420 #[inline]
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>>,
423 F: FnMut(&K) -> bool
424 {
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;
430 }
431
432 search_hashed_nonempty(table, hash, is_match, true)
433 }
434
435 /// Search for a pre-hashed key when the hash map is known to be non-empty.
436 #[inline]
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>>,
441 F: FnMut(&K) -> bool
442 {
443 // Do not check the capacity as an extra branch could slow the lookup.
444
445 let size = table.size();
446 let mut probe = Bucket::new(table, hash);
447 let mut displacement = 0;
448
449 loop {
450 let full = match probe.peek() {
451 Empty(bucket) => {
452 // Found a hole!
453 return InternalEntry::Vacant {
454 hash,
455 elem: NoElem(bucket, displacement),
456 };
457 }
458 Full(bucket) => bucket,
459 };
460
461 let probe_displacement = full.displacement();
462
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 {
468 hash,
469 elem: NeqElem(full, probe_displacement),
470 };
471 }
472
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 };
478 }
479 }
480 displacement += 1;
481 probe = full.next();
482 debug_assert!(displacement <= size);
483 }
484 }
485
486 /// Same as `search_hashed_nonempty` but for mutable access.
487 #[inline]
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>>,
492 F: FnMut(&K) -> bool
493 {
494 // Do not check the capacity as an extra branch could slow the lookup.
495
496 let size = table.size();
497 let mut probe = Bucket::new(table, hash);
498 let mut displacement = 0;
499
500 loop {
501 let mut full = match probe.peek() {
502 Empty(bucket) => {
503 // Found a hole!
504 return InternalEntry::Vacant {
505 hash,
506 elem: NoElem(bucket, displacement),
507 };
508 }
509 Full(bucket) => bucket,
510 };
511
512 let probe_displacement = full.displacement();
513
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 {
519 hash,
520 elem: NeqElem(full, probe_displacement),
521 };
522 }
523
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 };
529 }
530 }
531 displacement += 1;
532 probe = full.next();
533 debug_assert!(displacement <= size);
534 }
535 }
536
537 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
538 -> (K, V, &mut RawTable<K, V>)
539 {
540 let (empty, retkey, retval) = starting_bucket.take();
541 let mut gap = match empty.gap_peek() {
542 Ok(b) => b,
543 Err(b) => return (retkey, retval, b.into_table()),
544 };
545
546 while gap.full().displacement() != 0 {
547 gap = match gap.shift() {
548 Ok(b) => b,
549 Err(b) => {
550 return (retkey, retval, b.into_table());
551 },
552 };
553 }
554
555 // Now we've done all our shifting. Return the value we grabbed earlier.
556 (retkey, retval, gap.into_table())
557 }
558
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.
561 ///
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,
565 mut hash: SafeHash,
566 mut key: K,
567 mut val: V)
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();
577
578 loop {
579 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
580 hash = old_hash;
581 key = old_key;
582 val = old_val;
583
584 loop {
585 displacement += 1;
586 let probe = bucket.next();
587 debug_assert!(probe.index() != idx_end);
588
589 let full_bucket = match probe.peek() {
590 Empty(bucket) => {
591 // Found a hole!
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*.
595 //
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();
601 }
602 Full(bucket) => bucket,
603 };
604
605 let probe_displacement = full_bucket.displacement();
606
607 bucket = full_bucket;
608
609 // Robin hood! Steal the spot.
610 if probe_displacement < displacement {
611 displacement = probe_displacement;
612 break;
613 }
614 }
615 }
616 }
617
618 impl<K, V, S> HashMap<K, V, S>
619 where K: Eq + Hash,
620 S: BuildHasher
621 {
622 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
623 where X: Hash
624 {
625 table::make_hash(&self.hash_builder, x)
626 }
627
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.
631 #[inline]
632 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
633 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
634 where K: Borrow<Q>,
635 Q: Eq + Hash
636 {
637 if self.is_empty() {
638 return None;
639 }
640
641 let hash = self.make_hash(q);
642 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()), true)
643 .into_occupied_bucket()
644 }
645
646 #[inline]
647 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
648 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
649 where K: Borrow<Q>,
650 Q: Eq + Hash
651 {
652 if self.is_empty() {
653 return None;
654 }
655
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()
659 }
660
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();
666
667 loop {
668 // We don't need to compare hashes for value swap.
669 // Not even DIBs for Robin Hood.
670 buckets = match buckets.peek() {
671 Empty(empty) => {
672 empty.put(hash, k, v);
673 return;
674 }
675 Full(b) => b.into_bucket(),
676 };
677 buckets.next();
678 debug_assert!(buckets.index() != start_index);
679 }
680 }
681 }
682
683 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
684 /// Creates an empty `HashMap`.
685 ///
686 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
687 /// is first inserted into.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use std::collections::HashMap;
693 /// let mut map: HashMap<&str, i32> = HashMap::new();
694 /// ```
695 #[inline]
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn new() -> HashMap<K, V, RandomState> {
698 Default::default()
699 }
700
701 /// Creates an empty `HashMap` with the specified capacity.
702 ///
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.
705 ///
706 /// # Examples
707 ///
708 /// ```
709 /// use std::collections::HashMap;
710 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
711 /// ```
712 #[inline]
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())
716 }
717 }
718
719 impl<K, V, S> HashMap<K, V, S> {
720 /// Returns the number of elements the map can hold without reallocating.
721 ///
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.
724 ///
725 /// # Examples
726 ///
727 /// ```
728 /// use std::collections::HashMap;
729 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
730 /// assert!(map.capacity() >= 100);
731 /// ```
732 #[inline]
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn capacity(&self) -> usize {
735 self.resize_policy.capacity(self.raw_capacity())
736 }
737
738 /// Returns the hash map's raw capacity.
739 #[inline]
740 fn raw_capacity(&self) -> usize {
741 self.table.capacity()
742 }
743
744 /// An iterator visiting all keys in arbitrary order.
745 /// The iterator element type is `&'a K`.
746 ///
747 /// # Examples
748 ///
749 /// ```
750 /// use std::collections::HashMap;
751 ///
752 /// let mut map = HashMap::new();
753 /// map.insert("a", 1);
754 /// map.insert("b", 2);
755 /// map.insert("c", 3);
756 ///
757 /// for key in map.keys() {
758 /// println!("{}", key);
759 /// }
760 /// ```
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn keys(&self) -> Keys<K, V> {
763 Keys { inner: self.iter() }
764 }
765
766 /// An iterator visiting all values in arbitrary order.
767 /// The iterator element type is `&'a V`.
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// use std::collections::HashMap;
773 ///
774 /// let mut map = HashMap::new();
775 /// map.insert("a", 1);
776 /// map.insert("b", 2);
777 /// map.insert("c", 3);
778 ///
779 /// for val in map.values() {
780 /// println!("{}", val);
781 /// }
782 /// ```
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn values(&self) -> Values<K, V> {
785 Values { inner: self.iter() }
786 }
787
788 /// An iterator visiting all values mutably in arbitrary order.
789 /// The iterator element type is `&'a mut V`.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// use std::collections::HashMap;
795 ///
796 /// let mut map = HashMap::new();
797 ///
798 /// map.insert("a", 1);
799 /// map.insert("b", 2);
800 /// map.insert("c", 3);
801 ///
802 /// for val in map.values_mut() {
803 /// *val = *val + 10;
804 /// }
805 ///
806 /// for val in map.values() {
807 /// println!("{}", val);
808 /// }
809 /// ```
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() }
813 }
814
815 /// An iterator visiting all key-value pairs in arbitrary order.
816 /// The iterator element type is `(&'a K, &'a V)`.
817 ///
818 /// # Examples
819 ///
820 /// ```
821 /// use std::collections::HashMap;
822 ///
823 /// let mut map = HashMap::new();
824 /// map.insert("a", 1);
825 /// map.insert("b", 2);
826 /// map.insert("c", 3);
827 ///
828 /// for (key, val) in map.iter() {
829 /// println!("key: {} val: {}", key, val);
830 /// }
831 /// ```
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub fn iter(&self) -> Iter<K, V> {
834 Iter { inner: self.table.iter() }
835 }
836
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)`.
840 ///
841 /// # Examples
842 ///
843 /// ```
844 /// use std::collections::HashMap;
845 ///
846 /// let mut map = HashMap::new();
847 /// map.insert("a", 1);
848 /// map.insert("b", 2);
849 /// map.insert("c", 3);
850 ///
851 /// // Update all values
852 /// for (_, val) in map.iter_mut() {
853 /// *val *= 2;
854 /// }
855 ///
856 /// for (key, val) in &map {
857 /// println!("key: {} val: {}", key, val);
858 /// }
859 /// ```
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() }
863 }
864
865 /// Returns the number of elements in the map.
866 ///
867 /// # Examples
868 ///
869 /// ```
870 /// use std::collections::HashMap;
871 ///
872 /// let mut a = HashMap::new();
873 /// assert_eq!(a.len(), 0);
874 /// a.insert(1, "a");
875 /// assert_eq!(a.len(), 1);
876 /// ```
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn len(&self) -> usize {
879 self.table.size()
880 }
881
882 /// Returns `true` if the map contains no elements.
883 ///
884 /// # Examples
885 ///
886 /// ```
887 /// use std::collections::HashMap;
888 ///
889 /// let mut a = HashMap::new();
890 /// assert!(a.is_empty());
891 /// a.insert(1, "a");
892 /// assert!(!a.is_empty());
893 /// ```
894 #[inline]
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn is_empty(&self) -> bool {
897 self.len() == 0
898 }
899
900 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
901 /// allocated memory for reuse.
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// use std::collections::HashMap;
907 ///
908 /// let mut a = HashMap::new();
909 /// a.insert(1, "a");
910 /// a.insert(2, "b");
911 ///
912 /// for (k, v) in a.drain().take(1) {
913 /// assert!(k == 1 || k == 2);
914 /// assert!(v == "a" || v == "b");
915 /// }
916 ///
917 /// assert!(a.is_empty());
918 /// ```
919 #[inline]
920 #[stable(feature = "drain", since = "1.6.0")]
921 pub fn drain(&mut self) -> Drain<K, V> {
922 Drain { inner: self.table.drain() }
923 }
924
925 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
926 /// for reuse.
927 ///
928 /// # Examples
929 ///
930 /// ```
931 /// use std::collections::HashMap;
932 ///
933 /// let mut a = HashMap::new();
934 /// a.insert(1, "a");
935 /// a.clear();
936 /// assert!(a.is_empty());
937 /// ```
938 #[stable(feature = "rust1", since = "1.0.0")]
939 #[inline]
940 pub fn clear(&mut self) {
941 self.drain();
942 }
943 }
944
945 impl<K, V, S> HashMap<K, V, S>
946 where K: Eq + Hash,
947 S: BuildHasher
948 {
949 /// Creates an empty `HashMap` which will use the given hash builder to hash
950 /// keys.
951 ///
952 /// The created map has the default initial capacity.
953 ///
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.
958 ///
959 /// # Examples
960 ///
961 /// ```
962 /// use std::collections::HashMap;
963 /// use std::collections::hash_map::RandomState;
964 ///
965 /// let s = RandomState::new();
966 /// let mut map = HashMap::with_hasher(s);
967 /// map.insert(1, 2);
968 /// ```
969 #[inline]
970 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
971 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
972 HashMap {
973 hash_builder,
974 resize_policy: DefaultResizePolicy::new(),
975 table: RawTable::new(0),
976 }
977 }
978
979 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
980 /// to hash the keys.
981 ///
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.
984 ///
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.
989 ///
990 /// # Examples
991 ///
992 /// ```
993 /// use std::collections::HashMap;
994 /// use std::collections::hash_map::RandomState;
995 ///
996 /// let s = RandomState::new();
997 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
998 /// map.insert(1, 2);
999 /// ```
1000 #[inline]
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);
1005 HashMap {
1006 hash_builder,
1007 resize_policy,
1008 table: RawTable::new(raw_cap),
1009 }
1010 }
1011
1012 /// Returns a reference to the map's [`BuildHasher`].
1013 ///
1014 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
1015 ///
1016 /// # Examples
1017 ///
1018 /// ```
1019 /// use std::collections::HashMap;
1020 /// use std::collections::hash_map::RandomState;
1021 ///
1022 /// let hasher = RandomState::new();
1023 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
1024 /// let hasher: &RandomState = map.hasher();
1025 /// ```
1026 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
1027 pub fn hasher(&self) -> &S {
1028 &self.hash_builder
1029 }
1030
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.
1034 ///
1035 /// # Panics
1036 ///
1037 /// Panics if the new allocation size overflows [`usize`].
1038 ///
1039 /// [`usize`]: ../../std/primitive.usize.html
1040 ///
1041 /// # Examples
1042 ///
1043 /// ```
1044 /// use std::collections::HashMap;
1045 /// let mut map: HashMap<&str, i32> = HashMap::new();
1046 /// map.reserve(10);
1047 /// ```
1048 #[inline]
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 */ }
1055 }
1056 }
1057
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.
1061 ///
1062 /// # Errors
1063 ///
1064 /// If the capacity overflows, or the allocator reports a failure, then an error
1065 /// is returned.
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```
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?");
1074 /// ```
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)
1078 }
1079
1080 #[inline]
1081 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
1082 -> Result<(), CollectionAllocErr> {
1083
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)?;
1096 }
1097 Ok(())
1098 }
1099
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.
1105 #[inline(never)]
1106 #[cold]
1107 fn try_resize(
1108 &mut self,
1109 new_raw_cap: usize,
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);
1114
1115 let mut old_table = replace(
1116 &mut self.table,
1117 match fallibility {
1118 Infallible => RawTable::new(new_raw_cap),
1119 Fallible => RawTable::try_new(new_raw_cap)?,
1120 }
1121 );
1122 let old_size = old_table.size();
1123
1124 if old_table.size() == 0 {
1125 return Ok(());
1126 }
1127
1128 let mut bucket = Bucket::head_bucket(&mut old_table);
1129
1130 // This is how the buckets might be laid out in memory:
1131 // ($ marks an initialized bucket)
1132 // ________________
1133 // |$$$_$$$$$$_$$$$$|
1134 //
1135 // But we've skipped the entire initial cluster of buckets
1136 // and will continue iteration in this order:
1137 // ________________
1138 // |$$$$$$_$$$$$
1139 // ^ wrap around once end is reached
1140 // ________________
1141 // $$$_____________|
1142 // ^ exit once table.size == 0
1143 loop {
1144 bucket = match bucket.peek() {
1145 Full(bucket) => {
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 {
1150 break;
1151 }
1152 b.into_bucket()
1153 }
1154 Empty(b) => b.into_bucket(),
1155 };
1156 bucket.next();
1157 }
1158
1159 assert_eq!(self.table.size(), old_size);
1160 Ok(())
1161 }
1162
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.
1166 ///
1167 /// # Examples
1168 ///
1169 /// ```
1170 /// use std::collections::HashMap;
1171 ///
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);
1178 /// ```
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();
1185
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);
1189 }
1190
1191 debug_assert_eq!(self.table.size(), old_size);
1192 }
1193 }
1194
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.
1198 ///
1199 /// Panics if the current capacity is smaller than the supplied
1200 /// minimum capacity.
1201 ///
1202 /// # Examples
1203 ///
1204 /// ```
1205 /// #![feature(shrink_to)]
1206 /// use std::collections::HashMap;
1207 ///
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);
1216 /// ```
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");
1220
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();
1225
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);
1229 }
1230
1231 debug_assert_eq!(self.table.size(), old_size);
1232 }
1233 }
1234
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.
1238 ///
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);
1243 match entry {
1244 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1245 Some(Vacant(elem)) => {
1246 elem.insert(v);
1247 None
1248 }
1249 None => unreachable!(),
1250 }
1251 }
1252
1253 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1254 ///
1255 /// # Examples
1256 ///
1257 /// ```
1258 /// use std::collections::HashMap;
1259 ///
1260 /// let mut letters = HashMap::new();
1261 ///
1262 /// for ch in "a short treatise on fungi".chars() {
1263 /// let counter = letters.entry(ch).or_insert(0);
1264 /// *counter += 1;
1265 /// }
1266 ///
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);
1271 /// ```
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 pub fn entry(&mut self, key: K) -> Entry<K, V> {
1274 // Gotta resize now.
1275 self.reserve(1);
1276 let hash = self.make_hash(&key);
1277 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1278 .into_entry(key).expect("unreachable")
1279 }
1280
1281 /// Returns a reference to the value corresponding to the key.
1282 ///
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
1285 /// the key type.
1286 ///
1287 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1288 /// [`Hash`]: ../../std/hash/trait.Hash.html
1289 ///
1290 /// # Examples
1291 ///
1292 /// ```
1293 /// use std::collections::HashMap;
1294 ///
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);
1299 /// ```
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 #[inline]
1302 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1303 where K: Borrow<Q>,
1304 Q: Hash + Eq
1305 {
1306 self.search(k).map(|bucket| bucket.into_refs().1)
1307 }
1308
1309 /// Returns the key-value pair corresponding to the supplied key.
1310 ///
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
1313 /// the key type.
1314 ///
1315 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1316 /// [`Hash`]: ../../std/hash/trait.Hash.html
1317 ///
1318 /// # Examples
1319 ///
1320 /// ```
1321 /// #![feature(map_get_key_value)]
1322 /// use std::collections::HashMap;
1323 ///
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);
1328 /// ```
1329 #[unstable(feature = "map_get_key_value", issue = "49347")]
1330 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1331 where K: Borrow<Q>,
1332 Q: Hash + Eq
1333 {
1334 self.search(k).map(|bucket| bucket.into_refs())
1335 }
1336
1337 /// Returns `true` if the map contains a value for the specified key.
1338 ///
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
1341 /// the key type.
1342 ///
1343 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1344 /// [`Hash`]: ../../std/hash/trait.Hash.html
1345 ///
1346 /// # Examples
1347 ///
1348 /// ```
1349 /// use std::collections::HashMap;
1350 ///
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);
1355 /// ```
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1358 where K: Borrow<Q>,
1359 Q: Hash + Eq
1360 {
1361 self.search(k).is_some()
1362 }
1363
1364 /// Returns a mutable reference to the value corresponding to the key.
1365 ///
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
1368 /// the key type.
1369 ///
1370 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1371 /// [`Hash`]: ../../std/hash/trait.Hash.html
1372 ///
1373 /// # Examples
1374 ///
1375 /// ```
1376 /// use std::collections::HashMap;
1377 ///
1378 /// let mut map = HashMap::new();
1379 /// map.insert(1, "a");
1380 /// if let Some(x) = map.get_mut(&1) {
1381 /// *x = "b";
1382 /// }
1383 /// assert_eq!(map[&1], "b");
1384 /// ```
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1387 where K: Borrow<Q>,
1388 Q: Hash + Eq
1389 {
1390 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1391 }
1392
1393 /// Inserts a key-value pair into the map.
1394 ///
1395 /// If the map did not have this key present, [`None`] is returned.
1396 ///
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.
1401 ///
1402 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1403 /// [module-level documentation]: index.html#insert-and-complex-keys
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```
1408 /// use std::collections::HashMap;
1409 ///
1410 /// let mut map = HashMap::new();
1411 /// assert_eq!(map.insert(37, "a"), None);
1412 /// assert_eq!(map.is_empty(), false);
1413 ///
1414 /// map.insert(37, "b");
1415 /// assert_eq!(map.insert(37, "c"), Some("b"));
1416 /// assert_eq!(map[&37], "c");
1417 /// ```
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);
1421 self.reserve(1);
1422 self.insert_hashed_nocheck(hash, k, v)
1423 }
1424
1425 /// Removes a key from the map, returning the value at the key if the key
1426 /// was previously in the map.
1427 ///
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
1430 /// the key type.
1431 ///
1432 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1433 /// [`Hash`]: ../../std/hash/trait.Hash.html
1434 ///
1435 /// # Examples
1436 ///
1437 /// ```
1438 /// use std::collections::HashMap;
1439 ///
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);
1444 /// ```
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1447 where K: Borrow<Q>,
1448 Q: Hash + Eq
1449 {
1450 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1451 }
1452
1453 /// Removes a key from the map, returning the stored key and value if the
1454 /// key was previously in the map.
1455 ///
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
1458 /// the key type.
1459 ///
1460 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1461 /// [`Hash`]: ../../std/hash/trait.Hash.html
1462 ///
1463 /// # Examples
1464 ///
1465 /// ```
1466 /// use std::collections::HashMap;
1467 ///
1468 /// # fn main() {
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);
1473 /// # }
1474 /// ```
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)>
1477 where K: Borrow<Q>,
1478 Q: Hash + Eq
1479 {
1480 self.search_mut(k)
1481 .map(|bucket| {
1482 let (k, v, _) = pop_internal(bucket);
1483 (k, v)
1484 })
1485 }
1486
1487 /// Retains only the elements specified by the predicate.
1488 ///
1489 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1490 ///
1491 /// # Examples
1492 ///
1493 /// ```
1494 /// use std::collections::HashMap;
1495 ///
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);
1499 /// ```
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
1503 {
1504 if self.table.size() == 0 {
1505 return;
1506 }
1507 let mut elems_left = self.table.size();
1508 let mut bucket = Bucket::head_bucket(&mut self.table);
1509 bucket.prev();
1510 let start_index = bucket.index();
1511 while elems_left != 0 {
1512 bucket = match bucket.peek() {
1513 Full(mut full) => {
1514 elems_left -= 1;
1515 let should_remove = {
1516 let (k, v) = full.read_mut();
1517 !f(k, v)
1518 };
1519 if should_remove {
1520 let prev_raw = full.raw();
1521 let (_, _, t) = pop_internal(full);
1522 Bucket::new_from(prev_raw, t)
1523 } else {
1524 full.into_bucket()
1525 }
1526 },
1527 Empty(b) => {
1528 b.into_bucket()
1529 }
1530 };
1531 bucket.prev(); // reverse iteration
1532 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1533 }
1534 }
1535 }
1536
1537 impl<K, V, S> HashMap<K, V, S>
1538 where K: Eq + Hash,
1539 S: BuildHasher
1540 {
1541 /// Creates a raw entry builder for the HashMap.
1542 ///
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.
1547 ///
1548 /// Raw entries are useful for such exotic situations as:
1549 ///
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
1554 ///
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.
1559 ///
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.
1564 ///
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).
1572 #[inline(always)]
1573 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1574 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1575 self.reserve(1);
1576 RawEntryBuilderMut { map: self }
1577 }
1578
1579 /// Creates a raw immutable entry builder for the HashMap.
1580 ///
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.
1584 ///
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
1589 ///
1590 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1591 /// `get` should be preferred.
1592 ///
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 }
1597 }
1598 }
1599
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<K, V, S> PartialEq for HashMap<K, V, S>
1602 where K: Eq + Hash,
1603 V: PartialEq,
1604 S: BuildHasher
1605 {
1606 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1607 if self.len() != other.len() {
1608 return false;
1609 }
1610
1611 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1612 }
1613 }
1614
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<K, V, S> Eq for HashMap<K, V, S>
1617 where K: Eq + Hash,
1618 V: Eq,
1619 S: BuildHasher
1620 {
1621 }
1622
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,
1626 V: Debug,
1627 S: BuildHasher
1628 {
1629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1630 f.debug_map().entries(self.iter()).finish()
1631 }
1632 }
1633
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<K, V, S> Default for HashMap<K, V, S>
1636 where K: Eq + Hash,
1637 S: BuildHasher + Default
1638 {
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())
1642 }
1643 }
1644
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>,
1648 Q: Eq + Hash,
1649 S: BuildHasher
1650 {
1651 type Output = V;
1652
1653 /// Returns a reference to the value corresponding to the supplied key.
1654 ///
1655 /// # Panics
1656 ///
1657 /// Panics if the key is not present in the `HashMap`.
1658 #[inline]
1659 fn index(&self, key: &Q) -> &V {
1660 self.get(key).expect("no entry found for key")
1661 }
1662 }
1663
1664 /// An iterator over the entries of a `HashMap`.
1665 ///
1666 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1667 /// documentation for more.
1668 ///
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>,
1674 }
1675
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() }
1681 }
1682 }
1683
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 {
1687 f.debug_list()
1688 .entries(self.clone())
1689 .finish()
1690 }
1691 }
1692
1693 /// A mutable iterator over the entries of a `HashMap`.
1694 ///
1695 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1696 /// documentation for more.
1697 ///
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>,
1703 }
1704
1705 /// An owning iterator over the entries of a `HashMap`.
1706 ///
1707 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1708 /// (provided by the `IntoIterator` trait). See its documentation for more.
1709 ///
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>,
1715 }
1716
1717 /// An iterator over the keys of a `HashMap`.
1718 ///
1719 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1720 /// documentation for more.
1721 ///
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>,
1727 }
1728
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() }
1734 }
1735 }
1736
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 {
1740 f.debug_list()
1741 .entries(self.clone())
1742 .finish()
1743 }
1744 }
1745
1746 /// An iterator over the values of a `HashMap`.
1747 ///
1748 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1749 /// documentation for more.
1750 ///
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>,
1756 }
1757
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() }
1763 }
1764 }
1765
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 {
1769 f.debug_list()
1770 .entries(self.clone())
1771 .finish()
1772 }
1773 }
1774
1775 /// A draining iterator over the entries of a `HashMap`.
1776 ///
1777 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1778 /// documentation for more.
1779 ///
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>,
1785 }
1786
1787 /// A mutable iterator over the values of a `HashMap`.
1788 ///
1789 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1790 /// documentation for more.
1791 ///
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>,
1797 }
1798
1799 enum InternalEntry<K, V, M> {
1800 Occupied { elem: FullBucket<K, V, M> },
1801 Vacant {
1802 hash: SafeHash,
1803 elem: VacantEntryState<K, V, M>,
1804 },
1805 TableIsEmpty,
1806 }
1807
1808 impl<K, V, M> InternalEntry<K, V, M> {
1809 #[inline]
1810 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1811 match self {
1812 InternalEntry::Occupied { elem } => Some(elem),
1813 _ => None,
1814 }
1815 }
1816 }
1817
1818 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1819 #[inline]
1820 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1821 match self {
1822 InternalEntry::Occupied { elem } => {
1823 Some(Occupied(OccupiedEntry {
1824 key: Some(key),
1825 elem,
1826 }))
1827 }
1828 InternalEntry::Vacant { hash, elem } => {
1829 Some(Vacant(VacantEntry {
1830 hash,
1831 key,
1832 elem,
1833 }))
1834 }
1835 InternalEntry::TableIsEmpty => None,
1836 }
1837 }
1838 }
1839
1840 /// A builder for computing where in a HashMap a key-value pair would be stored.
1841 ///
1842 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1843 ///
1844 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1845
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>,
1849 }
1850
1851 /// A view into a single entry in a map, which may either be vacant or occupied.
1852 ///
1853 /// This is a lower-level version of [`Entry`].
1854 ///
1855 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1856 ///
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>),
1864 /// A vacant entry.
1865 Vacant(RawVacantEntryMut<'a, K, V, S>),
1866 }
1867
1868 /// A view into an occupied entry in a `HashMap`.
1869 /// It is part of the [`RawEntryMut`] enum.
1870 ///
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>>,
1875 }
1876
1877 /// A view into a vacant entry in a `HashMap`.
1878 /// It is part of the [`RawEntryMut`] enum.
1879 ///
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,
1885 }
1886
1887 /// A builder for computing where in a HashMap a key-value pair would be stored.
1888 ///
1889 /// See the [`HashMap::raw_entry`] docs for usage examples.
1890 ///
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>,
1895 }
1896
1897 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1898 where S: BuildHasher,
1899 K: Eq + Hash,
1900 {
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>
1904 where K: Borrow<Q>,
1905 Q: Hash + Eq
1906 {
1907 let mut hasher = self.map.hash_builder.build_hasher();
1908 k.hash(&mut hasher);
1909 self.from_key_hashed_nocheck(hasher.finish(), k)
1910 }
1911
1912 /// Creates a `RawEntryMut` from the given key and its hash.
1913 #[inline]
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>
1916 where K: Borrow<Q>,
1917 Q: Eq
1918 {
1919 self.from_hash(hash, |q| q.borrow().eq(k))
1920 }
1921
1922 #[inline]
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,
1925 {
1926 match search_hashed_nonempty_mut(&mut self.map.table,
1927 SafeHash::new(hash),
1928 is_match,
1929 compare_hashes) {
1930 InternalEntry::Occupied { elem } => {
1931 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1932 }
1933 InternalEntry::Vacant { elem, .. } => {
1934 RawEntryMut::Vacant(RawVacantEntryMut {
1935 elem,
1936 hash_builder: &self.map.hash_builder,
1937 })
1938 }
1939 InternalEntry::TableIsEmpty => {
1940 unreachable!()
1941 }
1942 }
1943 }
1944 /// Creates a `RawEntryMut` from the given hash.
1945 #[inline]
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,
1949 {
1950 self.search(hash, is_match, true)
1951 }
1952
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
1955 /// hash.
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,
1959 {
1960 self.search(hash, is_match, false)
1961 }
1962 }
1963
1964 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1965 where S: BuildHasher,
1966 {
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)>
1970 where K: Borrow<Q>,
1971 Q: Hash + Eq
1972 {
1973 let mut hasher = self.map.hash_builder.build_hasher();
1974 k.hash(&mut hasher);
1975 self.from_key_hashed_nocheck(hasher.finish(), k)
1976 }
1977
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)>
1981 where K: Borrow<Q>,
1982 Q: Hash + Eq
1983
1984 {
1985 self.from_hash(hash, |q| q.borrow().eq(k))
1986 }
1987
1988 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1989 where F: FnMut(&K) -> bool
1990 {
1991 if unsafe { unlikely(self.map.table.size() == 0) } {
1992 return None;
1993 }
1994 match search_hashed_nonempty(&self.map.table,
1995 SafeHash::new(hash),
1996 is_match,
1997 compare_hashes) {
1998 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
1999 InternalEntry::Vacant { .. } => None,
2000 InternalEntry::TableIsEmpty => unreachable!(),
2001 }
2002 }
2003
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
2008 {
2009 self.search(hash, is_match, true)
2010 }
2011
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
2014 /// hash.
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
2018 {
2019 self.search(hash, is_match, false)
2020 }
2021 }
2022
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.
2026 ///
2027 /// # Examples
2028 ///
2029 /// ```
2030 /// #![feature(hash_raw_entry)]
2031 /// use std::collections::HashMap;
2032 ///
2033 /// let mut map: HashMap<&str, u32> = HashMap::new();
2034 ///
2035 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2036 /// assert_eq!(map["poneyland"], 3);
2037 ///
2038 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2039 /// assert_eq!(map["poneyland"], 6);
2040 /// ```
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)
2043 where K: Hash,
2044 S: BuildHasher,
2045 {
2046 match self {
2047 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2048 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2049 }
2050 }
2051
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.
2054 ///
2055 /// # Examples
2056 ///
2057 /// ```
2058 /// #![feature(hash_raw_entry)]
2059 /// use std::collections::HashMap;
2060 ///
2061 /// let mut map: HashMap<&str, String> = HashMap::new();
2062 ///
2063 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2064 /// ("poneyland", "hoho".to_string())
2065 /// });
2066 ///
2067 /// assert_eq!(map["poneyland"], "hoho".to_string());
2068 /// ```
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),
2072 K: Hash,
2073 S: BuildHasher,
2074 {
2075 match self {
2076 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2077 RawEntryMut::Vacant(entry) => {
2078 let (k, v) = default();
2079 entry.insert(k, v)
2080 }
2081 }
2082 }
2083
2084 /// Provides in-place mutable access to an occupied entry before any
2085 /// potential inserts into the map.
2086 ///
2087 /// # Examples
2088 ///
2089 /// ```
2090 /// #![feature(hash_raw_entry)]
2091 /// use std::collections::HashMap;
2092 ///
2093 /// let mut map: HashMap<&str, u32> = HashMap::new();
2094 ///
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);
2100 ///
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);
2106 /// ```
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)
2110 {
2111 match self {
2112 RawEntryMut::Occupied(mut entry) => {
2113 {
2114 let (k, v) = entry.get_key_value_mut();
2115 f(k, v);
2116 }
2117 RawEntryMut::Occupied(entry)
2118 },
2119 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2120 }
2121 }
2122 }
2123
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 {
2128 self.elem.read().0
2129 }
2130
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
2135 }
2136
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
2142 }
2143
2144 /// Gets a reference to the value in the entry.
2145 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2146 pub fn get(&self) -> &V {
2147 self.elem.read().1
2148 }
2149
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
2155 }
2156
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
2161 }
2162
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) {
2166 self.elem.read()
2167 }
2168
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()
2173 }
2174
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()
2180 }
2181
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)
2186 }
2187
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)
2192 }
2193
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
2198 }
2199
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);
2204 (k, v)
2205 }
2206 }
2207
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)
2213 where K: Hash,
2214 S: BuildHasher,
2215 {
2216 let mut hasher = self.hash_builder.build_hasher();
2217 key.hash(&mut hasher);
2218 self.insert_hashed_nocheck(hasher.finish(), key, value)
2219 }
2220
2221 /// Sets the value of the entry with the VacantEntry's key,
2222 /// and returns a mutable reference to it.
2223 #[inline]
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);
2231 }
2232 robin_hood(bucket, disp, hash, key, value)
2233 },
2234 NoElem(mut bucket, disp) => {
2235 if disp >= DISPLACEMENT_THRESHOLD {
2236 bucket.table_mut().set_tag(true);
2237 }
2238 bucket.put(hash, key, value)
2239 },
2240 };
2241 b.into_mut_refs()
2242 }
2243 }
2244
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")
2249 .finish()
2250 }
2251 }
2252
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 {
2256 match *self {
2257 RawEntryMut::Vacant(ref v) => {
2258 f.debug_tuple("RawEntry")
2259 .field(v)
2260 .finish()
2261 }
2262 RawEntryMut::Occupied(ref o) => {
2263 f.debug_tuple("RawEntry")
2264 .field(o)
2265 .finish()
2266 }
2267 }
2268 }
2269 }
2270
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())
2277 .finish()
2278 }
2279 }
2280
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")
2285 .finish()
2286 }
2287 }
2288
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")
2293 .finish()
2294 }
2295 }
2296
2297 /// A view into a single entry in a map, which may either be vacant or occupied.
2298 ///
2299 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2300 ///
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>),
2309
2310 /// A vacant entry.
2311 #[stable(feature = "rust1", since = "1.0.0")]
2312 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2313 VacantEntry<'a, K, V>),
2314 }
2315
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 {
2319 match *self {
2320 Vacant(ref v) => {
2321 f.debug_tuple("Entry")
2322 .field(v)
2323 .finish()
2324 }
2325 Occupied(ref o) => {
2326 f.debug_tuple("Entry")
2327 .field(o)
2328 .finish()
2329 }
2330 }
2331 }
2332 }
2333
2334 /// A view into an occupied entry in a `HashMap`.
2335 /// It is part of the [`Entry`] enum.
2336 ///
2337 /// [`Entry`]: enum.Entry.html
2338 #[stable(feature = "rust1", since = "1.0.0")]
2339 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2340 key: Option<K>,
2341 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2342 }
2343
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())
2350 .finish()
2351 }
2352 }
2353
2354 /// A view into a vacant entry in a `HashMap`.
2355 /// It is part of the [`Entry`] enum.
2356 ///
2357 /// [`Entry`]: enum.Entry.html
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2360 hash: SafeHash,
2361 key: K,
2362 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2363 }
2364
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")
2369 .field(self.key())
2370 .finish()
2371 }
2372 }
2373
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),
2381 }
2382
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>;
2387
2388 fn into_iter(self) -> Iter<'a, K, V> {
2389 self.iter()
2390 }
2391 }
2392
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>;
2397
2398 fn into_iter(self) -> IterMut<'a, K, V> {
2399 self.iter_mut()
2400 }
2401 }
2402
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
2405 type Item = (K, V);
2406 type IntoIter = IntoIter<K, V>;
2407
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
2410 /// calling this.
2411 ///
2412 /// # Examples
2413 ///
2414 /// ```
2415 /// use std::collections::HashMap;
2416 ///
2417 /// let mut map = HashMap::new();
2418 /// map.insert("a", 1);
2419 /// map.insert("b", 2);
2420 /// map.insert("c", 3);
2421 ///
2422 /// // Not possible with .iter()
2423 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2424 /// ```
2425 fn into_iter(self) -> IntoIter<K, V> {
2426 IntoIter { inner: self.table.into_iter() }
2427 }
2428 }
2429
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);
2433
2434 #[inline]
2435 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2436 self.inner.next()
2437 }
2438 #[inline]
2439 fn size_hint(&self) -> (usize, Option<usize>) {
2440 self.inner.size_hint()
2441 }
2442 }
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2445 #[inline]
2446 fn len(&self) -> usize {
2447 self.inner.len()
2448 }
2449 }
2450
2451 #[stable(feature = "fused", since = "1.26.0")]
2452 impl<K, V> FusedIterator for Iter<'_, K, V> {}
2453
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);
2457
2458 #[inline]
2459 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2460 self.inner.next()
2461 }
2462 #[inline]
2463 fn size_hint(&self) -> (usize, Option<usize>) {
2464 self.inner.size_hint()
2465 }
2466 }
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2469 #[inline]
2470 fn len(&self) -> usize {
2471 self.inner.len()
2472 }
2473 }
2474 #[stable(feature = "fused", since = "1.26.0")]
2475 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2476
2477 #[stable(feature = "std_debug", since = "1.16.0")]
2478 impl<K, V> fmt::Debug for IterMut<'_, K, V>
2479 where K: fmt::Debug,
2480 V: fmt::Debug,
2481 {
2482 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2483 f.debug_list()
2484 .entries(self.inner.iter())
2485 .finish()
2486 }
2487 }
2488
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<K, V> Iterator for IntoIter<K, V> {
2491 type Item = (K, V);
2492
2493 #[inline]
2494 fn next(&mut self) -> Option<(K, V)> {
2495 self.inner.next().map(|(_, k, v)| (k, v))
2496 }
2497 #[inline]
2498 fn size_hint(&self) -> (usize, Option<usize>) {
2499 self.inner.size_hint()
2500 }
2501 }
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2504 #[inline]
2505 fn len(&self) -> usize {
2506 self.inner.len()
2507 }
2508 }
2509 #[stable(feature = "fused", since = "1.26.0")]
2510 impl<K, V> FusedIterator for IntoIter<K, V> {}
2511
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 {
2515 f.debug_list()
2516 .entries(self.inner.iter())
2517 .finish()
2518 }
2519 }
2520
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2523 type Item = &'a K;
2524
2525 #[inline]
2526 fn next(&mut self) -> Option<(&'a K)> {
2527 self.inner.next().map(|(k, _)| k)
2528 }
2529 #[inline]
2530 fn size_hint(&self) -> (usize, Option<usize>) {
2531 self.inner.size_hint()
2532 }
2533 }
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2536 #[inline]
2537 fn len(&self) -> usize {
2538 self.inner.len()
2539 }
2540 }
2541 #[stable(feature = "fused", since = "1.26.0")]
2542 impl<K, V> FusedIterator for Keys<'_, K, V> {}
2543
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<'a, K, V> Iterator for Values<'a, K, V> {
2546 type Item = &'a V;
2547
2548 #[inline]
2549 fn next(&mut self) -> Option<(&'a V)> {
2550 self.inner.next().map(|(_, v)| v)
2551 }
2552 #[inline]
2553 fn size_hint(&self) -> (usize, Option<usize>) {
2554 self.inner.size_hint()
2555 }
2556 }
2557 #[stable(feature = "rust1", since = "1.0.0")]
2558 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2559 #[inline]
2560 fn len(&self) -> usize {
2561 self.inner.len()
2562 }
2563 }
2564 #[stable(feature = "fused", since = "1.26.0")]
2565 impl<K, V> FusedIterator for Values<'_, K, V> {}
2566
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;
2570
2571 #[inline]
2572 fn next(&mut self) -> Option<(&'a mut V)> {
2573 self.inner.next().map(|(_, v)| v)
2574 }
2575 #[inline]
2576 fn size_hint(&self) -> (usize, Option<usize>) {
2577 self.inner.size_hint()
2578 }
2579 }
2580 #[stable(feature = "map_values_mut", since = "1.10.0")]
2581 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2582 #[inline]
2583 fn len(&self) -> usize {
2584 self.inner.len()
2585 }
2586 }
2587 #[stable(feature = "fused", since = "1.26.0")]
2588 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2589
2590 #[stable(feature = "std_debug", since = "1.16.0")]
2591 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
2592 where K: fmt::Debug,
2593 V: fmt::Debug,
2594 {
2595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2596 f.debug_list()
2597 .entries(self.inner.inner.iter())
2598 .finish()
2599 }
2600 }
2601
2602 #[stable(feature = "drain", since = "1.6.0")]
2603 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2604 type Item = (K, V);
2605
2606 #[inline]
2607 fn next(&mut self) -> Option<(K, V)> {
2608 self.inner.next().map(|(_, k, v)| (k, v))
2609 }
2610 #[inline]
2611 fn size_hint(&self) -> (usize, Option<usize>) {
2612 self.inner.size_hint()
2613 }
2614 }
2615 #[stable(feature = "drain", since = "1.6.0")]
2616 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2617 #[inline]
2618 fn len(&self) -> usize {
2619 self.inner.len()
2620 }
2621 }
2622 #[stable(feature = "fused", since = "1.26.0")]
2623 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2624
2625 #[stable(feature = "std_debug", since = "1.16.0")]
2626 impl<K, V> fmt::Debug for Drain<'_, K, V>
2627 where K: fmt::Debug,
2628 V: fmt::Debug,
2629 {
2630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2631 f.debug_list()
2632 .entries(self.inner.iter())
2633 .finish()
2634 }
2635 }
2636
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.
2641 ///
2642 /// # Examples
2643 ///
2644 /// ```
2645 /// use std::collections::HashMap;
2646 ///
2647 /// let mut map: HashMap<&str, u32> = HashMap::new();
2648 ///
2649 /// map.entry("poneyland").or_insert(3);
2650 /// assert_eq!(map["poneyland"], 3);
2651 ///
2652 /// *map.entry("poneyland").or_insert(10) *= 2;
2653 /// assert_eq!(map["poneyland"], 6);
2654 /// ```
2655 pub fn or_insert(self, default: V) -> &'a mut V {
2656 match self {
2657 Occupied(entry) => entry.into_mut(),
2658 Vacant(entry) => entry.insert(default),
2659 }
2660 }
2661
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.
2665 ///
2666 /// # Examples
2667 ///
2668 /// ```
2669 /// use std::collections::HashMap;
2670 ///
2671 /// let mut map: HashMap<&str, String> = HashMap::new();
2672 /// let s = "hoho".to_string();
2673 ///
2674 /// map.entry("poneyland").or_insert_with(|| s);
2675 ///
2676 /// assert_eq!(map["poneyland"], "hoho".to_string());
2677 /// ```
2678 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2679 match self {
2680 Occupied(entry) => entry.into_mut(),
2681 Vacant(entry) => entry.insert(default()),
2682 }
2683 }
2684
2685 /// Returns a reference to this entry's key.
2686 ///
2687 /// # Examples
2688 ///
2689 /// ```
2690 /// use std::collections::HashMap;
2691 ///
2692 /// let mut map: HashMap<&str, u32> = HashMap::new();
2693 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2694 /// ```
2695 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2696 pub fn key(&self) -> &K {
2697 match *self {
2698 Occupied(ref entry) => entry.key(),
2699 Vacant(ref entry) => entry.key(),
2700 }
2701 }
2702
2703 /// Provides in-place mutable access to an occupied entry before any
2704 /// potential inserts into the map.
2705 ///
2706 /// # Examples
2707 ///
2708 /// ```
2709 /// use std::collections::HashMap;
2710 ///
2711 /// let mut map: HashMap<&str, u32> = HashMap::new();
2712 ///
2713 /// map.entry("poneyland")
2714 /// .and_modify(|e| { *e += 1 })
2715 /// .or_insert(42);
2716 /// assert_eq!(map["poneyland"], 42);
2717 ///
2718 /// map.entry("poneyland")
2719 /// .and_modify(|e| { *e += 1 })
2720 /// .or_insert(42);
2721 /// assert_eq!(map["poneyland"], 43);
2722 /// ```
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)
2726 {
2727 match self {
2728 Occupied(mut entry) => {
2729 f(entry.get_mut());
2730 Occupied(entry)
2731 },
2732 Vacant(entry) => Vacant(entry),
2733 }
2734 }
2735
2736 }
2737
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.
2742 ///
2743 /// # Examples
2744 ///
2745 /// ```
2746 /// # fn main() {
2747 /// use std::collections::HashMap;
2748 ///
2749 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2750 /// map.entry("poneyland").or_default();
2751 ///
2752 /// assert_eq!(map["poneyland"], None);
2753 /// # }
2754 /// ```
2755 pub fn or_default(self) -> &'a mut V {
2756 match self {
2757 Occupied(entry) => entry.into_mut(),
2758 Vacant(entry) => entry.insert(Default::default()),
2759 }
2760 }
2761 }
2762
2763 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2764 /// Gets a reference to the key in the entry.
2765 ///
2766 /// # Examples
2767 ///
2768 /// ```
2769 /// use std::collections::HashMap;
2770 ///
2771 /// let mut map: HashMap<&str, u32> = HashMap::new();
2772 /// map.entry("poneyland").or_insert(12);
2773 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2774 /// ```
2775 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2776 pub fn key(&self) -> &K {
2777 self.elem.read().0
2778 }
2779
2780 /// Take the ownership of the key and value from the map.
2781 ///
2782 /// # Examples
2783 ///
2784 /// ```
2785 /// use std::collections::HashMap;
2786 /// use std::collections::hash_map::Entry;
2787 ///
2788 /// let mut map: HashMap<&str, u32> = HashMap::new();
2789 /// map.entry("poneyland").or_insert(12);
2790 ///
2791 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2792 /// // We delete the entry from the map.
2793 /// o.remove_entry();
2794 /// }
2795 ///
2796 /// assert_eq!(map.contains_key("poneyland"), false);
2797 /// ```
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);
2801 (k, v)
2802 }
2803
2804 /// Gets a reference to the value in the entry.
2805 ///
2806 /// # Examples
2807 ///
2808 /// ```
2809 /// use std::collections::HashMap;
2810 /// use std::collections::hash_map::Entry;
2811 ///
2812 /// let mut map: HashMap<&str, u32> = HashMap::new();
2813 /// map.entry("poneyland").or_insert(12);
2814 ///
2815 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2816 /// assert_eq!(o.get(), &12);
2817 /// }
2818 /// ```
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 pub fn get(&self) -> &V {
2821 self.elem.read().1
2822 }
2823
2824 /// Gets a mutable reference to the value in the entry.
2825 ///
2826 /// If you need a reference to the `OccupiedEntry` which may outlive the
2827 /// destruction of the `Entry` value, see [`into_mut`].
2828 ///
2829 /// [`into_mut`]: #method.into_mut
2830 ///
2831 /// # Examples
2832 ///
2833 /// ```
2834 /// use std::collections::HashMap;
2835 /// use std::collections::hash_map::Entry;
2836 ///
2837 /// let mut map: HashMap<&str, u32> = HashMap::new();
2838 /// map.entry("poneyland").or_insert(12);
2839 ///
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);
2844 ///
2845 /// // We can use the same Entry multiple times.
2846 /// *o.get_mut() += 2;
2847 /// }
2848 ///
2849 /// assert_eq!(map["poneyland"], 24);
2850 /// ```
2851 #[stable(feature = "rust1", since = "1.0.0")]
2852 pub fn get_mut(&mut self) -> &mut V {
2853 self.elem.read_mut().1
2854 }
2855
2856 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2857 /// with a lifetime bound to the map itself.
2858 ///
2859 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2860 ///
2861 /// [`get_mut`]: #method.get_mut
2862 ///
2863 /// # Examples
2864 ///
2865 /// ```
2866 /// use std::collections::HashMap;
2867 /// use std::collections::hash_map::Entry;
2868 ///
2869 /// let mut map: HashMap<&str, u32> = HashMap::new();
2870 /// map.entry("poneyland").or_insert(12);
2871 ///
2872 /// assert_eq!(map["poneyland"], 12);
2873 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2874 /// *o.into_mut() += 10;
2875 /// }
2876 ///
2877 /// assert_eq!(map["poneyland"], 22);
2878 /// ```
2879 #[stable(feature = "rust1", since = "1.0.0")]
2880 pub fn into_mut(self) -> &'a mut V {
2881 self.elem.into_mut_refs().1
2882 }
2883
2884 /// Sets the value of the entry, and returns the entry's old value.
2885 ///
2886 /// # Examples
2887 ///
2888 /// ```
2889 /// use std::collections::HashMap;
2890 /// use std::collections::hash_map::Entry;
2891 ///
2892 /// let mut map: HashMap<&str, u32> = HashMap::new();
2893 /// map.entry("poneyland").or_insert(12);
2894 ///
2895 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2896 /// assert_eq!(o.insert(15), 12);
2897 /// }
2898 ///
2899 /// assert_eq!(map["poneyland"], 15);
2900 /// ```
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);
2905 value
2906 }
2907
2908 /// Takes the value out of the entry, and returns it.
2909 ///
2910 /// # Examples
2911 ///
2912 /// ```
2913 /// use std::collections::HashMap;
2914 /// use std::collections::hash_map::Entry;
2915 ///
2916 /// let mut map: HashMap<&str, u32> = HashMap::new();
2917 /// map.entry("poneyland").or_insert(12);
2918 ///
2919 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2920 /// assert_eq!(o.remove(), 12);
2921 /// }
2922 ///
2923 /// assert_eq!(map.contains_key("poneyland"), false);
2924 /// ```
2925 #[stable(feature = "rust1", since = "1.0.0")]
2926 pub fn remove(self) -> V {
2927 pop_internal(self.elem).1
2928 }
2929
2930 /// Returns a key that was used for search.
2931 ///
2932 /// The key was retained for further use.
2933 fn take_key(&mut self) -> Option<K> {
2934 self.key.take()
2935 }
2936
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.
2939 ///
2940 /// # Examples
2941 ///
2942 /// ```
2943 /// #![feature(map_entry_replace)]
2944 /// use std::collections::hash_map::{Entry, HashMap};
2945 /// use std::rc::Rc;
2946 ///
2947 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2948 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2949 ///
2950 /// let my_key = Rc::new("Stringthing".to_string());
2951 ///
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);
2955 /// }
2956 ///
2957 /// ```
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();
2961
2962 let old_key = mem::replace(old_key, self.key.unwrap());
2963 let old_value = mem::replace(old_value, value);
2964
2965 (old_key, old_value)
2966 }
2967
2968 /// Replaces the key in the hash map with the key used to create this entry.
2969 ///
2970 /// # Examples
2971 ///
2972 /// ```
2973 /// #![feature(map_entry_replace)]
2974 /// use std::collections::hash_map::{Entry, HashMap};
2975 /// use std::rc::Rc;
2976 ///
2977 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2978 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2979 ///
2980 /// // Initialise known strings, run program, etc.
2981 ///
2982 /// reclaim_memory(&mut map, &known_strings);
2983 ///
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();
2989 /// }
2990 /// }
2991 /// }
2992 /// ```
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())
2997 }
2998 }
2999
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`.
3003 ///
3004 /// # Examples
3005 ///
3006 /// ```
3007 /// use std::collections::HashMap;
3008 ///
3009 /// let mut map: HashMap<&str, u32> = HashMap::new();
3010 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3011 /// ```
3012 #[stable(feature = "map_entry_keys", since = "1.10.0")]
3013 pub fn key(&self) -> &K {
3014 &self.key
3015 }
3016
3017 /// Take ownership of the key.
3018 ///
3019 /// # Examples
3020 ///
3021 /// ```
3022 /// use std::collections::HashMap;
3023 /// use std::collections::hash_map::Entry;
3024 ///
3025 /// let mut map: HashMap<&str, u32> = HashMap::new();
3026 ///
3027 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3028 /// v.into_key();
3029 /// }
3030 /// ```
3031 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3032 pub fn into_key(self) -> K {
3033 self.key
3034 }
3035
3036 /// Sets the value of the entry with the VacantEntry's key,
3037 /// and returns a mutable reference to it.
3038 ///
3039 /// # Examples
3040 ///
3041 /// ```
3042 /// use std::collections::HashMap;
3043 /// use std::collections::hash_map::Entry;
3044 ///
3045 /// let mut map: HashMap<&str, u32> = HashMap::new();
3046 ///
3047 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3048 /// o.insert(37);
3049 /// }
3050 /// assert_eq!(map["poneyland"], 37);
3051 /// ```
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);
3058 }
3059 robin_hood(bucket, disp, self.hash, self.key, value)
3060 },
3061 NoElem(mut bucket, disp) => {
3062 if disp >= DISPLACEMENT_THRESHOLD {
3063 bucket.table_mut().set_tag(true);
3064 }
3065 bucket.put(self.hash, self.key, value)
3066 },
3067 };
3068 b.into_mut_refs().1
3069 }
3070 }
3071
3072 #[stable(feature = "rust1", since = "1.0.0")]
3073 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3074 where K: Eq + Hash,
3075 S: BuildHasher + Default
3076 {
3077 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3078 let mut map = HashMap::with_hasher(Default::default());
3079 map.extend(iter);
3080 map
3081 }
3082 }
3083
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3086 where K: Eq + Hash,
3087 S: BuildHasher
3088 {
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() {
3096 iter.size_hint().0
3097 } else {
3098 (iter.size_hint().0 + 1) / 2
3099 };
3100 self.reserve(reserve);
3101 for (k, v) in iter {
3102 self.insert(k, v);
3103 }
3104 }
3105 }
3106
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,
3110 V: Copy,
3111 S: BuildHasher
3112 {
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)));
3115 }
3116 }
3117
3118 /// `RandomState` is the default state for [`HashMap`] types.
3119 ///
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.
3123 ///
3124 /// [`HashMap`]: struct.HashMap.html
3125 /// [`Hasher`]: ../../hash/trait.Hasher.html
3126 ///
3127 /// # Examples
3128 ///
3129 /// ```
3130 /// use std::collections::HashMap;
3131 /// use std::collections::hash_map::RandomState;
3132 ///
3133 /// let s = RandomState::new();
3134 /// let mut map = HashMap::with_hasher(s);
3135 /// map.insert(1, 2);
3136 /// ```
3137 #[derive(Clone)]
3138 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3139 pub struct RandomState {
3140 k0: u64,
3141 k1: u64,
3142 }
3143
3144 impl RandomState {
3145 /// Constructs a new `RandomState` that is initialized with random keys.
3146 ///
3147 /// # Examples
3148 ///
3149 /// ```
3150 /// use std::collections::hash_map::RandomState;
3151 ///
3152 /// let s = RandomState::new();
3153 /// ```
3154 #[inline]
3155 #[allow(deprecated)]
3156 // rand
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.
3165 //
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())
3172 });
3173
3174 KEYS.with(|keys| {
3175 let (k0, k1) = keys.get();
3176 keys.set((k0.wrapping_add(1), k1));
3177 RandomState { k0: k0, k1: k1 }
3178 })
3179 }
3180 }
3181
3182 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3183 impl BuildHasher for RandomState {
3184 type Hasher = DefaultHasher;
3185 #[inline]
3186 #[allow(deprecated)]
3187 fn build_hasher(&self) -> DefaultHasher {
3188 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3189 }
3190 }
3191
3192 /// The default [`Hasher`] used by [`RandomState`].
3193 ///
3194 /// The internal algorithm is not specified, and so it and its hashes should
3195 /// not be relied upon over releases.
3196 ///
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);
3203
3204 impl DefaultHasher {
3205 /// Creates a new `DefaultHasher`.
3206 ///
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))
3214 }
3215 }
3216
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()
3223 }
3224 }
3225
3226 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3227 impl Hasher for DefaultHasher {
3228 #[inline]
3229 fn write(&mut self, msg: &[u8]) {
3230 self.0.write(msg)
3231 }
3232
3233 #[inline]
3234 fn finish(&self) -> u64 {
3235 self.0.finish()
3236 }
3237 }
3238
3239 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3240 impl Default for RandomState {
3241 /// Constructs a new `RandomState`.
3242 #[inline]
3243 fn default() -> RandomState {
3244 RandomState::new()
3245 }
3246 }
3247
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 { .. }")
3252 }
3253 }
3254
3255 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3256 where K: Eq + Hash + Borrow<Q>,
3257 S: BuildHasher,
3258 Q: Eq + Hash
3259 {
3260 type Key = K;
3261
3262 #[inline]
3263 fn get(&self, key: &Q) -> Option<&K> {
3264 self.search(key).map(|bucket| bucket.into_refs().0)
3265 }
3266
3267 fn take(&mut self, key: &Q) -> Option<K> {
3268 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3269 }
3270
3271 #[inline]
3272 fn replace(&mut self, key: K) -> Option<K> {
3273 self.reserve(1);
3274
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))
3279 }
3280 Vacant(vacant) => {
3281 vacant.insert(());
3282 None
3283 }
3284 }
3285 }
3286 }
3287
3288 #[allow(dead_code)]
3289 fn assert_covariance() {
3290 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3291 v
3292 }
3293 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3294 v
3295 }
3296 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3297 v
3298 }
3299 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3300 v
3301 }
3302 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3303 v
3304 }
3305 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3306 v
3307 }
3308 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3309 v
3310 }
3311 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3312 v
3313 }
3314 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3315 v
3316 }
3317 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3318 v
3319 }
3320 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3321 -> Drain<'new, &'new str, &'new str> {
3322 d
3323 }
3324 }
3325
3326 #[cfg(test)]
3327 mod test_map {
3328 use super::HashMap;
3329 use super::Entry::{Occupied, Vacant};
3330 use super::RandomState;
3331 use cell::RefCell;
3332 use rand::{thread_rng, Rng};
3333 use realstd::collections::CollectionAllocErr::*;
3334 use realstd::mem::size_of;
3335 use realstd::usize;
3336
3337 #[test]
3338 fn test_zero_capacities() {
3339 type HM = HashMap<i32, i32>;
3340
3341 let m = HM::new();
3342 assert_eq!(m.capacity(), 0);
3343
3344 let m = HM::default();
3345 assert_eq!(m.capacity(), 0);
3346
3347 let m = HM::with_hasher(RandomState::new());
3348 assert_eq!(m.capacity(), 0);
3349
3350 let m = HM::with_capacity(0);
3351 assert_eq!(m.capacity(), 0);
3352
3353 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3354 assert_eq!(m.capacity(), 0);
3355
3356 let mut m = HM::new();
3357 m.insert(1, 1);
3358 m.insert(2, 2);
3359 m.remove(&1);
3360 m.remove(&2);
3361 m.shrink_to_fit();
3362 assert_eq!(m.capacity(), 0);
3363
3364 let mut m = HM::new();
3365 m.reserve(0);
3366 assert_eq!(m.capacity(), 0);
3367 }
3368
3369 #[test]
3370 fn test_create_capacity_zero() {
3371 let mut m = HashMap::with_capacity(0);
3372
3373 assert!(m.insert(1, 1).is_none());
3374
3375 assert!(m.contains_key(&1));
3376 assert!(!m.contains_key(&0));
3377 }
3378
3379 #[test]
3380 fn test_insert() {
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);
3389 }
3390
3391 #[test]
3392 fn test_clone() {
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);
3399 let m2 = m.clone();
3400 assert_eq!(*m2.get(&1).unwrap(), 2);
3401 assert_eq!(*m2.get(&2).unwrap(), 4);
3402 assert_eq!(m2.len(), 2);
3403 }
3404
3405 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3406
3407 #[derive(Hash, PartialEq, Eq)]
3408 struct Droppable {
3409 k: usize,
3410 }
3411
3412 impl Droppable {
3413 fn new(k: usize) -> Droppable {
3414 DROP_VECTOR.with(|slot| {
3415 slot.borrow_mut()[k] += 1;
3416 });
3417
3418 Droppable { k }
3419 }
3420 }
3421
3422 impl Drop for Droppable {
3423 fn drop(&mut self) {
3424 DROP_VECTOR.with(|slot| {
3425 slot.borrow_mut()[self.k] -= 1;
3426 });
3427 }
3428 }
3429
3430 impl Clone for Droppable {
3431 fn clone(&self) -> Droppable {
3432 Droppable::new(self.k)
3433 }
3434 }
3435
3436 #[test]
3437 fn test_drops() {
3438 DROP_VECTOR.with(|slot| {
3439 *slot.borrow_mut() = vec![0; 200];
3440 });
3441
3442 {
3443 let mut m = HashMap::new();
3444
3445 DROP_VECTOR.with(|v| {
3446 for i in 0..200 {
3447 assert_eq!(v.borrow()[i], 0);
3448 }
3449 });
3450
3451 for i in 0..100 {
3452 let d1 = Droppable::new(i);
3453 let d2 = Droppable::new(i + 100);
3454 m.insert(d1, d2);
3455 }
3456
3457 DROP_VECTOR.with(|v| {
3458 for i in 0..200 {
3459 assert_eq!(v.borrow()[i], 1);
3460 }
3461 });
3462
3463 for i in 0..50 {
3464 let k = Droppable::new(i);
3465 let v = m.remove(&k);
3466
3467 assert!(v.is_some());
3468
3469 DROP_VECTOR.with(|v| {
3470 assert_eq!(v.borrow()[i], 1);
3471 assert_eq!(v.borrow()[i+100], 1);
3472 });
3473 }
3474
3475 DROP_VECTOR.with(|v| {
3476 for i in 0..50 {
3477 assert_eq!(v.borrow()[i], 0);
3478 assert_eq!(v.borrow()[i+100], 0);
3479 }
3480
3481 for i in 50..100 {
3482 assert_eq!(v.borrow()[i], 1);
3483 assert_eq!(v.borrow()[i+100], 1);
3484 }
3485 });
3486 }
3487
3488 DROP_VECTOR.with(|v| {
3489 for i in 0..200 {
3490 assert_eq!(v.borrow()[i], 0);
3491 }
3492 });
3493 }
3494
3495 #[test]
3496 fn test_into_iter_drops() {
3497 DROP_VECTOR.with(|v| {
3498 *v.borrow_mut() = vec![0; 200];
3499 });
3500
3501 let hm = {
3502 let mut hm = HashMap::new();
3503
3504 DROP_VECTOR.with(|v| {
3505 for i in 0..200 {
3506 assert_eq!(v.borrow()[i], 0);
3507 }
3508 });
3509
3510 for i in 0..100 {
3511 let d1 = Droppable::new(i);
3512 let d2 = Droppable::new(i + 100);
3513 hm.insert(d1, d2);
3514 }
3515
3516 DROP_VECTOR.with(|v| {
3517 for i in 0..200 {
3518 assert_eq!(v.borrow()[i], 1);
3519 }
3520 });
3521
3522 hm
3523 };
3524
3525 // By the way, ensure that cloning doesn't screw up the dropping.
3526 drop(hm.clone());
3527
3528 {
3529 let mut half = hm.into_iter().take(50);
3530
3531 DROP_VECTOR.with(|v| {
3532 for i in 0..200 {
3533 assert_eq!(v.borrow()[i], 1);
3534 }
3535 });
3536
3537 for _ in half.by_ref() {}
3538
3539 DROP_VECTOR.with(|v| {
3540 let nk = (0..100)
3541 .filter(|&i| v.borrow()[i] == 1)
3542 .count();
3543
3544 let nv = (0..100)
3545 .filter(|&i| v.borrow()[i + 100] == 1)
3546 .count();
3547
3548 assert_eq!(nk, 50);
3549 assert_eq!(nv, 50);
3550 });
3551 };
3552
3553 DROP_VECTOR.with(|v| {
3554 for i in 0..200 {
3555 assert_eq!(v.borrow()[i], 0);
3556 }
3557 });
3558 }
3559
3560 #[test]
3561 fn test_empty_remove() {
3562 let mut m: HashMap<i32, bool> = HashMap::new();
3563 assert_eq!(m.remove(&0), None);
3564 }
3565
3566 #[test]
3567 fn test_empty_entry() {
3568 let mut m: HashMap<i32, bool> = HashMap::new();
3569 match m.entry(0) {
3570 Occupied(_) => panic!(),
3571 Vacant(_) => {}
3572 }
3573 assert!(*m.entry(0).or_insert(true));
3574 assert_eq!(m.len(), 1);
3575 }
3576
3577 #[test]
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);
3589 }
3590
3591 #[test]
3592 fn test_lots_of_insertions() {
3593 let mut m = HashMap::new();
3594
3595 // Try this a few times to make sure we never screw up the hashmap's
3596 // internal state.
3597 for _ in 0..10 {
3598 assert!(m.is_empty());
3599
3600 for i in 1..1001 {
3601 assert!(m.insert(i, i).is_none());
3602
3603 for j in 1..=i {
3604 let r = m.get(&j);
3605 assert_eq!(r, Some(&j));
3606 }
3607
3608 for j in i + 1..1001 {
3609 let r = m.get(&j);
3610 assert_eq!(r, None);
3611 }
3612 }
3613
3614 for i in 1001..2001 {
3615 assert!(!m.contains_key(&i));
3616 }
3617
3618 // remove forwards
3619 for i in 1..1001 {
3620 assert!(m.remove(&i).is_some());
3621
3622 for j in 1..=i {
3623 assert!(!m.contains_key(&j));
3624 }
3625
3626 for j in i + 1..1001 {
3627 assert!(m.contains_key(&j));
3628 }
3629 }
3630
3631 for i in 1..1001 {
3632 assert!(!m.contains_key(&i));
3633 }
3634
3635 for i in 1..1001 {
3636 assert!(m.insert(i, i).is_none());
3637 }
3638
3639 // remove backwards
3640 for i in (1..1001).rev() {
3641 assert!(m.remove(&i).is_some());
3642
3643 for j in i..1001 {
3644 assert!(!m.contains_key(&j));
3645 }
3646
3647 for j in 1..i {
3648 assert!(m.contains_key(&j));
3649 }
3650 }
3651 }
3652 }
3653
3654 #[test]
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());
3660 let new = 100;
3661 match m.get_mut(&5) {
3662 None => panic!(),
3663 Some(x) => *x = new,
3664 }
3665 assert_eq!(m.get(&5), Some(&new));
3666 }
3667
3668 #[test]
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);
3675 }
3676
3677 #[test]
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);
3686 }
3687
3688 #[test]
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);
3703 }
3704
3705 #[test]
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());
3712 }
3713
3714 #[test]
3715 fn test_remove() {
3716 let mut m = HashMap::new();
3717 m.insert(1, 2);
3718 assert_eq!(m.remove(&1), Some(2));
3719 assert_eq!(m.remove(&1), None);
3720 }
3721
3722 #[test]
3723 fn test_remove_entry() {
3724 let mut m = HashMap::new();
3725 m.insert(1, 2);
3726 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3727 assert_eq!(m.remove(&1), None);
3728 }
3729
3730 #[test]
3731 fn test_iterate() {
3732 let mut m = HashMap::with_capacity(4);
3733 for i in 0..32 {
3734 assert!(m.insert(i, i*2).is_none());
3735 }
3736 assert_eq!(m.len(), 32);
3737
3738 let mut observed: u32 = 0;
3739
3740 for (k, v) in &m {
3741 assert_eq!(*v, *k * 2);
3742 observed |= 1 << *k;
3743 }
3744 assert_eq!(observed, 0xFFFF_FFFF);
3745 }
3746
3747 #[test]
3748 fn test_keys() {
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));
3756 }
3757
3758 #[test]
3759 fn test_values() {
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'));
3767 }
3768
3769 #[test]
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
3775 }
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));
3781 }
3782
3783 #[test]
3784 fn test_find() {
3785 let mut m = HashMap::new();
3786 assert!(m.get(&1).is_none());
3787 m.insert(1, 2);
3788 match m.get(&1) {
3789 None => panic!(),
3790 Some(v) => assert_eq!(*v, 2),
3791 }
3792 }
3793
3794 #[test]
3795 fn test_eq() {
3796 let mut m1 = HashMap::new();
3797 m1.insert(1, 2);
3798 m1.insert(2, 3);
3799 m1.insert(3, 4);
3800
3801 let mut m2 = HashMap::new();
3802 m2.insert(1, 2);
3803 m2.insert(2, 3);
3804
3805 assert!(m1 != m2);
3806
3807 m2.insert(3, 4);
3808
3809 assert_eq!(m1, m2);
3810 }
3811
3812 #[test]
3813 fn test_show() {
3814 let mut map = HashMap::new();
3815 let empty: HashMap<i32, i32> = HashMap::new();
3816
3817 map.insert(1, 2);
3818 map.insert(3, 4);
3819
3820 let map_str = format!("{:?}", map);
3821
3822 assert!(map_str == "{1: 2, 3: 4}" ||
3823 map_str == "{3: 4, 1: 2}");
3824 assert_eq!(format!("{:?}", empty), "{}");
3825 }
3826
3827 #[test]
3828 fn test_expand() {
3829 let mut m = HashMap::new();
3830
3831 assert_eq!(m.len(), 0);
3832 assert!(m.is_empty());
3833
3834 let mut i = 0;
3835 let old_raw_cap = m.raw_capacity();
3836 while old_raw_cap == m.raw_capacity() {
3837 m.insert(i, i);
3838 i += 1;
3839 }
3840
3841 assert_eq!(m.len(), i);
3842 assert!(!m.is_empty());
3843 }
3844
3845 #[test]
3846 fn test_behavior_resize_policy() {
3847 let mut m = HashMap::new();
3848
3849 assert_eq!(m.len(), 0);
3850 assert_eq!(m.raw_capacity(), 0);
3851 assert!(m.is_empty());
3852
3853 m.insert(0, 0);
3854 m.remove(&0);
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();
3859
3860 assert_eq!(raw_cap, initial_raw_cap * 2);
3861
3862 let mut i = 0;
3863 for _ in 0..raw_cap * 3 / 4 {
3864 m.insert(i, i);
3865 i += 1;
3866 }
3867 // three quarters full
3868
3869 assert_eq!(m.len(), i);
3870 assert_eq!(m.raw_capacity(), raw_cap);
3871
3872 for _ in 0..raw_cap / 4 {
3873 m.insert(i, i);
3874 i += 1;
3875 }
3876 // half full
3877
3878 let new_raw_cap = m.raw_capacity();
3879 assert_eq!(new_raw_cap, raw_cap * 2);
3880
3881 for _ in 0..raw_cap / 2 - 1 {
3882 i -= 1;
3883 m.remove(&i);
3884 assert_eq!(m.raw_capacity(), new_raw_cap);
3885 }
3886 // A little more than one quarter full.
3887 m.shrink_to_fit();
3888 assert_eq!(m.raw_capacity(), raw_cap);
3889 // again, a little more than half full
3890 for _ in 0..raw_cap / 2 - 1 {
3891 i -= 1;
3892 m.remove(&i);
3893 }
3894 m.shrink_to_fit();
3895
3896 assert_eq!(m.len(), i);
3897 assert!(!m.is_empty());
3898 assert_eq!(m.raw_capacity(), initial_raw_cap);
3899 }
3900
3901 #[test]
3902 fn test_reserve_shrink_to_fit() {
3903 let mut m = HashMap::new();
3904 m.insert(0, 0);
3905 m.remove(&0);
3906 assert!(m.capacity() >= m.len());
3907 for i in 0..128 {
3908 m.insert(i, i);
3909 }
3910 m.reserve(256);
3911
3912 let usable_cap = m.capacity();
3913 for i in 128..(128 + 256) {
3914 m.insert(i, i);
3915 assert_eq!(m.capacity(), usable_cap);
3916 }
3917
3918 for i in 100..(128 + 256) {
3919 assert_eq!(m.remove(&i), Some(i));
3920 }
3921 m.shrink_to_fit();
3922
3923 assert_eq!(m.len(), 100);
3924 assert!(!m.is_empty());
3925 assert!(m.capacity() >= m.len());
3926
3927 for i in 0..100 {
3928 assert_eq!(m.remove(&i), Some(i));
3929 }
3930 m.shrink_to_fit();
3931 m.insert(0, 0);
3932
3933 assert_eq!(m.len(), 1);
3934 assert!(m.capacity() >= m.len());
3935 assert_eq!(m.remove(&0), Some(0));
3936 }
3937
3938 #[test]
3939 fn test_from_iter() {
3940 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3941
3942 let map: HashMap<_, _> = xs.iter().cloned().collect();
3943
3944 for &(k, v) in &xs {
3945 assert_eq!(map.get(&k), Some(&v));
3946 }
3947 }
3948
3949 #[test]
3950 fn test_size_hint() {
3951 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3952
3953 let map: HashMap<_, _> = xs.iter().cloned().collect();
3954
3955 let mut iter = map.iter();
3956
3957 for _ in iter.by_ref().take(3) {}
3958
3959 assert_eq!(iter.size_hint(), (3, Some(3)));
3960 }
3961
3962 #[test]
3963 fn test_iter_len() {
3964 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3965
3966 let map: HashMap<_, _> = xs.iter().cloned().collect();
3967
3968 let mut iter = map.iter();
3969
3970 for _ in iter.by_ref().take(3) {}
3971
3972 assert_eq!(iter.len(), 3);
3973 }
3974
3975 #[test]
3976 fn test_mut_size_hint() {
3977 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3978
3979 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3980
3981 let mut iter = map.iter_mut();
3982
3983 for _ in iter.by_ref().take(3) {}
3984
3985 assert_eq!(iter.size_hint(), (3, Some(3)));
3986 }
3987
3988 #[test]
3989 fn test_iter_mut_len() {
3990 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3991
3992 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3993
3994 let mut iter = map.iter_mut();
3995
3996 for _ in iter.by_ref().take(3) {}
3997
3998 assert_eq!(iter.len(), 3);
3999 }
4000
4001 #[test]
4002 fn test_index() {
4003 let mut map = HashMap::new();
4004
4005 map.insert(1, 2);
4006 map.insert(2, 1);
4007 map.insert(3, 4);
4008
4009 assert_eq!(map[&2], 1);
4010 }
4011
4012 #[test]
4013 #[should_panic]
4014 fn test_index_nonexistent() {
4015 let mut map = HashMap::new();
4016
4017 map.insert(1, 2);
4018 map.insert(2, 1);
4019 map.insert(3, 4);
4020
4021 map[&4];
4022 }
4023
4024 #[test]
4025 fn test_entry() {
4026 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4027
4028 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4029
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);
4036 }
4037 }
4038 assert_eq!(map.get(&1).unwrap(), &100);
4039 assert_eq!(map.len(), 6);
4040
4041
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;
4048 *v = new_v;
4049 }
4050 }
4051 assert_eq!(map.get(&2).unwrap(), &200);
4052 assert_eq!(map.len(), 6);
4053
4054 // Existing key (take)
4055 match map.entry(3) {
4056 Vacant(_) => unreachable!(),
4057 Occupied(view) => {
4058 assert_eq!(view.remove(), 30);
4059 }
4060 }
4061 assert_eq!(map.get(&3), None);
4062 assert_eq!(map.len(), 5);
4063
4064
4065 // Inexistent key (insert)
4066 match map.entry(10) {
4067 Occupied(_) => unreachable!(),
4068 Vacant(view) => {
4069 assert_eq!(*view.insert(1000), 1000);
4070 }
4071 }
4072 assert_eq!(map.get(&10).unwrap(), &1000);
4073 assert_eq!(map.len(), 6);
4074 }
4075
4076 #[test]
4077 fn test_entry_take_doesnt_corrupt() {
4078 #![allow(deprecated)] //rand
4079 // Test for #19292
4080 fn check(m: &HashMap<i32, ()>) {
4081 for k in m.keys() {
4082 assert!(m.contains_key(k),
4083 "{} is in keys() but not in the map?", k);
4084 }
4085 }
4086
4087 let mut m = HashMap::new();
4088 let mut rng = thread_rng();
4089
4090 // Populate the map with some items.
4091 for _ in 0..50 {
4092 let x = rng.gen_range(-10, 10);
4093 m.insert(x, ());
4094 }
4095
4096 for _ in 0..1000 {
4097 let x = rng.gen_range(-10, 10);
4098 match m.entry(x) {
4099 Vacant(_) => {}
4100 Occupied(e) => {
4101 e.remove();
4102 }
4103 }
4104
4105 check(&m);
4106 }
4107 }
4108
4109 #[test]
4110 fn test_extend_ref() {
4111 let mut a = HashMap::new();
4112 a.insert(1, "one");
4113 let mut b = HashMap::new();
4114 b.insert(2, "two");
4115 b.insert(3, "three");
4116
4117 a.extend(&b);
4118
4119 assert_eq!(a.len(), 3);
4120 assert_eq!(a[&1], "one");
4121 assert_eq!(a[&2], "two");
4122 assert_eq!(a[&3], "three");
4123 }
4124
4125 #[test]
4126 fn test_capacity_not_less_than_len() {
4127 let mut a = HashMap::new();
4128 let mut item = 0;
4129
4130 for _ in 0..116 {
4131 a.insert(item, 0);
4132 item += 1;
4133 }
4134
4135 assert!(a.capacity() > a.len());
4136
4137 let free = a.capacity() - a.len();
4138 for _ in 0..free {
4139 a.insert(item, 0);
4140 item += 1;
4141 }
4142
4143 assert_eq!(a.len(), a.capacity());
4144
4145 // Insert at capacity should cause allocation.
4146 a.insert(item, 0);
4147 assert!(a.capacity() > a.len());
4148 }
4149
4150 #[test]
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);
4159
4160 match a.entry(key.clone()) {
4161 Vacant(_) => panic!(),
4162 Occupied(e) => assert_eq!(key, *e.key()),
4163 }
4164 assert_eq!(a.len(), 1);
4165 assert_eq!(a[key], value);
4166 }
4167
4168 #[test]
4169 fn test_vacant_entry_key() {
4170 let mut a = HashMap::new();
4171 let key = "hello there";
4172 let value = "value goes here";
4173
4174 assert!(a.is_empty());
4175 match a.entry(key.clone()) {
4176 Occupied(_) => panic!(),
4177 Vacant(e) => {
4178 assert_eq!(key, *e.key());
4179 e.insert(value.clone());
4180 }
4181 }
4182 assert_eq!(a.len(), 1);
4183 assert_eq!(a[key], value);
4184 }
4185
4186 #[test]
4187 fn test_retain() {
4188 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4189
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);
4195 }
4196
4197 #[test]
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)));
4205
4206 for (&k, &v) in &second {
4207 let prev_cap = first.capacity();
4208 let expect_grow = first.len() == prev_cap;
4209 first.insert(k, v);
4210 if !expect_grow && first.capacity() != prev_cap {
4211 return;
4212 }
4213 }
4214 panic!("Adaptive early resize failed");
4215 }
4216
4217 #[test]
4218 fn test_try_reserve() {
4219
4220 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4221
4222 const MAX_USIZE: usize = usize::MAX;
4223
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;
4232
4233 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4234 } else { panic!("usize::MAX should trigger an overflow!"); }
4235
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!") }
4239 } else {
4240 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4241 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4242 }
4243 }
4244
4245 #[test]
4246 fn test_raw_entry() {
4247 use super::RawEntryMut::{Occupied, Vacant};
4248
4249 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4250
4251 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4252
4253 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4254 use core::hash::{BuildHasher, Hash, Hasher};
4255
4256 let mut hasher = map.hasher().build_hasher();
4257 k.hash(&mut hasher);
4258 hasher.finish()
4259 };
4260
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);
4267 }
4268 }
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);
4275
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;
4282 *v = new_v;
4283 }
4284 }
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);
4291
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!(),
4296 Occupied(view) => {
4297 assert_eq!(view.remove_entry(), (3, 30));
4298 }
4299 }
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);
4305
4306
4307 // Nonexistent key (insert)
4308 match map.raw_entry_mut().from_key(&10) {
4309 Occupied(_) => unreachable!(),
4310 Vacant(view) => {
4311 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4312 }
4313 }
4314 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4315 assert_eq!(map.len(), 6);
4316
4317 // Ensure all lookup methods produce equivalent results.
4318 for k in 0..12 {
4319 let hash = compute_hash(&map, k);
4320 let v = map.get(&k).cloned();
4321 let kv = v.as_ref().map(|v| (&k, v));
4322
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);
4327
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),
4331 }
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),
4335 }
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),
4339 }
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),
4343 }
4344 }
4345 }
4346
4347 }