]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Update issue number of `shrink_to` methods to point the tracking issue
[rust.git] / src / libstd / collections / hash / map.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use self::Entry::*;
12 use self::VacantEntryState::*;
13
14 use collections::CollectionAllocErr;
15 use cell::Cell;
16 use borrow::Borrow;
17 use cmp::max;
18 use fmt::{self, Debug};
19 #[allow(deprecated)]
20 use hash::{Hash, Hasher, BuildHasher, SipHasher13};
21 use iter::{FromIterator, FusedIterator};
22 use mem::{self, replace};
23 use ops::{Deref, DerefMut, Index};
24 use sys;
25
26 use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
27                    SafeHash};
28 use super::table::BucketState::{Empty, Full};
29 use super::table::Fallibility::{Fallible, Infallible};
30
31 const MIN_NONZERO_RAW_CAPACITY: usize = 32;     // must be a power of two
32
33 /// The default behavior of HashMap implements a maximum load factor of 90.9%.
34 #[derive(Clone)]
35 struct DefaultResizePolicy;
36
37 impl DefaultResizePolicy {
38     #[inline]
39     fn new() -> DefaultResizePolicy {
40         DefaultResizePolicy
41     }
42
43     /// A hash map's "capacity" is the number of elements it can hold without
44     /// being resized. Its "raw capacity" is the number of slots required to
45     /// provide that capacity, accounting for maximum loading. The raw capacity
46     /// is always zero or a power of two.
47     #[inline]
48     fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
49         if len == 0 {
50             Ok(0)
51         } else {
52             // 1. Account for loading: `raw_capacity >= len * 1.1`.
53             // 2. Ensure it is a power of two.
54             // 3. Ensure it is at least the minimum size.
55             let mut raw_cap = len.checked_mul(11)
56                 .map(|l| l / 10)
57                 .and_then(|l| l.checked_next_power_of_two())
58                 .ok_or(CollectionAllocErr::CapacityOverflow)?;
59
60             raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
61             Ok(raw_cap)
62         }
63     }
64
65     #[inline]
66     fn raw_capacity(&self, len: usize) -> usize {
67         self.try_raw_capacity(len).expect("raw_capacity overflow")
68     }
69
70     /// The capacity of the given raw capacity.
71     #[inline]
72     fn capacity(&self, raw_cap: usize) -> usize {
73         // This doesn't have to be checked for overflow since allocation size
74         // in bytes will overflow earlier than multiplication by 10.
75         //
76         // As per https://github.com/rust-lang/rust/pull/30991 this is updated
77         // to be: (raw_cap * den + den - 1) / num
78         (raw_cap * 10 + 10 - 1) / 11
79     }
80 }
81
82 // The main performance trick in this hashmap is called Robin Hood Hashing.
83 // It gains its excellent performance from one essential operation:
84 //
85 //    If an insertion collides with an existing element, and that element's
86 //    "probe distance" (how far away the element is from its ideal location)
87 //    is higher than how far we've already probed, swap the elements.
88 //
89 // This massively lowers variance in probe distance, and allows us to get very
90 // high load factors with good performance. The 90% load factor I use is rather
91 // conservative.
92 //
93 // > Why a load factor of approximately 90%?
94 //
95 // In general, all the distances to initial buckets will converge on the mean.
96 // At a load factor of α, the odds of finding the target bucket after k
97 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
98 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
99 // this down to make the math easier on the CPU and avoid its FPU.
100 // Since on average we start the probing in the middle of a cache line, this
101 // strategy pulls in two cache lines of hashes on every lookup. I think that's
102 // pretty good, but if you want to trade off some space, it could go down to one
103 // cache line on average with an α of 0.84.
104 //
105 // > Wait, what? Where did you get 1-α^k from?
106 //
107 // On the first probe, your odds of a collision with an existing element is α.
108 // The odds of doing this twice in a row is approximately α^2. For three times,
109 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
110 // colliding after k tries is 1-α^k.
111 //
112 // The paper from 1986 cited below mentions an implementation which keeps track
113 // of the distance-to-initial-bucket histogram. This approach is not suitable
114 // for modern architectures because it requires maintaining an internal data
115 // structure. This allows very good first guesses, but we are most concerned
116 // with guessing entire cache lines, not individual indexes. Furthermore, array
117 // accesses are no longer linear and in one direction, as we have now. There
118 // is also memory and cache pressure that this would entail that would be very
119 // difficult to properly see in a microbenchmark.
120 //
121 // ## Future Improvements (FIXME!)
122 //
123 // Allow the load factor to be changed dynamically and/or at initialization.
124 //
125 // Also, would it be possible for us to reuse storage when growing the
126 // underlying table? This is exactly the use case for 'realloc', and may
127 // be worth exploring.
128 //
129 // ## Future Optimizations (FIXME!)
130 //
131 // Another possible design choice that I made without any real reason is
132 // parameterizing the raw table over keys and values. Technically, all we need
133 // is the size and alignment of keys and values, and the code should be just as
134 // efficient (well, we might need one for power-of-two size and one for not...).
135 // This has the potential to reduce code bloat in rust executables, without
136 // really losing anything except 4 words (key size, key alignment, val size,
137 // val alignment) which can be passed in to every call of a `RawTable` function.
138 // This would definitely be an avenue worth exploring if people start complaining
139 // about the size of rust executables.
140 //
141 // Annotate exceedingly likely branches in `table::make_hash`
142 // and `search_hashed` to reduce instruction cache pressure
143 // and mispredictions once it becomes possible (blocked on issue #11092).
144 //
145 // Shrinking the table could simply reallocate in place after moving buckets
146 // to the first half.
147 //
148 // The growth algorithm (fragment of the Proof of Correctness)
149 // --------------------
150 //
151 // The growth algorithm is basically a fast path of the naive reinsertion-
152 // during-resize algorithm. Other paths should never be taken.
153 //
154 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
155 // by allocating a new table of capacity `2n`, and then individually reinsert
156 // each element in the old table into the new one. This guarantees that the
157 // new table is a valid robin hood hashtable with all the desired statistical
158 // properties. Remark that the order we reinsert the elements in should not
159 // matter. For simplicity and efficiency, we will consider only linear
160 // reinsertions, which consist of reinserting all elements in the old table
161 // into the new one by increasing order of index. However we will not be
162 // starting our reinsertions from index 0 in general. If we start from index
163 // i, for the purpose of reinsertion we will consider all elements with real
164 // index j < i to have virtual index n + j.
165 //
166 // Our hash generation scheme consists of generating a 64-bit hash and
167 // truncating the most significant bits. When moving to the new table, we
168 // simply introduce a new bit to the front of the hash. Therefore, if an
169 // element has ideal index i in the old table, it can have one of two ideal
170 // locations in the new table. If the new bit is 0, then the new ideal index
171 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
172 // we are producing two independent tables of size n, and for each element we
173 // independently choose which table to insert it into with equal probability.
174 // However, rather than wrapping around themselves on overflowing their
175 // indexes, the first table overflows into the second, and the second into the
176 // first. Visually, our new table will look something like:
177 //
178 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
179 //
180 // Where x's are elements inserted into the first table, y's are elements
181 // inserted into the second, and _'s are empty sections. We now define a few
182 // key concepts that we will use later. Note that this is a very abstract
183 // perspective of the table. A real resized table would be at least half
184 // empty.
185 //
186 // Theorem: A linear robin hood reinsertion from the first ideal element
187 // produces identical results to a linear naive reinsertion from the same
188 // element.
189 //
190 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
191 //
192 // Adaptive early resizing
193 // ----------------------
194 // To protect against degenerate performance scenarios (including DOS attacks),
195 // the implementation includes an adaptive behavior that can resize the map
196 // early (before its capacity is exceeded) when suspiciously long probe sequences
197 // are encountered.
198 //
199 // With this algorithm in place it would be possible to turn a CPU attack into
200 // a memory attack due to the aggressive resizing. To prevent that the
201 // adaptive behavior only triggers when the map is at least half full.
202 // This reduces the effectiveness of the algorithm but also makes it completely safe.
203 //
204 // The previous safety measure also prevents degenerate interactions with
205 // really bad quality hash algorithms that can make normal inputs look like a
206 // DOS attack.
207 //
208 const DISPLACEMENT_THRESHOLD: usize = 128;
209 //
210 // The threshold of 128 is chosen to minimize the chance of exceeding it.
211 // In particular, we want that chance to be less than 10^-8 with a load of 90%.
212 // For displacement, the smallest constant that fits our needs is 90,
213 // so we round that up to 128.
214 //
215 // At a load factor of α, the odds of finding the target bucket after exactly n
216 // unsuccessful probes[1] are
217 //
218 // Pr_α{displacement = n} =
219 // (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
220 //
221 // We use this formula to find the probability of triggering the adaptive behavior
222 //
223 // Pr_0.909{displacement > 128} = 1.601 * 10^-11
224 //
225 // 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
226 //    hashing with buckets.
227
228 /// A hash map implemented with linear probing and Robin Hood bucket stealing.
229 ///
230 /// By default, `HashMap` uses a hashing algorithm selected to provide
231 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
232 /// reasonable best-effort is made to generate this seed from a high quality,
233 /// secure source of randomness provided by the host without blocking the
234 /// program. Because of this, the randomness of the seed depends on the output
235 /// quality of the system's random number generator when the seed is created.
236 /// In particular, seeds generated when the system's entropy pool is abnormally
237 /// low such as during system boot may be of a lower quality.
238 ///
239 /// The default hashing algorithm is currently SipHash 1-3, though this is
240 /// subject to change at any point in the future. While its performance is very
241 /// competitive for medium sized keys, other hashing algorithms will outperform
242 /// it for small keys such as integers as well as large keys such as long
243 /// strings, though those algorithms will typically *not* protect against
244 /// attacks such as HashDoS.
245 ///
246 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
247 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
248 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
249 ///
250 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
251 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
252 /// If you implement these yourself, it is important that the following
253 /// property holds:
254 ///
255 /// ```text
256 /// k1 == k2 -> hash(k1) == hash(k2)
257 /// ```
258 ///
259 /// In other words, if two keys are equal, their hashes must be equal.
260 ///
261 /// It is a logic error for a key to be modified in such a way that the key's
262 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
263 /// the [`Eq`] trait, changes while it is in the map. This is normally only
264 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
265 ///
266 /// Relevant papers/articles:
267 ///
268 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
269 /// 2. Emmanuel Goossaert. ["Robin Hood
270 ///    hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
271 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
272 ///    deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// use std::collections::HashMap;
278 ///
279 /// // Type inference lets us omit an explicit type signature (which
280 /// // would be `HashMap<String, String>` in this example).
281 /// let mut book_reviews = HashMap::new();
282 ///
283 /// // Review some books.
284 /// book_reviews.insert(
285 ///     "Adventures of Huckleberry Finn".to_string(),
286 ///     "My favorite book.".to_string(),
287 /// );
288 /// book_reviews.insert(
289 ///     "Grimms' Fairy Tales".to_string(),
290 ///     "Masterpiece.".to_string(),
291 /// );
292 /// book_reviews.insert(
293 ///     "Pride and Prejudice".to_string(),
294 ///     "Very enjoyable.".to_string(),
295 /// );
296 /// book_reviews.insert(
297 ///     "The Adventures of Sherlock Holmes".to_string(),
298 ///     "Eye lyked it alot.".to_string(),
299 /// );
300 ///
301 /// // Check for a specific one.
302 /// // When collections store owned values (String), they can still be
303 /// // queried using references (&str).
304 /// if !book_reviews.contains_key("Les Misérables") {
305 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
306 ///              book_reviews.len());
307 /// }
308 ///
309 /// // oops, this review has a lot of spelling mistakes, let's delete it.
310 /// book_reviews.remove("The Adventures of Sherlock Holmes");
311 ///
312 /// // Look up the values associated with some keys.
313 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
314 /// for &book in &to_find {
315 ///     match book_reviews.get(book) {
316 ///         Some(review) => println!("{}: {}", book, review),
317 ///         None => println!("{} is unreviewed.", book)
318 ///     }
319 /// }
320 ///
321 /// // Iterate over everything.
322 /// for (book, review) in &book_reviews {
323 ///     println!("{}: \"{}\"", book, review);
324 /// }
325 /// ```
326 ///
327 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
328 /// for more complex methods of getting, setting, updating and removing keys and
329 /// their values:
330 ///
331 /// ```
332 /// use std::collections::HashMap;
333 ///
334 /// // type inference lets us omit an explicit type signature (which
335 /// // would be `HashMap<&str, u8>` in this example).
336 /// let mut player_stats = HashMap::new();
337 ///
338 /// fn random_stat_buff() -> u8 {
339 ///     // could actually return some random value here - let's just return
340 ///     // some fixed value for now
341 ///     42
342 /// }
343 ///
344 /// // insert a key only if it doesn't already exist
345 /// player_stats.entry("health").or_insert(100);
346 ///
347 /// // insert a key using a function that provides a new value only if it
348 /// // doesn't already exist
349 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
350 ///
351 /// // update a key, guarding against the key possibly not being set
352 /// let stat = player_stats.entry("attack").or_insert(100);
353 /// *stat += random_stat_buff();
354 /// ```
355 ///
356 /// The easiest way to use `HashMap` with a custom type as key is to derive [`Eq`] and [`Hash`].
357 /// We must also derive [`PartialEq`].
358 ///
359 /// [`Eq`]: ../../std/cmp/trait.Eq.html
360 /// [`Hash`]: ../../std/hash/trait.Hash.html
361 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
362 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
363 /// [`Cell`]: ../../std/cell/struct.Cell.html
364 /// [`default`]: #method.default
365 /// [`with_hasher`]: #method.with_hasher
366 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
367 /// [`fnv`]: https://crates.io/crates/fnv
368 ///
369 /// ```
370 /// use std::collections::HashMap;
371 ///
372 /// #[derive(Hash, Eq, PartialEq, Debug)]
373 /// struct Viking {
374 ///     name: String,
375 ///     country: String,
376 /// }
377 ///
378 /// impl Viking {
379 ///     /// Create a new Viking.
380 ///     fn new(name: &str, country: &str) -> Viking {
381 ///         Viking { name: name.to_string(), country: country.to_string() }
382 ///     }
383 /// }
384 ///
385 /// // Use a HashMap to store the vikings' health points.
386 /// let mut vikings = HashMap::new();
387 ///
388 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
389 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
390 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
391 ///
392 /// // Use derived implementation to print the status of the vikings.
393 /// for (viking, health) in &vikings {
394 ///     println!("{:?} has {} hp", viking, health);
395 /// }
396 /// ```
397 ///
398 /// A `HashMap` with fixed list of elements can be initialized from an array:
399 ///
400 /// ```
401 /// use std::collections::HashMap;
402 ///
403 /// fn main() {
404 ///     let timber_resources: HashMap<&str, i32> =
405 ///     [("Norway", 100),
406 ///      ("Denmark", 50),
407 ///      ("Iceland", 10)]
408 ///      .iter().cloned().collect();
409 ///     // use the values stored in map
410 /// }
411 /// ```
412
413 #[derive(Clone)]
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub struct HashMap<K, V, S = RandomState> {
416     // All hashes are keyed on these values, to prevent hash collision attacks.
417     hash_builder: S,
418
419     table: RawTable<K, V>,
420
421     resize_policy: DefaultResizePolicy,
422 }
423
424 /// Search for a pre-hashed key.
425 /// If you don't already know the hash, use search or search_mut instead
426 #[inline]
427 fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
428     where M: Deref<Target = RawTable<K, V>>,
429           F: FnMut(&K) -> bool
430 {
431     // This is the only function where capacity can be zero. To avoid
432     // undefined behavior when Bucket::new gets the raw bucket in this
433     // case, immediately return the appropriate search result.
434     if table.capacity() == 0 {
435         return InternalEntry::TableIsEmpty;
436     }
437
438     search_hashed_nonempty(table, hash, is_match, true)
439 }
440
441 /// Search for a pre-hashed key when the hash map is known to be non-empty.
442 #[inline]
443 fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
444                                       compare_hashes: bool)
445     -> InternalEntry<K, V, M>
446     where M: Deref<Target = RawTable<K, V>>,
447           F: FnMut(&K) -> bool
448 {
449     // Do not check the capacity as an extra branch could slow the lookup.
450
451     let size = table.size();
452     let mut probe = Bucket::new(table, hash);
453     let mut displacement = 0;
454
455     loop {
456         let full = match probe.peek() {
457             Empty(bucket) => {
458                 // Found a hole!
459                 return InternalEntry::Vacant {
460                     hash,
461                     elem: NoElem(bucket, displacement),
462                 };
463             }
464             Full(bucket) => bucket,
465         };
466
467         let probe_displacement = full.displacement();
468
469         if probe_displacement < displacement {
470             // Found a luckier bucket than me.
471             // We can finish the search early if we hit any bucket
472             // with a lower distance to initial bucket than we've probed.
473             return InternalEntry::Vacant {
474                 hash,
475                 elem: NeqElem(full, probe_displacement),
476             };
477         }
478
479         // If the hash doesn't match, it can't be this one..
480         if !compare_hashes || hash == full.hash() {
481             // If the key doesn't match, it can't be this one..
482             if is_match(full.read().0) {
483                 return InternalEntry::Occupied { elem: full };
484             }
485         }
486         displacement += 1;
487         probe = full.next();
488         debug_assert!(displacement <= size);
489     }
490 }
491
492 /// Same as `search_hashed_nonempty` but for mutable access.
493 #[inline]
494 fn search_hashed_nonempty_mut<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
495                                           compare_hashes: bool)
496     -> InternalEntry<K, V, M>
497     where M: DerefMut<Target = RawTable<K, V>>,
498           F: FnMut(&K) -> bool
499 {
500     // Do not check the capacity as an extra branch could slow the lookup.
501
502     let size = table.size();
503     let mut probe = Bucket::new(table, hash);
504     let mut displacement = 0;
505
506     loop {
507         let mut full = match probe.peek() {
508             Empty(bucket) => {
509                 // Found a hole!
510                 return InternalEntry::Vacant {
511                     hash,
512                     elem: NoElem(bucket, displacement),
513                 };
514             }
515             Full(bucket) => bucket,
516         };
517
518         let probe_displacement = full.displacement();
519
520         if probe_displacement < displacement {
521             // Found a luckier bucket than me.
522             // We can finish the search early if we hit any bucket
523             // with a lower distance to initial bucket than we've probed.
524             return InternalEntry::Vacant {
525                 hash,
526                 elem: NeqElem(full, probe_displacement),
527             };
528         }
529
530         // If the hash doesn't match, it can't be this one..
531         if hash == full.hash() || !compare_hashes {
532             // If the key doesn't match, it can't be this one..
533             if is_match(full.read_mut().0) {
534                 return InternalEntry::Occupied { elem: full };
535             }
536         }
537         displacement += 1;
538         probe = full.next();
539         debug_assert!(displacement <= size);
540     }
541 }
542
543 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
544     -> (K, V, &mut RawTable<K, V>)
545 {
546     let (empty, retkey, retval) = starting_bucket.take();
547     let mut gap = match empty.gap_peek() {
548         Ok(b) => b,
549         Err(b) => return (retkey, retval, b.into_table()),
550     };
551
552     while gap.full().displacement() != 0 {
553         gap = match gap.shift() {
554             Ok(b) => b,
555             Err(b) => {
556                 return (retkey, retval, b.into_table());
557             },
558         };
559     }
560
561     // Now we've done all our shifting. Return the value we grabbed earlier.
562     (retkey, retval, gap.into_table())
563 }
564
565 /// Perform robin hood bucket stealing at the given `bucket`. You must
566 /// also pass that bucket's displacement so we don't have to recalculate it.
567 ///
568 /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
569 fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
570                                 mut displacement: usize,
571                                 mut hash: SafeHash,
572                                 mut key: K,
573                                 mut val: V)
574                                 -> FullBucketMut<'a, K, V> {
575     let size = bucket.table().size();
576     let raw_capacity = bucket.table().capacity();
577     // There can be at most `size - dib` buckets to displace, because
578     // in the worst case, there are `size` elements and we already are
579     // `displacement` buckets away from the initial one.
580     let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
581     // Save the *starting point*.
582     let mut bucket = bucket.stash();
583
584     loop {
585         let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
586         hash = old_hash;
587         key = old_key;
588         val = old_val;
589
590         loop {
591             displacement += 1;
592             let probe = bucket.next();
593             debug_assert!(probe.index() != idx_end);
594
595             let full_bucket = match probe.peek() {
596                 Empty(bucket) => {
597                     // Found a hole!
598                     let bucket = bucket.put(hash, key, val);
599                     // Now that it's stolen, just read the value's pointer
600                     // right out of the table! Go back to the *starting point*.
601                     //
602                     // This use of `into_table` is misleading. It turns the
603                     // bucket, which is a FullBucket on top of a
604                     // FullBucketMut, into just one FullBucketMut. The "table"
605                     // refers to the inner FullBucketMut in this context.
606                     return bucket.into_table();
607                 }
608                 Full(bucket) => bucket,
609             };
610
611             let probe_displacement = full_bucket.displacement();
612
613             bucket = full_bucket;
614
615             // Robin hood! Steal the spot.
616             if probe_displacement < displacement {
617                 displacement = probe_displacement;
618                 break;
619             }
620         }
621     }
622 }
623
624 impl<K, V, S> HashMap<K, V, S>
625     where K: Eq + Hash,
626           S: BuildHasher
627 {
628     fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
629         where X: Hash
630     {
631         table::make_hash(&self.hash_builder, x)
632     }
633
634     /// Search for a key, yielding the index if it's found in the hashtable.
635     /// If you already have the hash for the key lying around, or if you need an
636     /// InternalEntry, use search_hashed or search_hashed_nonempty.
637     #[inline]
638     fn search<'a, Q: ?Sized>(&'a self, q: &Q)
639         -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
640         where K: Borrow<Q>,
641               Q: Eq + Hash
642     {
643         if self.is_empty() {
644             return None;
645         }
646
647         let hash = self.make_hash(q);
648         search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()), true)
649             .into_occupied_bucket()
650     }
651
652     #[inline]
653     fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
654         -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
655         where K: Borrow<Q>,
656               Q: Eq + Hash
657     {
658         if self.is_empty() {
659             return None;
660         }
661
662         let hash = self.make_hash(q);
663         search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()), true)
664             .into_occupied_bucket()
665     }
666
667     // The caller should ensure that invariants by Robin Hood Hashing hold
668     // and that there's space in the underlying table.
669     fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
670         let mut buckets = Bucket::new(&mut self.table, hash);
671         let start_index = buckets.index();
672
673         loop {
674             // We don't need to compare hashes for value swap.
675             // Not even DIBs for Robin Hood.
676             buckets = match buckets.peek() {
677                 Empty(empty) => {
678                     empty.put(hash, k, v);
679                     return;
680                 }
681                 Full(b) => b.into_bucket(),
682             };
683             buckets.next();
684             debug_assert!(buckets.index() != start_index);
685         }
686     }
687 }
688
689 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
690     /// Creates an empty `HashMap`.
691     ///
692     /// The hash map is initially created with a capacity of 0, so it will not allocate until it
693     /// is first inserted into.
694     ///
695     /// # Examples
696     ///
697     /// ```
698     /// use std::collections::HashMap;
699     /// let mut map: HashMap<&str, i32> = HashMap::new();
700     /// ```
701     #[inline]
702     #[stable(feature = "rust1", since = "1.0.0")]
703     pub fn new() -> HashMap<K, V, RandomState> {
704         Default::default()
705     }
706
707     /// Creates an empty `HashMap` with the specified capacity.
708     ///
709     /// The hash map will be able to hold at least `capacity` elements without
710     /// reallocating. If `capacity` is 0, the hash map will not allocate.
711     ///
712     /// # Examples
713     ///
714     /// ```
715     /// use std::collections::HashMap;
716     /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
717     /// ```
718     #[inline]
719     #[stable(feature = "rust1", since = "1.0.0")]
720     pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
721         HashMap::with_capacity_and_hasher(capacity, Default::default())
722     }
723 }
724
725 impl<K, V, S> HashMap<K, V, S>
726     where K: Eq + Hash,
727           S: BuildHasher
728 {
729     /// Creates an empty `HashMap` which will use the given hash builder to hash
730     /// keys.
731     ///
732     /// The created map has the default initial capacity.
733     ///
734     /// Warning: `hash_builder` is normally randomly generated, and
735     /// is designed to allow HashMaps to be resistant to attacks that
736     /// cause many collisions and very poor performance. Setting it
737     /// manually using this function can expose a DoS attack vector.
738     ///
739     /// # Examples
740     ///
741     /// ```
742     /// use std::collections::HashMap;
743     /// use std::collections::hash_map::RandomState;
744     ///
745     /// let s = RandomState::new();
746     /// let mut map = HashMap::with_hasher(s);
747     /// map.insert(1, 2);
748     /// ```
749     #[inline]
750     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
751     pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
752         HashMap {
753             hash_builder,
754             resize_policy: DefaultResizePolicy::new(),
755             table: RawTable::new(0),
756         }
757     }
758
759     /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
760     /// to hash the keys.
761     ///
762     /// The hash map will be able to hold at least `capacity` elements without
763     /// reallocating. If `capacity` is 0, the hash map will not allocate.
764     ///
765     /// Warning: `hash_builder` is normally randomly generated, and
766     /// is designed to allow HashMaps to be resistant to attacks that
767     /// cause many collisions and very poor performance. Setting it
768     /// manually using this function can expose a DoS attack vector.
769     ///
770     /// # Examples
771     ///
772     /// ```
773     /// use std::collections::HashMap;
774     /// use std::collections::hash_map::RandomState;
775     ///
776     /// let s = RandomState::new();
777     /// let mut map = HashMap::with_capacity_and_hasher(10, s);
778     /// map.insert(1, 2);
779     /// ```
780     #[inline]
781     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
782     pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
783         let resize_policy = DefaultResizePolicy::new();
784         let raw_cap = resize_policy.raw_capacity(capacity);
785         HashMap {
786             hash_builder,
787             resize_policy,
788             table: RawTable::new(raw_cap),
789         }
790     }
791
792     /// Returns a reference to the map's [`BuildHasher`].
793     ///
794     /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
795     ///
796     /// # Examples
797     ///
798     /// ```
799     /// use std::collections::HashMap;
800     /// use std::collections::hash_map::RandomState;
801     ///
802     /// let hasher = RandomState::new();
803     /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
804     /// let hasher: &RandomState = map.hasher();
805     /// ```
806     #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
807     pub fn hasher(&self) -> &S {
808         &self.hash_builder
809     }
810
811     /// Returns the number of elements the map can hold without reallocating.
812     ///
813     /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
814     /// more, but is guaranteed to be able to hold at least this many.
815     ///
816     /// # Examples
817     ///
818     /// ```
819     /// use std::collections::HashMap;
820     /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
821     /// assert!(map.capacity() >= 100);
822     /// ```
823     #[inline]
824     #[stable(feature = "rust1", since = "1.0.0")]
825     pub fn capacity(&self) -> usize {
826         self.resize_policy.capacity(self.raw_capacity())
827     }
828
829     /// Returns the hash map's raw capacity.
830     #[inline]
831     fn raw_capacity(&self) -> usize {
832         self.table.capacity()
833     }
834
835     /// Reserves capacity for at least `additional` more elements to be inserted
836     /// in the `HashMap`. The collection may reserve more space to avoid
837     /// frequent reallocations.
838     ///
839     /// # Panics
840     ///
841     /// Panics if the new allocation size overflows [`usize`].
842     ///
843     /// [`usize`]: ../../std/primitive.usize.html
844     ///
845     /// # Examples
846     ///
847     /// ```
848     /// use std::collections::HashMap;
849     /// let mut map: HashMap<&str, i32> = HashMap::new();
850     /// map.reserve(10);
851     /// ```
852     #[inline]
853     #[stable(feature = "rust1", since = "1.0.0")]
854     pub fn reserve(&mut self, additional: usize) {
855         match self.reserve_internal(additional, Infallible) {
856             Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
857             Err(CollectionAllocErr::AllocErr) => unreachable!(),
858             Ok(()) => { /* yay */ }
859         }
860     }
861
862     /// Tries to reserve capacity for at least `additional` more elements to be inserted
863     /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
864     /// frequent reallocations.
865     ///
866     /// # Errors
867     ///
868     /// If the capacity overflows, or the allocator reports a failure, then an error
869     /// is returned.
870     ///
871     /// # Examples
872     ///
873     /// ```
874     /// #![feature(try_reserve)]
875     /// use std::collections::HashMap;
876     /// let mut map: HashMap<&str, isize> = HashMap::new();
877     /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
878     /// ```
879     #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
880     pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
881         self.reserve_internal(additional, Fallible)
882     }
883
884     #[inline]
885     fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
886         -> Result<(), CollectionAllocErr> {
887
888         let remaining = self.capacity() - self.len(); // this can't overflow
889         if remaining < additional {
890             let min_cap = self.len()
891                 .checked_add(additional)
892                 .ok_or(CollectionAllocErr::CapacityOverflow)?;
893             let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
894             self.try_resize(raw_cap, fallibility)?;
895         } else if self.table.tag() && remaining <= self.len() {
896             // Probe sequence is too long and table is half full,
897             // resize early to reduce probing length.
898             let new_capacity = self.table.capacity() * 2;
899             self.try_resize(new_capacity, fallibility)?;
900         }
901         Ok(())
902     }
903
904     /// Resizes the internal vectors to a new capacity. It's your
905     /// responsibility to:
906     ///   1) Ensure `new_raw_cap` is enough for all the elements, accounting
907     ///      for the load factor.
908     ///   2) Ensure `new_raw_cap` is a power of two or zero.
909     #[inline(never)]
910     #[cold]
911     fn try_resize(
912         &mut self,
913         new_raw_cap: usize,
914         fallibility: Fallibility,
915     ) -> Result<(), CollectionAllocErr> {
916         assert!(self.table.size() <= new_raw_cap);
917         assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
918
919         let mut old_table = replace(
920             &mut self.table,
921             match fallibility {
922                 Infallible => RawTable::new(new_raw_cap),
923                 Fallible => RawTable::try_new(new_raw_cap)?,
924             }
925         );
926         let old_size = old_table.size();
927
928         if old_table.size() == 0 {
929             return Ok(());
930         }
931
932         let mut bucket = Bucket::head_bucket(&mut old_table);
933
934         // This is how the buckets might be laid out in memory:
935         // ($ marks an initialized bucket)
936         //  ________________
937         // |$$$_$$$$$$_$$$$$|
938         //
939         // But we've skipped the entire initial cluster of buckets
940         // and will continue iteration in this order:
941         //  ________________
942         //     |$$$$$$_$$$$$
943         //                  ^ wrap around once end is reached
944         //  ________________
945         //  $$$_____________|
946         //    ^ exit once table.size == 0
947         loop {
948             bucket = match bucket.peek() {
949                 Full(bucket) => {
950                     let h = bucket.hash();
951                     let (b, k, v) = bucket.take();
952                     self.insert_hashed_ordered(h, k, v);
953                     if b.table().size() == 0 {
954                         break;
955                     }
956                     b.into_bucket()
957                 }
958                 Empty(b) => b.into_bucket(),
959             };
960             bucket.next();
961         }
962
963         assert_eq!(self.table.size(), old_size);
964         Ok(())
965     }
966
967     /// Shrinks the capacity of the map as much as possible. It will drop
968     /// down as much as possible while maintaining the internal rules
969     /// and possibly leaving some space in accordance with the resize policy.
970     ///
971     /// # Examples
972     ///
973     /// ```
974     /// use std::collections::HashMap;
975     ///
976     /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
977     /// map.insert(1, 2);
978     /// map.insert(3, 4);
979     /// assert!(map.capacity() >= 100);
980     /// map.shrink_to_fit();
981     /// assert!(map.capacity() >= 2);
982     /// ```
983     #[stable(feature = "rust1", since = "1.0.0")]
984     pub fn shrink_to_fit(&mut self) {
985         let new_raw_cap = self.resize_policy.raw_capacity(self.len());
986         if self.raw_capacity() != new_raw_cap {
987             let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
988             let old_size = old_table.size();
989
990             // Shrink the table. Naive algorithm for resizing:
991             for (h, k, v) in old_table.into_iter() {
992                 self.insert_hashed_nocheck(h, k, v);
993             }
994
995             debug_assert_eq!(self.table.size(), old_size);
996         }
997     }
998
999     /// Shrinks the capacity of the map with a lower limit. It will drop
1000     /// down no lower than the supplied limit while maintaining the internal rules
1001     /// and possibly leaving some space in accordance with the resize policy.
1002     ///
1003     /// Panics if the current capacity is smaller than the supplied
1004     /// minimum capacity.
1005     ///
1006     /// # Examples
1007     ///
1008     /// ```
1009     /// #![feature(shrink_to)]
1010     /// use std::collections::HashMap;
1011     ///
1012     /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1013     /// map.insert(1, 2);
1014     /// map.insert(3, 4);
1015     /// assert!(map.capacity() >= 100);
1016     /// map.shrink_to(10);
1017     /// assert!(map.capacity() >= 10);
1018     /// map.shrink_to(0);
1019     /// assert!(map.capacity() >= 2);
1020     /// ```
1021     #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1022     pub fn shrink_to(&mut self, min_capacity: usize) {
1023         assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1024
1025         let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1026         if self.raw_capacity() != new_raw_cap {
1027             let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1028             let old_size = old_table.size();
1029
1030             // Shrink the table. Naive algorithm for resizing:
1031             for (h, k, v) in old_table.into_iter() {
1032                 self.insert_hashed_nocheck(h, k, v);
1033             }
1034
1035             debug_assert_eq!(self.table.size(), old_size);
1036         }
1037     }
1038
1039     /// Insert a pre-hashed key-value pair, without first checking
1040     /// that there's enough room in the buckets. Returns a reference to the
1041     /// newly insert value.
1042     ///
1043     /// If the key already exists, the hashtable will be returned untouched
1044     /// and a reference to the existing element will be returned.
1045     fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1046         let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1047         match entry {
1048             Some(Occupied(mut elem)) => Some(elem.insert(v)),
1049             Some(Vacant(elem)) => {
1050                 elem.insert(v);
1051                 None
1052             }
1053             None => unreachable!(),
1054         }
1055     }
1056
1057     /// An iterator visiting all keys in arbitrary order.
1058     /// The iterator element type is `&'a K`.
1059     ///
1060     /// # Examples
1061     ///
1062     /// ```
1063     /// use std::collections::HashMap;
1064     ///
1065     /// let mut map = HashMap::new();
1066     /// map.insert("a", 1);
1067     /// map.insert("b", 2);
1068     /// map.insert("c", 3);
1069     ///
1070     /// for key in map.keys() {
1071     ///     println!("{}", key);
1072     /// }
1073     /// ```
1074     #[stable(feature = "rust1", since = "1.0.0")]
1075     pub fn keys(&self) -> Keys<K, V> {
1076         Keys { inner: self.iter() }
1077     }
1078
1079     /// An iterator visiting all values in arbitrary order.
1080     /// The iterator element type is `&'a V`.
1081     ///
1082     /// # Examples
1083     ///
1084     /// ```
1085     /// use std::collections::HashMap;
1086     ///
1087     /// let mut map = HashMap::new();
1088     /// map.insert("a", 1);
1089     /// map.insert("b", 2);
1090     /// map.insert("c", 3);
1091     ///
1092     /// for val in map.values() {
1093     ///     println!("{}", val);
1094     /// }
1095     /// ```
1096     #[stable(feature = "rust1", since = "1.0.0")]
1097     pub fn values(&self) -> Values<K, V> {
1098         Values { inner: self.iter() }
1099     }
1100
1101     /// An iterator visiting all values mutably in arbitrary order.
1102     /// The iterator element type is `&'a mut V`.
1103     ///
1104     /// # Examples
1105     ///
1106     /// ```
1107     /// use std::collections::HashMap;
1108     ///
1109     /// let mut map = HashMap::new();
1110     ///
1111     /// map.insert("a", 1);
1112     /// map.insert("b", 2);
1113     /// map.insert("c", 3);
1114     ///
1115     /// for val in map.values_mut() {
1116     ///     *val = *val + 10;
1117     /// }
1118     ///
1119     /// for val in map.values() {
1120     ///     println!("{}", val);
1121     /// }
1122     /// ```
1123     #[stable(feature = "map_values_mut", since = "1.10.0")]
1124     pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1125         ValuesMut { inner: self.iter_mut() }
1126     }
1127
1128     /// An iterator visiting all key-value pairs in arbitrary order.
1129     /// The iterator element type is `(&'a K, &'a V)`.
1130     ///
1131     /// # Examples
1132     ///
1133     /// ```
1134     /// use std::collections::HashMap;
1135     ///
1136     /// let mut map = HashMap::new();
1137     /// map.insert("a", 1);
1138     /// map.insert("b", 2);
1139     /// map.insert("c", 3);
1140     ///
1141     /// for (key, val) in map.iter() {
1142     ///     println!("key: {} val: {}", key, val);
1143     /// }
1144     /// ```
1145     #[stable(feature = "rust1", since = "1.0.0")]
1146     pub fn iter(&self) -> Iter<K, V> {
1147         Iter { inner: self.table.iter() }
1148     }
1149
1150     /// An iterator visiting all key-value pairs in arbitrary order,
1151     /// with mutable references to the values.
1152     /// The iterator element type is `(&'a K, &'a mut V)`.
1153     ///
1154     /// # Examples
1155     ///
1156     /// ```
1157     /// use std::collections::HashMap;
1158     ///
1159     /// let mut map = HashMap::new();
1160     /// map.insert("a", 1);
1161     /// map.insert("b", 2);
1162     /// map.insert("c", 3);
1163     ///
1164     /// // Update all values
1165     /// for (_, val) in map.iter_mut() {
1166     ///     *val *= 2;
1167     /// }
1168     ///
1169     /// for (key, val) in &map {
1170     ///     println!("key: {} val: {}", key, val);
1171     /// }
1172     /// ```
1173     #[stable(feature = "rust1", since = "1.0.0")]
1174     pub fn iter_mut(&mut self) -> IterMut<K, V> {
1175         IterMut { inner: self.table.iter_mut() }
1176     }
1177
1178     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1179     ///
1180     /// # Examples
1181     ///
1182     /// ```
1183     /// use std::collections::HashMap;
1184     ///
1185     /// let mut letters = HashMap::new();
1186     ///
1187     /// for ch in "a short treatise on fungi".chars() {
1188     ///     let counter = letters.entry(ch).or_insert(0);
1189     ///     *counter += 1;
1190     /// }
1191     ///
1192     /// assert_eq!(letters[&'s'], 2);
1193     /// assert_eq!(letters[&'t'], 3);
1194     /// assert_eq!(letters[&'u'], 1);
1195     /// assert_eq!(letters.get(&'y'), None);
1196     /// ```
1197     #[stable(feature = "rust1", since = "1.0.0")]
1198     pub fn entry(&mut self, key: K) -> Entry<K, V> {
1199         // Gotta resize now.
1200         self.reserve(1);
1201         let hash = self.make_hash(&key);
1202         search_hashed(&mut self.table, hash, |q| q.eq(&key))
1203             .into_entry(key).expect("unreachable")
1204     }
1205
1206     /// Returns the number of elements in the map.
1207     ///
1208     /// # Examples
1209     ///
1210     /// ```
1211     /// use std::collections::HashMap;
1212     ///
1213     /// let mut a = HashMap::new();
1214     /// assert_eq!(a.len(), 0);
1215     /// a.insert(1, "a");
1216     /// assert_eq!(a.len(), 1);
1217     /// ```
1218     #[stable(feature = "rust1", since = "1.0.0")]
1219     pub fn len(&self) -> usize {
1220         self.table.size()
1221     }
1222
1223     /// Returns true if the map contains no elements.
1224     ///
1225     /// # Examples
1226     ///
1227     /// ```
1228     /// use std::collections::HashMap;
1229     ///
1230     /// let mut a = HashMap::new();
1231     /// assert!(a.is_empty());
1232     /// a.insert(1, "a");
1233     /// assert!(!a.is_empty());
1234     /// ```
1235     #[inline]
1236     #[stable(feature = "rust1", since = "1.0.0")]
1237     pub fn is_empty(&self) -> bool {
1238         self.len() == 0
1239     }
1240
1241     /// Clears the map, returning all key-value pairs as an iterator. Keeps the
1242     /// allocated memory for reuse.
1243     ///
1244     /// # Examples
1245     ///
1246     /// ```
1247     /// use std::collections::HashMap;
1248     ///
1249     /// let mut a = HashMap::new();
1250     /// a.insert(1, "a");
1251     /// a.insert(2, "b");
1252     ///
1253     /// for (k, v) in a.drain().take(1) {
1254     ///     assert!(k == 1 || k == 2);
1255     ///     assert!(v == "a" || v == "b");
1256     /// }
1257     ///
1258     /// assert!(a.is_empty());
1259     /// ```
1260     #[inline]
1261     #[stable(feature = "drain", since = "1.6.0")]
1262     pub fn drain(&mut self) -> Drain<K, V> {
1263         Drain { inner: self.table.drain() }
1264     }
1265
1266     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1267     /// for reuse.
1268     ///
1269     /// # Examples
1270     ///
1271     /// ```
1272     /// use std::collections::HashMap;
1273     ///
1274     /// let mut a = HashMap::new();
1275     /// a.insert(1, "a");
1276     /// a.clear();
1277     /// assert!(a.is_empty());
1278     /// ```
1279     #[stable(feature = "rust1", since = "1.0.0")]
1280     #[inline]
1281     pub fn clear(&mut self) {
1282         self.drain();
1283     }
1284
1285     /// Returns a reference to the value corresponding to the key.
1286     ///
1287     /// The key may be any borrowed form of the map's key type, but
1288     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1289     /// the key type.
1290     ///
1291     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1292     /// [`Hash`]: ../../std/hash/trait.Hash.html
1293     ///
1294     /// # Examples
1295     ///
1296     /// ```
1297     /// use std::collections::HashMap;
1298     ///
1299     /// let mut map = HashMap::new();
1300     /// map.insert(1, "a");
1301     /// assert_eq!(map.get(&1), Some(&"a"));
1302     /// assert_eq!(map.get(&2), None);
1303     /// ```
1304     #[stable(feature = "rust1", since = "1.0.0")]
1305     #[inline]
1306     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1307         where K: Borrow<Q>,
1308               Q: Hash + Eq
1309     {
1310         self.search(k).map(|bucket| bucket.into_refs().1)
1311     }
1312
1313     /// Returns the key-value pair corresponding to the supplied key.
1314     ///
1315     /// The supplied key may be any borrowed form of the map's key type, but
1316     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1317     /// the key type.
1318     ///
1319     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1320     /// [`Hash`]: ../../std/hash/trait.Hash.html
1321     ///
1322     /// # Examples
1323     ///
1324     /// ```
1325     /// #![feature(map_get_key_value)]
1326     /// use std::collections::HashMap;
1327     ///
1328     /// let mut map = HashMap::new();
1329     /// map.insert(1, "a");
1330     /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1331     /// assert_eq!(map.get_key_value(&2), None);
1332     /// ```
1333     #[unstable(feature = "map_get_key_value", issue = "49347")]
1334     pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1335         where K: Borrow<Q>,
1336               Q: Hash + Eq
1337     {
1338         self.search(k).map(|bucket| bucket.into_refs())
1339     }
1340
1341     /// Returns true if the map contains a value for the specified key.
1342     ///
1343     /// The key may be any borrowed form of the map's key type, but
1344     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1345     /// the key type.
1346     ///
1347     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1348     /// [`Hash`]: ../../std/hash/trait.Hash.html
1349     ///
1350     /// # Examples
1351     ///
1352     /// ```
1353     /// use std::collections::HashMap;
1354     ///
1355     /// let mut map = HashMap::new();
1356     /// map.insert(1, "a");
1357     /// assert_eq!(map.contains_key(&1), true);
1358     /// assert_eq!(map.contains_key(&2), false);
1359     /// ```
1360     #[stable(feature = "rust1", since = "1.0.0")]
1361     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1362         where K: Borrow<Q>,
1363               Q: Hash + Eq
1364     {
1365         self.search(k).is_some()
1366     }
1367
1368     /// Returns a mutable reference to the value corresponding to the key.
1369     ///
1370     /// The key may be any borrowed form of the map's key type, but
1371     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1372     /// the key type.
1373     ///
1374     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1375     /// [`Hash`]: ../../std/hash/trait.Hash.html
1376     ///
1377     /// # Examples
1378     ///
1379     /// ```
1380     /// use std::collections::HashMap;
1381     ///
1382     /// let mut map = HashMap::new();
1383     /// map.insert(1, "a");
1384     /// if let Some(x) = map.get_mut(&1) {
1385     ///     *x = "b";
1386     /// }
1387     /// assert_eq!(map[&1], "b");
1388     /// ```
1389     #[stable(feature = "rust1", since = "1.0.0")]
1390     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1391         where K: Borrow<Q>,
1392               Q: Hash + Eq
1393     {
1394         self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1395     }
1396
1397     /// Inserts a key-value pair into the map.
1398     ///
1399     /// If the map did not have this key present, [`None`] is returned.
1400     ///
1401     /// If the map did have this key present, the value is updated, and the old
1402     /// value is returned. The key is not updated, though; this matters for
1403     /// types that can be `==` without being identical. See the [module-level
1404     /// documentation] for more.
1405     ///
1406     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1407     /// [module-level documentation]: index.html#insert-and-complex-keys
1408     ///
1409     /// # Examples
1410     ///
1411     /// ```
1412     /// use std::collections::HashMap;
1413     ///
1414     /// let mut map = HashMap::new();
1415     /// assert_eq!(map.insert(37, "a"), None);
1416     /// assert_eq!(map.is_empty(), false);
1417     ///
1418     /// map.insert(37, "b");
1419     /// assert_eq!(map.insert(37, "c"), Some("b"));
1420     /// assert_eq!(map[&37], "c");
1421     /// ```
1422     #[stable(feature = "rust1", since = "1.0.0")]
1423     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1424         let hash = self.make_hash(&k);
1425         self.reserve(1);
1426         self.insert_hashed_nocheck(hash, k, v)
1427     }
1428
1429     /// Removes a key from the map, returning the value at the key if the key
1430     /// was previously in the map.
1431     ///
1432     /// The key may be any borrowed form of the map's key type, but
1433     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1434     /// the key type.
1435     ///
1436     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1437     /// [`Hash`]: ../../std/hash/trait.Hash.html
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// use std::collections::HashMap;
1443     ///
1444     /// let mut map = HashMap::new();
1445     /// map.insert(1, "a");
1446     /// assert_eq!(map.remove(&1), Some("a"));
1447     /// assert_eq!(map.remove(&1), None);
1448     /// ```
1449     #[stable(feature = "rust1", since = "1.0.0")]
1450     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1451         where K: Borrow<Q>,
1452               Q: Hash + Eq
1453     {
1454         self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1455     }
1456
1457     /// Removes a key from the map, returning the stored key and value if the
1458     /// key was previously in the map.
1459     ///
1460     /// The key may be any borrowed form of the map's key type, but
1461     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1462     /// the key type.
1463     ///
1464     /// [`Eq`]: ../../std/cmp/trait.Eq.html
1465     /// [`Hash`]: ../../std/hash/trait.Hash.html
1466     ///
1467     /// # Examples
1468     ///
1469     /// ```
1470     /// use std::collections::HashMap;
1471     ///
1472     /// # fn main() {
1473     /// let mut map = HashMap::new();
1474     /// map.insert(1, "a");
1475     /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1476     /// assert_eq!(map.remove(&1), None);
1477     /// # }
1478     /// ```
1479     #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1480     pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1481         where K: Borrow<Q>,
1482               Q: Hash + Eq
1483     {
1484         self.search_mut(k)
1485             .map(|bucket| {
1486                 let (k, v, _) = pop_internal(bucket);
1487                 (k, v)
1488             })
1489     }
1490
1491     /// Retains only the elements specified by the predicate.
1492     ///
1493     /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1494     ///
1495     /// # Examples
1496     ///
1497     /// ```
1498     /// use std::collections::HashMap;
1499     ///
1500     /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1501     /// map.retain(|&k, _| k % 2 == 0);
1502     /// assert_eq!(map.len(), 4);
1503     /// ```
1504     #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1505     pub fn retain<F>(&mut self, mut f: F)
1506         where F: FnMut(&K, &mut V) -> bool
1507     {
1508         if self.table.size() == 0 {
1509             return;
1510         }
1511         let mut elems_left = self.table.size();
1512         let mut bucket = Bucket::head_bucket(&mut self.table);
1513         bucket.prev();
1514         let start_index = bucket.index();
1515         while elems_left != 0 {
1516             bucket = match bucket.peek() {
1517                 Full(mut full) => {
1518                     elems_left -= 1;
1519                     let should_remove = {
1520                         let (k, v) = full.read_mut();
1521                         !f(k, v)
1522                     };
1523                     if should_remove {
1524                         let prev_raw = full.raw();
1525                         let (_, _, t) = pop_internal(full);
1526                         Bucket::new_from(prev_raw, t)
1527                     } else {
1528                         full.into_bucket()
1529                     }
1530                 },
1531                 Empty(b) => {
1532                     b.into_bucket()
1533                 }
1534             };
1535             bucket.prev();  // reverse iteration
1536             debug_assert!(elems_left == 0 || bucket.index() != start_index);
1537         }
1538     }
1539 }
1540
1541 impl<K, V, S> HashMap<K, V, S>
1542     where K: Eq + Hash,
1543           S: BuildHasher
1544 {
1545     /// Creates a raw entry builder for the HashMap.
1546     ///
1547     /// Raw entries provide the lowest level of control for searching and
1548     /// manipulating a map. They must be manually initialized with a hash and
1549     /// then manually searched. After this, insertions into a vacant entry
1550     /// still require an owned key to be provided.
1551     ///
1552     /// Raw entries are useful for such exotic situations as:
1553     ///
1554     /// * Hash memoization
1555     /// * Deferring the creation of an owned key until it is known to be required
1556     /// * Using a search key that doesn't work with the Borrow trait
1557     /// * Using custom comparison logic without newtype wrappers
1558     ///
1559     /// Because raw entries provide much more low-level control, it's much easier
1560     /// to put the HashMap into an inconsistent state which, while memory-safe,
1561     /// will cause the map to produce seemingly random results. Higher-level and
1562     /// more foolproof APIs like `entry` should be preferred when possible.
1563     ///
1564     /// In particular, the hash used to initialized the raw entry must still be
1565     /// consistent with the hash of the key that is ultimately stored in the entry.
1566     /// This is because implementations of HashMap may need to recompute hashes
1567     /// when resizing, at which point only the keys are available.
1568     ///
1569     /// Raw entries give mutable access to the keys. This must not be used
1570     /// to modify how the key would compare or hash, as the map will not re-evaluate
1571     /// where the key should go, meaning the keys may become "lost" if their
1572     /// location does not reflect their state. For instance, if you change a key
1573     /// so that the map now contains keys which compare equal, search may start
1574     /// acting erratically, with two keys randomly masking each other. Implementations
1575     /// are free to assume this doesn't happen (within the limits of memory-safety).
1576     #[inline(always)]
1577     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1578     pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<K, V, S> {
1579         self.reserve(1);
1580         RawEntryBuilderMut { map: self }
1581     }
1582
1583     /// Creates a raw immutable entry builder for the HashMap.
1584     ///
1585     /// Raw entries provide the lowest level of control for searching and
1586     /// manipulating a map. They must be manually initialized with a hash and
1587     /// then manually searched.
1588     ///
1589     /// This is useful for
1590     /// * Hash memoization
1591     /// * Using a search key that doesn't work with the Borrow trait
1592     /// * Using custom comparison logic without newtype wrappers
1593     ///
1594     /// Unless you are in such a situation, higher-level and more foolproof APIs like
1595     /// `get` should be preferred.
1596     ///
1597     /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1598     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1599     pub fn raw_entry(&self) -> RawEntryBuilder<K, V, S> {
1600         RawEntryBuilder { map: self }
1601     }
1602 }
1603
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<K, V, S> PartialEq for HashMap<K, V, S>
1606     where K: Eq + Hash,
1607           V: PartialEq,
1608           S: BuildHasher
1609 {
1610     fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1611         if self.len() != other.len() {
1612             return false;
1613         }
1614
1615         self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1616     }
1617 }
1618
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<K, V, S> Eq for HashMap<K, V, S>
1621     where K: Eq + Hash,
1622           V: Eq,
1623           S: BuildHasher
1624 {
1625 }
1626
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<K, V, S> Debug for HashMap<K, V, S>
1629     where K: Eq + Hash + Debug,
1630           V: Debug,
1631           S: BuildHasher
1632 {
1633     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1634         f.debug_map().entries(self.iter()).finish()
1635     }
1636 }
1637
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<K, V, S> Default for HashMap<K, V, S>
1640     where K: Eq + Hash,
1641           S: BuildHasher + Default
1642 {
1643     /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1644     fn default() -> HashMap<K, V, S> {
1645         HashMap::with_hasher(Default::default())
1646     }
1647 }
1648
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
1651     where K: Eq + Hash + Borrow<Q>,
1652           Q: Eq + Hash,
1653           S: BuildHasher
1654 {
1655     type Output = V;
1656
1657     /// Returns a reference to the value corresponding to the supplied key.
1658     ///
1659     /// # Panics
1660     ///
1661     /// Panics if the key is not present in the `HashMap`.
1662     #[inline]
1663     fn index(&self, key: &Q) -> &V {
1664         self.get(key).expect("no entry found for key")
1665     }
1666 }
1667
1668 /// An iterator over the entries of a `HashMap`.
1669 ///
1670 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1671 /// documentation for more.
1672 ///
1673 /// [`iter`]: struct.HashMap.html#method.iter
1674 /// [`HashMap`]: struct.HashMap.html
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 pub struct Iter<'a, K: 'a, V: 'a> {
1677     inner: table::Iter<'a, K, V>,
1678 }
1679
1680 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<'a, K, V> Clone for Iter<'a, K, V> {
1683     fn clone(&self) -> Iter<'a, K, V> {
1684         Iter { inner: self.inner.clone() }
1685     }
1686 }
1687
1688 #[stable(feature = "std_debug", since = "1.16.0")]
1689 impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
1690     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1691         f.debug_list()
1692             .entries(self.clone())
1693             .finish()
1694     }
1695 }
1696
1697 /// A mutable iterator over the entries of a `HashMap`.
1698 ///
1699 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1700 /// documentation for more.
1701 ///
1702 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1703 /// [`HashMap`]: struct.HashMap.html
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub struct IterMut<'a, K: 'a, V: 'a> {
1706     inner: table::IterMut<'a, K, V>,
1707 }
1708
1709 /// An owning iterator over the entries of a `HashMap`.
1710 ///
1711 /// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1712 /// (provided by the `IntoIterator` trait). See its documentation for more.
1713 ///
1714 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1715 /// [`HashMap`]: struct.HashMap.html
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub struct IntoIter<K, V> {
1718     pub(super) inner: table::IntoIter<K, V>,
1719 }
1720
1721 /// An iterator over the keys of a `HashMap`.
1722 ///
1723 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1724 /// documentation for more.
1725 ///
1726 /// [`keys`]: struct.HashMap.html#method.keys
1727 /// [`HashMap`]: struct.HashMap.html
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub struct Keys<'a, K: 'a, V: 'a> {
1730     inner: Iter<'a, K, V>,
1731 }
1732
1733 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl<'a, K, V> Clone for Keys<'a, K, V> {
1736     fn clone(&self) -> Keys<'a, K, V> {
1737         Keys { inner: self.inner.clone() }
1738     }
1739 }
1740
1741 #[stable(feature = "std_debug", since = "1.16.0")]
1742 impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
1743     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1744         f.debug_list()
1745             .entries(self.clone())
1746             .finish()
1747     }
1748 }
1749
1750 /// An iterator over the values of a `HashMap`.
1751 ///
1752 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1753 /// documentation for more.
1754 ///
1755 /// [`values`]: struct.HashMap.html#method.values
1756 /// [`HashMap`]: struct.HashMap.html
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 pub struct Values<'a, K: 'a, V: 'a> {
1759     inner: Iter<'a, K, V>,
1760 }
1761
1762 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<'a, K, V> Clone for Values<'a, K, V> {
1765     fn clone(&self) -> Values<'a, K, V> {
1766         Values { inner: self.inner.clone() }
1767     }
1768 }
1769
1770 #[stable(feature = "std_debug", since = "1.16.0")]
1771 impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
1772     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1773         f.debug_list()
1774             .entries(self.clone())
1775             .finish()
1776     }
1777 }
1778
1779 /// A draining iterator over the entries of a `HashMap`.
1780 ///
1781 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1782 /// documentation for more.
1783 ///
1784 /// [`drain`]: struct.HashMap.html#method.drain
1785 /// [`HashMap`]: struct.HashMap.html
1786 #[stable(feature = "drain", since = "1.6.0")]
1787 pub struct Drain<'a, K: 'a, V: 'a> {
1788     pub(super) inner: table::Drain<'a, K, V>,
1789 }
1790
1791 /// A mutable iterator over the values of a `HashMap`.
1792 ///
1793 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1794 /// documentation for more.
1795 ///
1796 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1797 /// [`HashMap`]: struct.HashMap.html
1798 #[stable(feature = "map_values_mut", since = "1.10.0")]
1799 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1800     inner: IterMut<'a, K, V>,
1801 }
1802
1803 enum InternalEntry<K, V, M> {
1804     Occupied { elem: FullBucket<K, V, M> },
1805     Vacant {
1806         hash: SafeHash,
1807         elem: VacantEntryState<K, V, M>,
1808     },
1809     TableIsEmpty,
1810 }
1811
1812 impl<K, V, M> InternalEntry<K, V, M> {
1813     #[inline]
1814     fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1815         match self {
1816             InternalEntry::Occupied { elem } => Some(elem),
1817             _ => None,
1818         }
1819     }
1820 }
1821
1822 impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1823     #[inline]
1824     fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1825         match self {
1826             InternalEntry::Occupied { elem } => {
1827                 Some(Occupied(OccupiedEntry {
1828                     key: Some(key),
1829                     elem,
1830                 }))
1831             }
1832             InternalEntry::Vacant { hash, elem } => {
1833                 Some(Vacant(VacantEntry {
1834                     hash,
1835                     key,
1836                     elem,
1837                 }))
1838             }
1839             InternalEntry::TableIsEmpty => None,
1840         }
1841     }
1842 }
1843
1844 /// A builder for computing where in a HashMap a key-value pair would be stored.
1845 ///
1846 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1847 ///
1848 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1849
1850 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1851 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1852     map: &'a mut HashMap<K, V, S>,
1853 }
1854
1855 /// A view into a single entry in a map, which may either be vacant or occupied.
1856 ///
1857 /// This is a lower-level version of [`Entry`].
1858 ///
1859 /// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1860 ///
1861 /// [`HashMap`]: struct.HashMap.html
1862 /// [`Entry`]: enum.Entry.html
1863 /// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1864 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1865 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1866     /// An occupied entry.
1867     Occupied(RawOccupiedEntryMut<'a, K, V>),
1868     /// A vacant entry.
1869     Vacant(RawVacantEntryMut<'a, K, V, S>),
1870 }
1871
1872 /// A view into an occupied entry in a `HashMap`.
1873 /// It is part of the [`RawEntryMut`] enum.
1874 ///
1875 /// [`RawEntryMut`]: enum.RawEntryMut.html
1876 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1877 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1878     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1879 }
1880
1881 /// A view into a vacant entry in a `HashMap`.
1882 /// It is part of the [`RawEntryMut`] enum.
1883 ///
1884 /// [`RawEntryMut`]: enum.RawEntryMut.html
1885 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1886 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1887     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1888     hash_builder: &'a S,
1889 }
1890
1891 /// A builder for computing where in a HashMap a key-value pair would be stored.
1892 ///
1893 /// See the [`HashMap::raw_entry`] docs for usage examples.
1894 ///
1895 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1896 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1897 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1898     map: &'a HashMap<K, V, S>,
1899 }
1900
1901 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1902     where S: BuildHasher,
1903           K: Eq + Hash,
1904 {
1905     /// Create a `RawEntryMut` from the given key.
1906     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1907     pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1908         where K: Borrow<Q>,
1909               Q: Hash + Eq
1910     {
1911         let mut hasher = self.map.hash_builder.build_hasher();
1912         k.hash(&mut hasher);
1913         self.from_key_hashed_nocheck(hasher.finish(), k)
1914     }
1915
1916     /// Create a `RawEntryMut` from the given key and its hash.
1917     #[inline]
1918     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1919     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1920         where K: Borrow<Q>,
1921               Q: Eq
1922     {
1923         self.from_hash(hash, |q| q.borrow().eq(k))
1924     }
1925
1926     #[inline]
1927     fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool)  -> RawEntryMut<'a, K, V, S>
1928         where for<'b> F: FnMut(&'b K) -> bool,
1929     {
1930         match search_hashed_nonempty_mut(&mut self.map.table,
1931                                          SafeHash::new(hash),
1932                                          is_match,
1933                                          compare_hashes) {
1934             InternalEntry::Occupied { elem } => {
1935                 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1936             }
1937             InternalEntry::Vacant { elem, .. } => {
1938                 RawEntryMut::Vacant(RawVacantEntryMut {
1939                     elem,
1940                     hash_builder: &self.map.hash_builder,
1941                 })
1942             }
1943             InternalEntry::TableIsEmpty => {
1944                 unreachable!()
1945             }
1946         }
1947     }
1948     /// Create a `RawEntryMut` from the given hash.
1949     #[inline]
1950     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1951     pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1952         where for<'b> F: FnMut(&'b K) -> bool,
1953     {
1954         self.search(hash, is_match, true)
1955     }
1956
1957     /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1958     /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1959     /// hash.
1960     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1961     pub fn search_bucket<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1962         where for<'b> F: FnMut(&'b K) -> bool,
1963     {
1964         self.search(hash, is_match, false)
1965     }
1966 }
1967
1968 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1969     where S: BuildHasher,
1970 {
1971     /// Access an entry by key.
1972     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1973     pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1974         where K: Borrow<Q>,
1975               Q: Hash + Eq
1976     {
1977         let mut hasher = self.map.hash_builder.build_hasher();
1978         k.hash(&mut hasher);
1979         self.from_key_hashed_nocheck(hasher.finish(), k)
1980     }
1981
1982     /// Access an entry by a key and its hash.
1983     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1984     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1985         where K: Borrow<Q>,
1986               Q: Hash + Eq
1987
1988     {
1989         self.from_hash(hash, |q| q.borrow().eq(k))
1990     }
1991
1992     fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1993         where F: FnMut(&K) -> bool
1994     {
1995         match search_hashed_nonempty(&self.map.table,
1996                                      SafeHash::new(hash),
1997                                      is_match,
1998                                      compare_hashes) {
1999             InternalEntry::Occupied { elem } => Some(elem.into_refs()),
2000             InternalEntry::Vacant { .. } => None,
2001             InternalEntry::TableIsEmpty => unreachable!(),
2002         }
2003     }
2004
2005     /// Access an entry by hash.
2006     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2007     pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2008         where F: FnMut(&K) -> bool
2009     {
2010         self.search(hash, is_match, true)
2011     }
2012
2013     /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2014     /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2015     /// hash.
2016     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2017     pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2018         where F: FnMut(&K) -> bool
2019     {
2020         self.search(hash, is_match, false)
2021     }
2022 }
2023
2024 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2025     /// Ensures a value is in the entry by inserting the default if empty, and returns
2026     /// mutable references to the key and value in the entry.
2027     ///
2028     /// # Examples
2029     ///
2030     /// ```
2031     /// #![feature(hash_raw_entry)]
2032     /// use std::collections::HashMap;
2033     ///
2034     /// let mut map: HashMap<&str, u32> = HashMap::new();
2035     ///
2036     /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2037     /// assert_eq!(map["poneyland"], 3);
2038     ///
2039     /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2040     /// assert_eq!(map["poneyland"], 6);
2041     /// ```
2042     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2043     pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2044         where K: Hash,
2045               S: BuildHasher,
2046     {
2047         match self {
2048             RawEntryMut::Occupied(entry) => entry.into_key_value(),
2049             RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2050         }
2051     }
2052
2053     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2054     /// and returns mutable references to the key and value in the entry.
2055     ///
2056     /// # Examples
2057     ///
2058     /// ```
2059     /// #![feature(hash_raw_entry)]
2060     /// use std::collections::HashMap;
2061     ///
2062     /// let mut map: HashMap<&str, String> = HashMap::new();
2063     ///
2064     /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2065     ///     ("poneyland", "hoho".to_string())
2066     /// });
2067     ///
2068     /// assert_eq!(map["poneyland"], "hoho".to_string());
2069     /// ```
2070     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2071     pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2072         where F: FnOnce() -> (K, V),
2073               K: Hash,
2074               S: BuildHasher,
2075     {
2076         match self {
2077             RawEntryMut::Occupied(entry) => entry.into_key_value(),
2078             RawEntryMut::Vacant(entry) => {
2079                 let (k, v) = default();
2080                 entry.insert(k, v)
2081             }
2082         }
2083     }
2084
2085     /// Provides in-place mutable access to an occupied entry before any
2086     /// potential inserts into the map.
2087     ///
2088     /// # Examples
2089     ///
2090     /// ```
2091     /// #![feature(hash_raw_entry)]
2092     /// use std::collections::HashMap;
2093     ///
2094     /// let mut map: HashMap<&str, u32> = HashMap::new();
2095     ///
2096     /// map.raw_entry_mut()
2097     ///    .from_key("poneyland")
2098     ///    .and_modify(|_k, v| { *v += 1 })
2099     ///    .or_insert("poneyland", 42);
2100     /// assert_eq!(map["poneyland"], 42);
2101     ///
2102     /// map.raw_entry_mut()
2103     ///    .from_key("poneyland")
2104     ///    .and_modify(|_k, v| { *v += 1 })
2105     ///    .or_insert("poneyland", 0);
2106     /// assert_eq!(map["poneyland"], 43);
2107     /// ```
2108     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2109     pub fn and_modify<F>(self, f: F) -> Self
2110         where F: FnOnce(&mut K, &mut V)
2111     {
2112         match self {
2113             RawEntryMut::Occupied(mut entry) => {
2114                 {
2115                     let (k, v) = entry.get_key_value_mut();
2116                     f(k, v);
2117                 }
2118                 RawEntryMut::Occupied(entry)
2119             },
2120             RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2121         }
2122     }
2123 }
2124
2125 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2126     /// Gets a reference to the key in the entry.
2127     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2128     pub fn key(&self) -> &K {
2129         self.elem.read().0
2130     }
2131
2132     /// Gets a mutable reference to the key in the entry.
2133     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2134     pub fn key_mut(&mut self) -> &mut K {
2135         self.elem.read_mut().0
2136     }
2137
2138     /// Converts the entry into a mutable reference to the key in the entry
2139     /// with a lifetime bound to the map itself.
2140     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2141     pub fn into_key(self) -> &'a mut K {
2142         self.elem.into_mut_refs().0
2143     }
2144
2145     /// Gets a reference to the value in the entry.
2146     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2147     pub fn get(&self) -> &V {
2148         self.elem.read().1
2149     }
2150
2151     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2152     /// with a lifetime bound to the map itself.
2153     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2154     pub fn into_mut(self) -> &'a mut V {
2155         self.elem.into_mut_refs().1
2156     }
2157
2158     /// Gets a mutable reference to the value in the entry.
2159     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2160     pub fn get_mut(&mut self) -> &mut V {
2161         self.elem.read_mut().1
2162     }
2163
2164     /// Gets a reference to the key and value in the entry.
2165     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2166     pub fn get_key_value(&mut self) -> (&K, &V) {
2167         self.elem.read()
2168     }
2169
2170     /// Gets a mutable reference to the key and value in the entry.
2171     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2172     pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2173         self.elem.read_mut()
2174     }
2175
2176     /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2177     /// with a lifetime bound to the map itself.
2178     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2179     pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2180         self.elem.into_mut_refs()
2181     }
2182
2183     /// Sets the value of the entry, and returns the entry's old value.
2184     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2185     pub fn insert(&mut self, value: V) -> V {
2186         mem::replace(self.get_mut(), value)
2187     }
2188
2189     /// Sets the value of the entry, and returns the entry's old value.
2190     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2191     pub fn insert_key(&mut self, key: K) -> K {
2192         mem::replace(self.key_mut(), key)
2193     }
2194
2195     /// Takes the value out of the entry, and returns it.
2196     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2197     pub fn remove(self) -> V {
2198         pop_internal(self.elem).1
2199     }
2200
2201     /// Take the ownership of the key and value from the map.
2202     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2203     pub fn remove_entry(self) -> (K, V) {
2204         let (k, v, _) = pop_internal(self.elem);
2205         (k, v)
2206     }
2207 }
2208
2209 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2210     /// Sets the value of the entry with the VacantEntry's key,
2211     /// and returns a mutable reference to it.
2212     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2213     pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2214         where K: Hash,
2215               S: BuildHasher,
2216     {
2217         let mut hasher = self.hash_builder.build_hasher();
2218         key.hash(&mut hasher);
2219         self.insert_hashed_nocheck(hasher.finish(), key, value)
2220     }
2221
2222     /// Sets the value of the entry with the VacantEntry's key,
2223     /// and returns a mutable reference to it.
2224     #[inline]
2225     #[unstable(feature = "hash_raw_entry", issue = "56167")]
2226     pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2227         let hash = SafeHash::new(hash);
2228         let b = match self.elem {
2229             NeqElem(mut bucket, disp) => {
2230                 if disp >= DISPLACEMENT_THRESHOLD {
2231                     bucket.table_mut().set_tag(true);
2232                 }
2233                 robin_hood(bucket, disp, hash, key, value)
2234             },
2235             NoElem(mut bucket, disp) => {
2236                 if disp >= DISPLACEMENT_THRESHOLD {
2237                     bucket.table_mut().set_tag(true);
2238                 }
2239                 bucket.put(hash, key, value)
2240             },
2241         };
2242         b.into_mut_refs()
2243     }
2244 }
2245
2246 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2247 impl<'a, K, V, S> Debug for RawEntryBuilderMut<'a, K, V, S> {
2248     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2249         f.debug_struct("RawEntryBuilder")
2250          .finish()
2251     }
2252 }
2253
2254 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2255 impl<'a, K: Debug, V: Debug, S> Debug for RawEntryMut<'a, K, V, S> {
2256     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2257         match *self {
2258             RawEntryMut::Vacant(ref v) => {
2259                 f.debug_tuple("RawEntry")
2260                     .field(v)
2261                     .finish()
2262             }
2263             RawEntryMut::Occupied(ref o) => {
2264                 f.debug_tuple("RawEntry")
2265                     .field(o)
2266                     .finish()
2267             }
2268         }
2269     }
2270 }
2271
2272 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2273 impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'a, K, V> {
2274     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2275         f.debug_struct("RawOccupiedEntryMut")
2276          .field("key", self.key())
2277          .field("value", self.get())
2278          .finish()
2279     }
2280 }
2281
2282 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2283 impl<'a, K, V, S> Debug for RawVacantEntryMut<'a, K, V, S> {
2284     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2285         f.debug_struct("RawVacantEntryMut")
2286          .finish()
2287     }
2288 }
2289
2290 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2291 impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> {
2292     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2293         f.debug_struct("RawEntryBuilder")
2294          .finish()
2295     }
2296 }
2297
2298 /// A view into a single entry in a map, which may either be vacant or occupied.
2299 ///
2300 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2301 ///
2302 /// [`HashMap`]: struct.HashMap.html
2303 /// [`entry`]: struct.HashMap.html#method.entry
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 pub enum Entry<'a, K: 'a, V: 'a> {
2306     /// An occupied entry.
2307     #[stable(feature = "rust1", since = "1.0.0")]
2308     Occupied(#[stable(feature = "rust1", since = "1.0.0")]
2309              OccupiedEntry<'a, K, V>),
2310
2311     /// A vacant entry.
2312     #[stable(feature = "rust1", since = "1.0.0")]
2313     Vacant(#[stable(feature = "rust1", since = "1.0.0")]
2314            VacantEntry<'a, K, V>),
2315 }
2316
2317 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2318 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
2319     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2320         match *self {
2321             Vacant(ref v) => {
2322                 f.debug_tuple("Entry")
2323                     .field(v)
2324                     .finish()
2325             }
2326             Occupied(ref o) => {
2327                 f.debug_tuple("Entry")
2328                     .field(o)
2329                     .finish()
2330             }
2331         }
2332     }
2333 }
2334
2335 /// A view into an occupied entry in a `HashMap`.
2336 /// It is part of the [`Entry`] enum.
2337 ///
2338 /// [`Entry`]: enum.Entry.html
2339 #[stable(feature = "rust1", since = "1.0.0")]
2340 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2341     key: Option<K>,
2342     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2343 }
2344
2345 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2346 impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
2347     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2348         f.debug_struct("OccupiedEntry")
2349             .field("key", self.key())
2350             .field("value", self.get())
2351             .finish()
2352     }
2353 }
2354
2355 /// A view into a vacant entry in a `HashMap`.
2356 /// It is part of the [`Entry`] enum.
2357 ///
2358 /// [`Entry`]: enum.Entry.html
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2361     hash: SafeHash,
2362     key: K,
2363     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2364 }
2365
2366 #[stable(feature= "debug_hash_map", since = "1.12.0")]
2367 impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
2368     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2369         f.debug_tuple("VacantEntry")
2370             .field(self.key())
2371             .finish()
2372     }
2373 }
2374
2375 /// Possible states of a VacantEntry.
2376 enum VacantEntryState<K, V, M> {
2377     /// The index is occupied, but the key to insert has precedence,
2378     /// and will kick the current one out on insertion.
2379     NeqElem(FullBucket<K, V, M>, usize),
2380     /// The index is genuinely vacant.
2381     NoElem(EmptyBucket<K, V, M>, usize),
2382 }
2383
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
2386     where K: Eq + Hash,
2387           S: BuildHasher
2388 {
2389     type Item = (&'a K, &'a V);
2390     type IntoIter = Iter<'a, K, V>;
2391
2392     fn into_iter(self) -> Iter<'a, K, V> {
2393         self.iter()
2394     }
2395 }
2396
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
2399     where K: Eq + Hash,
2400           S: BuildHasher
2401 {
2402     type Item = (&'a K, &'a mut V);
2403     type IntoIter = IterMut<'a, K, V>;
2404
2405     fn into_iter(self) -> IterMut<'a, K, V> {
2406         self.iter_mut()
2407     }
2408 }
2409
2410 #[stable(feature = "rust1", since = "1.0.0")]
2411 impl<K, V, S> IntoIterator for HashMap<K, V, S>
2412     where K: Eq + Hash,
2413           S: BuildHasher
2414 {
2415     type Item = (K, V);
2416     type IntoIter = IntoIter<K, V>;
2417
2418     /// Creates a consuming iterator, that is, one that moves each key-value
2419     /// pair out of the map in arbitrary order. The map cannot be used after
2420     /// calling this.
2421     ///
2422     /// # Examples
2423     ///
2424     /// ```
2425     /// use std::collections::HashMap;
2426     ///
2427     /// let mut map = HashMap::new();
2428     /// map.insert("a", 1);
2429     /// map.insert("b", 2);
2430     /// map.insert("c", 3);
2431     ///
2432     /// // Not possible with .iter()
2433     /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2434     /// ```
2435     fn into_iter(self) -> IntoIter<K, V> {
2436         IntoIter { inner: self.table.into_iter() }
2437     }
2438 }
2439
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2442     type Item = (&'a K, &'a V);
2443
2444     #[inline]
2445     fn next(&mut self) -> Option<(&'a K, &'a V)> {
2446         self.inner.next()
2447     }
2448     #[inline]
2449     fn size_hint(&self) -> (usize, Option<usize>) {
2450         self.inner.size_hint()
2451     }
2452 }
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
2455     #[inline]
2456     fn len(&self) -> usize {
2457         self.inner.len()
2458     }
2459 }
2460
2461 #[stable(feature = "fused", since = "1.26.0")]
2462 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2463
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2466     type Item = (&'a K, &'a mut V);
2467
2468     #[inline]
2469     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2470         self.inner.next()
2471     }
2472     #[inline]
2473     fn size_hint(&self) -> (usize, Option<usize>) {
2474         self.inner.size_hint()
2475     }
2476 }
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
2479     #[inline]
2480     fn len(&self) -> usize {
2481         self.inner.len()
2482     }
2483 }
2484 #[stable(feature = "fused", since = "1.26.0")]
2485 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2486
2487 #[stable(feature = "std_debug", since = "1.16.0")]
2488 impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
2489     where K: fmt::Debug,
2490           V: fmt::Debug,
2491 {
2492     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2493         f.debug_list()
2494             .entries(self.inner.iter())
2495             .finish()
2496     }
2497 }
2498
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 impl<K, V> Iterator for IntoIter<K, V> {
2501     type Item = (K, V);
2502
2503     #[inline]
2504     fn next(&mut self) -> Option<(K, V)> {
2505         self.inner.next().map(|(_, k, v)| (k, v))
2506     }
2507     #[inline]
2508     fn size_hint(&self) -> (usize, Option<usize>) {
2509         self.inner.size_hint()
2510     }
2511 }
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2514     #[inline]
2515     fn len(&self) -> usize {
2516         self.inner.len()
2517     }
2518 }
2519 #[stable(feature = "fused", since = "1.26.0")]
2520 impl<K, V> FusedIterator for IntoIter<K, V> {}
2521
2522 #[stable(feature = "std_debug", since = "1.16.0")]
2523 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2524     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2525         f.debug_list()
2526             .entries(self.inner.iter())
2527             .finish()
2528     }
2529 }
2530
2531 #[stable(feature = "rust1", since = "1.0.0")]
2532 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2533     type Item = &'a K;
2534
2535     #[inline]
2536     fn next(&mut self) -> Option<(&'a K)> {
2537         self.inner.next().map(|(k, _)| k)
2538     }
2539     #[inline]
2540     fn size_hint(&self) -> (usize, Option<usize>) {
2541         self.inner.size_hint()
2542     }
2543 }
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2546     #[inline]
2547     fn len(&self) -> usize {
2548         self.inner.len()
2549     }
2550 }
2551 #[stable(feature = "fused", since = "1.26.0")]
2552 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2553
2554 #[stable(feature = "rust1", since = "1.0.0")]
2555 impl<'a, K, V> Iterator for Values<'a, K, V> {
2556     type Item = &'a V;
2557
2558     #[inline]
2559     fn next(&mut self) -> Option<(&'a V)> {
2560         self.inner.next().map(|(_, v)| v)
2561     }
2562     #[inline]
2563     fn size_hint(&self) -> (usize, Option<usize>) {
2564         self.inner.size_hint()
2565     }
2566 }
2567 #[stable(feature = "rust1", since = "1.0.0")]
2568 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2569     #[inline]
2570     fn len(&self) -> usize {
2571         self.inner.len()
2572     }
2573 }
2574 #[stable(feature = "fused", since = "1.26.0")]
2575 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2576
2577 #[stable(feature = "map_values_mut", since = "1.10.0")]
2578 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2579     type Item = &'a mut V;
2580
2581     #[inline]
2582     fn next(&mut self) -> Option<(&'a mut V)> {
2583         self.inner.next().map(|(_, v)| v)
2584     }
2585     #[inline]
2586     fn size_hint(&self) -> (usize, Option<usize>) {
2587         self.inner.size_hint()
2588     }
2589 }
2590 #[stable(feature = "map_values_mut", since = "1.10.0")]
2591 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2592     #[inline]
2593     fn len(&self) -> usize {
2594         self.inner.len()
2595     }
2596 }
2597 #[stable(feature = "fused", since = "1.26.0")]
2598 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2599
2600 #[stable(feature = "std_debug", since = "1.16.0")]
2601 impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
2602     where K: fmt::Debug,
2603           V: fmt::Debug,
2604 {
2605     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2606         f.debug_list()
2607             .entries(self.inner.inner.iter())
2608             .finish()
2609     }
2610 }
2611
2612 #[stable(feature = "drain", since = "1.6.0")]
2613 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2614     type Item = (K, V);
2615
2616     #[inline]
2617     fn next(&mut self) -> Option<(K, V)> {
2618         self.inner.next().map(|(_, k, v)| (k, v))
2619     }
2620     #[inline]
2621     fn size_hint(&self) -> (usize, Option<usize>) {
2622         self.inner.size_hint()
2623     }
2624 }
2625 #[stable(feature = "drain", since = "1.6.0")]
2626 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
2627     #[inline]
2628     fn len(&self) -> usize {
2629         self.inner.len()
2630     }
2631 }
2632 #[stable(feature = "fused", since = "1.26.0")]
2633 impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
2634
2635 #[stable(feature = "std_debug", since = "1.16.0")]
2636 impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
2637     where K: fmt::Debug,
2638           V: fmt::Debug,
2639 {
2640     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2641         f.debug_list()
2642             .entries(self.inner.iter())
2643             .finish()
2644     }
2645 }
2646
2647 impl<'a, K, V> Entry<'a, K, V> {
2648     #[stable(feature = "rust1", since = "1.0.0")]
2649     /// Ensures a value is in the entry by inserting the default if empty, and returns
2650     /// a mutable reference to the value in the entry.
2651     ///
2652     /// # Examples
2653     ///
2654     /// ```
2655     /// use std::collections::HashMap;
2656     ///
2657     /// let mut map: HashMap<&str, u32> = HashMap::new();
2658     ///
2659     /// map.entry("poneyland").or_insert(3);
2660     /// assert_eq!(map["poneyland"], 3);
2661     ///
2662     /// *map.entry("poneyland").or_insert(10) *= 2;
2663     /// assert_eq!(map["poneyland"], 6);
2664     /// ```
2665     pub fn or_insert(self, default: V) -> &'a mut V {
2666         match self {
2667             Occupied(entry) => entry.into_mut(),
2668             Vacant(entry) => entry.insert(default),
2669         }
2670     }
2671
2672     #[stable(feature = "rust1", since = "1.0.0")]
2673     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2674     /// and returns a mutable reference to the value in the entry.
2675     ///
2676     /// # Examples
2677     ///
2678     /// ```
2679     /// use std::collections::HashMap;
2680     ///
2681     /// let mut map: HashMap<&str, String> = HashMap::new();
2682     /// let s = "hoho".to_string();
2683     ///
2684     /// map.entry("poneyland").or_insert_with(|| s);
2685     ///
2686     /// assert_eq!(map["poneyland"], "hoho".to_string());
2687     /// ```
2688     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2689         match self {
2690             Occupied(entry) => entry.into_mut(),
2691             Vacant(entry) => entry.insert(default()),
2692         }
2693     }
2694
2695     /// Returns a reference to this entry's key.
2696     ///
2697     /// # Examples
2698     ///
2699     /// ```
2700     /// use std::collections::HashMap;
2701     ///
2702     /// let mut map: HashMap<&str, u32> = HashMap::new();
2703     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2704     /// ```
2705     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2706     pub fn key(&self) -> &K {
2707         match *self {
2708             Occupied(ref entry) => entry.key(),
2709             Vacant(ref entry) => entry.key(),
2710         }
2711     }
2712
2713     /// Provides in-place mutable access to an occupied entry before any
2714     /// potential inserts into the map.
2715     ///
2716     /// # Examples
2717     ///
2718     /// ```
2719     /// use std::collections::HashMap;
2720     ///
2721     /// let mut map: HashMap<&str, u32> = HashMap::new();
2722     ///
2723     /// map.entry("poneyland")
2724     ///    .and_modify(|e| { *e += 1 })
2725     ///    .or_insert(42);
2726     /// assert_eq!(map["poneyland"], 42);
2727     ///
2728     /// map.entry("poneyland")
2729     ///    .and_modify(|e| { *e += 1 })
2730     ///    .or_insert(42);
2731     /// assert_eq!(map["poneyland"], 43);
2732     /// ```
2733     #[stable(feature = "entry_and_modify", since = "1.26.0")]
2734     pub fn and_modify<F>(self, f: F) -> Self
2735         where F: FnOnce(&mut V)
2736     {
2737         match self {
2738             Occupied(mut entry) => {
2739                 f(entry.get_mut());
2740                 Occupied(entry)
2741             },
2742             Vacant(entry) => Vacant(entry),
2743         }
2744     }
2745
2746 }
2747
2748 impl<'a, K, V: Default> Entry<'a, K, V> {
2749     #[stable(feature = "entry_or_default", since = "1.28.0")]
2750     /// Ensures a value is in the entry by inserting the default value if empty,
2751     /// and returns a mutable reference to the value in the entry.
2752     ///
2753     /// # Examples
2754     ///
2755     /// ```
2756     /// # fn main() {
2757     /// use std::collections::HashMap;
2758     ///
2759     /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2760     /// map.entry("poneyland").or_default();
2761     ///
2762     /// assert_eq!(map["poneyland"], None);
2763     /// # }
2764     /// ```
2765     pub fn or_default(self) -> &'a mut V {
2766         match self {
2767             Occupied(entry) => entry.into_mut(),
2768             Vacant(entry) => entry.insert(Default::default()),
2769         }
2770     }
2771 }
2772
2773 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2774     /// Gets a reference to the key in the entry.
2775     ///
2776     /// # Examples
2777     ///
2778     /// ```
2779     /// use std::collections::HashMap;
2780     ///
2781     /// let mut map: HashMap<&str, u32> = HashMap::new();
2782     /// map.entry("poneyland").or_insert(12);
2783     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2784     /// ```
2785     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2786     pub fn key(&self) -> &K {
2787         self.elem.read().0
2788     }
2789
2790     /// Take the ownership of the key and value from the map.
2791     ///
2792     /// # Examples
2793     ///
2794     /// ```
2795     /// use std::collections::HashMap;
2796     /// use std::collections::hash_map::Entry;
2797     ///
2798     /// let mut map: HashMap<&str, u32> = HashMap::new();
2799     /// map.entry("poneyland").or_insert(12);
2800     ///
2801     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2802     ///     // We delete the entry from the map.
2803     ///     o.remove_entry();
2804     /// }
2805     ///
2806     /// assert_eq!(map.contains_key("poneyland"), false);
2807     /// ```
2808     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2809     pub fn remove_entry(self) -> (K, V) {
2810         let (k, v, _) = pop_internal(self.elem);
2811         (k, v)
2812     }
2813
2814     /// Gets a reference to the value in the entry.
2815     ///
2816     /// # Examples
2817     ///
2818     /// ```
2819     /// use std::collections::HashMap;
2820     /// use std::collections::hash_map::Entry;
2821     ///
2822     /// let mut map: HashMap<&str, u32> = HashMap::new();
2823     /// map.entry("poneyland").or_insert(12);
2824     ///
2825     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2826     ///     assert_eq!(o.get(), &12);
2827     /// }
2828     /// ```
2829     #[stable(feature = "rust1", since = "1.0.0")]
2830     pub fn get(&self) -> &V {
2831         self.elem.read().1
2832     }
2833
2834     /// Gets a mutable reference to the value in the entry.
2835     ///
2836     /// If you need a reference to the `OccupiedEntry` which may outlive the
2837     /// destruction of the `Entry` value, see [`into_mut`].
2838     ///
2839     /// [`into_mut`]: #method.into_mut
2840     ///
2841     /// # Examples
2842     ///
2843     /// ```
2844     /// use std::collections::HashMap;
2845     /// use std::collections::hash_map::Entry;
2846     ///
2847     /// let mut map: HashMap<&str, u32> = HashMap::new();
2848     /// map.entry("poneyland").or_insert(12);
2849     ///
2850     /// assert_eq!(map["poneyland"], 12);
2851     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2852     ///     *o.get_mut() += 10;
2853     ///     assert_eq!(*o.get(), 22);
2854     ///
2855     ///     // We can use the same Entry multiple times.
2856     ///     *o.get_mut() += 2;
2857     /// }
2858     ///
2859     /// assert_eq!(map["poneyland"], 24);
2860     /// ```
2861     #[stable(feature = "rust1", since = "1.0.0")]
2862     pub fn get_mut(&mut self) -> &mut V {
2863         self.elem.read_mut().1
2864     }
2865
2866     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2867     /// with a lifetime bound to the map itself.
2868     ///
2869     /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2870     ///
2871     /// [`get_mut`]: #method.get_mut
2872     ///
2873     /// # Examples
2874     ///
2875     /// ```
2876     /// use std::collections::HashMap;
2877     /// use std::collections::hash_map::Entry;
2878     ///
2879     /// let mut map: HashMap<&str, u32> = HashMap::new();
2880     /// map.entry("poneyland").or_insert(12);
2881     ///
2882     /// assert_eq!(map["poneyland"], 12);
2883     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2884     ///     *o.into_mut() += 10;
2885     /// }
2886     ///
2887     /// assert_eq!(map["poneyland"], 22);
2888     /// ```
2889     #[stable(feature = "rust1", since = "1.0.0")]
2890     pub fn into_mut(self) -> &'a mut V {
2891         self.elem.into_mut_refs().1
2892     }
2893
2894     /// Sets the value of the entry, and returns the entry's old value.
2895     ///
2896     /// # Examples
2897     ///
2898     /// ```
2899     /// use std::collections::HashMap;
2900     /// use std::collections::hash_map::Entry;
2901     ///
2902     /// let mut map: HashMap<&str, u32> = HashMap::new();
2903     /// map.entry("poneyland").or_insert(12);
2904     ///
2905     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2906     ///     assert_eq!(o.insert(15), 12);
2907     /// }
2908     ///
2909     /// assert_eq!(map["poneyland"], 15);
2910     /// ```
2911     #[stable(feature = "rust1", since = "1.0.0")]
2912     pub fn insert(&mut self, mut value: V) -> V {
2913         let old_value = self.get_mut();
2914         mem::swap(&mut value, old_value);
2915         value
2916     }
2917
2918     /// Takes the value out of the entry, and returns it.
2919     ///
2920     /// # Examples
2921     ///
2922     /// ```
2923     /// use std::collections::HashMap;
2924     /// use std::collections::hash_map::Entry;
2925     ///
2926     /// let mut map: HashMap<&str, u32> = HashMap::new();
2927     /// map.entry("poneyland").or_insert(12);
2928     ///
2929     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2930     ///     assert_eq!(o.remove(), 12);
2931     /// }
2932     ///
2933     /// assert_eq!(map.contains_key("poneyland"), false);
2934     /// ```
2935     #[stable(feature = "rust1", since = "1.0.0")]
2936     pub fn remove(self) -> V {
2937         pop_internal(self.elem).1
2938     }
2939
2940     /// Returns a key that was used for search.
2941     ///
2942     /// The key was retained for further use.
2943     fn take_key(&mut self) -> Option<K> {
2944         self.key.take()
2945     }
2946
2947     /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2948     /// the key used to create this entry.
2949     ///
2950     /// # Examples
2951     ///
2952     /// ```
2953     /// #![feature(map_entry_replace)]
2954     /// use std::collections::hash_map::{Entry, HashMap};
2955     /// use std::rc::Rc;
2956     ///
2957     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2958     /// map.insert(Rc::new("Stringthing".to_string()), 15);
2959     ///
2960     /// let my_key = Rc::new("Stringthing".to_string());
2961     ///
2962     /// if let Entry::Occupied(entry) = map.entry(my_key) {
2963     ///     // Also replace the key with a handle to our other key.
2964     ///     let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2965     /// }
2966     ///
2967     /// ```
2968     #[unstable(feature = "map_entry_replace", issue = "44286")]
2969     pub fn replace_entry(mut self, value: V) -> (K, V) {
2970         let (old_key, old_value) = self.elem.read_mut();
2971
2972         let old_key = mem::replace(old_key, self.key.unwrap());
2973         let old_value = mem::replace(old_value, value);
2974
2975         (old_key, old_value)
2976     }
2977
2978     /// Replaces the key in the hash map with the key used to create this entry.
2979     ///
2980     /// # Examples
2981     ///
2982     /// ```
2983     /// #![feature(map_entry_replace)]
2984     /// use std::collections::hash_map::{Entry, HashMap};
2985     /// use std::rc::Rc;
2986     ///
2987     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2988     /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2989     ///
2990     /// // Initialise known strings, run program, etc.
2991     ///
2992     /// reclaim_memory(&mut map, &known_strings);
2993     ///
2994     /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2995     ///     for s in known_strings {
2996     ///         if let Entry::Occupied(entry) = map.entry(s.clone()) {
2997     ///             // Replaces the entry's key with our version of it in `known_strings`.
2998     ///             entry.replace_key();
2999     ///         }
3000     ///     }
3001     /// }
3002     /// ```
3003     #[unstable(feature = "map_entry_replace", issue = "44286")]
3004     pub fn replace_key(mut self) -> K {
3005         let (old_key, _) = self.elem.read_mut();
3006         mem::replace(old_key, self.key.unwrap())
3007     }
3008 }
3009
3010 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3011     /// Gets a reference to the key that would be used when inserting a value
3012     /// through the `VacantEntry`.
3013     ///
3014     /// # Examples
3015     ///
3016     /// ```
3017     /// use std::collections::HashMap;
3018     ///
3019     /// let mut map: HashMap<&str, u32> = HashMap::new();
3020     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3021     /// ```
3022     #[stable(feature = "map_entry_keys", since = "1.10.0")]
3023     pub fn key(&self) -> &K {
3024         &self.key
3025     }
3026
3027     /// Take ownership of the key.
3028     ///
3029     /// # Examples
3030     ///
3031     /// ```
3032     /// use std::collections::HashMap;
3033     /// use std::collections::hash_map::Entry;
3034     ///
3035     /// let mut map: HashMap<&str, u32> = HashMap::new();
3036     ///
3037     /// if let Entry::Vacant(v) = map.entry("poneyland") {
3038     ///     v.into_key();
3039     /// }
3040     /// ```
3041     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3042     pub fn into_key(self) -> K {
3043         self.key
3044     }
3045
3046     /// Sets the value of the entry with the VacantEntry's key,
3047     /// and returns a mutable reference to it.
3048     ///
3049     /// # Examples
3050     ///
3051     /// ```
3052     /// use std::collections::HashMap;
3053     /// use std::collections::hash_map::Entry;
3054     ///
3055     /// let mut map: HashMap<&str, u32> = HashMap::new();
3056     ///
3057     /// if let Entry::Vacant(o) = map.entry("poneyland") {
3058     ///     o.insert(37);
3059     /// }
3060     /// assert_eq!(map["poneyland"], 37);
3061     /// ```
3062     #[stable(feature = "rust1", since = "1.0.0")]
3063     pub fn insert(self, value: V) -> &'a mut V {
3064         let b = match self.elem {
3065             NeqElem(mut bucket, disp) => {
3066                 if disp >= DISPLACEMENT_THRESHOLD {
3067                     bucket.table_mut().set_tag(true);
3068                 }
3069                 robin_hood(bucket, disp, self.hash, self.key, value)
3070             },
3071             NoElem(mut bucket, disp) => {
3072                 if disp >= DISPLACEMENT_THRESHOLD {
3073                     bucket.table_mut().set_tag(true);
3074                 }
3075                 bucket.put(self.hash, self.key, value)
3076             },
3077         };
3078         b.into_mut_refs().1
3079     }
3080 }
3081
3082 #[stable(feature = "rust1", since = "1.0.0")]
3083 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3084     where K: Eq + Hash,
3085           S: BuildHasher + Default
3086 {
3087     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3088         let mut map = HashMap::with_hasher(Default::default());
3089         map.extend(iter);
3090         map
3091     }
3092 }
3093
3094 #[stable(feature = "rust1", since = "1.0.0")]
3095 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3096     where K: Eq + Hash,
3097           S: BuildHasher
3098 {
3099     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3100         // Keys may be already present or show multiple times in the iterator.
3101         // Reserve the entire hint lower bound if the map is empty.
3102         // Otherwise reserve half the hint (rounded up), so the map
3103         // will only resize twice in the worst case.
3104         let iter = iter.into_iter();
3105         let reserve = if self.is_empty() {
3106             iter.size_hint().0
3107         } else {
3108             (iter.size_hint().0 + 1) / 2
3109         };
3110         self.reserve(reserve);
3111         for (k, v) in iter {
3112             self.insert(k, v);
3113         }
3114     }
3115 }
3116
3117 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3118 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3119     where K: Eq + Hash + Copy,
3120           V: Copy,
3121           S: BuildHasher
3122 {
3123     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3124         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3125     }
3126 }
3127
3128 /// `RandomState` is the default state for [`HashMap`] types.
3129 ///
3130 /// A particular instance `RandomState` will create the same instances of
3131 /// [`Hasher`], but the hashers created by two different `RandomState`
3132 /// instances are unlikely to produce the same result for the same values.
3133 ///
3134 /// [`HashMap`]: struct.HashMap.html
3135 /// [`Hasher`]: ../../hash/trait.Hasher.html
3136 ///
3137 /// # Examples
3138 ///
3139 /// ```
3140 /// use std::collections::HashMap;
3141 /// use std::collections::hash_map::RandomState;
3142 ///
3143 /// let s = RandomState::new();
3144 /// let mut map = HashMap::with_hasher(s);
3145 /// map.insert(1, 2);
3146 /// ```
3147 #[derive(Clone)]
3148 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3149 pub struct RandomState {
3150     k0: u64,
3151     k1: u64,
3152 }
3153
3154 impl RandomState {
3155     /// Constructs a new `RandomState` that is initialized with random keys.
3156     ///
3157     /// # Examples
3158     ///
3159     /// ```
3160     /// use std::collections::hash_map::RandomState;
3161     ///
3162     /// let s = RandomState::new();
3163     /// ```
3164     #[inline]
3165     #[allow(deprecated)]
3166     // rand
3167     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3168     pub fn new() -> RandomState {
3169         // Historically this function did not cache keys from the OS and instead
3170         // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3171         // was discovered, however, that because we re-seed the thread-local RNG
3172         // from the OS periodically that this can cause excessive slowdown when
3173         // many hash maps are created on a thread. To solve this performance
3174         // trap we cache the first set of randomly generated keys per-thread.
3175         //
3176         // Later in #36481 it was discovered that exposing a deterministic
3177         // iteration order allows a form of DOS attack. To counter that we
3178         // increment one of the seeds on every RandomState creation, giving
3179         // every corresponding HashMap a different iteration order.
3180         thread_local!(static KEYS: Cell<(u64, u64)> = {
3181             Cell::new(sys::hashmap_random_keys())
3182         });
3183
3184         KEYS.with(|keys| {
3185             let (k0, k1) = keys.get();
3186             keys.set((k0.wrapping_add(1), k1));
3187             RandomState { k0: k0, k1: k1 }
3188         })
3189     }
3190 }
3191
3192 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3193 impl BuildHasher for RandomState {
3194     type Hasher = DefaultHasher;
3195     #[inline]
3196     #[allow(deprecated)]
3197     fn build_hasher(&self) -> DefaultHasher {
3198         DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3199     }
3200 }
3201
3202 /// The default [`Hasher`] used by [`RandomState`].
3203 ///
3204 /// The internal algorithm is not specified, and so it and its hashes should
3205 /// not be relied upon over releases.
3206 ///
3207 /// [`RandomState`]: struct.RandomState.html
3208 /// [`Hasher`]: ../../hash/trait.Hasher.html
3209 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3210 #[allow(deprecated)]
3211 #[derive(Clone, Debug)]
3212 pub struct DefaultHasher(SipHasher13);
3213
3214 impl DefaultHasher {
3215     /// Creates a new `DefaultHasher`.
3216     ///
3217     /// This hasher is not guaranteed to be the same as all other
3218     /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3219     /// instances created through `new` or `default`.
3220     #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3221     #[allow(deprecated)]
3222     pub fn new() -> DefaultHasher {
3223         DefaultHasher(SipHasher13::new_with_keys(0, 0))
3224     }
3225 }
3226
3227 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3228 impl Default for DefaultHasher {
3229     /// Creates a new `DefaultHasher` using [`new`][DefaultHasher::new].
3230     /// See its documentation for more.
3231     fn default() -> DefaultHasher {
3232         DefaultHasher::new()
3233     }
3234 }
3235
3236 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3237 impl Hasher for DefaultHasher {
3238     #[inline]
3239     fn write(&mut self, msg: &[u8]) {
3240         self.0.write(msg)
3241     }
3242
3243     #[inline]
3244     fn finish(&self) -> u64 {
3245         self.0.finish()
3246     }
3247 }
3248
3249 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3250 impl Default for RandomState {
3251     /// Constructs a new `RandomState`.
3252     #[inline]
3253     fn default() -> RandomState {
3254         RandomState::new()
3255     }
3256 }
3257
3258 #[stable(feature = "std_debug", since = "1.16.0")]
3259 impl fmt::Debug for RandomState {
3260     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3261         f.pad("RandomState { .. }")
3262     }
3263 }
3264
3265 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3266     where K: Eq + Hash + Borrow<Q>,
3267           S: BuildHasher,
3268           Q: Eq + Hash
3269 {
3270     type Key = K;
3271
3272     #[inline]
3273     fn get(&self, key: &Q) -> Option<&K> {
3274         self.search(key).map(|bucket| bucket.into_refs().0)
3275     }
3276
3277     fn take(&mut self, key: &Q) -> Option<K> {
3278         self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3279     }
3280
3281     #[inline]
3282     fn replace(&mut self, key: K) -> Option<K> {
3283         self.reserve(1);
3284
3285         match self.entry(key) {
3286             Occupied(mut occupied) => {
3287                 let key = occupied.take_key().unwrap();
3288                 Some(mem::replace(occupied.elem.read_mut().0, key))
3289             }
3290             Vacant(vacant) => {
3291                 vacant.insert(());
3292                 None
3293             }
3294         }
3295     }
3296 }
3297
3298 #[allow(dead_code)]
3299 fn assert_covariance() {
3300     fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3301         v
3302     }
3303     fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3304         v
3305     }
3306     fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3307         v
3308     }
3309     fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3310         v
3311     }
3312     fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3313         v
3314     }
3315     fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3316         v
3317     }
3318     fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3319         v
3320     }
3321     fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3322         v
3323     }
3324     fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3325         v
3326     }
3327     fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3328         v
3329     }
3330     fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3331                    -> Drain<'new, &'new str, &'new str> {
3332         d
3333     }
3334 }
3335
3336 #[cfg(test)]
3337 mod test_map {
3338     use super::HashMap;
3339     use super::Entry::{Occupied, Vacant};
3340     use super::RandomState;
3341     use cell::RefCell;
3342     use rand::{thread_rng, Rng};
3343     use realstd::collections::CollectionAllocErr::*;
3344     use realstd::mem::size_of;
3345     use realstd::usize;
3346
3347     #[test]
3348     fn test_zero_capacities() {
3349         type HM = HashMap<i32, i32>;
3350
3351         let m = HM::new();
3352         assert_eq!(m.capacity(), 0);
3353
3354         let m = HM::default();
3355         assert_eq!(m.capacity(), 0);
3356
3357         let m = HM::with_hasher(RandomState::new());
3358         assert_eq!(m.capacity(), 0);
3359
3360         let m = HM::with_capacity(0);
3361         assert_eq!(m.capacity(), 0);
3362
3363         let m = HM::with_capacity_and_hasher(0, RandomState::new());
3364         assert_eq!(m.capacity(), 0);
3365
3366         let mut m = HM::new();
3367         m.insert(1, 1);
3368         m.insert(2, 2);
3369         m.remove(&1);
3370         m.remove(&2);
3371         m.shrink_to_fit();
3372         assert_eq!(m.capacity(), 0);
3373
3374         let mut m = HM::new();
3375         m.reserve(0);
3376         assert_eq!(m.capacity(), 0);
3377     }
3378
3379     #[test]
3380     fn test_create_capacity_zero() {
3381         let mut m = HashMap::with_capacity(0);
3382
3383         assert!(m.insert(1, 1).is_none());
3384
3385         assert!(m.contains_key(&1));
3386         assert!(!m.contains_key(&0));
3387     }
3388
3389     #[test]
3390     fn test_insert() {
3391         let mut m = HashMap::new();
3392         assert_eq!(m.len(), 0);
3393         assert!(m.insert(1, 2).is_none());
3394         assert_eq!(m.len(), 1);
3395         assert!(m.insert(2, 4).is_none());
3396         assert_eq!(m.len(), 2);
3397         assert_eq!(*m.get(&1).unwrap(), 2);
3398         assert_eq!(*m.get(&2).unwrap(), 4);
3399     }
3400
3401     #[test]
3402     fn test_clone() {
3403         let mut m = HashMap::new();
3404         assert_eq!(m.len(), 0);
3405         assert!(m.insert(1, 2).is_none());
3406         assert_eq!(m.len(), 1);
3407         assert!(m.insert(2, 4).is_none());
3408         assert_eq!(m.len(), 2);
3409         let m2 = m.clone();
3410         assert_eq!(*m2.get(&1).unwrap(), 2);
3411         assert_eq!(*m2.get(&2).unwrap(), 4);
3412         assert_eq!(m2.len(), 2);
3413     }
3414
3415     thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3416
3417     #[derive(Hash, PartialEq, Eq)]
3418     struct Droppable {
3419         k: usize,
3420     }
3421
3422     impl Droppable {
3423         fn new(k: usize) -> Droppable {
3424             DROP_VECTOR.with(|slot| {
3425                 slot.borrow_mut()[k] += 1;
3426             });
3427
3428             Droppable { k }
3429         }
3430     }
3431
3432     impl Drop for Droppable {
3433         fn drop(&mut self) {
3434             DROP_VECTOR.with(|slot| {
3435                 slot.borrow_mut()[self.k] -= 1;
3436             });
3437         }
3438     }
3439
3440     impl Clone for Droppable {
3441         fn clone(&self) -> Droppable {
3442             Droppable::new(self.k)
3443         }
3444     }
3445
3446     #[test]
3447     fn test_drops() {
3448         DROP_VECTOR.with(|slot| {
3449             *slot.borrow_mut() = vec![0; 200];
3450         });
3451
3452         {
3453             let mut m = HashMap::new();
3454
3455             DROP_VECTOR.with(|v| {
3456                 for i in 0..200 {
3457                     assert_eq!(v.borrow()[i], 0);
3458                 }
3459             });
3460
3461             for i in 0..100 {
3462                 let d1 = Droppable::new(i);
3463                 let d2 = Droppable::new(i + 100);
3464                 m.insert(d1, d2);
3465             }
3466
3467             DROP_VECTOR.with(|v| {
3468                 for i in 0..200 {
3469                     assert_eq!(v.borrow()[i], 1);
3470                 }
3471             });
3472
3473             for i in 0..50 {
3474                 let k = Droppable::new(i);
3475                 let v = m.remove(&k);
3476
3477                 assert!(v.is_some());
3478
3479                 DROP_VECTOR.with(|v| {
3480                     assert_eq!(v.borrow()[i], 1);
3481                     assert_eq!(v.borrow()[i+100], 1);
3482                 });
3483             }
3484
3485             DROP_VECTOR.with(|v| {
3486                 for i in 0..50 {
3487                     assert_eq!(v.borrow()[i], 0);
3488                     assert_eq!(v.borrow()[i+100], 0);
3489                 }
3490
3491                 for i in 50..100 {
3492                     assert_eq!(v.borrow()[i], 1);
3493                     assert_eq!(v.borrow()[i+100], 1);
3494                 }
3495             });
3496         }
3497
3498         DROP_VECTOR.with(|v| {
3499             for i in 0..200 {
3500                 assert_eq!(v.borrow()[i], 0);
3501             }
3502         });
3503     }
3504
3505     #[test]
3506     fn test_into_iter_drops() {
3507         DROP_VECTOR.with(|v| {
3508             *v.borrow_mut() = vec![0; 200];
3509         });
3510
3511         let hm = {
3512             let mut hm = HashMap::new();
3513
3514             DROP_VECTOR.with(|v| {
3515                 for i in 0..200 {
3516                     assert_eq!(v.borrow()[i], 0);
3517                 }
3518             });
3519
3520             for i in 0..100 {
3521                 let d1 = Droppable::new(i);
3522                 let d2 = Droppable::new(i + 100);
3523                 hm.insert(d1, d2);
3524             }
3525
3526             DROP_VECTOR.with(|v| {
3527                 for i in 0..200 {
3528                     assert_eq!(v.borrow()[i], 1);
3529                 }
3530             });
3531
3532             hm
3533         };
3534
3535         // By the way, ensure that cloning doesn't screw up the dropping.
3536         drop(hm.clone());
3537
3538         {
3539             let mut half = hm.into_iter().take(50);
3540
3541             DROP_VECTOR.with(|v| {
3542                 for i in 0..200 {
3543                     assert_eq!(v.borrow()[i], 1);
3544                 }
3545             });
3546
3547             for _ in half.by_ref() {}
3548
3549             DROP_VECTOR.with(|v| {
3550                 let nk = (0..100)
3551                     .filter(|&i| v.borrow()[i] == 1)
3552                     .count();
3553
3554                 let nv = (0..100)
3555                     .filter(|&i| v.borrow()[i + 100] == 1)
3556                     .count();
3557
3558                 assert_eq!(nk, 50);
3559                 assert_eq!(nv, 50);
3560             });
3561         };
3562
3563         DROP_VECTOR.with(|v| {
3564             for i in 0..200 {
3565                 assert_eq!(v.borrow()[i], 0);
3566             }
3567         });
3568     }
3569
3570     #[test]
3571     fn test_empty_remove() {
3572         let mut m: HashMap<i32, bool> = HashMap::new();
3573         assert_eq!(m.remove(&0), None);
3574     }
3575
3576     #[test]
3577     fn test_empty_entry() {
3578         let mut m: HashMap<i32, bool> = HashMap::new();
3579         match m.entry(0) {
3580             Occupied(_) => panic!(),
3581             Vacant(_) => {}
3582         }
3583         assert!(*m.entry(0).or_insert(true));
3584         assert_eq!(m.len(), 1);
3585     }
3586
3587     #[test]
3588     fn test_empty_iter() {
3589         let mut m: HashMap<i32, bool> = HashMap::new();
3590         assert_eq!(m.drain().next(), None);
3591         assert_eq!(m.keys().next(), None);
3592         assert_eq!(m.values().next(), None);
3593         assert_eq!(m.values_mut().next(), None);
3594         assert_eq!(m.iter().next(), None);
3595         assert_eq!(m.iter_mut().next(), None);
3596         assert_eq!(m.len(), 0);
3597         assert!(m.is_empty());
3598         assert_eq!(m.into_iter().next(), None);
3599     }
3600
3601     #[test]
3602     fn test_lots_of_insertions() {
3603         let mut m = HashMap::new();
3604
3605         // Try this a few times to make sure we never screw up the hashmap's
3606         // internal state.
3607         for _ in 0..10 {
3608             assert!(m.is_empty());
3609
3610             for i in 1..1001 {
3611                 assert!(m.insert(i, i).is_none());
3612
3613                 for j in 1..i + 1 {
3614                     let r = m.get(&j);
3615                     assert_eq!(r, Some(&j));
3616                 }
3617
3618                 for j in i + 1..1001 {
3619                     let r = m.get(&j);
3620                     assert_eq!(r, None);
3621                 }
3622             }
3623
3624             for i in 1001..2001 {
3625                 assert!(!m.contains_key(&i));
3626             }
3627
3628             // remove forwards
3629             for i in 1..1001 {
3630                 assert!(m.remove(&i).is_some());
3631
3632                 for j in 1..i + 1 {
3633                     assert!(!m.contains_key(&j));
3634                 }
3635
3636                 for j in i + 1..1001 {
3637                     assert!(m.contains_key(&j));
3638                 }
3639             }
3640
3641             for i in 1..1001 {
3642                 assert!(!m.contains_key(&i));
3643             }
3644
3645             for i in 1..1001 {
3646                 assert!(m.insert(i, i).is_none());
3647             }
3648
3649             // remove backwards
3650             for i in (1..1001).rev() {
3651                 assert!(m.remove(&i).is_some());
3652
3653                 for j in i..1001 {
3654                     assert!(!m.contains_key(&j));
3655                 }
3656
3657                 for j in 1..i {
3658                     assert!(m.contains_key(&j));
3659                 }
3660             }
3661         }
3662     }
3663
3664     #[test]
3665     fn test_find_mut() {
3666         let mut m = HashMap::new();
3667         assert!(m.insert(1, 12).is_none());
3668         assert!(m.insert(2, 8).is_none());
3669         assert!(m.insert(5, 14).is_none());
3670         let new = 100;
3671         match m.get_mut(&5) {
3672             None => panic!(),
3673             Some(x) => *x = new,
3674         }
3675         assert_eq!(m.get(&5), Some(&new));
3676     }
3677
3678     #[test]
3679     fn test_insert_overwrite() {
3680         let mut m = HashMap::new();
3681         assert!(m.insert(1, 2).is_none());
3682         assert_eq!(*m.get(&1).unwrap(), 2);
3683         assert!(!m.insert(1, 3).is_none());
3684         assert_eq!(*m.get(&1).unwrap(), 3);
3685     }
3686
3687     #[test]
3688     fn test_insert_conflicts() {
3689         let mut m = HashMap::with_capacity(4);
3690         assert!(m.insert(1, 2).is_none());
3691         assert!(m.insert(5, 3).is_none());
3692         assert!(m.insert(9, 4).is_none());
3693         assert_eq!(*m.get(&9).unwrap(), 4);
3694         assert_eq!(*m.get(&5).unwrap(), 3);
3695         assert_eq!(*m.get(&1).unwrap(), 2);
3696     }
3697
3698     #[test]
3699     fn test_conflict_remove() {
3700         let mut m = HashMap::with_capacity(4);
3701         assert!(m.insert(1, 2).is_none());
3702         assert_eq!(*m.get(&1).unwrap(), 2);
3703         assert!(m.insert(5, 3).is_none());
3704         assert_eq!(*m.get(&1).unwrap(), 2);
3705         assert_eq!(*m.get(&5).unwrap(), 3);
3706         assert!(m.insert(9, 4).is_none());
3707         assert_eq!(*m.get(&1).unwrap(), 2);
3708         assert_eq!(*m.get(&5).unwrap(), 3);
3709         assert_eq!(*m.get(&9).unwrap(), 4);
3710         assert!(m.remove(&1).is_some());
3711         assert_eq!(*m.get(&9).unwrap(), 4);
3712         assert_eq!(*m.get(&5).unwrap(), 3);
3713     }
3714
3715     #[test]
3716     fn test_is_empty() {
3717         let mut m = HashMap::with_capacity(4);
3718         assert!(m.insert(1, 2).is_none());
3719         assert!(!m.is_empty());
3720         assert!(m.remove(&1).is_some());
3721         assert!(m.is_empty());
3722     }
3723
3724     #[test]
3725     fn test_remove() {
3726         let mut m = HashMap::new();
3727         m.insert(1, 2);
3728         assert_eq!(m.remove(&1), Some(2));
3729         assert_eq!(m.remove(&1), None);
3730     }
3731
3732     #[test]
3733     fn test_remove_entry() {
3734         let mut m = HashMap::new();
3735         m.insert(1, 2);
3736         assert_eq!(m.remove_entry(&1), Some((1, 2)));
3737         assert_eq!(m.remove(&1), None);
3738     }
3739
3740     #[test]
3741     fn test_iterate() {
3742         let mut m = HashMap::with_capacity(4);
3743         for i in 0..32 {
3744             assert!(m.insert(i, i*2).is_none());
3745         }
3746         assert_eq!(m.len(), 32);
3747
3748         let mut observed: u32 = 0;
3749
3750         for (k, v) in &m {
3751             assert_eq!(*v, *k * 2);
3752             observed |= 1 << *k;
3753         }
3754         assert_eq!(observed, 0xFFFF_FFFF);
3755     }
3756
3757     #[test]
3758     fn test_keys() {
3759         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3760         let map: HashMap<_, _> = vec.into_iter().collect();
3761         let keys: Vec<_> = map.keys().cloned().collect();
3762         assert_eq!(keys.len(), 3);
3763         assert!(keys.contains(&1));
3764         assert!(keys.contains(&2));
3765         assert!(keys.contains(&3));
3766     }
3767
3768     #[test]
3769     fn test_values() {
3770         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3771         let map: HashMap<_, _> = vec.into_iter().collect();
3772         let values: Vec<_> = map.values().cloned().collect();
3773         assert_eq!(values.len(), 3);
3774         assert!(values.contains(&'a'));
3775         assert!(values.contains(&'b'));
3776         assert!(values.contains(&'c'));
3777     }
3778
3779     #[test]
3780     fn test_values_mut() {
3781         let vec = vec![(1, 1), (2, 2), (3, 3)];
3782         let mut map: HashMap<_, _> = vec.into_iter().collect();
3783         for value in map.values_mut() {
3784             *value = (*value) * 2
3785         }
3786         let values: Vec<_> = map.values().cloned().collect();
3787         assert_eq!(values.len(), 3);
3788         assert!(values.contains(&2));
3789         assert!(values.contains(&4));
3790         assert!(values.contains(&6));
3791     }
3792
3793     #[test]
3794     fn test_find() {
3795         let mut m = HashMap::new();
3796         assert!(m.get(&1).is_none());
3797         m.insert(1, 2);
3798         match m.get(&1) {
3799             None => panic!(),
3800             Some(v) => assert_eq!(*v, 2),
3801         }
3802     }
3803
3804     #[test]
3805     fn test_eq() {
3806         let mut m1 = HashMap::new();
3807         m1.insert(1, 2);
3808         m1.insert(2, 3);
3809         m1.insert(3, 4);
3810
3811         let mut m2 = HashMap::new();
3812         m2.insert(1, 2);
3813         m2.insert(2, 3);
3814
3815         assert!(m1 != m2);
3816
3817         m2.insert(3, 4);
3818
3819         assert_eq!(m1, m2);
3820     }
3821
3822     #[test]
3823     fn test_show() {
3824         let mut map = HashMap::new();
3825         let empty: HashMap<i32, i32> = HashMap::new();
3826
3827         map.insert(1, 2);
3828         map.insert(3, 4);
3829
3830         let map_str = format!("{:?}", map);
3831
3832         assert!(map_str == "{1: 2, 3: 4}" ||
3833                 map_str == "{3: 4, 1: 2}");
3834         assert_eq!(format!("{:?}", empty), "{}");
3835     }
3836
3837     #[test]
3838     fn test_expand() {
3839         let mut m = HashMap::new();
3840
3841         assert_eq!(m.len(), 0);
3842         assert!(m.is_empty());
3843
3844         let mut i = 0;
3845         let old_raw_cap = m.raw_capacity();
3846         while old_raw_cap == m.raw_capacity() {
3847             m.insert(i, i);
3848             i += 1;
3849         }
3850
3851         assert_eq!(m.len(), i);
3852         assert!(!m.is_empty());
3853     }
3854
3855     #[test]
3856     fn test_behavior_resize_policy() {
3857         let mut m = HashMap::new();
3858
3859         assert_eq!(m.len(), 0);
3860         assert_eq!(m.raw_capacity(), 0);
3861         assert!(m.is_empty());
3862
3863         m.insert(0, 0);
3864         m.remove(&0);
3865         assert!(m.is_empty());
3866         let initial_raw_cap = m.raw_capacity();
3867         m.reserve(initial_raw_cap);
3868         let raw_cap = m.raw_capacity();
3869
3870         assert_eq!(raw_cap, initial_raw_cap * 2);
3871
3872         let mut i = 0;
3873         for _ in 0..raw_cap * 3 / 4 {
3874             m.insert(i, i);
3875             i += 1;
3876         }
3877         // three quarters full
3878
3879         assert_eq!(m.len(), i);
3880         assert_eq!(m.raw_capacity(), raw_cap);
3881
3882         for _ in 0..raw_cap / 4 {
3883             m.insert(i, i);
3884             i += 1;
3885         }
3886         // half full
3887
3888         let new_raw_cap = m.raw_capacity();
3889         assert_eq!(new_raw_cap, raw_cap * 2);
3890
3891         for _ in 0..raw_cap / 2 - 1 {
3892             i -= 1;
3893             m.remove(&i);
3894             assert_eq!(m.raw_capacity(), new_raw_cap);
3895         }
3896         // A little more than one quarter full.
3897         m.shrink_to_fit();
3898         assert_eq!(m.raw_capacity(), raw_cap);
3899         // again, a little more than half full
3900         for _ in 0..raw_cap / 2 - 1 {
3901             i -= 1;
3902             m.remove(&i);
3903         }
3904         m.shrink_to_fit();
3905
3906         assert_eq!(m.len(), i);
3907         assert!(!m.is_empty());
3908         assert_eq!(m.raw_capacity(), initial_raw_cap);
3909     }
3910
3911     #[test]
3912     fn test_reserve_shrink_to_fit() {
3913         let mut m = HashMap::new();
3914         m.insert(0, 0);
3915         m.remove(&0);
3916         assert!(m.capacity() >= m.len());
3917         for i in 0..128 {
3918             m.insert(i, i);
3919         }
3920         m.reserve(256);
3921
3922         let usable_cap = m.capacity();
3923         for i in 128..(128 + 256) {
3924             m.insert(i, i);
3925             assert_eq!(m.capacity(), usable_cap);
3926         }
3927
3928         for i in 100..(128 + 256) {
3929             assert_eq!(m.remove(&i), Some(i));
3930         }
3931         m.shrink_to_fit();
3932
3933         assert_eq!(m.len(), 100);
3934         assert!(!m.is_empty());
3935         assert!(m.capacity() >= m.len());
3936
3937         for i in 0..100 {
3938             assert_eq!(m.remove(&i), Some(i));
3939         }
3940         m.shrink_to_fit();
3941         m.insert(0, 0);
3942
3943         assert_eq!(m.len(), 1);
3944         assert!(m.capacity() >= m.len());
3945         assert_eq!(m.remove(&0), Some(0));
3946     }
3947
3948     #[test]
3949     fn test_from_iter() {
3950         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3951
3952         let map: HashMap<_, _> = xs.iter().cloned().collect();
3953
3954         for &(k, v) in &xs {
3955             assert_eq!(map.get(&k), Some(&v));
3956         }
3957     }
3958
3959     #[test]
3960     fn test_size_hint() {
3961         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3962
3963         let map: HashMap<_, _> = xs.iter().cloned().collect();
3964
3965         let mut iter = map.iter();
3966
3967         for _ in iter.by_ref().take(3) {}
3968
3969         assert_eq!(iter.size_hint(), (3, Some(3)));
3970     }
3971
3972     #[test]
3973     fn test_iter_len() {
3974         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3975
3976         let map: HashMap<_, _> = xs.iter().cloned().collect();
3977
3978         let mut iter = map.iter();
3979
3980         for _ in iter.by_ref().take(3) {}
3981
3982         assert_eq!(iter.len(), 3);
3983     }
3984
3985     #[test]
3986     fn test_mut_size_hint() {
3987         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3988
3989         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3990
3991         let mut iter = map.iter_mut();
3992
3993         for _ in iter.by_ref().take(3) {}
3994
3995         assert_eq!(iter.size_hint(), (3, Some(3)));
3996     }
3997
3998     #[test]
3999     fn test_iter_mut_len() {
4000         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
4001
4002         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4003
4004         let mut iter = map.iter_mut();
4005
4006         for _ in iter.by_ref().take(3) {}
4007
4008         assert_eq!(iter.len(), 3);
4009     }
4010
4011     #[test]
4012     fn test_index() {
4013         let mut map = HashMap::new();
4014
4015         map.insert(1, 2);
4016         map.insert(2, 1);
4017         map.insert(3, 4);
4018
4019         assert_eq!(map[&2], 1);
4020     }
4021
4022     #[test]
4023     #[should_panic]
4024     fn test_index_nonexistent() {
4025         let mut map = HashMap::new();
4026
4027         map.insert(1, 2);
4028         map.insert(2, 1);
4029         map.insert(3, 4);
4030
4031         map[&4];
4032     }
4033
4034     #[test]
4035     fn test_entry() {
4036         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4037
4038         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4039
4040         // Existing key (insert)
4041         match map.entry(1) {
4042             Vacant(_) => unreachable!(),
4043             Occupied(mut view) => {
4044                 assert_eq!(view.get(), &10);
4045                 assert_eq!(view.insert(100), 10);
4046             }
4047         }
4048         assert_eq!(map.get(&1).unwrap(), &100);
4049         assert_eq!(map.len(), 6);
4050
4051
4052         // Existing key (update)
4053         match map.entry(2) {
4054             Vacant(_) => unreachable!(),
4055             Occupied(mut view) => {
4056                 let v = view.get_mut();
4057                 let new_v = (*v) * 10;
4058                 *v = new_v;
4059             }
4060         }
4061         assert_eq!(map.get(&2).unwrap(), &200);
4062         assert_eq!(map.len(), 6);
4063
4064         // Existing key (take)
4065         match map.entry(3) {
4066             Vacant(_) => unreachable!(),
4067             Occupied(view) => {
4068                 assert_eq!(view.remove(), 30);
4069             }
4070         }
4071         assert_eq!(map.get(&3), None);
4072         assert_eq!(map.len(), 5);
4073
4074
4075         // Inexistent key (insert)
4076         match map.entry(10) {
4077             Occupied(_) => unreachable!(),
4078             Vacant(view) => {
4079                 assert_eq!(*view.insert(1000), 1000);
4080             }
4081         }
4082         assert_eq!(map.get(&10).unwrap(), &1000);
4083         assert_eq!(map.len(), 6);
4084     }
4085
4086     #[test]
4087     fn test_entry_take_doesnt_corrupt() {
4088         #![allow(deprecated)] //rand
4089         // Test for #19292
4090         fn check(m: &HashMap<i32, ()>) {
4091             for k in m.keys() {
4092                 assert!(m.contains_key(k),
4093                         "{} is in keys() but not in the map?", k);
4094             }
4095         }
4096
4097         let mut m = HashMap::new();
4098         let mut rng = thread_rng();
4099
4100         // Populate the map with some items.
4101         for _ in 0..50 {
4102             let x = rng.gen_range(-10, 10);
4103             m.insert(x, ());
4104         }
4105
4106         for _ in 0..1000 {
4107             let x = rng.gen_range(-10, 10);
4108             match m.entry(x) {
4109                 Vacant(_) => {}
4110                 Occupied(e) => {
4111                     e.remove();
4112                 }
4113             }
4114
4115             check(&m);
4116         }
4117     }
4118
4119     #[test]
4120     fn test_extend_ref() {
4121         let mut a = HashMap::new();
4122         a.insert(1, "one");
4123         let mut b = HashMap::new();
4124         b.insert(2, "two");
4125         b.insert(3, "three");
4126
4127         a.extend(&b);
4128
4129         assert_eq!(a.len(), 3);
4130         assert_eq!(a[&1], "one");
4131         assert_eq!(a[&2], "two");
4132         assert_eq!(a[&3], "three");
4133     }
4134
4135     #[test]
4136     fn test_capacity_not_less_than_len() {
4137         let mut a = HashMap::new();
4138         let mut item = 0;
4139
4140         for _ in 0..116 {
4141             a.insert(item, 0);
4142             item += 1;
4143         }
4144
4145         assert!(a.capacity() > a.len());
4146
4147         let free = a.capacity() - a.len();
4148         for _ in 0..free {
4149             a.insert(item, 0);
4150             item += 1;
4151         }
4152
4153         assert_eq!(a.len(), a.capacity());
4154
4155         // Insert at capacity should cause allocation.
4156         a.insert(item, 0);
4157         assert!(a.capacity() > a.len());
4158     }
4159
4160     #[test]
4161     fn test_occupied_entry_key() {
4162         let mut a = HashMap::new();
4163         let key = "hello there";
4164         let value = "value goes here";
4165         assert!(a.is_empty());
4166         a.insert(key.clone(), value.clone());
4167         assert_eq!(a.len(), 1);
4168         assert_eq!(a[key], value);
4169
4170         match a.entry(key.clone()) {
4171             Vacant(_) => panic!(),
4172             Occupied(e) => assert_eq!(key, *e.key()),
4173         }
4174         assert_eq!(a.len(), 1);
4175         assert_eq!(a[key], value);
4176     }
4177
4178     #[test]
4179     fn test_vacant_entry_key() {
4180         let mut a = HashMap::new();
4181         let key = "hello there";
4182         let value = "value goes here";
4183
4184         assert!(a.is_empty());
4185         match a.entry(key.clone()) {
4186             Occupied(_) => panic!(),
4187             Vacant(e) => {
4188                 assert_eq!(key, *e.key());
4189                 e.insert(value.clone());
4190             }
4191         }
4192         assert_eq!(a.len(), 1);
4193         assert_eq!(a[key], value);
4194     }
4195
4196     #[test]
4197     fn test_retain() {
4198         let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4199
4200         map.retain(|&k, _| k % 2 == 0);
4201         assert_eq!(map.len(), 50);
4202         assert_eq!(map[&2], 20);
4203         assert_eq!(map[&4], 40);
4204         assert_eq!(map[&6], 60);
4205     }
4206
4207     #[test]
4208     fn test_adaptive() {
4209         const TEST_LEN: usize = 5000;
4210         // by cloning we get maps with the same hasher seed
4211         let mut first = HashMap::new();
4212         let mut second = first.clone();
4213         first.extend((0..TEST_LEN).map(|i| (i, i)));
4214         second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4215
4216         for (&k, &v) in &second {
4217             let prev_cap = first.capacity();
4218             let expect_grow = first.len() == prev_cap;
4219             first.insert(k, v);
4220             if !expect_grow && first.capacity() != prev_cap {
4221                 return;
4222             }
4223         }
4224         panic!("Adaptive early resize failed");
4225     }
4226
4227     #[test]
4228     fn test_try_reserve() {
4229
4230         let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4231
4232         const MAX_USIZE: usize = usize::MAX;
4233
4234         // HashMap and RawTables use complicated size calculations
4235         // hashes_size is sizeof(HashUint) * capacity;
4236         // pairs_size is sizeof((K. V)) * capacity;
4237         // alignment_hashes_size is 8
4238         // alignment_pairs size is 4
4239         let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4240         // The following formula is used to calculate the new capacity
4241         let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4242
4243         if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4244         } else { panic!("usize::MAX should trigger an overflow!"); }
4245
4246         if size_of::<usize>() < 8 {
4247             if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4248             } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4249         } else {
4250             if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4251             } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4252         }
4253     }
4254
4255     #[test]
4256     fn test_raw_entry() {
4257         use super::RawEntryMut::{Occupied, Vacant};
4258
4259         let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4260
4261         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4262
4263         let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4264             use core::hash::{BuildHasher, Hash, Hasher};
4265
4266             let mut hasher = map.hasher().build_hasher();
4267             k.hash(&mut hasher);
4268             hasher.finish()
4269         };
4270
4271         // Existing key (insert)
4272         match map.raw_entry_mut().from_key(&1) {
4273             Vacant(_) => unreachable!(),
4274             Occupied(mut view) => {
4275                 assert_eq!(view.get(), &10);
4276                 assert_eq!(view.insert(100), 10);
4277             }
4278         }
4279         let hash1 = compute_hash(&map, 1);
4280         assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4281         assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4282         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4283         assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4284         assert_eq!(map.len(), 6);
4285
4286         // Existing key (update)
4287         match map.raw_entry_mut().from_key(&2) {
4288             Vacant(_) => unreachable!(),
4289             Occupied(mut view) => {
4290                 let v = view.get_mut();
4291                 let new_v = (*v) * 10;
4292                 *v = new_v;
4293             }
4294         }
4295         let hash2 = compute_hash(&map, 2);
4296         assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4297         assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4298         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4299         assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4300         assert_eq!(map.len(), 6);
4301
4302         // Existing key (take)
4303         let hash3 = compute_hash(&map, 3);
4304         match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4305             Vacant(_) => unreachable!(),
4306             Occupied(view) => {
4307                 assert_eq!(view.remove_entry(), (3, 30));
4308             }
4309         }
4310         assert_eq!(map.raw_entry().from_key(&3), None);
4311         assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4312         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4313         assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4314         assert_eq!(map.len(), 5);
4315
4316
4317         // Nonexistent key (insert)
4318         match map.raw_entry_mut().from_key(&10) {
4319             Occupied(_) => unreachable!(),
4320             Vacant(view) => {
4321                 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4322             }
4323         }
4324         assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4325         assert_eq!(map.len(), 6);
4326
4327         // Ensure all lookup methods produce equivalent results.
4328         for k in 0..12 {
4329             let hash = compute_hash(&map, k);
4330             let v = map.get(&k).cloned();
4331             let kv = v.as_ref().map(|v| (&k, v));
4332
4333             assert_eq!(map.raw_entry().from_key(&k), kv);
4334             assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4335             assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4336             assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4337
4338             match map.raw_entry_mut().from_key(&k) {
4339                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4340                 Vacant(_) => assert_eq!(v, None),
4341             }
4342             match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
4343                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4344                 Vacant(_) => assert_eq!(v, None),
4345             }
4346             match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
4347                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4348                 Vacant(_) => assert_eq!(v, None),
4349             }
4350             match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4351                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4352                 Vacant(_) => assert_eq!(v, None),
4353             }
4354         }
4355     }
4356
4357 }