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