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