]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[rust.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     where K: Eq + Hash,
721           S: BuildHasher
722 {
723     /// Creates an empty `HashMap` which will use the given hash builder to hash
724     /// keys.
725     ///
726     /// The created map has the default initial capacity.
727     ///
728     /// Warning: `hash_builder` is normally randomly generated, and
729     /// is designed to allow HashMaps to be resistant to attacks that
730     /// cause many collisions and very poor performance. Setting it
731     /// manually using this function can expose a DoS attack vector.
732     ///
733     /// # Examples
734     ///
735     /// ```
736     /// use std::collections::HashMap;
737     /// use std::collections::hash_map::RandomState;
738     ///
739     /// let s = RandomState::new();
740     /// let mut map = HashMap::with_hasher(s);
741     /// map.insert(1, 2);
742     /// ```
743     #[inline]
744     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
745     pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
746         HashMap {
747             hash_builder,
748             resize_policy: DefaultResizePolicy::new(),
749             table: RawTable::new(0),
750         }
751     }
752
753     /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
754     /// to hash the keys.
755     ///
756     /// The hash map will be able to hold at least `capacity` elements without
757     /// reallocating. If `capacity` is 0, the hash map will not allocate.
758     ///
759     /// Warning: `hash_builder` is normally randomly generated, and
760     /// is designed to allow HashMaps to be resistant to attacks that
761     /// cause many collisions and very poor performance. Setting it
762     /// manually using this function can expose a DoS attack vector.
763     ///
764     /// # Examples
765     ///
766     /// ```
767     /// use std::collections::HashMap;
768     /// use std::collections::hash_map::RandomState;
769     ///
770     /// let s = RandomState::new();
771     /// let mut map = HashMap::with_capacity_and_hasher(10, s);
772     /// map.insert(1, 2);
773     /// ```
774     #[inline]
775     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
776     pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
777         let resize_policy = DefaultResizePolicy::new();
778         let raw_cap = resize_policy.raw_capacity(capacity);
779         HashMap {
780             hash_builder,
781             resize_policy,
782             table: RawTable::new(raw_cap),
783         }
784     }
785
786     /// Returns a reference to the map's [`BuildHasher`].
787     ///
788     /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
789     ///
790     /// # Examples
791     ///
792     /// ```
793     /// use std::collections::HashMap;
794     /// use std::collections::hash_map::RandomState;
795     ///
796     /// let hasher = RandomState::new();
797     /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
798     /// let hasher: &RandomState = map.hasher();
799     /// ```
800     #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
801     pub fn hasher(&self) -> &S {
802         &self.hash_builder
803     }
804
805     /// Returns the number of elements the map can hold without reallocating.
806     ///
807     /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
808     /// more, but is guaranteed to be able to hold at least this many.
809     ///
810     /// # Examples
811     ///
812     /// ```
813     /// use std::collections::HashMap;
814     /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
815     /// assert!(map.capacity() >= 100);
816     /// ```
817     #[inline]
818     #[stable(feature = "rust1", since = "1.0.0")]
819     pub fn capacity(&self) -> usize {
820         self.resize_policy.capacity(self.raw_capacity())
821     }
822
823     /// Returns the hash map's raw capacity.
824     #[inline]
825     fn raw_capacity(&self) -> usize {
826         self.table.capacity()
827     }
828
829     /// Reserves capacity for at least `additional` more elements to be inserted
830     /// in the `HashMap`. The collection may reserve more space to avoid
831     /// frequent reallocations.
832     ///
833     /// # Panics
834     ///
835     /// Panics if the new allocation size overflows [`usize`].
836     ///
837     /// [`usize`]: ../../std/primitive.usize.html
838     ///
839     /// # Examples
840     ///
841     /// ```
842     /// use std::collections::HashMap;
843     /// let mut map: HashMap<&str, i32> = HashMap::new();
844     /// map.reserve(10);
845     /// ```
846     #[inline]
847     #[stable(feature = "rust1", since = "1.0.0")]
848     pub fn reserve(&mut self, additional: usize) {
849         match self.reserve_internal(additional, Infallible) {
850             Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
851             Err(CollectionAllocErr::AllocErr) => unreachable!(),
852             Ok(()) => { /* yay */ }
853         }
854     }
855
856     /// Tries to reserve capacity for at least `additional` more elements to be inserted
857     /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
858     /// frequent reallocations.
859     ///
860     /// # Errors
861     ///
862     /// If the capacity overflows, or the allocator reports a failure, then an error
863     /// is returned.
864     ///
865     /// # Examples
866     ///
867     /// ```
868     /// #![feature(try_reserve)]
869     /// use std::collections::HashMap;
870     /// let mut map: HashMap<&str, isize> = HashMap::new();
871     /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
872     /// ```
873     #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
874     pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
875         self.reserve_internal(additional, Fallible)
876     }
877
878     #[inline]
879     fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
880         -> Result<(), CollectionAllocErr> {
881
882         let remaining = self.capacity() - self.len(); // this can't overflow
883         if remaining < additional {
884             let min_cap = self.len()
885                 .checked_add(additional)
886                 .ok_or(CollectionAllocErr::CapacityOverflow)?;
887             let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
888             self.try_resize(raw_cap, fallibility)?;
889         } else if self.table.tag() && remaining <= self.len() {
890             // Probe sequence is too long and table is half full,
891             // resize early to reduce probing length.
892             let new_capacity = self.table.capacity() * 2;
893             self.try_resize(new_capacity, fallibility)?;
894         }
895         Ok(())
896     }
897
898     /// Resizes the internal vectors to a new capacity. It's your
899     /// responsibility to:
900     ///   1) Ensure `new_raw_cap` is enough for all the elements, accounting
901     ///      for the load factor.
902     ///   2) Ensure `new_raw_cap` is a power of two or zero.
903     #[inline(never)]
904     #[cold]
905     fn try_resize(
906         &mut self,
907         new_raw_cap: usize,
908         fallibility: Fallibility,
909     ) -> Result<(), CollectionAllocErr> {
910         assert!(self.table.size() <= new_raw_cap);
911         assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
912
913         let mut old_table = replace(
914             &mut self.table,
915             match fallibility {
916                 Infallible => RawTable::new(new_raw_cap),
917                 Fallible => RawTable::try_new(new_raw_cap)?,
918             }
919         );
920         let old_size = old_table.size();
921
922         if old_table.size() == 0 {
923             return Ok(());
924         }
925
926         let mut bucket = Bucket::head_bucket(&mut old_table);
927
928         // This is how the buckets might be laid out in memory:
929         // ($ marks an initialized bucket)
930         //  ________________
931         // |$$$_$$$$$$_$$$$$|
932         //
933         // But we've skipped the entire initial cluster of buckets
934         // and will continue iteration in this order:
935         //  ________________
936         //     |$$$$$$_$$$$$
937         //                  ^ wrap around once end is reached
938         //  ________________
939         //  $$$_____________|
940         //    ^ exit once table.size == 0
941         loop {
942             bucket = match bucket.peek() {
943                 Full(bucket) => {
944                     let h = bucket.hash();
945                     let (b, k, v) = bucket.take();
946                     self.insert_hashed_ordered(h, k, v);
947                     if b.table().size() == 0 {
948                         break;
949                     }
950                     b.into_bucket()
951                 }
952                 Empty(b) => b.into_bucket(),
953             };
954             bucket.next();
955         }
956
957         assert_eq!(self.table.size(), old_size);
958         Ok(())
959     }
960
961     /// Shrinks the capacity of the map as much as possible. It will drop
962     /// down as much as possible while maintaining the internal rules
963     /// and possibly leaving some space in accordance with the resize policy.
964     ///
965     /// # Examples
966     ///
967     /// ```
968     /// use std::collections::HashMap;
969     ///
970     /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
971     /// map.insert(1, 2);
972     /// map.insert(3, 4);
973     /// assert!(map.capacity() >= 100);
974     /// map.shrink_to_fit();
975     /// assert!(map.capacity() >= 2);
976     /// ```
977     #[stable(feature = "rust1", since = "1.0.0")]
978     pub fn shrink_to_fit(&mut self) {
979         let new_raw_cap = self.resize_policy.raw_capacity(self.len());
980         if self.raw_capacity() != new_raw_cap {
981             let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
982             let old_size = old_table.size();
983
984             // Shrink the table. Naive algorithm for resizing:
985             for (h, k, v) in old_table.into_iter() {
986                 self.insert_hashed_nocheck(h, k, v);
987             }
988
989             debug_assert_eq!(self.table.size(), old_size);
990         }
991     }
992
993     /// Shrinks the capacity of the map with a lower limit. It will drop
994     /// down no lower than the supplied limit while maintaining the internal rules
995     /// and possibly leaving some space in accordance with the resize policy.
996     ///
997     /// Panics if the current capacity is smaller than the supplied
998     /// minimum capacity.
999     ///
1000     /// # Examples
1001     ///
1002     /// ```
1003     /// #![feature(shrink_to)]
1004     /// use std::collections::HashMap;
1005     ///
1006     /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1007     /// map.insert(1, 2);
1008     /// map.insert(3, 4);
1009     /// assert!(map.capacity() >= 100);
1010     /// map.shrink_to(10);
1011     /// assert!(map.capacity() >= 10);
1012     /// map.shrink_to(0);
1013     /// assert!(map.capacity() >= 2);
1014     /// ```
1015     #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1016     pub fn shrink_to(&mut self, min_capacity: usize) {
1017         assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1018
1019         let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1020         if self.raw_capacity() != new_raw_cap {
1021             let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1022             let old_size = old_table.size();
1023
1024             // Shrink the table. Naive algorithm for resizing:
1025             for (h, k, v) in old_table.into_iter() {
1026                 self.insert_hashed_nocheck(h, k, v);
1027             }
1028
1029             debug_assert_eq!(self.table.size(), old_size);
1030         }
1031     }
1032
1033     /// Insert a pre-hashed key-value pair, without first checking
1034     /// that there's enough room in the buckets. Returns a reference to the
1035     /// newly insert value.
1036     ///
1037     /// If the key already exists, the hashtable will be returned untouched
1038     /// and a reference to the existing element will be returned.
1039     fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1040         let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1041         match entry {
1042             Some(Occupied(mut elem)) => Some(elem.insert(v)),
1043             Some(Vacant(elem)) => {
1044                 elem.insert(v);
1045                 None
1046             }
1047             None => unreachable!(),
1048         }
1049     }
1050
1051     /// An iterator visiting all keys in arbitrary order.
1052     /// The iterator element type is `&'a K`.
1053     ///
1054     /// # Examples
1055     ///
1056     /// ```
1057     /// use std::collections::HashMap;
1058     ///
1059     /// let mut map = HashMap::new();
1060     /// map.insert("a", 1);
1061     /// map.insert("b", 2);
1062     /// map.insert("c", 3);
1063     ///
1064     /// for key in map.keys() {
1065     ///     println!("{}", key);
1066     /// }
1067     /// ```
1068     #[stable(feature = "rust1", since = "1.0.0")]
1069     pub fn keys(&self) -> Keys<K, V> {
1070         Keys { inner: self.iter() }
1071     }
1072
1073     /// An iterator visiting all values in arbitrary order.
1074     /// The iterator element type is `&'a V`.
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// use std::collections::HashMap;
1080     ///
1081     /// let mut map = HashMap::new();
1082     /// map.insert("a", 1);
1083     /// map.insert("b", 2);
1084     /// map.insert("c", 3);
1085     ///
1086     /// for val in map.values() {
1087     ///     println!("{}", val);
1088     /// }
1089     /// ```
1090     #[stable(feature = "rust1", since = "1.0.0")]
1091     pub fn values(&self) -> Values<K, V> {
1092         Values { inner: self.iter() }
1093     }
1094
1095     /// An iterator visiting all values mutably in arbitrary order.
1096     /// The iterator element type is `&'a mut V`.
1097     ///
1098     /// # Examples
1099     ///
1100     /// ```
1101     /// use std::collections::HashMap;
1102     ///
1103     /// let mut map = HashMap::new();
1104     ///
1105     /// map.insert("a", 1);
1106     /// map.insert("b", 2);
1107     /// map.insert("c", 3);
1108     ///
1109     /// for val in map.values_mut() {
1110     ///     *val = *val + 10;
1111     /// }
1112     ///
1113     /// for val in map.values() {
1114     ///     println!("{}", val);
1115     /// }
1116     /// ```
1117     #[stable(feature = "map_values_mut", since = "1.10.0")]
1118     pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1119         ValuesMut { inner: self.iter_mut() }
1120     }
1121
1122     /// An iterator visiting all key-value pairs in arbitrary order.
1123     /// The iterator element type is `(&'a K, &'a V)`.
1124     ///
1125     /// # Examples
1126     ///
1127     /// ```
1128     /// use std::collections::HashMap;
1129     ///
1130     /// let mut map = HashMap::new();
1131     /// map.insert("a", 1);
1132     /// map.insert("b", 2);
1133     /// map.insert("c", 3);
1134     ///
1135     /// for (key, val) in map.iter() {
1136     ///     println!("key: {} val: {}", key, val);
1137     /// }
1138     /// ```
1139     #[stable(feature = "rust1", since = "1.0.0")]
1140     pub fn iter(&self) -> Iter<K, V> {
1141         Iter { inner: self.table.iter() }
1142     }
1143
1144     /// An iterator visiting all key-value pairs in arbitrary order,
1145     /// with mutable references to the values.
1146     /// The iterator element type is `(&'a K, &'a mut V)`.
1147     ///
1148     /// # Examples
1149     ///
1150     /// ```
1151     /// use std::collections::HashMap;
1152     ///
1153     /// let mut map = HashMap::new();
1154     /// map.insert("a", 1);
1155     /// map.insert("b", 2);
1156     /// map.insert("c", 3);
1157     ///
1158     /// // Update all values
1159     /// for (_, val) in map.iter_mut() {
1160     ///     *val *= 2;
1161     /// }
1162     ///
1163     /// for (key, val) in &map {
1164     ///     println!("key: {} val: {}", key, val);
1165     /// }
1166     /// ```
1167     #[stable(feature = "rust1", since = "1.0.0")]
1168     pub fn iter_mut(&mut self) -> IterMut<K, V> {
1169         IterMut { inner: self.table.iter_mut() }
1170     }
1171
1172     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1173     ///
1174     /// # Examples
1175     ///
1176     /// ```
1177     /// use std::collections::HashMap;
1178     ///
1179     /// let mut letters = HashMap::new();
1180     ///
1181     /// for ch in "a short treatise on fungi".chars() {
1182     ///     let counter = letters.entry(ch).or_insert(0);
1183     ///     *counter += 1;
1184     /// }
1185     ///
1186     /// assert_eq!(letters[&'s'], 2);
1187     /// assert_eq!(letters[&'t'], 3);
1188     /// assert_eq!(letters[&'u'], 1);
1189     /// assert_eq!(letters.get(&'y'), None);
1190     /// ```
1191     #[stable(feature = "rust1", since = "1.0.0")]
1192     pub fn entry(&mut self, key: K) -> Entry<K, V> {
1193         // Gotta resize now.
1194         self.reserve(1);
1195         let hash = self.make_hash(&key);
1196         search_hashed(&mut self.table, hash, |q| q.eq(&key))
1197             .into_entry(key).expect("unreachable")
1198     }
1199
1200     /// Returns the number of elements in the map.
1201     ///
1202     /// # Examples
1203     ///
1204     /// ```
1205     /// use std::collections::HashMap;
1206     ///
1207     /// let mut a = HashMap::new();
1208     /// assert_eq!(a.len(), 0);
1209     /// a.insert(1, "a");
1210     /// assert_eq!(a.len(), 1);
1211     /// ```
1212     #[stable(feature = "rust1", since = "1.0.0")]
1213     pub fn len(&self) -> usize {
1214         self.table.size()
1215     }
1216
1217     /// Returns `true` if the map contains no elements.
1218     ///
1219     /// # Examples
1220     ///
1221     /// ```
1222     /// use std::collections::HashMap;
1223     ///
1224     /// let mut a = HashMap::new();
1225     /// assert!(a.is_empty());
1226     /// a.insert(1, "a");
1227     /// assert!(!a.is_empty());
1228     /// ```
1229     #[inline]
1230     #[stable(feature = "rust1", since = "1.0.0")]
1231     pub fn is_empty(&self) -> bool {
1232         self.len() == 0
1233     }
1234
1235     /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1236     /// allocated memory for reuse.
1237     ///
1238     /// # Examples
1239     ///
1240     /// ```
1241     /// use std::collections::HashMap;
1242     ///
1243     /// let mut a = HashMap::new();
1244     /// a.insert(1, "a");
1245     /// a.insert(2, "b");
1246     ///
1247     /// for (k, v) in a.drain().take(1) {
1248     ///     assert!(k == 1 || k == 2);
1249     ///     assert!(v == "a" || v == "b");
1250     /// }
1251     ///
1252     /// assert!(a.is_empty());
1253     /// ```
1254     #[inline]
1255     #[stable(feature = "drain", since = "1.6.0")]
1256     pub fn drain(&mut self) -> Drain<K, V> {
1257         Drain { inner: self.table.drain() }
1258     }
1259
1260     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1261     /// for reuse.
1262     ///
1263     /// # Examples
1264     ///
1265     /// ```
1266     /// use std::collections::HashMap;
1267     ///
1268     /// let mut a = HashMap::new();
1269     /// a.insert(1, "a");
1270     /// a.clear();
1271     /// assert!(a.is_empty());
1272     /// ```
1273     #[stable(feature = "rust1", since = "1.0.0")]
1274     #[inline]
1275     pub fn clear(&mut self) {
1276         self.drain();
1277     }
1278
1279     /// Returns a reference to the value corresponding to the key.
1280     ///
1281     /// The key may be any borrowed form of the map's key type, but
1282     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1283     /// the key type.
1284     ///
1285     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1286     /// [`Hash`]: ../../std/hash/trait.Hash.html
1287     ///
1288     /// # Examples
1289     ///
1290     /// ```
1291     /// use std::collections::HashMap;
1292     ///
1293     /// let mut map = HashMap::new();
1294     /// map.insert(1, "a");
1295     /// assert_eq!(map.get(&1), Some(&"a"));
1296     /// assert_eq!(map.get(&2), None);
1297     /// ```
1298     #[stable(feature = "rust1", since = "1.0.0")]
1299     #[inline]
1300     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1301         where K: Borrow<Q>,
1302               Q: Hash + Eq
1303     {
1304         self.search(k).map(|bucket| bucket.into_refs().1)
1305     }
1306
1307     /// Returns the key-value pair corresponding to the supplied key.
1308     ///
1309     /// The supplied key may be any borrowed form of the map's key type, but
1310     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1311     /// the key type.
1312     ///
1313     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1314     /// [`Hash`]: ../../std/hash/trait.Hash.html
1315     ///
1316     /// # Examples
1317     ///
1318     /// ```
1319     /// #![feature(map_get_key_value)]
1320     /// use std::collections::HashMap;
1321     ///
1322     /// let mut map = HashMap::new();
1323     /// map.insert(1, "a");
1324     /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1325     /// assert_eq!(map.get_key_value(&2), None);
1326     /// ```
1327     #[unstable(feature = "map_get_key_value", issue = "49347")]
1328     pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1329         where K: Borrow<Q>,
1330               Q: Hash + Eq
1331     {
1332         self.search(k).map(|bucket| bucket.into_refs())
1333     }
1334
1335     /// Returns `true` if the map contains a value for the specified key.
1336     ///
1337     /// The key may be any borrowed form of the map's key type, but
1338     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1339     /// the key type.
1340     ///
1341     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1342     /// [`Hash`]: ../../std/hash/trait.Hash.html
1343     ///
1344     /// # Examples
1345     ///
1346     /// ```
1347     /// use std::collections::HashMap;
1348     ///
1349     /// let mut map = HashMap::new();
1350     /// map.insert(1, "a");
1351     /// assert_eq!(map.contains_key(&1), true);
1352     /// assert_eq!(map.contains_key(&2), false);
1353     /// ```
1354     #[stable(feature = "rust1", since = "1.0.0")]
1355     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1356         where K: Borrow<Q>,
1357               Q: Hash + Eq
1358     {
1359         self.search(k).is_some()
1360     }
1361
1362     /// Returns a mutable reference to the value corresponding to the key.
1363     ///
1364     /// The key may be any borrowed form of the map's key type, but
1365     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1366     /// the key type.
1367     ///
1368     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1369     /// [`Hash`]: ../../std/hash/trait.Hash.html
1370     ///
1371     /// # Examples
1372     ///
1373     /// ```
1374     /// use std::collections::HashMap;
1375     ///
1376     /// let mut map = HashMap::new();
1377     /// map.insert(1, "a");
1378     /// if let Some(x) = map.get_mut(&1) {
1379     ///     *x = "b";
1380     /// }
1381     /// assert_eq!(map[&1], "b");
1382     /// ```
1383     #[stable(feature = "rust1", since = "1.0.0")]
1384     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1385         where K: Borrow<Q>,
1386               Q: Hash + Eq
1387     {
1388         self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1389     }
1390
1391     /// Inserts a key-value pair into the map.
1392     ///
1393     /// If the map did not have this key present, [`None`] is returned.
1394     ///
1395     /// If the map did have this key present, the value is updated, and the old
1396     /// value is returned. The key is not updated, though; this matters for
1397     /// types that can be `==` without being identical. See the [module-level
1398     /// documentation] for more.
1399     ///
1400     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1401     /// [module-level documentation]: index.html#insert-and-complex-keys
1402     ///
1403     /// # Examples
1404     ///
1405     /// ```
1406     /// use std::collections::HashMap;
1407     ///
1408     /// let mut map = HashMap::new();
1409     /// assert_eq!(map.insert(37, "a"), None);
1410     /// assert_eq!(map.is_empty(), false);
1411     ///
1412     /// map.insert(37, "b");
1413     /// assert_eq!(map.insert(37, "c"), Some("b"));
1414     /// assert_eq!(map[&37], "c");
1415     /// ```
1416     #[stable(feature = "rust1", since = "1.0.0")]
1417     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1418         let hash = self.make_hash(&k);
1419         self.reserve(1);
1420         self.insert_hashed_nocheck(hash, k, v)
1421     }
1422
1423     /// Removes a key from the map, returning the value at the key if the key
1424     /// was previously in the map.
1425     ///
1426     /// The key may be any borrowed form of the map's key type, but
1427     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1428     /// the key type.
1429     ///
1430     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1431     /// [`Hash`]: ../../std/hash/trait.Hash.html
1432     ///
1433     /// # Examples
1434     ///
1435     /// ```
1436     /// use std::collections::HashMap;
1437     ///
1438     /// let mut map = HashMap::new();
1439     /// map.insert(1, "a");
1440     /// assert_eq!(map.remove(&1), Some("a"));
1441     /// assert_eq!(map.remove(&1), None);
1442     /// ```
1443     #[stable(feature = "rust1", since = "1.0.0")]
1444     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1445         where K: Borrow<Q>,
1446               Q: Hash + Eq
1447     {
1448         self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1449     }
1450
1451     /// Removes a key from the map, returning the stored key and value if the
1452     /// key was previously in the map.
1453     ///
1454     /// The key may be any borrowed form of the map's key type, but
1455     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1456     /// the key type.
1457     ///
1458     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1459     /// [`Hash`]: ../../std/hash/trait.Hash.html
1460     ///
1461     /// # Examples
1462     ///
1463     /// ```
1464     /// use std::collections::HashMap;
1465     ///
1466     /// # fn main() {
1467     /// let mut map = HashMap::new();
1468     /// map.insert(1, "a");
1469     /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1470     /// assert_eq!(map.remove(&1), None);
1471     /// # }
1472     /// ```
1473     #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1474     pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1475         where K: Borrow<Q>,
1476               Q: Hash + Eq
1477     {
1478         self.search_mut(k)
1479             .map(|bucket| {
1480                 let (k, v, _) = pop_internal(bucket);
1481                 (k, v)
1482             })
1483     }
1484
1485     /// Retains only the elements specified by the predicate.
1486     ///
1487     /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```
1492     /// use std::collections::HashMap;
1493     ///
1494     /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1495     /// map.retain(|&k, _| k % 2 == 0);
1496     /// assert_eq!(map.len(), 4);
1497     /// ```
1498     #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1499     pub fn retain<F>(&mut self, mut f: F)
1500         where F: FnMut(&K, &mut V) -> bool
1501     {
1502         if self.table.size() == 0 {
1503             return;
1504         }
1505         let mut elems_left = self.table.size();
1506         let mut bucket = Bucket::head_bucket(&mut self.table);
1507         bucket.prev();
1508         let start_index = bucket.index();
1509         while elems_left != 0 {
1510             bucket = match bucket.peek() {
1511                 Full(mut full) => {
1512                     elems_left -= 1;
1513                     let should_remove = {
1514                         let (k, v) = full.read_mut();
1515                         !f(k, v)
1516                     };
1517                     if should_remove {
1518                         let prev_raw = full.raw();
1519                         let (_, _, t) = pop_internal(full);
1520                         Bucket::new_from(prev_raw, t)
1521                     } else {
1522                         full.into_bucket()
1523                     }
1524                 },
1525                 Empty(b) => {
1526                     b.into_bucket()
1527                 }
1528             };
1529             bucket.prev();  // reverse iteration
1530             debug_assert!(elems_left == 0 || bucket.index() != start_index);
1531         }
1532     }
1533 }
1534
1535 impl<K, V, S> HashMap<K, V, S>
1536     where K: Eq + Hash,
1537           S: BuildHasher
1538 {
1539     /// Creates a raw entry builder for the HashMap.
1540     ///
1541     /// Raw entries provide the lowest level of control for searching and
1542     /// manipulating a map. They must be manually initialized with a hash and
1543     /// then manually searched. After this, insertions into a vacant entry
1544     /// still require an owned key to be provided.
1545     ///
1546     /// Raw entries are useful for such exotic situations as:
1547     ///
1548     /// * Hash memoization
1549     /// * Deferring the creation of an owned key until it is known to be required
1550     /// * Using a search key that doesn't work with the Borrow trait
1551     /// * Using custom comparison logic without newtype wrappers
1552     ///
1553     /// Because raw entries provide much more low-level control, it's much easier
1554     /// to put the HashMap into an inconsistent state which, while memory-safe,
1555     /// will cause the map to produce seemingly random results. Higher-level and
1556     /// more foolproof APIs like `entry` should be preferred when possible.
1557     ///
1558     /// In particular, the hash used to initialized the raw entry must still be
1559     /// consistent with the hash of the key that is ultimately stored in the entry.
1560     /// This is because implementations of HashMap may need to recompute hashes
1561     /// when resizing, at which point only the keys are available.
1562     ///
1563     /// Raw entries give mutable access to the keys. This must not be used
1564     /// to modify how the key would compare or hash, as the map will not re-evaluate
1565     /// where the key should go, meaning the keys may become "lost" if their
1566     /// location does not reflect their state. For instance, if you change a key
1567     /// so that the map now contains keys which compare equal, search may start
1568     /// acting erratically, with two keys randomly masking each other. Implementations
1569     /// are free to assume this doesn't happen (within the limits of memory-safety).
1570     #[inline(always)]
1571     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1572     pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1573         self.reserve(1);
1574         RawEntryBuilderMut { map: self }
1575     }
1576
1577     /// Creates a raw immutable entry builder for the HashMap.
1578     ///
1579     /// Raw entries provide the lowest level of control for searching and
1580     /// manipulating a map. They must be manually initialized with a hash and
1581     /// then manually searched.
1582     ///
1583     /// This is useful for
1584     /// * Hash memoization
1585     /// * Using a search key that doesn't work with the Borrow trait
1586     /// * Using custom comparison logic without newtype wrappers
1587     ///
1588     /// Unless you are in such a situation, higher-level and more foolproof APIs like
1589     /// `get` should be preferred.
1590     ///
1591     /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1592     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1593     pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1594         RawEntryBuilder { map: self }
1595     }
1596 }
1597
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<K, V, S> PartialEq for HashMap<K, V, S>
1600     where K: Eq + Hash,
1601           V: PartialEq,
1602           S: BuildHasher
1603 {
1604     fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1605         if self.len() != other.len() {
1606             return false;
1607         }
1608
1609         self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1610     }
1611 }
1612
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<K, V, S> Eq for HashMap<K, V, S>
1615     where K: Eq + Hash,
1616           V: Eq,
1617           S: BuildHasher
1618 {
1619 }
1620
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<K, V, S> Debug for HashMap<K, V, S>
1623     where K: Eq + Hash + Debug,
1624           V: Debug,
1625           S: BuildHasher
1626 {
1627     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1628         f.debug_map().entries(self.iter()).finish()
1629     }
1630 }
1631
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl<K, V, S> Default for HashMap<K, V, S>
1634     where K: Eq + Hash,
1635           S: BuildHasher + Default
1636 {
1637     /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1638     fn default() -> HashMap<K, V, S> {
1639         HashMap::with_hasher(Default::default())
1640     }
1641 }
1642
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1645     where K: Eq + Hash + Borrow<Q>,
1646           Q: Eq + Hash,
1647           S: BuildHasher
1648 {
1649     type Output = V;
1650
1651     /// Returns a reference to the value corresponding to the supplied key.
1652     ///
1653     /// # Panics
1654     ///
1655     /// Panics if the key is not present in the `HashMap`.
1656     #[inline]
1657     fn index(&self, key: &Q) -> &V {
1658         self.get(key).expect("no entry found for key")
1659     }
1660 }
1661
1662 /// An iterator over the entries of a `HashMap`.
1663 ///
1664 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1665 /// documentation for more.
1666 ///
1667 /// [`iter`]: struct.HashMap.html#method.iter
1668 /// [`HashMap`]: struct.HashMap.html
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub struct Iter<'a, K: 'a, V: 'a> {
1671     inner: table::Iter<'a, K, V>,
1672 }
1673
1674 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<'a, K, V> Clone for Iter<'a, K, V> {
1677     fn clone(&self) -> Iter<'a, K, V> {
1678         Iter { inner: self.inner.clone() }
1679     }
1680 }
1681
1682 #[stable(feature = "std_debug", since = "1.16.0")]
1683 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1684     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1685         f.debug_list()
1686             .entries(self.clone())
1687             .finish()
1688     }
1689 }
1690
1691 /// A mutable iterator over the entries of a `HashMap`.
1692 ///
1693 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1694 /// documentation for more.
1695 ///
1696 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1697 /// [`HashMap`]: struct.HashMap.html
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 pub struct IterMut<'a, K: 'a, V: 'a> {
1700     inner: table::IterMut<'a, K, V>,
1701 }
1702
1703 /// An owning iterator over the entries of a `HashMap`.
1704 ///
1705 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1706 /// (provided by the `IntoIterator` trait). See its documentation for more.
1707 ///
1708 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1709 /// [`HashMap`]: struct.HashMap.html
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub struct IntoIter<K, V> {
1712     pub(super) inner: table::IntoIter<K, V>,
1713 }
1714
1715 /// An iterator over the keys of a `HashMap`.
1716 ///
1717 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1718 /// documentation for more.
1719 ///
1720 /// [`keys`]: struct.HashMap.html#method.keys
1721 /// [`HashMap`]: struct.HashMap.html
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub struct Keys<'a, K: 'a, V: 'a> {
1724     inner: Iter<'a, K, V>,
1725 }
1726
1727 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl<'a, K, V> Clone for Keys<'a, K, V> {
1730     fn clone(&self) -> Keys<'a, K, V> {
1731         Keys { inner: self.inner.clone() }
1732     }
1733 }
1734
1735 #[stable(feature = "std_debug", since = "1.16.0")]
1736 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1737     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1738         f.debug_list()
1739             .entries(self.clone())
1740             .finish()
1741     }
1742 }
1743
1744 /// An iterator over the values of a `HashMap`.
1745 ///
1746 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1747 /// documentation for more.
1748 ///
1749 /// [`values`]: struct.HashMap.html#method.values
1750 /// [`HashMap`]: struct.HashMap.html
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub struct Values<'a, K: 'a, V: 'a> {
1753     inner: Iter<'a, K, V>,
1754 }
1755
1756 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a, K, V> Clone for Values<'a, K, V> {
1759     fn clone(&self) -> Values<'a, K, V> {
1760         Values { inner: self.inner.clone() }
1761     }
1762 }
1763
1764 #[stable(feature = "std_debug", since = "1.16.0")]
1765 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1766     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1767         f.debug_list()
1768             .entries(self.clone())
1769             .finish()
1770     }
1771 }
1772
1773 /// A draining iterator over the entries of a `HashMap`.
1774 ///
1775 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1776 /// documentation for more.
1777 ///
1778 /// [`drain`]: struct.HashMap.html#method.drain
1779 /// [`HashMap`]: struct.HashMap.html
1780 #[stable(feature = "drain", since = "1.6.0")]
1781 pub struct Drain<'a, K: 'a, V: 'a> {
1782     pub(super) inner: table::Drain<'a, K, V>,
1783 }
1784
1785 /// A mutable iterator over the values of a `HashMap`.
1786 ///
1787 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1788 /// documentation for more.
1789 ///
1790 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1791 /// [`HashMap`]: struct.HashMap.html
1792 #[stable(feature = "map_values_mut", since = "1.10.0")]
1793 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1794     inner: IterMut<'a, K, V>,
1795 }
1796
1797 enum InternalEntry<K, V, M> {
1798     Occupied { elem: FullBucket<K, V, M> },
1799     Vacant {
1800         hash: SafeHash,
1801         elem: VacantEntryState<K, V, M>,
1802     },
1803     TableIsEmpty,
1804 }
1805
1806 impl<K, V, M> InternalEntry<K, V, M> {
1807     #[inline]
1808     fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1809         match self {
1810             InternalEntry::Occupied { elem } => Some(elem),
1811             _ => None,
1812         }
1813     }
1814 }
1815
1816 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1817     #[inline]
1818     fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1819         match self {
1820             InternalEntry::Occupied { elem } => {
1821                 Some(Occupied(OccupiedEntry {
1822                     key: Some(key),
1823                     elem,
1824                 }))
1825             }
1826             InternalEntry::Vacant { hash, elem } => {
1827                 Some(Vacant(VacantEntry {
1828                     hash,
1829                     key,
1830                     elem,
1831                 }))
1832             }
1833             InternalEntry::TableIsEmpty => None,
1834         }
1835     }
1836 }
1837
1838 /// A builder for computing where in a HashMap a key-value pair would be stored.
1839 ///
1840 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1841 ///
1842 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1843
1844 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1845 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1846     map: &'a mut HashMap<K, V, S>,
1847 }
1848
1849 /// A view into a single entry in a map, which may either be vacant or occupied.
1850 ///
1851 /// This is a lower-level version of [`Entry`].
1852 ///
1853 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1854 ///
1855 /// [`HashMap`]: struct.HashMap.html
1856 /// [`Entry`]: enum.Entry.html
1857 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1858 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1859 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1860     /// An occupied entry.
1861     Occupied(RawOccupiedEntryMut<'a, K, V>),
1862     /// A vacant entry.
1863     Vacant(RawVacantEntryMut<'a, K, V, S>),
1864 }
1865
1866 /// A view into an occupied entry in a `HashMap`.
1867 /// It is part of the [`RawEntryMut`] enum.
1868 ///
1869 /// [`RawEntryMut`]: enum.RawEntryMut.html
1870 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1871 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1872     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1873 }
1874
1875 /// A view into a vacant entry in a `HashMap`.
1876 /// It is part of the [`RawEntryMut`] enum.
1877 ///
1878 /// [`RawEntryMut`]: enum.RawEntryMut.html
1879 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1880 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1881     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1882     hash_builder: &'a S,
1883 }
1884
1885 /// A builder for computing where in a HashMap a key-value pair would be stored.
1886 ///
1887 /// See the [`HashMap::raw_entry`] docs for usage examples.
1888 ///
1889 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1890 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1891 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1892     map: &'a HashMap<K, V, S>,
1893 }
1894
1895 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1896     where S: BuildHasher,
1897           K: Eq + Hash,
1898 {
1899     /// Creates a `RawEntryMut` from the given key.
1900     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1901     pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1902         where K: Borrow<Q>,
1903               Q: Hash + Eq
1904     {
1905         let mut hasher = self.map.hash_builder.build_hasher();
1906         k.hash(&mut hasher);
1907         self.from_key_hashed_nocheck(hasher.finish(), k)
1908     }
1909
1910     /// Creates a `RawEntryMut` from the given key and its hash.
1911     #[inline]
1912     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1913     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1914         where K: Borrow<Q>,
1915               Q: Eq
1916     {
1917         self.from_hash(hash, |q| q.borrow().eq(k))
1918     }
1919
1920     #[inline]
1921     fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool)  -> RawEntryMut<'a, K, V, S>
1922         where for<'b> F: FnMut(&'b K) -> bool,
1923     {
1924         match search_hashed_nonempty_mut(&mut self.map.table,
1925                                          SafeHash::new(hash),
1926                                          is_match,
1927                                          compare_hashes) {
1928             InternalEntry::Occupied { elem } => {
1929                 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1930             }
1931             InternalEntry::Vacant { elem, .. } => {
1932                 RawEntryMut::Vacant(RawVacantEntryMut {
1933                     elem,
1934                     hash_builder: &self.map.hash_builder,
1935                 })
1936             }
1937             InternalEntry::TableIsEmpty => {
1938                 unreachable!()
1939             }
1940         }
1941     }
1942     /// Creates a `RawEntryMut` from the given hash.
1943     #[inline]
1944     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1945     pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1946         where for<'b> F: FnMut(&'b K) -> bool,
1947     {
1948         self.search(hash, is_match, true)
1949     }
1950
1951     /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1952     /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1953     /// hash.
1954     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1955     pub fn search_bucket<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1956         where for<'b> F: FnMut(&'b K) -> bool,
1957     {
1958         self.search(hash, is_match, false)
1959     }
1960 }
1961
1962 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1963     where S: BuildHasher,
1964 {
1965     /// Access an entry by key.
1966     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1967     pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1968         where K: Borrow<Q>,
1969               Q: Hash + Eq
1970     {
1971         let mut hasher = self.map.hash_builder.build_hasher();
1972         k.hash(&mut hasher);
1973         self.from_key_hashed_nocheck(hasher.finish(), k)
1974     }
1975
1976     /// Access an entry by a key and its hash.
1977     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1978     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1979         where K: Borrow<Q>,
1980               Q: Hash + Eq
1981
1982     {
1983         self.from_hash(hash, |q| q.borrow().eq(k))
1984     }
1985
1986     fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1987         where F: FnMut(&K) -> bool
1988     {
1989         if unsafe { unlikely(self.map.table.size() == 0) } {
1990             return None;
1991         }
1992         match search_hashed_nonempty(&self.map.table,
1993                                      SafeHash::new(hash),
1994                                      is_match,
1995                                      compare_hashes) {
1996             InternalEntry::Occupied { elem } => Some(elem.into_refs()),
1997             InternalEntry::Vacant { .. } => None,
1998             InternalEntry::TableIsEmpty => unreachable!(),
1999         }
2000     }
2001
2002     /// Access an entry by hash.
2003     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2004     pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2005         where F: FnMut(&K) -> bool
2006     {
2007         self.search(hash, is_match, true)
2008     }
2009
2010     /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2011     /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2012     /// hash.
2013     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2014     pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2015         where F: FnMut(&K) -> bool
2016     {
2017         self.search(hash, is_match, false)
2018     }
2019 }
2020
2021 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2022     /// Ensures a value is in the entry by inserting the default if empty, and returns
2023     /// mutable references to the key and value in the entry.
2024     ///
2025     /// # Examples
2026     ///
2027     /// ```
2028     /// #![feature(hash_raw_entry)]
2029     /// use std::collections::HashMap;
2030     ///
2031     /// let mut map: HashMap<&str, u32> = HashMap::new();
2032     ///
2033     /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2034     /// assert_eq!(map["poneyland"], 3);
2035     ///
2036     /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2037     /// assert_eq!(map["poneyland"], 6);
2038     /// ```
2039     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2040     pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2041         where K: Hash,
2042               S: BuildHasher,
2043     {
2044         match self {
2045             RawEntryMut::Occupied(entry) => entry.into_key_value(),
2046             RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2047         }
2048     }
2049
2050     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2051     /// and returns mutable references to the key and value in the entry.
2052     ///
2053     /// # Examples
2054     ///
2055     /// ```
2056     /// #![feature(hash_raw_entry)]
2057     /// use std::collections::HashMap;
2058     ///
2059     /// let mut map: HashMap<&str, String> = HashMap::new();
2060     ///
2061     /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2062     ///     ("poneyland", "hoho".to_string())
2063     /// });
2064     ///
2065     /// assert_eq!(map["poneyland"], "hoho".to_string());
2066     /// ```
2067     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2068     pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2069         where F: FnOnce() -> (K, V),
2070               K: Hash,
2071               S: BuildHasher,
2072     {
2073         match self {
2074             RawEntryMut::Occupied(entry) => entry.into_key_value(),
2075             RawEntryMut::Vacant(entry) => {
2076                 let (k, v) = default();
2077                 entry.insert(k, v)
2078             }
2079         }
2080     }
2081
2082     /// Provides in-place mutable access to an occupied entry before any
2083     /// potential inserts into the map.
2084     ///
2085     /// # Examples
2086     ///
2087     /// ```
2088     /// #![feature(hash_raw_entry)]
2089     /// use std::collections::HashMap;
2090     ///
2091     /// let mut map: HashMap<&str, u32> = HashMap::new();
2092     ///
2093     /// map.raw_entry_mut()
2094     ///    .from_key("poneyland")
2095     ///    .and_modify(|_k, v| { *v += 1 })
2096     ///    .or_insert("poneyland", 42);
2097     /// assert_eq!(map["poneyland"], 42);
2098     ///
2099     /// map.raw_entry_mut()
2100     ///    .from_key("poneyland")
2101     ///    .and_modify(|_k, v| { *v += 1 })
2102     ///    .or_insert("poneyland", 0);
2103     /// assert_eq!(map["poneyland"], 43);
2104     /// ```
2105     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2106     pub fn and_modify<F>(self, f: F) -> Self
2107         where F: FnOnce(&mut K, &mut V)
2108     {
2109         match self {
2110             RawEntryMut::Occupied(mut entry) => {
2111                 {
2112                     let (k, v) = entry.get_key_value_mut();
2113                     f(k, v);
2114                 }
2115                 RawEntryMut::Occupied(entry)
2116             },
2117             RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2118         }
2119     }
2120 }
2121
2122 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2123     /// Gets a reference to the key in the entry.
2124     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2125     pub fn key(&self) -> &K {
2126         self.elem.read().0
2127     }
2128
2129     /// Gets a mutable reference to the key in the entry.
2130     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2131     pub fn key_mut(&mut self) -> &mut K {
2132         self.elem.read_mut().0
2133     }
2134
2135     /// Converts the entry into a mutable reference to the key in the entry
2136     /// with a lifetime bound to the map itself.
2137     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2138     pub fn into_key(self) -> &'a mut K {
2139         self.elem.into_mut_refs().0
2140     }
2141
2142     /// Gets a reference to the value in the entry.
2143     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2144     pub fn get(&self) -> &V {
2145         self.elem.read().1
2146     }
2147
2148     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2149     /// with a lifetime bound to the map itself.
2150     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2151     pub fn into_mut(self) -> &'a mut V {
2152         self.elem.into_mut_refs().1
2153     }
2154
2155     /// Gets a mutable reference to the value in the entry.
2156     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2157     pub fn get_mut(&mut self) -> &mut V {
2158         self.elem.read_mut().1
2159     }
2160
2161     /// Gets a reference to the key and value in the entry.
2162     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2163     pub fn get_key_value(&mut self) -> (&K, &V) {
2164         self.elem.read()
2165     }
2166
2167     /// Gets a mutable reference to the key and value in the entry.
2168     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2169     pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2170         self.elem.read_mut()
2171     }
2172
2173     /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2174     /// with a lifetime bound to the map itself.
2175     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2176     pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2177         self.elem.into_mut_refs()
2178     }
2179
2180     /// Sets the value of the entry, and returns the entry's old value.
2181     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2182     pub fn insert(&mut self, value: V) -> V {
2183         mem::replace(self.get_mut(), value)
2184     }
2185
2186     /// Sets the value of the entry, and returns the entry's old value.
2187     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2188     pub fn insert_key(&mut self, key: K) -> K {
2189         mem::replace(self.key_mut(), key)
2190     }
2191
2192     /// Takes the value out of the entry, and returns it.
2193     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2194     pub fn remove(self) -> V {
2195         pop_internal(self.elem).1
2196     }
2197
2198     /// Take the ownership of the key and value from the map.
2199     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2200     pub fn remove_entry(self) -> (K, V) {
2201         let (k, v, _) = pop_internal(self.elem);
2202         (k, v)
2203     }
2204 }
2205
2206 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2207     /// Sets the value of the entry with the VacantEntry's key,
2208     /// and returns a mutable reference to it.
2209     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2210     pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2211         where K: Hash,
2212               S: BuildHasher,
2213     {
2214         let mut hasher = self.hash_builder.build_hasher();
2215         key.hash(&mut hasher);
2216         self.insert_hashed_nocheck(hasher.finish(), key, value)
2217     }
2218
2219     /// Sets the value of the entry with the VacantEntry's key,
2220     /// and returns a mutable reference to it.
2221     #[inline]
2222     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2223     pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2224         let hash = SafeHash::new(hash);
2225         let b = match self.elem {
2226             NeqElem(mut bucket, disp) => {
2227                 if disp >= DISPLACEMENT_THRESHOLD {
2228                     bucket.table_mut().set_tag(true);
2229                 }
2230                 robin_hood(bucket, disp, hash, key, value)
2231             },
2232             NoElem(mut bucket, disp) => {
2233                 if disp >= DISPLACEMENT_THRESHOLD {
2234                     bucket.table_mut().set_tag(true);
2235                 }
2236                 bucket.put(hash, key, value)
2237             },
2238         };
2239         b.into_mut_refs()
2240     }
2241 }
2242
2243 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2244 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2245     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2246         f.debug_struct("RawEntryBuilder")
2247          .finish()
2248     }
2249 }
2250
2251 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2252 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2253     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2254         match *self {
2255             RawEntryMut::Vacant(ref v) => {
2256                 f.debug_tuple("RawEntry")
2257                     .field(v)
2258                     .finish()
2259             }
2260             RawEntryMut::Occupied(ref o) => {
2261                 f.debug_tuple("RawEntry")
2262                     .field(o)
2263                     .finish()
2264             }
2265         }
2266     }
2267 }
2268
2269 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2270 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2271     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2272         f.debug_struct("RawOccupiedEntryMut")
2273          .field("key", self.key())
2274          .field("value", self.get())
2275          .finish()
2276     }
2277 }
2278
2279 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2280 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2281     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2282         f.debug_struct("RawVacantEntryMut")
2283          .finish()
2284     }
2285 }
2286
2287 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2288 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2289     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2290         f.debug_struct("RawEntryBuilder")
2291          .finish()
2292     }
2293 }
2294
2295 /// A view into a single entry in a map, which may either be vacant or occupied.
2296 ///
2297 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2298 ///
2299 /// [`HashMap`]: struct.HashMap.html
2300 /// [`entry`]: struct.HashMap.html#method.entry
2301 #[stable(feature = "rust1", since = "1.0.0")]
2302 pub enum Entry<'a, K: 'a, V: 'a> {
2303     /// An occupied entry.
2304     #[stable(feature = "rust1", since = "1.0.0")]
2305     Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2306              OccupiedEntry<'a, K, V>),
2307
2308     /// A vacant entry.
2309     #[stable(feature = "rust1", since = "1.0.0")]
2310     Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2311            VacantEntry<'a, K, V>),
2312 }
2313
2314 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2315 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2316     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2317         match *self {
2318             Vacant(ref v) => {
2319                 f.debug_tuple("Entry")
2320                     .field(v)
2321                     .finish()
2322             }
2323             Occupied(ref o) => {
2324                 f.debug_tuple("Entry")
2325                     .field(o)
2326                     .finish()
2327             }
2328         }
2329     }
2330 }
2331
2332 /// A view into an occupied entry in a `HashMap`.
2333 /// It is part of the [`Entry`] enum.
2334 ///
2335 /// [`Entry`]: enum.Entry.html
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2338     key: Option<K>,
2339     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2340 }
2341
2342 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2343 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2344     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2345         f.debug_struct("OccupiedEntry")
2346             .field("key", self.key())
2347             .field("value", self.get())
2348             .finish()
2349     }
2350 }
2351
2352 /// A view into a vacant entry in a `HashMap`.
2353 /// It is part of the [`Entry`] enum.
2354 ///
2355 /// [`Entry`]: enum.Entry.html
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2358     hash: SafeHash,
2359     key: K,
2360     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2361 }
2362
2363 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2364 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2365     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2366         f.debug_tuple("VacantEntry")
2367             .field(self.key())
2368             .finish()
2369     }
2370 }
2371
2372 /// Possible states of a VacantEntry.
2373 enum VacantEntryState<K, V, M> {
2374     /// The index is occupied, but the key to insert has precedence,
2375     /// and will kick the current one out on insertion.
2376     NeqElem(FullBucket<K, V, M>, usize),
2377     /// The index is genuinely vacant.
2378     NoElem(EmptyBucket<K, V, M>, usize),
2379 }
2380
2381 #[stable(feature = "rust1", since = "1.0.0")]
2382 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2383     where K: Eq + Hash,
2384           S: BuildHasher
2385 {
2386     type Item = (&'a K, &'a V);
2387     type IntoIter = Iter<'a, K, V>;
2388
2389     fn into_iter(self) -> Iter<'a, K, V> {
2390         self.iter()
2391     }
2392 }
2393
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2396     where K: Eq + Hash,
2397           S: BuildHasher
2398 {
2399     type Item = (&'a K, &'a mut V);
2400     type IntoIter = IterMut<'a, K, V>;
2401
2402     fn into_iter(self) -> IterMut<'a, K, V> {
2403         self.iter_mut()
2404     }
2405 }
2406
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2409     where K: Eq + Hash,
2410           S: BuildHasher
2411 {
2412     type Item = (K, V);
2413     type IntoIter = IntoIter<K, V>;
2414
2415     /// Creates a consuming iterator, that is, one that moves each key-value
2416     /// pair out of the map in arbitrary order. The map cannot be used after
2417     /// calling this.
2418     ///
2419     /// # Examples
2420     ///
2421     /// ```
2422     /// use std::collections::HashMap;
2423     ///
2424     /// let mut map = HashMap::new();
2425     /// map.insert("a", 1);
2426     /// map.insert("b", 2);
2427     /// map.insert("c", 3);
2428     ///
2429     /// // Not possible with .iter()
2430     /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2431     /// ```
2432     fn into_iter(self) -> IntoIter<K, V> {
2433         IntoIter { inner: self.table.into_iter() }
2434     }
2435 }
2436
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2439     type Item = (&'a K, &'a V);
2440
2441     #[inline]
2442     fn next(&mut self) -> Option<(&'a K, &'a V)> {
2443         self.inner.next()
2444     }
2445     #[inline]
2446     fn size_hint(&self) -> (usize, Option<usize>) {
2447         self.inner.size_hint()
2448     }
2449 }
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2452     #[inline]
2453     fn len(&self) -> usize {
2454         self.inner.len()
2455     }
2456 }
2457
2458 #[stable(feature = "fused", since = "1.26.0")]
2459 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2460
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2463     type Item = (&'a K, &'a mut V);
2464
2465     #[inline]
2466     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2467         self.inner.next()
2468     }
2469     #[inline]
2470     fn size_hint(&self) -> (usize, Option<usize>) {
2471         self.inner.size_hint()
2472     }
2473 }
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2476     #[inline]
2477     fn len(&self) -> usize {
2478         self.inner.len()
2479     }
2480 }
2481 #[stable(feature = "fused", since = "1.26.0")]
2482 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2483
2484 #[stable(feature = "std_debug", since = "1.16.0")]
2485 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2486     where K: fmt::Debug,
2487           V: fmt::Debug,
2488 {
2489     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2490         f.debug_list()
2491             .entries(self.inner.iter())
2492             .finish()
2493     }
2494 }
2495
2496 #[stable(feature = "rust1", since = "1.0.0")]
2497 impl<K, V> Iterator for IntoIter<K, V> {
2498     type Item = (K, V);
2499
2500     #[inline]
2501     fn next(&mut self) -> Option<(K, V)> {
2502         self.inner.next().map(|(_, k, v)| (k, v))
2503     }
2504     #[inline]
2505     fn size_hint(&self) -> (usize, Option<usize>) {
2506         self.inner.size_hint()
2507     }
2508 }
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2511     #[inline]
2512     fn len(&self) -> usize {
2513         self.inner.len()
2514     }
2515 }
2516 #[stable(feature = "fused", since = "1.26.0")]
2517 impl<K, V> FusedIterator for IntoIter<K, V> {}
2518
2519 #[stable(feature = "std_debug", since = "1.16.0")]
2520 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2521     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2522         f.debug_list()
2523             .entries(self.inner.iter())
2524             .finish()
2525     }
2526 }
2527
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2530     type Item = &'a K;
2531
2532     #[inline]
2533     fn next(&mut self) -> Option<(&'a K)> {
2534         self.inner.next().map(|(k, _)| k)
2535     }
2536     #[inline]
2537     fn size_hint(&self) -> (usize, Option<usize>) {
2538         self.inner.size_hint()
2539     }
2540 }
2541 #[stable(feature = "rust1", since = "1.0.0")]
2542 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2543     #[inline]
2544     fn len(&self) -> usize {
2545         self.inner.len()
2546     }
2547 }
2548 #[stable(feature = "fused", since = "1.26.0")]
2549 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2550
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 impl<'a, K, V> Iterator for Values<'a, K, V> {
2553     type Item = &'a V;
2554
2555     #[inline]
2556     fn next(&mut self) -> Option<(&'a V)> {
2557         self.inner.next().map(|(_, v)| v)
2558     }
2559     #[inline]
2560     fn size_hint(&self) -> (usize, Option<usize>) {
2561         self.inner.size_hint()
2562     }
2563 }
2564 #[stable(feature = "rust1", since = "1.0.0")]
2565 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2566     #[inline]
2567     fn len(&self) -> usize {
2568         self.inner.len()
2569     }
2570 }
2571 #[stable(feature = "fused", since = "1.26.0")]
2572 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2573
2574 #[stable(feature = "map_values_mut", since = "1.10.0")]
2575 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2576     type Item = &'a mut V;
2577
2578     #[inline]
2579     fn next(&mut self) -> Option<(&'a mut V)> {
2580         self.inner.next().map(|(_, v)| v)
2581     }
2582     #[inline]
2583     fn size_hint(&self) -> (usize, Option<usize>) {
2584         self.inner.size_hint()
2585     }
2586 }
2587 #[stable(feature = "map_values_mut", since = "1.10.0")]
2588 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2589     #[inline]
2590     fn len(&self) -> usize {
2591         self.inner.len()
2592     }
2593 }
2594 #[stable(feature = "fused", since = "1.26.0")]
2595 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2596
2597 #[stable(feature = "std_debug", since = "1.16.0")]
2598 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2599     where K: fmt::Debug,
2600           V: fmt::Debug,
2601 {
2602     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2603         f.debug_list()
2604             .entries(self.inner.inner.iter())
2605             .finish()
2606     }
2607 }
2608
2609 #[stable(feature = "drain", since = "1.6.0")]
2610 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2611     type Item = (K, V);
2612
2613     #[inline]
2614     fn next(&mut self) -> Option<(K, V)> {
2615         self.inner.next().map(|(_, k, v)| (k, v))
2616     }
2617     #[inline]
2618     fn size_hint(&self) -> (usize, Option<usize>) {
2619         self.inner.size_hint()
2620     }
2621 }
2622 #[stable(feature = "drain", since = "1.6.0")]
2623 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2624     #[inline]
2625     fn len(&self) -> usize {
2626         self.inner.len()
2627     }
2628 }
2629 #[stable(feature = "fused", since = "1.26.0")]
2630 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2631
2632 #[stable(feature = "std_debug", since = "1.16.0")]
2633 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2634     where K: fmt::Debug,
2635           V: fmt::Debug,
2636 {
2637     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2638         f.debug_list()
2639             .entries(self.inner.iter())
2640             .finish()
2641     }
2642 }
2643
2644 impl<'a, K, V> Entry<'a, K, V> {
2645     #[stable(feature = "rust1", since = "1.0.0")]
2646     /// Ensures a value is in the entry by inserting the default if empty, and returns
2647     /// a mutable reference to the value in the entry.
2648     ///
2649     /// # Examples
2650     ///
2651     /// ```
2652     /// use std::collections::HashMap;
2653     ///
2654     /// let mut map: HashMap<&str, u32> = HashMap::new();
2655     ///
2656     /// map.entry("poneyland").or_insert(3);
2657     /// assert_eq!(map["poneyland"], 3);
2658     ///
2659     /// *map.entry("poneyland").or_insert(10) *= 2;
2660     /// assert_eq!(map["poneyland"], 6);
2661     /// ```
2662     pub fn or_insert(self, default: V) -> &'a mut V {
2663         match self {
2664             Occupied(entry) => entry.into_mut(),
2665             Vacant(entry) => entry.insert(default),
2666         }
2667     }
2668
2669     #[stable(feature = "rust1", since = "1.0.0")]
2670     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2671     /// and returns a mutable reference to the value in the entry.
2672     ///
2673     /// # Examples
2674     ///
2675     /// ```
2676     /// use std::collections::HashMap;
2677     ///
2678     /// let mut map: HashMap<&str, String> = HashMap::new();
2679     /// let s = "hoho".to_string();
2680     ///
2681     /// map.entry("poneyland").or_insert_with(|| s);
2682     ///
2683     /// assert_eq!(map["poneyland"], "hoho".to_string());
2684     /// ```
2685     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2686         match self {
2687             Occupied(entry) => entry.into_mut(),
2688             Vacant(entry) => entry.insert(default()),
2689         }
2690     }
2691
2692     /// Returns a reference to this entry's key.
2693     ///
2694     /// # Examples
2695     ///
2696     /// ```
2697     /// use std::collections::HashMap;
2698     ///
2699     /// let mut map: HashMap<&str, u32> = HashMap::new();
2700     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2701     /// ```
2702     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2703     pub fn key(&self) -> &K {
2704         match *self {
2705             Occupied(ref entry) => entry.key(),
2706             Vacant(ref entry) => entry.key(),
2707         }
2708     }
2709
2710     /// Provides in-place mutable access to an occupied entry before any
2711     /// potential inserts into the map.
2712     ///
2713     /// # Examples
2714     ///
2715     /// ```
2716     /// use std::collections::HashMap;
2717     ///
2718     /// let mut map: HashMap<&str, u32> = HashMap::new();
2719     ///
2720     /// map.entry("poneyland")
2721     ///    .and_modify(|e| { *e += 1 })
2722     ///    .or_insert(42);
2723     /// assert_eq!(map["poneyland"], 42);
2724     ///
2725     /// map.entry("poneyland")
2726     ///    .and_modify(|e| { *e += 1 })
2727     ///    .or_insert(42);
2728     /// assert_eq!(map["poneyland"], 43);
2729     /// ```
2730     #[stable(feature = "entry_and_modify", since = "1.26.0")]
2731     pub fn and_modify<F>(self, f: F) -> Self
2732         where F: FnOnce(&mut V)
2733     {
2734         match self {
2735             Occupied(mut entry) => {
2736                 f(entry.get_mut());
2737                 Occupied(entry)
2738             },
2739             Vacant(entry) => Vacant(entry),
2740         }
2741     }
2742
2743 }
2744
2745 impl<'a, K, V: Default> Entry<'a, K, V> {
2746     #[stable(feature = "entry_or_default", since = "1.28.0")]
2747     /// Ensures a value is in the entry by inserting the default value if empty,
2748     /// and returns a mutable reference to the value in the entry.
2749     ///
2750     /// # Examples
2751     ///
2752     /// ```
2753     /// # fn main() {
2754     /// use std::collections::HashMap;
2755     ///
2756     /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2757     /// map.entry("poneyland").or_default();
2758     ///
2759     /// assert_eq!(map["poneyland"], None);
2760     /// # }
2761     /// ```
2762     pub fn or_default(self) -> &'a mut V {
2763         match self {
2764             Occupied(entry) => entry.into_mut(),
2765             Vacant(entry) => entry.insert(Default::default()),
2766         }
2767     }
2768 }
2769
2770 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2771     /// Gets a reference to the key in the entry.
2772     ///
2773     /// # Examples
2774     ///
2775     /// ```
2776     /// use std::collections::HashMap;
2777     ///
2778     /// let mut map: HashMap<&str, u32> = HashMap::new();
2779     /// map.entry("poneyland").or_insert(12);
2780     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2781     /// ```
2782     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2783     pub fn key(&self) -> &K {
2784         self.elem.read().0
2785     }
2786
2787     /// Take the ownership of the key and value from the map.
2788     ///
2789     /// # Examples
2790     ///
2791     /// ```
2792     /// use std::collections::HashMap;
2793     /// use std::collections::hash_map::Entry;
2794     ///
2795     /// let mut map: HashMap<&str, u32> = HashMap::new();
2796     /// map.entry("poneyland").or_insert(12);
2797     ///
2798     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2799     ///     // We delete the entry from the map.
2800     ///     o.remove_entry();
2801     /// }
2802     ///
2803     /// assert_eq!(map.contains_key("poneyland"), false);
2804     /// ```
2805     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2806     pub fn remove_entry(self) -> (K, V) {
2807         let (k, v, _) = pop_internal(self.elem);
2808         (k, v)
2809     }
2810
2811     /// Gets a reference to the value in the entry.
2812     ///
2813     /// # Examples
2814     ///
2815     /// ```
2816     /// use std::collections::HashMap;
2817     /// use std::collections::hash_map::Entry;
2818     ///
2819     /// let mut map: HashMap<&str, u32> = HashMap::new();
2820     /// map.entry("poneyland").or_insert(12);
2821     ///
2822     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2823     ///     assert_eq!(o.get(), &12);
2824     /// }
2825     /// ```
2826     #[stable(feature = "rust1", since = "1.0.0")]
2827     pub fn get(&self) -> &V {
2828         self.elem.read().1
2829     }
2830
2831     /// Gets a mutable reference to the value in the entry.
2832     ///
2833     /// If you need a reference to the `OccupiedEntry` which may outlive the
2834     /// destruction of the `Entry` value, see [`into_mut`].
2835     ///
2836     /// [`into_mut`]: #method.into_mut
2837     ///
2838     /// # Examples
2839     ///
2840     /// ```
2841     /// use std::collections::HashMap;
2842     /// use std::collections::hash_map::Entry;
2843     ///
2844     /// let mut map: HashMap<&str, u32> = HashMap::new();
2845     /// map.entry("poneyland").or_insert(12);
2846     ///
2847     /// assert_eq!(map["poneyland"], 12);
2848     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2849     ///     *o.get_mut() += 10;
2850     ///     assert_eq!(*o.get(), 22);
2851     ///
2852     ///     // We can use the same Entry multiple times.
2853     ///     *o.get_mut() += 2;
2854     /// }
2855     ///
2856     /// assert_eq!(map["poneyland"], 24);
2857     /// ```
2858     #[stable(feature = "rust1", since = "1.0.0")]
2859     pub fn get_mut(&mut self) -> &mut V {
2860         self.elem.read_mut().1
2861     }
2862
2863     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2864     /// with a lifetime bound to the map itself.
2865     ///
2866     /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2867     ///
2868     /// [`get_mut`]: #method.get_mut
2869     ///
2870     /// # Examples
2871     ///
2872     /// ```
2873     /// use std::collections::HashMap;
2874     /// use std::collections::hash_map::Entry;
2875     ///
2876     /// let mut map: HashMap<&str, u32> = HashMap::new();
2877     /// map.entry("poneyland").or_insert(12);
2878     ///
2879     /// assert_eq!(map["poneyland"], 12);
2880     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2881     ///     *o.into_mut() += 10;
2882     /// }
2883     ///
2884     /// assert_eq!(map["poneyland"], 22);
2885     /// ```
2886     #[stable(feature = "rust1", since = "1.0.0")]
2887     pub fn into_mut(self) -> &'a mut V {
2888         self.elem.into_mut_refs().1
2889     }
2890
2891     /// Sets the value of the entry, and returns the entry's old value.
2892     ///
2893     /// # Examples
2894     ///
2895     /// ```
2896     /// use std::collections::HashMap;
2897     /// use std::collections::hash_map::Entry;
2898     ///
2899     /// let mut map: HashMap<&str, u32> = HashMap::new();
2900     /// map.entry("poneyland").or_insert(12);
2901     ///
2902     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2903     ///     assert_eq!(o.insert(15), 12);
2904     /// }
2905     ///
2906     /// assert_eq!(map["poneyland"], 15);
2907     /// ```
2908     #[stable(feature = "rust1", since = "1.0.0")]
2909     pub fn insert(&mut self, mut value: V) -> V {
2910         let old_value = self.get_mut();
2911         mem::swap(&mut value, old_value);
2912         value
2913     }
2914
2915     /// Takes the value out of the entry, and returns it.
2916     ///
2917     /// # Examples
2918     ///
2919     /// ```
2920     /// use std::collections::HashMap;
2921     /// use std::collections::hash_map::Entry;
2922     ///
2923     /// let mut map: HashMap<&str, u32> = HashMap::new();
2924     /// map.entry("poneyland").or_insert(12);
2925     ///
2926     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2927     ///     assert_eq!(o.remove(), 12);
2928     /// }
2929     ///
2930     /// assert_eq!(map.contains_key("poneyland"), false);
2931     /// ```
2932     #[stable(feature = "rust1", since = "1.0.0")]
2933     pub fn remove(self) -> V {
2934         pop_internal(self.elem).1
2935     }
2936
2937     /// Returns a key that was used for search.
2938     ///
2939     /// The key was retained for further use.
2940     fn take_key(&mut self) -> Option<K> {
2941         self.key.take()
2942     }
2943
2944     /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2945     /// the key used to create this entry.
2946     ///
2947     /// # Examples
2948     ///
2949     /// ```
2950     /// #![feature(map_entry_replace)]
2951     /// use std::collections::hash_map::{Entry, HashMap};
2952     /// use std::rc::Rc;
2953     ///
2954     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2955     /// map.insert(Rc::new("Stringthing".to_string()), 15);
2956     ///
2957     /// let my_key = Rc::new("Stringthing".to_string());
2958     ///
2959     /// if let Entry::Occupied(entry) = map.entry(my_key) {
2960     ///     // Also replace the key with a handle to our other key.
2961     ///     let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2962     /// }
2963     ///
2964     /// ```
2965     #[unstable(feature = "map_entry_replace", issue = "44286")]
2966     pub fn replace_entry(mut self, value: V) -> (K, V) {
2967         let (old_key, old_value) = self.elem.read_mut();
2968
2969         let old_key = mem::replace(old_key, self.key.unwrap());
2970         let old_value = mem::replace(old_value, value);
2971
2972         (old_key, old_value)
2973     }
2974
2975     /// Replaces the key in the hash map with the key used to create this entry.
2976     ///
2977     /// # Examples
2978     ///
2979     /// ```
2980     /// #![feature(map_entry_replace)]
2981     /// use std::collections::hash_map::{Entry, HashMap};
2982     /// use std::rc::Rc;
2983     ///
2984     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2985     /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2986     ///
2987     /// // Initialise known strings, run program, etc.
2988     ///
2989     /// reclaim_memory(&mut map, &known_strings);
2990     ///
2991     /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2992     ///     for s in known_strings {
2993     ///         if let Entry::Occupied(entry) = map.entry(s.clone()) {
2994     ///             // Replaces the entry's key with our version of it in `known_strings`.
2995     ///             entry.replace_key();
2996     ///         }
2997     ///     }
2998     /// }
2999     /// ```
3000     #[unstable(feature = "map_entry_replace", issue = "44286")]
3001     pub fn replace_key(mut self) -> K {
3002         let (old_key, _) = self.elem.read_mut();
3003         mem::replace(old_key, self.key.unwrap())
3004     }
3005 }
3006
3007 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3008     /// Gets a reference to the key that would be used when inserting a value
3009     /// through the `VacantEntry`.
3010     ///
3011     /// # Examples
3012     ///
3013     /// ```
3014     /// use std::collections::HashMap;
3015     ///
3016     /// let mut map: HashMap<&str, u32> = HashMap::new();
3017     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3018     /// ```
3019     #[stable(feature = "map_entry_keys", since = "1.10.0")]
3020     pub fn key(&self) -> &K {
3021         &self.key
3022     }
3023
3024     /// Take ownership of the key.
3025     ///
3026     /// # Examples
3027     ///
3028     /// ```
3029     /// use std::collections::HashMap;
3030     /// use std::collections::hash_map::Entry;
3031     ///
3032     /// let mut map: HashMap<&str, u32> = HashMap::new();
3033     ///
3034     /// if let Entry::Vacant(v) = map.entry("poneyland") {
3035     ///     v.into_key();
3036     /// }
3037     /// ```
3038     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3039     pub fn into_key(self) -> K {
3040         self.key
3041     }
3042
3043     /// Sets the value of the entry with the VacantEntry's key,
3044     /// and returns a mutable reference to it.
3045     ///
3046     /// # Examples
3047     ///
3048     /// ```
3049     /// use std::collections::HashMap;
3050     /// use std::collections::hash_map::Entry;
3051     ///
3052     /// let mut map: HashMap<&str, u32> = HashMap::new();
3053     ///
3054     /// if let Entry::Vacant(o) = map.entry("poneyland") {
3055     ///     o.insert(37);
3056     /// }
3057     /// assert_eq!(map["poneyland"], 37);
3058     /// ```
3059     #[stable(feature = "rust1", since = "1.0.0")]
3060     pub fn insert(self, value: V) -> &'a mut V {
3061         let b = match self.elem {
3062             NeqElem(mut bucket, disp) => {
3063                 if disp >= DISPLACEMENT_THRESHOLD {
3064                     bucket.table_mut().set_tag(true);
3065                 }
3066                 robin_hood(bucket, disp, self.hash, self.key, value)
3067             },
3068             NoElem(mut bucket, disp) => {
3069                 if disp >= DISPLACEMENT_THRESHOLD {
3070                     bucket.table_mut().set_tag(true);
3071                 }
3072                 bucket.put(self.hash, self.key, value)
3073             },
3074         };
3075         b.into_mut_refs().1
3076     }
3077 }
3078
3079 #[stable(feature = "rust1", since = "1.0.0")]
3080 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3081     where K: Eq + Hash,
3082           S: BuildHasher + Default
3083 {
3084     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3085         let mut map = HashMap::with_hasher(Default::default());
3086         map.extend(iter);
3087         map
3088     }
3089 }
3090
3091 #[stable(feature = "rust1", since = "1.0.0")]
3092 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3093     where K: Eq + Hash,
3094           S: BuildHasher
3095 {
3096     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3097         // Keys may be already present or show multiple times in the iterator.
3098         // Reserve the entire hint lower bound if the map is empty.
3099         // Otherwise reserve half the hint (rounded up), so the map
3100         // will only resize twice in the worst case.
3101         let iter = iter.into_iter();
3102         let reserve = if self.is_empty() {
3103             iter.size_hint().0
3104         } else {
3105             (iter.size_hint().0 + 1) / 2
3106         };
3107         self.reserve(reserve);
3108         for (k, v) in iter {
3109             self.insert(k, v);
3110         }
3111     }
3112 }
3113
3114 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3115 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3116     where K: Eq + Hash + Copy,
3117           V: Copy,
3118           S: BuildHasher
3119 {
3120     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3121         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3122     }
3123 }
3124
3125 /// `RandomState` is the default state for [`HashMap`] types.
3126 ///
3127 /// A particular instance `RandomState` will create the same instances of
3128 /// [`Hasher`], but the hashers created by two different `RandomState`
3129 /// instances are unlikely to produce the same result for the same values.
3130 ///
3131 /// [`HashMap`]: struct.HashMap.html
3132 /// [`Hasher`]: ../../hash/trait.Hasher.html
3133 ///
3134 /// # Examples
3135 ///
3136 /// ```
3137 /// use std::collections::HashMap;
3138 /// use std::collections::hash_map::RandomState;
3139 ///
3140 /// let s = RandomState::new();
3141 /// let mut map = HashMap::with_hasher(s);
3142 /// map.insert(1, 2);
3143 /// ```
3144 #[derive(Clone)]
3145 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3146 pub struct RandomState {
3147     k0: u64,
3148     k1: u64,
3149 }
3150
3151 impl RandomState {
3152     /// Constructs a new `RandomState` that is initialized with random keys.
3153     ///
3154     /// # Examples
3155     ///
3156     /// ```
3157     /// use std::collections::hash_map::RandomState;
3158     ///
3159     /// let s = RandomState::new();
3160     /// ```
3161     #[inline]
3162     #[allow(deprecated)]
3163     // rand
3164     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3165     pub fn new() -> RandomState {
3166         // Historically this function did not cache keys from the OS and instead
3167         // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3168         // was discovered, however, that because we re-seed the thread-local RNG
3169         // from the OS periodically that this can cause excessive slowdown when
3170         // many hash maps are created on a thread. To solve this performance
3171         // trap we cache the first set of randomly generated keys per-thread.
3172         //
3173         // Later in #36481 it was discovered that exposing a deterministic
3174         // iteration order allows a form of DOS attack. To counter that we
3175         // increment one of the seeds on every RandomState creation, giving
3176         // every corresponding HashMap a different iteration order.
3177         thread_local!(static KEYS: Cell<(u64, u64)> = {
3178             Cell::new(sys::hashmap_random_keys())
3179         });
3180
3181         KEYS.with(|keys| {
3182             let (k0, k1) = keys.get();
3183             keys.set((k0.wrapping_add(1), k1));
3184             RandomState { k0: k0, k1: k1 }
3185         })
3186     }
3187 }
3188
3189 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3190 impl BuildHasher for RandomState {
3191     type Hasher = DefaultHasher;
3192     #[inline]
3193     #[allow(deprecated)]
3194     fn build_hasher(&self) -> DefaultHasher {
3195         DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3196     }
3197 }
3198
3199 /// The default [`Hasher`] used by [`RandomState`].
3200 ///
3201 /// The internal algorithm is not specified, and so it and its hashes should
3202 /// not be relied upon over releases.
3203 ///
3204 /// [`RandomState`]: struct.RandomState.html
3205 /// [`Hasher`]: ../../hash/trait.Hasher.html
3206 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3207 #[allow(deprecated)]
3208 #[derive(Clone, Debug)]
3209 pub struct DefaultHasher(SipHasher13);
3210
3211 impl DefaultHasher {
3212     /// Creates a new `DefaultHasher`.
3213     ///
3214     /// This hasher is not guaranteed to be the same as all other
3215     /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3216     /// instances created through `new` or `default`.
3217     #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3218     #[allow(deprecated)]
3219     pub fn new() -> DefaultHasher {
3220         DefaultHasher(SipHasher13::new_with_keys(0, 0))
3221     }
3222 }
3223
3224 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3225 impl Default for DefaultHasher {
3226     /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3227     /// See its documentation for more.
3228     fn default() -> DefaultHasher {
3229         DefaultHasher::new()
3230     }
3231 }
3232
3233 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3234 impl Hasher for DefaultHasher {
3235     #[inline]
3236     fn write(&mut self, msg: &[u8]) {
3237         self.0.write(msg)
3238     }
3239
3240     #[inline]
3241     fn finish(&self) -> u64 {
3242         self.0.finish()
3243     }
3244 }
3245
3246 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3247 impl Default for RandomState {
3248     /// Constructs a new `RandomState`.
3249     #[inline]
3250     fn default() -> RandomState {
3251         RandomState::new()
3252     }
3253 }
3254
3255 #[stable(feature = "std_debug", since = "1.16.0")]
3256 impl fmt::Debug for RandomState {
3257     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3258         f.pad("RandomState { .. }")
3259     }
3260 }
3261
3262 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3263     where K: Eq + Hash + Borrow<Q>,
3264           S: BuildHasher,
3265           Q: Eq + Hash
3266 {
3267     type Key = K;
3268
3269     #[inline]
3270     fn get(&self, key: &Q) -> Option<&K> {
3271         self.search(key).map(|bucket| bucket.into_refs().0)
3272     }
3273
3274     fn take(&mut self, key: &Q) -> Option<K> {
3275         self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3276     }
3277
3278     #[inline]
3279     fn replace(&mut self, key: K) -> Option<K> {
3280         self.reserve(1);
3281
3282         match self.entry(key) {
3283             Occupied(mut occupied) => {
3284                 let key = occupied.take_key().unwrap();
3285                 Some(mem::replace(occupied.elem.read_mut().0, key))
3286             }
3287             Vacant(vacant) => {
3288                 vacant.insert(());
3289                 None
3290             }
3291         }
3292     }
3293 }
3294
3295 #[allow(dead_code)]
3296 fn assert_covariance() {
3297     fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3298         v
3299     }
3300     fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3301         v
3302     }
3303     fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3304         v
3305     }
3306     fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3307         v
3308     }
3309     fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3310         v
3311     }
3312     fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3313         v
3314     }
3315     fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3316         v
3317     }
3318     fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3319         v
3320     }
3321     fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3322         v
3323     }
3324     fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3325         v
3326     }
3327     fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3328                    -> Drain<'new, &'new str, &'new str> {
3329         d
3330     }
3331 }
3332
3333 #[cfg(test)]
3334 mod test_map {
3335     use super::HashMap;
3336     use super::Entry::{Occupied, Vacant};
3337     use super::RandomState;
3338     use cell::RefCell;
3339     use rand::{thread_rng, Rng};
3340     use realstd::collections::CollectionAllocErr::*;
3341     use realstd::mem::size_of;
3342     use realstd::usize;
3343
3344     #[test]
3345     fn test_zero_capacities() {
3346         type HM = HashMap<i32, i32>;
3347
3348         let m = HM::new();
3349         assert_eq!(m.capacity(), 0);
3350
3351         let m = HM::default();
3352         assert_eq!(m.capacity(), 0);
3353
3354         let m = HM::with_hasher(RandomState::new());
3355         assert_eq!(m.capacity(), 0);
3356
3357         let m = HM::with_capacity(0);
3358         assert_eq!(m.capacity(), 0);
3359
3360         let m = HM::with_capacity_and_hasher(0, RandomState::new());
3361         assert_eq!(m.capacity(), 0);
3362
3363         let mut m = HM::new();
3364         m.insert(1, 1);
3365         m.insert(2, 2);
3366         m.remove(&1);
3367         m.remove(&2);
3368         m.shrink_to_fit();
3369         assert_eq!(m.capacity(), 0);
3370
3371         let mut m = HM::new();
3372         m.reserve(0);
3373         assert_eq!(m.capacity(), 0);
3374     }
3375
3376     #[test]
3377     fn test_create_capacity_zero() {
3378         let mut m = HashMap::with_capacity(0);
3379
3380         assert!(m.insert(1, 1).is_none());
3381
3382         assert!(m.contains_key(&1));
3383         assert!(!m.contains_key(&0));
3384     }
3385
3386     #[test]
3387     fn test_insert() {
3388         let mut m = HashMap::new();
3389         assert_eq!(m.len(), 0);
3390         assert!(m.insert(1, 2).is_none());
3391         assert_eq!(m.len(), 1);
3392         assert!(m.insert(2, 4).is_none());
3393         assert_eq!(m.len(), 2);
3394         assert_eq!(*m.get(&1).unwrap(), 2);
3395         assert_eq!(*m.get(&2).unwrap(), 4);
3396     }
3397
3398     #[test]
3399     fn test_clone() {
3400         let mut m = HashMap::new();
3401         assert_eq!(m.len(), 0);
3402         assert!(m.insert(1, 2).is_none());
3403         assert_eq!(m.len(), 1);
3404         assert!(m.insert(2, 4).is_none());
3405         assert_eq!(m.len(), 2);
3406         let m2 = m.clone();
3407         assert_eq!(*m2.get(&1).unwrap(), 2);
3408         assert_eq!(*m2.get(&2).unwrap(), 4);
3409         assert_eq!(m2.len(), 2);
3410     }
3411
3412     thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3413
3414     #[derive(Hash, PartialEq, Eq)]
3415     struct Droppable {
3416         k: usize,
3417     }
3418
3419     impl Droppable {
3420         fn new(k: usize) -> Droppable {
3421             DROP_VECTOR.with(|slot| {
3422                 slot.borrow_mut()[k] += 1;
3423             });
3424
3425             Droppable { k }
3426         }
3427     }
3428
3429     impl Drop for Droppable {
3430         fn drop(&mut self) {
3431             DROP_VECTOR.with(|slot| {
3432                 slot.borrow_mut()[self.k] -= 1;
3433             });
3434         }
3435     }
3436
3437     impl Clone for Droppable {
3438         fn clone(&self) -> Droppable {
3439             Droppable::new(self.k)
3440         }
3441     }
3442
3443     #[test]
3444     fn test_drops() {
3445         DROP_VECTOR.with(|slot| {
3446             *slot.borrow_mut() = vec![0; 200];
3447         });
3448
3449         {
3450             let mut m = HashMap::new();
3451
3452             DROP_VECTOR.with(|v| {
3453                 for i in 0..200 {
3454                     assert_eq!(v.borrow()[i], 0);
3455                 }
3456             });
3457
3458             for i in 0..100 {
3459                 let d1 = Droppable::new(i);
3460                 let d2 = Droppable::new(i + 100);
3461                 m.insert(d1, d2);
3462             }
3463
3464             DROP_VECTOR.with(|v| {
3465                 for i in 0..200 {
3466                     assert_eq!(v.borrow()[i], 1);
3467                 }
3468             });
3469
3470             for i in 0..50 {
3471                 let k = Droppable::new(i);
3472                 let v = m.remove(&k);
3473
3474                 assert!(v.is_some());
3475
3476                 DROP_VECTOR.with(|v| {
3477                     assert_eq!(v.borrow()[i], 1);
3478                     assert_eq!(v.borrow()[i+100], 1);
3479                 });
3480             }
3481
3482             DROP_VECTOR.with(|v| {
3483                 for i in 0..50 {
3484                     assert_eq!(v.borrow()[i], 0);
3485                     assert_eq!(v.borrow()[i+100], 0);
3486                 }
3487
3488                 for i in 50..100 {
3489                     assert_eq!(v.borrow()[i], 1);
3490                     assert_eq!(v.borrow()[i+100], 1);
3491                 }
3492             });
3493         }
3494
3495         DROP_VECTOR.with(|v| {
3496             for i in 0..200 {
3497                 assert_eq!(v.borrow()[i], 0);
3498             }
3499         });
3500     }
3501
3502     #[test]
3503     fn test_into_iter_drops() {
3504         DROP_VECTOR.with(|v| {
3505             *v.borrow_mut() = vec![0; 200];
3506         });
3507
3508         let hm = {
3509             let mut hm = HashMap::new();
3510
3511             DROP_VECTOR.with(|v| {
3512                 for i in 0..200 {
3513                     assert_eq!(v.borrow()[i], 0);
3514                 }
3515             });
3516
3517             for i in 0..100 {
3518                 let d1 = Droppable::new(i);
3519                 let d2 = Droppable::new(i + 100);
3520                 hm.insert(d1, d2);
3521             }
3522
3523             DROP_VECTOR.with(|v| {
3524                 for i in 0..200 {
3525                     assert_eq!(v.borrow()[i], 1);
3526                 }
3527             });
3528
3529             hm
3530         };
3531
3532         // By the way, ensure that cloning doesn't screw up the dropping.
3533         drop(hm.clone());
3534
3535         {
3536             let mut half = hm.into_iter().take(50);
3537
3538             DROP_VECTOR.with(|v| {
3539                 for i in 0..200 {
3540                     assert_eq!(v.borrow()[i], 1);
3541                 }
3542             });
3543
3544             for _ in half.by_ref() {}
3545
3546             DROP_VECTOR.with(|v| {
3547                 let nk = (0..100)
3548                     .filter(|&i| v.borrow()[i] == 1)
3549                     .count();
3550
3551                 let nv = (0..100)
3552                     .filter(|&i| v.borrow()[i + 100] == 1)
3553                     .count();
3554
3555                 assert_eq!(nk, 50);
3556                 assert_eq!(nv, 50);
3557             });
3558         };
3559
3560         DROP_VECTOR.with(|v| {
3561             for i in 0..200 {
3562                 assert_eq!(v.borrow()[i], 0);
3563             }
3564         });
3565     }
3566
3567     #[test]
3568     fn test_empty_remove() {
3569         let mut m: HashMap<i32, bool> = HashMap::new();
3570         assert_eq!(m.remove(&0), None);
3571     }
3572
3573     #[test]
3574     fn test_empty_entry() {
3575         let mut m: HashMap<i32, bool> = HashMap::new();
3576         match m.entry(0) {
3577             Occupied(_) => panic!(),
3578             Vacant(_) => {}
3579         }
3580         assert!(*m.entry(0).or_insert(true));
3581         assert_eq!(m.len(), 1);
3582     }
3583
3584     #[test]
3585     fn test_empty_iter() {
3586         let mut m: HashMap<i32, bool> = HashMap::new();
3587         assert_eq!(m.drain().next(), None);
3588         assert_eq!(m.keys().next(), None);
3589         assert_eq!(m.values().next(), None);
3590         assert_eq!(m.values_mut().next(), None);
3591         assert_eq!(m.iter().next(), None);
3592         assert_eq!(m.iter_mut().next(), None);
3593         assert_eq!(m.len(), 0);
3594         assert!(m.is_empty());
3595         assert_eq!(m.into_iter().next(), None);
3596     }
3597
3598     #[test]
3599     fn test_lots_of_insertions() {
3600         let mut m = HashMap::new();
3601
3602         // Try this a few times to make sure we never screw up the hashmap's
3603         // internal state.
3604         for _ in 0..10 {
3605             assert!(m.is_empty());
3606
3607             for i in 1..1001 {
3608                 assert!(m.insert(i, i).is_none());
3609
3610                 for j in 1..=i {
3611                     let r = m.get(&j);
3612                     assert_eq!(r, Some(&j));
3613                 }
3614
3615                 for j in i + 1..1001 {
3616                     let r = m.get(&j);
3617                     assert_eq!(r, None);
3618                 }
3619             }
3620
3621             for i in 1001..2001 {
3622                 assert!(!m.contains_key(&i));
3623             }
3624
3625             // remove forwards
3626             for i in 1..1001 {
3627                 assert!(m.remove(&i).is_some());
3628
3629                 for j in 1..=i {
3630                     assert!(!m.contains_key(&j));
3631                 }
3632
3633                 for j in i + 1..1001 {
3634                     assert!(m.contains_key(&j));
3635                 }
3636             }
3637
3638             for i in 1..1001 {
3639                 assert!(!m.contains_key(&i));
3640             }
3641
3642             for i in 1..1001 {
3643                 assert!(m.insert(i, i).is_none());
3644             }
3645
3646             // remove backwards
3647             for i in (1..1001).rev() {
3648                 assert!(m.remove(&i).is_some());
3649
3650                 for j in i..1001 {
3651                     assert!(!m.contains_key(&j));
3652                 }
3653
3654                 for j in 1..i {
3655                     assert!(m.contains_key(&j));
3656                 }
3657             }
3658         }
3659     }
3660
3661     #[test]
3662     fn test_find_mut() {
3663         let mut m = HashMap::new();
3664         assert!(m.insert(1, 12).is_none());
3665         assert!(m.insert(2, 8).is_none());
3666         assert!(m.insert(5, 14).is_none());
3667         let new = 100;
3668         match m.get_mut(&5) {
3669             None => panic!(),
3670             Some(x) => *x = new,
3671         }
3672         assert_eq!(m.get(&5), Some(&new));
3673     }
3674
3675     #[test]
3676     fn test_insert_overwrite() {
3677         let mut m = HashMap::new();
3678         assert!(m.insert(1, 2).is_none());
3679         assert_eq!(*m.get(&1).unwrap(), 2);
3680         assert!(!m.insert(1, 3).is_none());
3681         assert_eq!(*m.get(&1).unwrap(), 3);
3682     }
3683
3684     #[test]
3685     fn test_insert_conflicts() {
3686         let mut m = HashMap::with_capacity(4);
3687         assert!(m.insert(1, 2).is_none());
3688         assert!(m.insert(5, 3).is_none());
3689         assert!(m.insert(9, 4).is_none());
3690         assert_eq!(*m.get(&9).unwrap(), 4);
3691         assert_eq!(*m.get(&5).unwrap(), 3);
3692         assert_eq!(*m.get(&1).unwrap(), 2);
3693     }
3694
3695     #[test]
3696     fn test_conflict_remove() {
3697         let mut m = HashMap::with_capacity(4);
3698         assert!(m.insert(1, 2).is_none());
3699         assert_eq!(*m.get(&1).unwrap(), 2);
3700         assert!(m.insert(5, 3).is_none());
3701         assert_eq!(*m.get(&1).unwrap(), 2);
3702         assert_eq!(*m.get(&5).unwrap(), 3);
3703         assert!(m.insert(9, 4).is_none());
3704         assert_eq!(*m.get(&1).unwrap(), 2);
3705         assert_eq!(*m.get(&5).unwrap(), 3);
3706         assert_eq!(*m.get(&9).unwrap(), 4);
3707         assert!(m.remove(&1).is_some());
3708         assert_eq!(*m.get(&9).unwrap(), 4);
3709         assert_eq!(*m.get(&5).unwrap(), 3);
3710     }
3711
3712     #[test]
3713     fn test_is_empty() {
3714         let mut m = HashMap::with_capacity(4);
3715         assert!(m.insert(1, 2).is_none());
3716         assert!(!m.is_empty());
3717         assert!(m.remove(&1).is_some());
3718         assert!(m.is_empty());
3719     }
3720
3721     #[test]
3722     fn test_remove() {
3723         let mut m = HashMap::new();
3724         m.insert(1, 2);
3725         assert_eq!(m.remove(&1), Some(2));
3726         assert_eq!(m.remove(&1), None);
3727     }
3728
3729     #[test]
3730     fn test_remove_entry() {
3731         let mut m = HashMap::new();
3732         m.insert(1, 2);
3733         assert_eq!(m.remove_entry(&1), Some((1, 2)));
3734         assert_eq!(m.remove(&1), None);
3735     }
3736
3737     #[test]
3738     fn test_iterate() {
3739         let mut m = HashMap::with_capacity(4);
3740         for i in 0..32 {
3741             assert!(m.insert(i, i*2).is_none());
3742         }
3743         assert_eq!(m.len(), 32);
3744
3745         let mut observed: u32 = 0;
3746
3747         for (k, v) in &m {
3748             assert_eq!(*v, *k * 2);
3749             observed |= 1 << *k;
3750         }
3751         assert_eq!(observed, 0xFFFF_FFFF);
3752     }
3753
3754     #[test]
3755     fn test_keys() {
3756         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3757         let map: HashMap<_, _> = vec.into_iter().collect();
3758         let keys: Vec<_> = map.keys().cloned().collect();
3759         assert_eq!(keys.len(), 3);
3760         assert!(keys.contains(&1));
3761         assert!(keys.contains(&2));
3762         assert!(keys.contains(&3));
3763     }
3764
3765     #[test]
3766     fn test_values() {
3767         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3768         let map: HashMap<_, _> = vec.into_iter().collect();
3769         let values: Vec<_> = map.values().cloned().collect();
3770         assert_eq!(values.len(), 3);
3771         assert!(values.contains(&'a'));
3772         assert!(values.contains(&'b'));
3773         assert!(values.contains(&'c'));
3774     }
3775
3776     #[test]
3777     fn test_values_mut() {
3778         let vec = vec![(1, 1), (2, 2), (3, 3)];
3779         let mut map: HashMap<_, _> = vec.into_iter().collect();
3780         for value in map.values_mut() {
3781             *value = (*value) * 2
3782         }
3783         let values: Vec<_> = map.values().cloned().collect();
3784         assert_eq!(values.len(), 3);
3785         assert!(values.contains(&2));
3786         assert!(values.contains(&4));
3787         assert!(values.contains(&6));
3788     }
3789
3790     #[test]
3791     fn test_find() {
3792         let mut m = HashMap::new();
3793         assert!(m.get(&1).is_none());
3794         m.insert(1, 2);
3795         match m.get(&1) {
3796             None => panic!(),
3797             Some(v) => assert_eq!(*v, 2),
3798         }
3799     }
3800
3801     #[test]
3802     fn test_eq() {
3803         let mut m1 = HashMap::new();
3804         m1.insert(1, 2);
3805         m1.insert(2, 3);
3806         m1.insert(3, 4);
3807
3808         let mut m2 = HashMap::new();
3809         m2.insert(1, 2);
3810         m2.insert(2, 3);
3811
3812         assert!(m1 != m2);
3813
3814         m2.insert(3, 4);
3815
3816         assert_eq!(m1, m2);
3817     }
3818
3819     #[test]
3820     fn test_show() {
3821         let mut map = HashMap::new();
3822         let empty: HashMap<i32, i32> = HashMap::new();
3823
3824         map.insert(1, 2);
3825         map.insert(3, 4);
3826
3827         let map_str = format!("{:?}", map);
3828
3829         assert!(map_str == "{1: 2, 3: 4}" ||
3830                 map_str == "{3: 4, 1: 2}");
3831         assert_eq!(format!("{:?}", empty), "{}");
3832     }
3833
3834     #[test]
3835     fn test_expand() {
3836         let mut m = HashMap::new();
3837
3838         assert_eq!(m.len(), 0);
3839         assert!(m.is_empty());
3840
3841         let mut i = 0;
3842         let old_raw_cap = m.raw_capacity();
3843         while old_raw_cap == m.raw_capacity() {
3844             m.insert(i, i);
3845             i += 1;
3846         }
3847
3848         assert_eq!(m.len(), i);
3849         assert!(!m.is_empty());
3850     }
3851
3852     #[test]
3853     fn test_behavior_resize_policy() {
3854         let mut m = HashMap::new();
3855
3856         assert_eq!(m.len(), 0);
3857         assert_eq!(m.raw_capacity(), 0);
3858         assert!(m.is_empty());
3859
3860         m.insert(0, 0);
3861         m.remove(&0);
3862         assert!(m.is_empty());
3863         let initial_raw_cap = m.raw_capacity();
3864         m.reserve(initial_raw_cap);
3865         let raw_cap = m.raw_capacity();
3866
3867         assert_eq!(raw_cap, initial_raw_cap * 2);
3868
3869         let mut i = 0;
3870         for _ in 0..raw_cap * 3 / 4 {
3871             m.insert(i, i);
3872             i += 1;
3873         }
3874         // three quarters full
3875
3876         assert_eq!(m.len(), i);
3877         assert_eq!(m.raw_capacity(), raw_cap);
3878
3879         for _ in 0..raw_cap / 4 {
3880             m.insert(i, i);
3881             i += 1;
3882         }
3883         // half full
3884
3885         let new_raw_cap = m.raw_capacity();
3886         assert_eq!(new_raw_cap, raw_cap * 2);
3887
3888         for _ in 0..raw_cap / 2 - 1 {
3889             i -= 1;
3890             m.remove(&i);
3891             assert_eq!(m.raw_capacity(), new_raw_cap);
3892         }
3893         // A little more than one quarter full.
3894         m.shrink_to_fit();
3895         assert_eq!(m.raw_capacity(), raw_cap);
3896         // again, a little more than half full
3897         for _ in 0..raw_cap / 2 - 1 {
3898             i -= 1;
3899             m.remove(&i);
3900         }
3901         m.shrink_to_fit();
3902
3903         assert_eq!(m.len(), i);
3904         assert!(!m.is_empty());
3905         assert_eq!(m.raw_capacity(), initial_raw_cap);
3906     }
3907
3908     #[test]
3909     fn test_reserve_shrink_to_fit() {
3910         let mut m = HashMap::new();
3911         m.insert(0, 0);
3912         m.remove(&0);
3913         assert!(m.capacity() >= m.len());
3914         for i in 0..128 {
3915             m.insert(i, i);
3916         }
3917         m.reserve(256);
3918
3919         let usable_cap = m.capacity();
3920         for i in 128..(128 + 256) {
3921             m.insert(i, i);
3922             assert_eq!(m.capacity(), usable_cap);
3923         }
3924
3925         for i in 100..(128 + 256) {
3926             assert_eq!(m.remove(&i), Some(i));
3927         }
3928         m.shrink_to_fit();
3929
3930         assert_eq!(m.len(), 100);
3931         assert!(!m.is_empty());
3932         assert!(m.capacity() >= m.len());
3933
3934         for i in 0..100 {
3935             assert_eq!(m.remove(&i), Some(i));
3936         }
3937         m.shrink_to_fit();
3938         m.insert(0, 0);
3939
3940         assert_eq!(m.len(), 1);
3941         assert!(m.capacity() >= m.len());
3942         assert_eq!(m.remove(&0), Some(0));
3943     }
3944
3945     #[test]
3946     fn test_from_iter() {
3947         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3948
3949         let map: HashMap<_, _> = xs.iter().cloned().collect();
3950
3951         for &(k, v) in &xs {
3952             assert_eq!(map.get(&k), Some(&v));
3953         }
3954     }
3955
3956     #[test]
3957     fn test_size_hint() {
3958         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3959
3960         let map: HashMap<_, _> = xs.iter().cloned().collect();
3961
3962         let mut iter = map.iter();
3963
3964         for _ in iter.by_ref().take(3) {}
3965
3966         assert_eq!(iter.size_hint(), (3, Some(3)));
3967     }
3968
3969     #[test]
3970     fn test_iter_len() {
3971         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3972
3973         let map: HashMap<_, _> = xs.iter().cloned().collect();
3974
3975         let mut iter = map.iter();
3976
3977         for _ in iter.by_ref().take(3) {}
3978
3979         assert_eq!(iter.len(), 3);
3980     }
3981
3982     #[test]
3983     fn test_mut_size_hint() {
3984         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3985
3986         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3987
3988         let mut iter = map.iter_mut();
3989
3990         for _ in iter.by_ref().take(3) {}
3991
3992         assert_eq!(iter.size_hint(), (3, Some(3)));
3993     }
3994
3995     #[test]
3996     fn test_iter_mut_len() {
3997         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3998
3999         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4000
4001         let mut iter = map.iter_mut();
4002
4003         for _ in iter.by_ref().take(3) {}
4004
4005         assert_eq!(iter.len(), 3);
4006     }
4007
4008     #[test]
4009     fn test_index() {
4010         let mut map = HashMap::new();
4011
4012         map.insert(1, 2);
4013         map.insert(2, 1);
4014         map.insert(3, 4);
4015
4016         assert_eq!(map[&2], 1);
4017     }
4018
4019     #[test]
4020     #[should_panic]
4021     fn test_index_nonexistent() {
4022         let mut map = HashMap::new();
4023
4024         map.insert(1, 2);
4025         map.insert(2, 1);
4026         map.insert(3, 4);
4027
4028         map[&4];
4029     }
4030
4031     #[test]
4032     fn test_entry() {
4033         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4034
4035         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4036
4037         // Existing key (insert)
4038         match map.entry(1) {
4039             Vacant(_) => unreachable!(),
4040             Occupied(mut view) => {
4041                 assert_eq!(view.get(), &10);
4042                 assert_eq!(view.insert(100), 10);
4043             }
4044         }
4045         assert_eq!(map.get(&1).unwrap(), &100);
4046         assert_eq!(map.len(), 6);
4047
4048
4049         // Existing key (update)
4050         match map.entry(2) {
4051             Vacant(_) => unreachable!(),
4052             Occupied(mut view) => {
4053                 let v = view.get_mut();
4054                 let new_v = (*v) * 10;
4055                 *v = new_v;
4056             }
4057         }
4058         assert_eq!(map.get(&2).unwrap(), &200);
4059         assert_eq!(map.len(), 6);
4060
4061         // Existing key (take)
4062         match map.entry(3) {
4063             Vacant(_) => unreachable!(),
4064             Occupied(view) => {
4065                 assert_eq!(view.remove(), 30);
4066             }
4067         }
4068         assert_eq!(map.get(&3), None);
4069         assert_eq!(map.len(), 5);
4070
4071
4072         // Inexistent key (insert)
4073         match map.entry(10) {
4074             Occupied(_) => unreachable!(),
4075             Vacant(view) => {
4076                 assert_eq!(*view.insert(1000), 1000);
4077             }
4078         }
4079         assert_eq!(map.get(&10).unwrap(), &1000);
4080         assert_eq!(map.len(), 6);
4081     }
4082
4083     #[test]
4084     fn test_entry_take_doesnt_corrupt() {
4085         #![allow(deprecated)] //rand
4086         // Test for #19292
4087         fn check(m: &HashMap<i32, ()>) {
4088             for k in m.keys() {
4089                 assert!(m.contains_key(k),
4090                         "{} is in keys() but not in the map?", k);
4091             }
4092         }
4093
4094         let mut m = HashMap::new();
4095         let mut rng = thread_rng();
4096
4097         // Populate the map with some items.
4098         for _ in 0..50 {
4099             let x = rng.gen_range(-10, 10);
4100             m.insert(x, ());
4101         }
4102
4103         for _ in 0..1000 {
4104             let x = rng.gen_range(-10, 10);
4105             match m.entry(x) {
4106                 Vacant(_) => {}
4107                 Occupied(e) => {
4108                     e.remove();
4109                 }
4110             }
4111
4112             check(&m);
4113         }
4114     }
4115
4116     #[test]
4117     fn test_extend_ref() {
4118         let mut a = HashMap::new();
4119         a.insert(1, "one");
4120         let mut b = HashMap::new();
4121         b.insert(2, "two");
4122         b.insert(3, "three");
4123
4124         a.extend(&b);
4125
4126         assert_eq!(a.len(), 3);
4127         assert_eq!(a[&1], "one");
4128         assert_eq!(a[&2], "two");
4129         assert_eq!(a[&3], "three");
4130     }
4131
4132     #[test]
4133     fn test_capacity_not_less_than_len() {
4134         let mut a = HashMap::new();
4135         let mut item = 0;
4136
4137         for _ in 0..116 {
4138             a.insert(item, 0);
4139             item += 1;
4140         }
4141
4142         assert!(a.capacity() > a.len());
4143
4144         let free = a.capacity() - a.len();
4145         for _ in 0..free {
4146             a.insert(item, 0);
4147             item += 1;
4148         }
4149
4150         assert_eq!(a.len(), a.capacity());
4151
4152         // Insert at capacity should cause allocation.
4153         a.insert(item, 0);
4154         assert!(a.capacity() > a.len());
4155     }
4156
4157     #[test]
4158     fn test_occupied_entry_key() {
4159         let mut a = HashMap::new();
4160         let key = "hello there";
4161         let value = "value goes here";
4162         assert!(a.is_empty());
4163         a.insert(key.clone(), value.clone());
4164         assert_eq!(a.len(), 1);
4165         assert_eq!(a[key], value);
4166
4167         match a.entry(key.clone()) {
4168             Vacant(_) => panic!(),
4169             Occupied(e) => assert_eq!(key, *e.key()),
4170         }
4171         assert_eq!(a.len(), 1);
4172         assert_eq!(a[key], value);
4173     }
4174
4175     #[test]
4176     fn test_vacant_entry_key() {
4177         let mut a = HashMap::new();
4178         let key = "hello there";
4179         let value = "value goes here";
4180
4181         assert!(a.is_empty());
4182         match a.entry(key.clone()) {
4183             Occupied(_) => panic!(),
4184             Vacant(e) => {
4185                 assert_eq!(key, *e.key());
4186                 e.insert(value.clone());
4187             }
4188         }
4189         assert_eq!(a.len(), 1);
4190         assert_eq!(a[key], value);
4191     }
4192
4193     #[test]
4194     fn test_retain() {
4195         let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4196
4197         map.retain(|&k, _| k % 2 == 0);
4198         assert_eq!(map.len(), 50);
4199         assert_eq!(map[&2], 20);
4200         assert_eq!(map[&4], 40);
4201         assert_eq!(map[&6], 60);
4202     }
4203
4204     #[test]
4205     fn test_adaptive() {
4206         const TEST_LEN: usize = 5000;
4207         // by cloning we get maps with the same hasher seed
4208         let mut first = HashMap::new();
4209         let mut second = first.clone();
4210         first.extend((0..TEST_LEN).map(|i| (i, i)));
4211         second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4212
4213         for (&k, &v) in &second {
4214             let prev_cap = first.capacity();
4215             let expect_grow = first.len() == prev_cap;
4216             first.insert(k, v);
4217             if !expect_grow && first.capacity() != prev_cap {
4218                 return;
4219             }
4220         }
4221         panic!("Adaptive early resize failed");
4222     }
4223
4224     #[test]
4225     fn test_try_reserve() {
4226
4227         let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4228
4229         const MAX_USIZE: usize = usize::MAX;
4230
4231         // HashMap and RawTables use complicated size calculations
4232         // hashes_size is sizeof(HashUint) * capacity;
4233         // pairs_size is sizeof((K. V)) * capacity;
4234         // alignment_hashes_size is 8
4235         // alignment_pairs size is 4
4236         let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4237         // The following formula is used to calculate the new capacity
4238         let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4239
4240         if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4241         } else { panic!("usize::MAX should trigger an overflow!"); }
4242
4243         if size_of::<usize>() < 8 {
4244             if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4245             } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4246         } else {
4247             if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4248             } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4249         }
4250     }
4251
4252     #[test]
4253     fn test_raw_entry() {
4254         use super::RawEntryMut::{Occupied, Vacant};
4255
4256         let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4257
4258         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4259
4260         let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4261             use core::hash::{BuildHasher, Hash, Hasher};
4262
4263             let mut hasher = map.hasher().build_hasher();
4264             k.hash(&mut hasher);
4265             hasher.finish()
4266         };
4267
4268         // Existing key (insert)
4269         match map.raw_entry_mut().from_key(&1) {
4270             Vacant(_) => unreachable!(),
4271             Occupied(mut view) => {
4272                 assert_eq!(view.get(), &10);
4273                 assert_eq!(view.insert(100), 10);
4274             }
4275         }
4276         let hash1 = compute_hash(&map, 1);
4277         assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4278         assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4279         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4280         assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4281         assert_eq!(map.len(), 6);
4282
4283         // Existing key (update)
4284         match map.raw_entry_mut().from_key(&2) {
4285             Vacant(_) => unreachable!(),
4286             Occupied(mut view) => {
4287                 let v = view.get_mut();
4288                 let new_v = (*v) * 10;
4289                 *v = new_v;
4290             }
4291         }
4292         let hash2 = compute_hash(&map, 2);
4293         assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4294         assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4295         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4296         assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4297         assert_eq!(map.len(), 6);
4298
4299         // Existing key (take)
4300         let hash3 = compute_hash(&map, 3);
4301         match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4302             Vacant(_) => unreachable!(),
4303             Occupied(view) => {
4304                 assert_eq!(view.remove_entry(), (3, 30));
4305             }
4306         }
4307         assert_eq!(map.raw_entry().from_key(&3), None);
4308         assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4309         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4310         assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4311         assert_eq!(map.len(), 5);
4312
4313
4314         // Nonexistent key (insert)
4315         match map.raw_entry_mut().from_key(&10) {
4316             Occupied(_) => unreachable!(),
4317             Vacant(view) => {
4318                 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4319             }
4320         }
4321         assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4322         assert_eq!(map.len(), 6);
4323
4324         // Ensure all lookup methods produce equivalent results.
4325         for k in 0..12 {
4326             let hash = compute_hash(&map, k);
4327             let v = map.get(&k).cloned();
4328             let kv = v.as_ref().map(|v| (&k, v));
4329
4330             assert_eq!(map.raw_entry().from_key(&k), kv);
4331             assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4332             assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4333             assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4334
4335             match map.raw_entry_mut().from_key(&k) {
4336                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4337                 Vacant(_) => assert_eq!(v, None),
4338             }
4339             match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
4340                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4341                 Vacant(_) => assert_eq!(v, None),
4342             }
4343             match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
4344                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4345                 Vacant(_) => assert_eq!(v, None),
4346             }
4347             match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4348                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4349                 Vacant(_) => assert_eq!(v, None),
4350             }
4351         }
4352     }
4353
4354 }