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