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