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