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