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