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