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