]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Auto merge of #22839 - lifthrasiir:better-backtrace, r=alexcrichton
[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::Borrow;
18 use clone::Clone;
19 use cmp::{max, Eq, PartialEq};
20 use default::Default;
21 use fmt::{self, Debug};
22 use hash::{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     let rp = DefaultResizePolicy;
92     for n in 0..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 README.md
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, Debug)]
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"), 25);
290 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
291 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
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(feature = "rust1", since = "1.0.0")]
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: usize,
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> HashMap<K, V, S>
443     where K: Eq + Hash, S: HashState
444 {
445     fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
446         table::make_hash(&self.hash_state, x)
447     }
448
449     /// Search for a key, yielding the index if it's found in the hashtable.
450     /// If you already have the hash for the key lying around, use
451     /// search_hashed.
452     fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>>
453         where K: Borrow<Q>, Q: Eq + Hash
454     {
455         let hash = self.make_hash(q);
456         search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
457             .into_option()
458     }
459
460     fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>>
461         where K: Borrow<Q>, Q: Eq + Hash
462     {
463         let hash = self.make_hash(q);
464         search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
465             .into_option()
466     }
467
468     // The caller should ensure that invariants by Robin Hood Hashing hold.
469     fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
470         let cap = self.table.capacity();
471         let mut buckets = Bucket::new(&mut self.table, hash);
472         let ib = buckets.index();
473
474         while buckets.index() != ib + cap {
475             // We don't need to compare hashes for value swap.
476             // Not even DIBs for Robin Hood.
477             buckets = match buckets.peek() {
478                 Empty(empty) => {
479                     empty.put(hash, k, v);
480                     return;
481                 }
482                 Full(b) => b.into_bucket()
483             };
484             buckets.next();
485         }
486         panic!("Internal HashMap error: Out of space.");
487     }
488 }
489
490 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
491     /// Create an empty HashMap.
492     ///
493     /// # Example
494     ///
495     /// ```
496     /// use std::collections::HashMap;
497     /// let mut map: HashMap<&str, int> = HashMap::new();
498     /// ```
499     #[inline]
500     #[stable(feature = "rust1", since = "1.0.0")]
501     pub fn new() -> HashMap<K, V, RandomState> {
502         Default::default()
503     }
504
505     /// Creates an empty hash map with the given initial capacity.
506     ///
507     /// # Example
508     ///
509     /// ```
510     /// use std::collections::HashMap;
511     /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
512     /// ```
513     #[inline]
514     #[stable(feature = "rust1", since = "1.0.0")]
515     pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
516         HashMap::with_capacity_and_hash_state(capacity, Default::default())
517     }
518 }
519
520 impl<K, V, S> HashMap<K, V, S>
521     where K: Eq + Hash, S: HashState
522 {
523     /// Creates an empty hashmap which will use the given hasher to hash keys.
524     ///
525     /// The creates map has the default initial capacity.
526     ///
527     /// # Example
528     ///
529     /// ```
530     /// use std::collections::HashMap;
531     /// use std::collections::hash_map::RandomState;
532     ///
533     /// let s = RandomState::new();
534     /// let mut map = HashMap::with_hash_state(s);
535     /// map.insert(1, 2);
536     /// ```
537     #[inline]
538     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
539     pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> {
540         HashMap {
541             hash_state:    hash_state,
542             resize_policy: DefaultResizePolicy::new(),
543             table:         RawTable::new(0),
544         }
545     }
546
547     /// Create an empty HashMap with space for at least `capacity`
548     /// elements, using `hasher` to hash the keys.
549     ///
550     /// Warning: `hasher` is normally randomly generated, and
551     /// is designed to allow HashMaps to be resistant to attacks that
552     /// cause many collisions and very poor performance. Setting it
553     /// manually using this function can expose a DoS attack vector.
554     ///
555     /// # Example
556     ///
557     /// ```
558     /// use std::collections::HashMap;
559     /// use std::collections::hash_map::RandomState;
560     ///
561     /// let s = RandomState::new();
562     /// let mut map = HashMap::with_capacity_and_hash_state(10, s);
563     /// map.insert(1, 2);
564     /// ```
565     #[inline]
566     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
567     pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
568                                         -> HashMap<K, V, S> {
569         let resize_policy = DefaultResizePolicy::new();
570         let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
571         let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
572         assert!(internal_cap >= capacity, "capacity overflow");
573         HashMap {
574             hash_state:    hash_state,
575             resize_policy: resize_policy,
576             table:         RawTable::new(internal_cap),
577         }
578     }
579
580     /// Returns the number of elements the map can hold without reallocating.
581     ///
582     /// # Example
583     ///
584     /// ```
585     /// use std::collections::HashMap;
586     /// let map: HashMap<int, int> = HashMap::with_capacity(100);
587     /// assert!(map.capacity() >= 100);
588     /// ```
589     #[inline]
590     #[stable(feature = "rust1", since = "1.0.0")]
591     pub fn capacity(&self) -> usize {
592         self.resize_policy.usable_capacity(self.table.capacity())
593     }
594
595     /// Reserves capacity for at least `additional` more elements to be inserted
596     /// in the `HashMap`. The collection may reserve more space to avoid
597     /// frequent reallocations.
598     ///
599     /// # Panics
600     ///
601     /// Panics if the new allocation size overflows `usize`.
602     ///
603     /// # Example
604     ///
605     /// ```
606     /// use std::collections::HashMap;
607     /// let mut map: HashMap<&str, int> = HashMap::new();
608     /// map.reserve(10);
609     /// ```
610     #[stable(feature = "rust1", since = "1.0.0")]
611     pub fn reserve(&mut self, additional: usize) {
612         let new_size = self.len().checked_add(additional).expect("capacity overflow");
613         let min_cap = self.resize_policy.min_capacity(new_size);
614
615         // An invalid value shouldn't make us run out of space. This includes
616         // an overflow check.
617         assert!(new_size <= min_cap);
618
619         if self.table.capacity() < min_cap {
620             let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
621             self.resize(new_capacity);
622         }
623     }
624
625     /// Resizes the internal vectors to a new capacity. It's your responsibility to:
626     ///   1) Make sure the new capacity is enough for all the elements, accounting
627     ///      for the load factor.
628     ///   2) Ensure new_capacity is a power of two or zero.
629     fn resize(&mut self, new_capacity: usize) {
630         assert!(self.table.size() <= new_capacity);
631         assert!(new_capacity.is_power_of_two() || new_capacity == 0);
632
633         let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
634         let old_size = old_table.size();
635
636         if old_table.capacity() == 0 || old_table.size() == 0 {
637             return;
638         }
639
640         // Grow the table.
641         // Specialization of the other branch.
642         let mut bucket = Bucket::first(&mut old_table);
643
644         // "So a few of the first shall be last: for many be called,
645         // but few chosen."
646         //
647         // We'll most likely encounter a few buckets at the beginning that
648         // have their initial buckets near the end of the table. They were
649         // placed at the beginning as the probe wrapped around the table
650         // during insertion. We must skip forward to a bucket that won't
651         // get reinserted too early and won't unfairly steal others spot.
652         // This eliminates the need for robin hood.
653         loop {
654             bucket = match bucket.peek() {
655                 Full(full) => {
656                     if full.distance() == 0 {
657                         // This bucket occupies its ideal spot.
658                         // It indicates the start of another "cluster".
659                         bucket = full.into_bucket();
660                         break;
661                     }
662                     // Leaving this bucket in the last cluster for later.
663                     full.into_bucket()
664                 }
665                 Empty(b) => {
666                     // Encountered a hole between clusters.
667                     b.into_bucket()
668                 }
669             };
670             bucket.next();
671         }
672
673         // This is how the buckets might be laid out in memory:
674         // ($ marks an initialized bucket)
675         //  ________________
676         // |$$$_$$$$$$_$$$$$|
677         //
678         // But we've skipped the entire initial cluster of buckets
679         // and will continue iteration in this order:
680         //  ________________
681         //     |$$$$$$_$$$$$
682         //                  ^ wrap around once end is reached
683         //  ________________
684         //  $$$_____________|
685         //    ^ exit once table.size == 0
686         loop {
687             bucket = match bucket.peek() {
688                 Full(bucket) => {
689                     let h = bucket.hash();
690                     let (b, k, v) = bucket.take();
691                     self.insert_hashed_ordered(h, k, v);
692                     {
693                         let t = b.table(); // FIXME "lifetime too short".
694                         if t.size() == 0 { break }
695                     };
696                     b.into_bucket()
697                 }
698                 Empty(b) => b.into_bucket()
699             };
700             bucket.next();
701         }
702
703         assert_eq!(self.table.size(), old_size);
704     }
705
706     /// Shrinks the capacity of the map as much as possible. It will drop
707     /// down as much as possible while maintaining the internal rules
708     /// and possibly leaving some space in accordance with the resize policy.
709     ///
710     /// # Example
711     ///
712     /// ```
713     /// use std::collections::HashMap;
714     ///
715     /// let mut map: HashMap<int, int> = HashMap::with_capacity(100);
716     /// map.insert(1, 2);
717     /// map.insert(3, 4);
718     /// assert!(map.capacity() >= 100);
719     /// map.shrink_to_fit();
720     /// assert!(map.capacity() >= 2);
721     /// ```
722     #[stable(feature = "rust1", since = "1.0.0")]
723     pub fn shrink_to_fit(&mut self) {
724         let min_capacity = self.resize_policy.min_capacity(self.len());
725         let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
726
727         // An invalid value shouldn't make us run out of space.
728         debug_assert!(self.len() <= min_capacity);
729
730         if self.table.capacity() != min_capacity {
731             let old_table = replace(&mut self.table, RawTable::new(min_capacity));
732             let old_size = old_table.size();
733
734             // Shrink the table. Naive algorithm for resizing:
735             for (h, k, v) in old_table.into_iter() {
736                 self.insert_hashed_nocheck(h, k, v);
737             }
738
739             debug_assert_eq!(self.table.size(), old_size);
740         }
741     }
742
743     /// Insert a pre-hashed key-value pair, without first checking
744     /// that there's enough room in the buckets. Returns a reference to the
745     /// newly insert value.
746     ///
747     /// If the key already exists, the hashtable will be returned untouched
748     /// and a reference to the existing element will be returned.
749     fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> &mut V {
750         self.insert_or_replace_with(hash, k, v, |_, _, _| ())
751     }
752
753     fn insert_or_replace_with<'a, F>(&'a mut self,
754                                      hash: SafeHash,
755                                      k: K,
756                                      v: V,
757                                      mut found_existing: F)
758                                      -> &'a mut V where
759         F: FnMut(&mut K, &mut V, V),
760     {
761         // Worst case, we'll find one empty bucket among `size + 1` buckets.
762         let size = self.table.size();
763         let mut probe = Bucket::new(&mut self.table, hash);
764         let ib = probe.index();
765
766         loop {
767             let mut bucket = match probe.peek() {
768                 Empty(bucket) => {
769                     // Found a hole!
770                     return bucket.put(hash, k, v).into_mut_refs().1;
771                 }
772                 Full(bucket) => bucket
773             };
774
775             // hash matches?
776             if bucket.hash() == hash {
777                 // key matches?
778                 if k == *bucket.read_mut().0 {
779                     let (bucket_k, bucket_v) = bucket.into_mut_refs();
780                     debug_assert!(k == *bucket_k);
781                     // Key already exists. Get its reference.
782                     found_existing(bucket_k, bucket_v, v);
783                     return bucket_v;
784                 }
785             }
786
787             let robin_ib = bucket.index() as int - bucket.distance() as int;
788
789             if (ib as int) < robin_ib {
790                 // Found a luckier bucket than me. Better steal his spot.
791                 return robin_hood(bucket, robin_ib as usize, hash, k, v);
792             }
793
794             probe = bucket.next();
795             assert!(probe.index() != ib + size + 1);
796         }
797     }
798
799     /// An iterator visiting all keys in arbitrary order.
800     /// Iterator element type is `&'a K`.
801     ///
802     /// # Example
803     ///
804     /// ```
805     /// use std::collections::HashMap;
806     ///
807     /// let mut map = HashMap::new();
808     /// map.insert("a", 1);
809     /// map.insert("b", 2);
810     /// map.insert("c", 3);
811     ///
812     /// for key in map.keys() {
813     ///     println!("{}", key);
814     /// }
815     /// ```
816     #[stable(feature = "rust1", since = "1.0.0")]
817     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
818         fn first<A, B>((a, _): (A, B)) -> A { a }
819         let first: fn((&'a K,&'a V)) -> &'a K = first; // coerce to fn ptr
820
821         Keys { inner: self.iter().map(first) }
822     }
823
824     /// An iterator visiting all values in arbitrary order.
825     /// Iterator element type is `&'a V`.
826     ///
827     /// # Example
828     ///
829     /// ```
830     /// use std::collections::HashMap;
831     ///
832     /// let mut map = HashMap::new();
833     /// map.insert("a", 1);
834     /// map.insert("b", 2);
835     /// map.insert("c", 3);
836     ///
837     /// for val in map.values() {
838     ///     println!("{}", val);
839     /// }
840     /// ```
841     #[stable(feature = "rust1", since = "1.0.0")]
842     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
843         fn second<A, B>((_, b): (A, B)) -> B { b }
844         let second: fn((&'a K,&'a V)) -> &'a V = second; // coerce to fn ptr
845
846         Values { inner: self.iter().map(second) }
847     }
848
849     /// An iterator visiting all key-value pairs in arbitrary order.
850     /// Iterator element type is `(&'a K, &'a V)`.
851     ///
852     /// # Example
853     ///
854     /// ```
855     /// use std::collections::HashMap;
856     ///
857     /// let mut map = HashMap::new();
858     /// map.insert("a", 1);
859     /// map.insert("b", 2);
860     /// map.insert("c", 3);
861     ///
862     /// for (key, val) in map.iter() {
863     ///     println!("key: {} val: {}", key, val);
864     /// }
865     /// ```
866     #[stable(feature = "rust1", since = "1.0.0")]
867     pub fn iter(&self) -> Iter<K, V> {
868         Iter { inner: self.table.iter() }
869     }
870
871     /// An iterator visiting all key-value pairs in arbitrary order,
872     /// with mutable references to the values.
873     /// Iterator element type is `(&'a K, &'a mut V)`.
874     ///
875     /// # Example
876     ///
877     /// ```
878     /// use std::collections::HashMap;
879     ///
880     /// let mut map = HashMap::new();
881     /// map.insert("a", 1);
882     /// map.insert("b", 2);
883     /// map.insert("c", 3);
884     ///
885     /// // Update all values
886     /// for (_, val) in map.iter_mut() {
887     ///     *val *= 2;
888     /// }
889     ///
890     /// for (key, val) in map.iter() {
891     ///     println!("key: {} val: {}", key, val);
892     /// }
893     /// ```
894     #[stable(feature = "rust1", since = "1.0.0")]
895     pub fn iter_mut(&mut self) -> IterMut<K, V> {
896         IterMut { inner: self.table.iter_mut() }
897     }
898
899     /// Creates a consuming iterator, that is, one that moves each key-value
900     /// pair out of the map in arbitrary order. The map cannot be used after
901     /// calling this.
902     ///
903     /// # Example
904     ///
905     /// ```
906     /// use std::collections::HashMap;
907     ///
908     /// let mut map = HashMap::new();
909     /// map.insert("a", 1);
910     /// map.insert("b", 2);
911     /// map.insert("c", 3);
912     ///
913     /// // Not possible with .iter()
914     /// let vec: Vec<(&str, int)> = map.into_iter().collect();
915     /// ```
916     #[stable(feature = "rust1", since = "1.0.0")]
917     pub fn into_iter(self) -> IntoIter<K, V> {
918         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
919         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two;
920
921         IntoIter {
922             inner: self.table.into_iter().map(last_two)
923         }
924     }
925
926     /// Gets the given key's corresponding entry in the map for in-place manipulation.
927     #[stable(feature = "rust1", since = "1.0.0")]
928     pub fn entry(&mut self, key: K) -> Entry<K, V> {
929         // Gotta resize now.
930         self.reserve(1);
931
932         let hash = self.make_hash(&key);
933         search_entry_hashed(&mut self.table, hash, key)
934     }
935
936     /// Returns the number of elements in the map.
937     ///
938     /// # Example
939     ///
940     /// ```
941     /// use std::collections::HashMap;
942     ///
943     /// let mut a = HashMap::new();
944     /// assert_eq!(a.len(), 0);
945     /// a.insert(1, "a");
946     /// assert_eq!(a.len(), 1);
947     /// ```
948     #[stable(feature = "rust1", since = "1.0.0")]
949     pub fn len(&self) -> usize { self.table.size() }
950
951     /// Returns true if the map contains no elements.
952     ///
953     /// # Example
954     ///
955     /// ```
956     /// use std::collections::HashMap;
957     ///
958     /// let mut a = HashMap::new();
959     /// assert!(a.is_empty());
960     /// a.insert(1, "a");
961     /// assert!(!a.is_empty());
962     /// ```
963     #[inline]
964     #[stable(feature = "rust1", since = "1.0.0")]
965     pub fn is_empty(&self) -> bool { self.len() == 0 }
966
967     /// Clears the map, returning all key-value pairs as an iterator. Keeps the
968     /// allocated memory for reuse.
969     ///
970     /// # Example
971     ///
972     /// ```
973     /// use std::collections::HashMap;
974     ///
975     /// let mut a = HashMap::new();
976     /// a.insert(1, "a");
977     /// a.insert(2, "b");
978     ///
979     /// for (k, v) in a.drain().take(1) {
980     ///     assert!(k == 1 || k == 2);
981     ///     assert!(v == "a" || v == "b");
982     /// }
983     ///
984     /// assert!(a.is_empty());
985     /// ```
986     #[inline]
987     #[unstable(feature = "std_misc",
988                reason = "matches collection reform specification, waiting for dust to settle")]
989     pub fn drain(&mut self) -> Drain<K, V> {
990         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
991         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two; // coerce to fn pointer
992
993         Drain {
994             inner: self.table.drain().map(last_two),
995         }
996     }
997
998     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
999     /// for reuse.
1000     ///
1001     /// # Example
1002     ///
1003     /// ```
1004     /// use std::collections::HashMap;
1005     ///
1006     /// let mut a = HashMap::new();
1007     /// a.insert(1, "a");
1008     /// a.clear();
1009     /// assert!(a.is_empty());
1010     /// ```
1011     #[stable(feature = "rust1", since = "1.0.0")]
1012     #[inline]
1013     pub fn clear(&mut self) {
1014         self.drain();
1015     }
1016
1017     /// Returns a reference to the value corresponding to the key.
1018     ///
1019     /// The key may be any borrowed form of the map's key type, but
1020     /// `Hash` and `Eq` on the borrowed form *must* match those for
1021     /// the key type.
1022     ///
1023     /// # Example
1024     ///
1025     /// ```
1026     /// use std::collections::HashMap;
1027     ///
1028     /// let mut map = HashMap::new();
1029     /// map.insert(1, "a");
1030     /// assert_eq!(map.get(&1), Some(&"a"));
1031     /// assert_eq!(map.get(&2), None);
1032     /// ```
1033     #[stable(feature = "rust1", since = "1.0.0")]
1034     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1035         where K: Borrow<Q>, Q: Hash + Eq
1036     {
1037         self.search(k).map(|bucket| bucket.into_refs().1)
1038     }
1039
1040     /// Returns true if the map contains a value for the specified key.
1041     ///
1042     /// The key may be any borrowed form of the map's key type, but
1043     /// `Hash` and `Eq` on the borrowed form *must* match those for
1044     /// the key type.
1045     ///
1046     /// # Example
1047     ///
1048     /// ```
1049     /// use std::collections::HashMap;
1050     ///
1051     /// let mut map = HashMap::new();
1052     /// map.insert(1, "a");
1053     /// assert_eq!(map.contains_key(&1), true);
1054     /// assert_eq!(map.contains_key(&2), false);
1055     /// ```
1056     #[stable(feature = "rust1", since = "1.0.0")]
1057     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1058         where K: Borrow<Q>, Q: Hash + Eq
1059     {
1060         self.search(k).is_some()
1061     }
1062
1063     /// Returns a mutable reference to the value corresponding to the key.
1064     ///
1065     /// The key may be any borrowed form of the map's key type, but
1066     /// `Hash` and `Eq` on the borrowed form *must* match those for
1067     /// the key type.
1068     ///
1069     /// # Example
1070     ///
1071     /// ```
1072     /// use std::collections::HashMap;
1073     ///
1074     /// let mut map = HashMap::new();
1075     /// map.insert(1, "a");
1076     /// match map.get_mut(&1) {
1077     ///     Some(x) => *x = "b",
1078     ///     None => (),
1079     /// }
1080     /// assert_eq!(map[1], "b");
1081     /// ```
1082     #[stable(feature = "rust1", since = "1.0.0")]
1083     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1084         where K: Borrow<Q>, Q: Hash + Eq
1085     {
1086         self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1087     }
1088
1089     /// Inserts a key-value pair from the map. If the key already had a value
1090     /// present in the map, that value is returned. Otherwise, `None` is returned.
1091     ///
1092     /// # Example
1093     ///
1094     /// ```
1095     /// use std::collections::HashMap;
1096     ///
1097     /// let mut map = HashMap::new();
1098     /// assert_eq!(map.insert(37, "a"), None);
1099     /// assert_eq!(map.is_empty(), false);
1100     ///
1101     /// map.insert(37, "b");
1102     /// assert_eq!(map.insert(37, "c"), Some("b"));
1103     /// assert_eq!(map[37], "c");
1104     /// ```
1105     #[stable(feature = "rust1", since = "1.0.0")]
1106     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1107         let hash = self.make_hash(&k);
1108         self.reserve(1);
1109
1110         let mut retval = None;
1111         self.insert_or_replace_with(hash, k, v, |_, val_ref, val| {
1112             retval = Some(replace(val_ref, val));
1113         });
1114         retval
1115     }
1116
1117     /// Removes a key from the map, returning the value at the key if the key
1118     /// was previously in the map.
1119     ///
1120     /// The key may be any borrowed form of the map's key type, but
1121     /// `Hash` and `Eq` on the borrowed form *must* match those for
1122     /// the key type.
1123     ///
1124     /// # Example
1125     ///
1126     /// ```
1127     /// use std::collections::HashMap;
1128     ///
1129     /// let mut map = HashMap::new();
1130     /// map.insert(1, "a");
1131     /// assert_eq!(map.remove(&1), Some("a"));
1132     /// assert_eq!(map.remove(&1), None);
1133     /// ```
1134     #[stable(feature = "rust1", since = "1.0.0")]
1135     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1136         where K: Borrow<Q>, Q: Hash + Eq
1137     {
1138         if self.table.size() == 0 {
1139             return None
1140         }
1141
1142         self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1143     }
1144 }
1145
1146 fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)
1147         -> Entry<'a, K, V>
1148 {
1149     // Worst case, we'll find one empty bucket among `size + 1` buckets.
1150     let size = table.size();
1151     let mut probe = Bucket::new(table, hash);
1152     let ib = probe.index();
1153
1154     loop {
1155         let bucket = match probe.peek() {
1156             Empty(bucket) => {
1157                 // Found a hole!
1158                 return Vacant(VacantEntry {
1159                     hash: hash,
1160                     key: k,
1161                     elem: NoElem(bucket),
1162                 });
1163             },
1164             Full(bucket) => bucket
1165         };
1166
1167         // hash matches?
1168         if bucket.hash() == hash {
1169             // key matches?
1170             if k == *bucket.read().0 {
1171                 return Occupied(OccupiedEntry{
1172                     elem: bucket,
1173                 });
1174             }
1175         }
1176
1177         let robin_ib = bucket.index() as int - bucket.distance() as int;
1178
1179         if (ib as int) < robin_ib {
1180             // Found a luckier bucket than me. Better steal his spot.
1181             return Vacant(VacantEntry {
1182                 hash: hash,
1183                 key: k,
1184                 elem: NeqElem(bucket, robin_ib as usize),
1185             });
1186         }
1187
1188         probe = bucket.next();
1189         assert!(probe.index() != ib + size + 1);
1190     }
1191 }
1192
1193 impl<K, V, S> PartialEq for HashMap<K, V, S>
1194     where K: Eq + Hash, V: PartialEq, S: HashState
1195 {
1196     fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1197         if self.len() != other.len() { return false; }
1198
1199         self.iter().all(|(key, value)|
1200             other.get(key).map_or(false, |v| *value == *v)
1201         )
1202     }
1203 }
1204
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<K, V, S> Eq for HashMap<K, V, S>
1207     where K: Eq + Hash, V: Eq, S: HashState
1208 {}
1209
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<K, V, S> Debug for HashMap<K, V, S>
1212     where K: Eq + Hash + Debug, V: Debug, S: HashState
1213 {
1214     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1215         try!(write!(f, "{{"));
1216
1217         for (i, (k, v)) in self.iter().enumerate() {
1218             if i != 0 { try!(write!(f, ", ")); }
1219             try!(write!(f, "{:?}: {:?}", *k, *v));
1220         }
1221
1222         write!(f, "}}")
1223     }
1224 }
1225
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<K, V, S> Default for HashMap<K, V, S>
1228     where K: Eq + Hash,
1229           S: HashState + Default,
1230 {
1231     fn default() -> HashMap<K, V, S> {
1232         HashMap::with_hash_state(Default::default())
1233     }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<K, Q: ?Sized, V, S> Index<Q> for HashMap<K, V, S>
1238     where K: Eq + Hash + Borrow<Q>,
1239           Q: Eq + Hash,
1240           S: HashState,
1241 {
1242     type Output = V;
1243
1244     #[inline]
1245     fn index<'a>(&'a self, index: &Q) -> &'a V {
1246         self.get(index).expect("no entry found for key")
1247     }
1248 }
1249
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<K, V, S, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
1252     where K: Eq + Hash + Borrow<Q>,
1253           Q: Eq + Hash,
1254           S: HashState,
1255 {
1256     #[inline]
1257     fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
1258         self.get_mut(index).expect("no entry found for key")
1259     }
1260 }
1261
1262 /// HashMap iterator.
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 pub struct Iter<'a, K: 'a, V: 'a> {
1265     inner: table::Iter<'a, K, V>
1266 }
1267
1268 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1269 impl<'a, K, V> Clone for Iter<'a, K, V> {
1270     fn clone(&self) -> Iter<'a, K, V> {
1271         Iter {
1272             inner: self.inner.clone()
1273         }
1274     }
1275 }
1276
1277 /// HashMap mutable values iterator.
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub struct IterMut<'a, K: 'a, V: 'a> {
1280     inner: table::IterMut<'a, K, V>
1281 }
1282
1283 /// HashMap move iterator.
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub struct IntoIter<K, V> {
1286     inner: iter::Map<table::IntoIter<K, V>, fn((SafeHash, K, V)) -> (K, V)>
1287 }
1288
1289 /// HashMap keys iterator.
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub struct Keys<'a, K: 'a, V: 'a> {
1292     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
1293 }
1294
1295 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1296 impl<'a, K, V> Clone for Keys<'a, K, V> {
1297     fn clone(&self) -> Keys<'a, K, V> {
1298         Keys {
1299             inner: self.inner.clone()
1300         }
1301     }
1302 }
1303
1304 /// HashMap values iterator.
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub struct Values<'a, K: 'a, V: 'a> {
1307     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
1308 }
1309
1310 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1311 impl<'a, K, V> Clone for Values<'a, K, V> {
1312     fn clone(&self) -> Values<'a, K, V> {
1313         Values {
1314             inner: self.inner.clone()
1315         }
1316     }
1317 }
1318
1319 /// HashMap drain iterator.
1320 #[unstable(feature = "std_misc",
1321            reason = "matches collection reform specification, waiting for dust to settle")]
1322 pub struct Drain<'a, K: 'a, V: 'a> {
1323     inner: iter::Map<table::Drain<'a, K, V>, fn((SafeHash, K, V)) -> (K, V)>
1324 }
1325
1326 /// A view into a single occupied location in a HashMap.
1327 #[unstable(feature = "std_misc",
1328            reason = "precise API still being fleshed out")]
1329 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1330     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1331 }
1332
1333 /// A view into a single empty location in a HashMap.
1334 #[unstable(feature = "std_misc",
1335            reason = "precise API still being fleshed out")]
1336 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1337     hash: SafeHash,
1338     key: K,
1339     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1340 }
1341
1342 /// A view into a single location in a map, which may be vacant or occupied.
1343 #[unstable(feature = "std_misc",
1344            reason = "precise API still being fleshed out")]
1345 pub enum Entry<'a, K: 'a, V: 'a> {
1346     /// An occupied Entry.
1347     Occupied(OccupiedEntry<'a, K, V>),
1348     /// A vacant Entry.
1349     Vacant(VacantEntry<'a, K, V>),
1350 }
1351
1352 /// Possible states of a VacantEntry.
1353 enum VacantEntryState<K, V, M> {
1354     /// The index is occupied, but the key to insert has precedence,
1355     /// and will kick the current one out on insertion.
1356     NeqElem(FullBucket<K, V, M>, usize),
1357     /// The index is genuinely vacant.
1358     NoElem(EmptyBucket<K, V, M>),
1359 }
1360
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1363     where K: Eq + Hash, S: HashState
1364 {
1365     type Item = (&'a K, &'a V);
1366     type IntoIter = Iter<'a, K, V>;
1367
1368     fn into_iter(self) -> Iter<'a, K, V> {
1369         self.iter()
1370     }
1371 }
1372
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1375     where K: Eq + Hash, S: HashState
1376 {
1377     type Item = (&'a K, &'a mut V);
1378     type IntoIter = IterMut<'a, K, V>;
1379
1380     fn into_iter(mut self) -> IterMut<'a, K, V> {
1381         self.iter_mut()
1382     }
1383 }
1384
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1387     where K: Eq + Hash, S: HashState
1388 {
1389     type Item = (K, V);
1390     type IntoIter = IntoIter<K, V>;
1391
1392     fn into_iter(self) -> IntoIter<K, V> {
1393         self.into_iter()
1394     }
1395 }
1396
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1399     type Item = (&'a K, &'a V);
1400
1401     #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1402     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1403 }
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1406     #[inline] fn len(&self) -> usize { self.inner.len() }
1407 }
1408
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1411     type Item = (&'a K, &'a mut V);
1412
1413     #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1414     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1415 }
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1418     #[inline] fn len(&self) -> usize { self.inner.len() }
1419 }
1420
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<K, V> Iterator for IntoIter<K, V> {
1423     type Item = (K, V);
1424
1425     #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1426     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1427 }
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1430     #[inline] fn len(&self) -> usize { self.inner.len() }
1431 }
1432
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1435     type Item = &'a K;
1436
1437     #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1438     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1439 }
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1442     #[inline] fn len(&self) -> usize { self.inner.len() }
1443 }
1444
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl<'a, K, V> Iterator for Values<'a, K, V> {
1447     type Item = &'a V;
1448
1449     #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1450     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1451 }
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1454     #[inline] fn len(&self) -> usize { self.inner.len() }
1455 }
1456
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1459     type Item = (K, V);
1460
1461     #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1462     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1463 }
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1466     #[inline] fn len(&self) -> usize { self.inner.len() }
1467 }
1468
1469 #[unstable(feature = "std_misc",
1470            reason = "matches collection reform v2 specification, waiting for dust to settle")]
1471 impl<'a, K, V> Entry<'a, K, V> {
1472     /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant.
1473     pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1474         match self {
1475             Occupied(entry) => Ok(entry.into_mut()),
1476             Vacant(entry) => Err(entry),
1477         }
1478     }
1479 }
1480
1481 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1482     /// Gets a reference to the value in the entry.
1483     #[stable(feature = "rust1", since = "1.0.0")]
1484     pub fn get(&self) -> &V {
1485         self.elem.read().1
1486     }
1487
1488     /// Gets a mutable reference to the value in the entry.
1489     #[stable(feature = "rust1", since = "1.0.0")]
1490     pub fn get_mut(&mut self) -> &mut V {
1491         self.elem.read_mut().1
1492     }
1493
1494     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1495     /// with a lifetime bound to the map itself
1496     #[stable(feature = "rust1", since = "1.0.0")]
1497     pub fn into_mut(self) -> &'a mut V {
1498         self.elem.into_mut_refs().1
1499     }
1500
1501     /// Sets the value of the entry, and returns the entry's old value
1502     #[stable(feature = "rust1", since = "1.0.0")]
1503     pub fn insert(&mut self, mut value: V) -> V {
1504         let old_value = self.get_mut();
1505         mem::swap(&mut value, old_value);
1506         value
1507     }
1508
1509     /// Takes the value out of the entry, and returns it
1510     #[stable(feature = "rust1", since = "1.0.0")]
1511     pub fn remove(self) -> V {
1512         pop_internal(self.elem).1
1513     }
1514 }
1515
1516 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1517     /// Sets the value of the entry with the VacantEntry's key,
1518     /// and returns a mutable reference to it
1519     #[stable(feature = "rust1", since = "1.0.0")]
1520     pub fn insert(self, value: V) -> &'a mut V {
1521         match self.elem {
1522             NeqElem(bucket, ib) => {
1523                 robin_hood(bucket, ib, self.hash, self.key, value)
1524             }
1525             NoElem(bucket) => {
1526                 bucket.put(self.hash, self.key, value).into_mut_refs().1
1527             }
1528         }
1529     }
1530 }
1531
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1534     where K: Eq + Hash, S: HashState + Default
1535 {
1536     fn from_iter<T: IntoIterator<Item=(K, V)>>(iterable: T) -> HashMap<K, V, S> {
1537         let iter = iterable.into_iter();
1538         let lower = iter.size_hint().0;
1539         let mut map = HashMap::with_capacity_and_hash_state(lower,
1540                                                             Default::default());
1541         map.extend(iter);
1542         map
1543     }
1544 }
1545
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1548     where K: Eq + Hash, S: HashState
1549 {
1550     fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1551         for (k, v) in iter {
1552             self.insert(k, v);
1553         }
1554     }
1555 }
1556
1557
1558 /// `RandomState` is the default state for `HashMap` types.
1559 ///
1560 /// A particular instance `RandomState` will create the same instances of
1561 /// `Hasher`, but the hashers created by two different `RandomState`
1562 /// instances are unlikely to produce the same result for the same values.
1563 #[derive(Clone)]
1564 #[unstable(feature = "std_misc",
1565            reason = "hashing an hash maps may be altered")]
1566 pub struct RandomState {
1567     k0: u64,
1568     k1: u64,
1569 }
1570
1571 #[unstable(feature = "std_misc",
1572            reason = "hashing an hash maps may be altered")]
1573 impl RandomState {
1574     /// Construct a new `RandomState` that is initialized with random keys.
1575     #[inline]
1576     #[allow(deprecated)]
1577     pub fn new() -> RandomState {
1578         let mut r = rand::thread_rng();
1579         RandomState { k0: r.gen(), k1: r.gen() }
1580     }
1581 }
1582
1583 #[unstable(feature = "std_misc",
1584            reason = "hashing an hash maps may be altered")]
1585 impl HashState for RandomState {
1586     type Hasher = SipHasher;
1587     fn hasher(&self) -> SipHasher {
1588         SipHasher::new_with_keys(self.k0, self.k1)
1589     }
1590 }
1591
1592 #[unstable(feature = "std_misc",
1593            reason = "hashing an hash maps may be altered")]
1594 impl Default for RandomState {
1595     #[inline]
1596     fn default() -> RandomState {
1597         RandomState::new()
1598     }
1599 }
1600
1601 #[cfg(test)]
1602 mod test_map {
1603     use prelude::v1::*;
1604
1605     use super::HashMap;
1606     use super::Entry::{Occupied, Vacant};
1607     use iter::{range_inclusive, range_step_inclusive, repeat};
1608     use cell::RefCell;
1609     use rand::{weak_rng, Rng};
1610
1611     #[test]
1612     fn test_create_capacity_zero() {
1613         let mut m = HashMap::with_capacity(0);
1614
1615         assert!(m.insert(1, 1).is_none());
1616
1617         assert!(m.contains_key(&1));
1618         assert!(!m.contains_key(&0));
1619     }
1620
1621     #[test]
1622     fn test_insert() {
1623         let mut m = HashMap::new();
1624         assert_eq!(m.len(), 0);
1625         assert!(m.insert(1, 2).is_none());
1626         assert_eq!(m.len(), 1);
1627         assert!(m.insert(2, 4).is_none());
1628         assert_eq!(m.len(), 2);
1629         assert_eq!(*m.get(&1).unwrap(), 2);
1630         assert_eq!(*m.get(&2).unwrap(), 4);
1631     }
1632
1633     thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
1634
1635     #[derive(Hash, PartialEq, Eq)]
1636     struct Dropable {
1637         k: usize
1638     }
1639
1640     impl Dropable {
1641         fn new(k: usize) -> Dropable {
1642             DROP_VECTOR.with(|slot| {
1643                 slot.borrow_mut()[k] += 1;
1644             });
1645
1646             Dropable { k: k }
1647         }
1648     }
1649
1650     impl Drop for Dropable {
1651         fn drop(&mut self) {
1652             DROP_VECTOR.with(|slot| {
1653                 slot.borrow_mut()[self.k] -= 1;
1654             });
1655         }
1656     }
1657
1658     impl Clone for Dropable {
1659         fn clone(&self) -> Dropable {
1660             Dropable::new(self.k)
1661         }
1662     }
1663
1664     #[test]
1665     fn test_drops() {
1666         DROP_VECTOR.with(|slot| {
1667             *slot.borrow_mut() = repeat(0).take(200).collect();
1668         });
1669
1670         {
1671             let mut m = HashMap::new();
1672
1673             DROP_VECTOR.with(|v| {
1674                 for i in 0..200 {
1675                     assert_eq!(v.borrow()[i], 0);
1676                 }
1677             });
1678
1679             for i in 0..100 {
1680                 let d1 = Dropable::new(i);
1681                 let d2 = Dropable::new(i+100);
1682                 m.insert(d1, d2);
1683             }
1684
1685             DROP_VECTOR.with(|v| {
1686                 for i in 0..200 {
1687                     assert_eq!(v.borrow()[i], 1);
1688                 }
1689             });
1690
1691             for i in 0..50 {
1692                 let k = Dropable::new(i);
1693                 let v = m.remove(&k);
1694
1695                 assert!(v.is_some());
1696
1697                 DROP_VECTOR.with(|v| {
1698                     assert_eq!(v.borrow()[i], 1);
1699                     assert_eq!(v.borrow()[i+100], 1);
1700                 });
1701             }
1702
1703             DROP_VECTOR.with(|v| {
1704                 for i in 0..50 {
1705                     assert_eq!(v.borrow()[i], 0);
1706                     assert_eq!(v.borrow()[i+100], 0);
1707                 }
1708
1709                 for i in 50..100 {
1710                     assert_eq!(v.borrow()[i], 1);
1711                     assert_eq!(v.borrow()[i+100], 1);
1712                 }
1713             });
1714         }
1715
1716         DROP_VECTOR.with(|v| {
1717             for i in 0..200 {
1718                 assert_eq!(v.borrow()[i], 0);
1719             }
1720         });
1721     }
1722
1723     #[test]
1724     fn test_move_iter_drops() {
1725         DROP_VECTOR.with(|v| {
1726             *v.borrow_mut() = repeat(0).take(200).collect();
1727         });
1728
1729         let hm = {
1730             let mut hm = HashMap::new();
1731
1732             DROP_VECTOR.with(|v| {
1733                 for i in 0..200 {
1734                     assert_eq!(v.borrow()[i], 0);
1735                 }
1736             });
1737
1738             for i in 0..100 {
1739                 let d1 = Dropable::new(i);
1740                 let d2 = Dropable::new(i+100);
1741                 hm.insert(d1, d2);
1742             }
1743
1744             DROP_VECTOR.with(|v| {
1745                 for i in 0..200 {
1746                     assert_eq!(v.borrow()[i], 1);
1747                 }
1748             });
1749
1750             hm
1751         };
1752
1753         // By the way, ensure that cloning doesn't screw up the dropping.
1754         drop(hm.clone());
1755
1756         {
1757             let mut half = hm.into_iter().take(50);
1758
1759             DROP_VECTOR.with(|v| {
1760                 for i in 0..200 {
1761                     assert_eq!(v.borrow()[i], 1);
1762                 }
1763             });
1764
1765             for _ in half.by_ref() {}
1766
1767             DROP_VECTOR.with(|v| {
1768                 let nk = (0..100).filter(|&i| {
1769                     v.borrow()[i] == 1
1770                 }).count();
1771
1772                 let nv = (0..100).filter(|&i| {
1773                     v.borrow()[i+100] == 1
1774                 }).count();
1775
1776                 assert_eq!(nk, 50);
1777                 assert_eq!(nv, 50);
1778             });
1779         };
1780
1781         DROP_VECTOR.with(|v| {
1782             for i in 0..200 {
1783                 assert_eq!(v.borrow()[i], 0);
1784             }
1785         });
1786     }
1787
1788     #[test]
1789     fn test_empty_pop() {
1790         let mut m: HashMap<int, bool> = HashMap::new();
1791         assert_eq!(m.remove(&0), None);
1792     }
1793
1794     #[test]
1795     fn test_lots_of_insertions() {
1796         let mut m = HashMap::new();
1797
1798         // Try this a few times to make sure we never screw up the hashmap's
1799         // internal state.
1800         for _ in 0..10 {
1801             assert!(m.is_empty());
1802
1803             for i in range_inclusive(1, 1000) {
1804                 assert!(m.insert(i, i).is_none());
1805
1806                 for j in range_inclusive(1, i) {
1807                     let r = m.get(&j);
1808                     assert_eq!(r, Some(&j));
1809                 }
1810
1811                 for j in range_inclusive(i+1, 1000) {
1812                     let r = m.get(&j);
1813                     assert_eq!(r, None);
1814                 }
1815             }
1816
1817             for i in range_inclusive(1001, 2000) {
1818                 assert!(!m.contains_key(&i));
1819             }
1820
1821             // remove forwards
1822             for i in range_inclusive(1, 1000) {
1823                 assert!(m.remove(&i).is_some());
1824
1825                 for j in range_inclusive(1, i) {
1826                     assert!(!m.contains_key(&j));
1827                 }
1828
1829                 for j in range_inclusive(i+1, 1000) {
1830                     assert!(m.contains_key(&j));
1831                 }
1832             }
1833
1834             for i in range_inclusive(1, 1000) {
1835                 assert!(!m.contains_key(&i));
1836             }
1837
1838             for i in range_inclusive(1, 1000) {
1839                 assert!(m.insert(i, i).is_none());
1840             }
1841
1842             // remove backwards
1843             for i in range_step_inclusive(1000, 1, -1) {
1844                 assert!(m.remove(&i).is_some());
1845
1846                 for j in range_inclusive(i, 1000) {
1847                     assert!(!m.contains_key(&j));
1848                 }
1849
1850                 for j in range_inclusive(1, i-1) {
1851                     assert!(m.contains_key(&j));
1852                 }
1853             }
1854         }
1855     }
1856
1857     #[test]
1858     fn test_find_mut() {
1859         let mut m = HashMap::new();
1860         assert!(m.insert(1, 12).is_none());
1861         assert!(m.insert(2, 8).is_none());
1862         assert!(m.insert(5, 14).is_none());
1863         let new = 100;
1864         match m.get_mut(&5) {
1865             None => panic!(), Some(x) => *x = new
1866         }
1867         assert_eq!(m.get(&5), Some(&new));
1868     }
1869
1870     #[test]
1871     fn test_insert_overwrite() {
1872         let mut m = HashMap::new();
1873         assert!(m.insert(1, 2).is_none());
1874         assert_eq!(*m.get(&1).unwrap(), 2);
1875         assert!(!m.insert(1, 3).is_none());
1876         assert_eq!(*m.get(&1).unwrap(), 3);
1877     }
1878
1879     #[test]
1880     fn test_insert_conflicts() {
1881         let mut m = HashMap::with_capacity(4);
1882         assert!(m.insert(1, 2).is_none());
1883         assert!(m.insert(5, 3).is_none());
1884         assert!(m.insert(9, 4).is_none());
1885         assert_eq!(*m.get(&9).unwrap(), 4);
1886         assert_eq!(*m.get(&5).unwrap(), 3);
1887         assert_eq!(*m.get(&1).unwrap(), 2);
1888     }
1889
1890     #[test]
1891     fn test_conflict_remove() {
1892         let mut m = HashMap::with_capacity(4);
1893         assert!(m.insert(1, 2).is_none());
1894         assert_eq!(*m.get(&1).unwrap(), 2);
1895         assert!(m.insert(5, 3).is_none());
1896         assert_eq!(*m.get(&1).unwrap(), 2);
1897         assert_eq!(*m.get(&5).unwrap(), 3);
1898         assert!(m.insert(9, 4).is_none());
1899         assert_eq!(*m.get(&1).unwrap(), 2);
1900         assert_eq!(*m.get(&5).unwrap(), 3);
1901         assert_eq!(*m.get(&9).unwrap(), 4);
1902         assert!(m.remove(&1).is_some());
1903         assert_eq!(*m.get(&9).unwrap(), 4);
1904         assert_eq!(*m.get(&5).unwrap(), 3);
1905     }
1906
1907     #[test]
1908     fn test_is_empty() {
1909         let mut m = HashMap::with_capacity(4);
1910         assert!(m.insert(1, 2).is_none());
1911         assert!(!m.is_empty());
1912         assert!(m.remove(&1).is_some());
1913         assert!(m.is_empty());
1914     }
1915
1916     #[test]
1917     fn test_pop() {
1918         let mut m = HashMap::new();
1919         m.insert(1, 2);
1920         assert_eq!(m.remove(&1), Some(2));
1921         assert_eq!(m.remove(&1), None);
1922     }
1923
1924     #[test]
1925     fn test_iterate() {
1926         let mut m = HashMap::with_capacity(4);
1927         for i in 0..32 {
1928             assert!(m.insert(i, i*2).is_none());
1929         }
1930         assert_eq!(m.len(), 32);
1931
1932         let mut observed: u32 = 0;
1933
1934         for (k, v) in &m {
1935             assert_eq!(*v, *k * 2);
1936             observed |= 1 << *k;
1937         }
1938         assert_eq!(observed, 0xFFFF_FFFF);
1939     }
1940
1941     #[test]
1942     fn test_keys() {
1943         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1944         let map: HashMap<_, _> = vec.into_iter().collect();
1945         let keys: Vec<_> = map.keys().cloned().collect();
1946         assert_eq!(keys.len(), 3);
1947         assert!(keys.contains(&1));
1948         assert!(keys.contains(&2));
1949         assert!(keys.contains(&3));
1950     }
1951
1952     #[test]
1953     fn test_values() {
1954         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1955         let map: HashMap<_, _> = vec.into_iter().collect();
1956         let values: Vec<_> = map.values().cloned().collect();
1957         assert_eq!(values.len(), 3);
1958         assert!(values.contains(&'a'));
1959         assert!(values.contains(&'b'));
1960         assert!(values.contains(&'c'));
1961     }
1962
1963     #[test]
1964     fn test_find() {
1965         let mut m = HashMap::new();
1966         assert!(m.get(&1).is_none());
1967         m.insert(1, 2);
1968         match m.get(&1) {
1969             None => panic!(),
1970             Some(v) => assert_eq!(*v, 2)
1971         }
1972     }
1973
1974     #[test]
1975     fn test_eq() {
1976         let mut m1 = HashMap::new();
1977         m1.insert(1, 2);
1978         m1.insert(2, 3);
1979         m1.insert(3, 4);
1980
1981         let mut m2 = HashMap::new();
1982         m2.insert(1, 2);
1983         m2.insert(2, 3);
1984
1985         assert!(m1 != m2);
1986
1987         m2.insert(3, 4);
1988
1989         assert_eq!(m1, m2);
1990     }
1991
1992     #[test]
1993     fn test_show() {
1994         let mut map = HashMap::new();
1995         let empty: HashMap<i32, i32> = HashMap::new();
1996
1997         map.insert(1, 2);
1998         map.insert(3, 4);
1999
2000         let map_str = format!("{:?}", map);
2001
2002         assert!(map_str == "{1: 2, 3: 4}" ||
2003                 map_str == "{3: 4, 1: 2}");
2004         assert_eq!(format!("{:?}", empty), "{}");
2005     }
2006
2007     #[test]
2008     fn test_expand() {
2009         let mut m = HashMap::new();
2010
2011         assert_eq!(m.len(), 0);
2012         assert!(m.is_empty());
2013
2014         let mut i = 0;
2015         let old_cap = m.table.capacity();
2016         while old_cap == m.table.capacity() {
2017             m.insert(i, i);
2018             i += 1;
2019         }
2020
2021         assert_eq!(m.len(), i);
2022         assert!(!m.is_empty());
2023     }
2024
2025     #[test]
2026     fn test_behavior_resize_policy() {
2027         let mut m = HashMap::new();
2028
2029         assert_eq!(m.len(), 0);
2030         assert_eq!(m.table.capacity(), 0);
2031         assert!(m.is_empty());
2032
2033         m.insert(0, 0);
2034         m.remove(&0);
2035         assert!(m.is_empty());
2036         let initial_cap = m.table.capacity();
2037         m.reserve(initial_cap);
2038         let cap = m.table.capacity();
2039
2040         assert_eq!(cap, initial_cap * 2);
2041
2042         let mut i = 0;
2043         for _ in 0..cap * 3 / 4 {
2044             m.insert(i, i);
2045             i += 1;
2046         }
2047         // three quarters full
2048
2049         assert_eq!(m.len(), i);
2050         assert_eq!(m.table.capacity(), cap);
2051
2052         for _ in 0..cap / 4 {
2053             m.insert(i, i);
2054             i += 1;
2055         }
2056         // half full
2057
2058         let new_cap = m.table.capacity();
2059         assert_eq!(new_cap, cap * 2);
2060
2061         for _ in 0..cap / 2 - 1 {
2062             i -= 1;
2063             m.remove(&i);
2064             assert_eq!(m.table.capacity(), new_cap);
2065         }
2066         // A little more than one quarter full.
2067         m.shrink_to_fit();
2068         assert_eq!(m.table.capacity(), cap);
2069         // again, a little more than half full
2070         for _ in 0..cap / 2 - 1 {
2071             i -= 1;
2072             m.remove(&i);
2073         }
2074         m.shrink_to_fit();
2075
2076         assert_eq!(m.len(), i);
2077         assert!(!m.is_empty());
2078         assert_eq!(m.table.capacity(), initial_cap);
2079     }
2080
2081     #[test]
2082     fn test_reserve_shrink_to_fit() {
2083         let mut m = HashMap::new();
2084         m.insert(0, 0);
2085         m.remove(&0);
2086         assert!(m.capacity() >= m.len());
2087         for i in 0..128 {
2088             m.insert(i, i);
2089         }
2090         m.reserve(256);
2091
2092         let usable_cap = m.capacity();
2093         for i in 128..(128 + 256) {
2094             m.insert(i, i);
2095             assert_eq!(m.capacity(), usable_cap);
2096         }
2097
2098         for i in 100..(128 + 256) {
2099             assert_eq!(m.remove(&i), Some(i));
2100         }
2101         m.shrink_to_fit();
2102
2103         assert_eq!(m.len(), 100);
2104         assert!(!m.is_empty());
2105         assert!(m.capacity() >= m.len());
2106
2107         for i in 0..100 {
2108             assert_eq!(m.remove(&i), Some(i));
2109         }
2110         m.shrink_to_fit();
2111         m.insert(0, 0);
2112
2113         assert_eq!(m.len(), 1);
2114         assert!(m.capacity() >= m.len());
2115         assert_eq!(m.remove(&0), Some(0));
2116     }
2117
2118     #[test]
2119     fn test_from_iter() {
2120         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2121
2122         let map: HashMap<_, _> = xs.iter().cloned().collect();
2123
2124         for &(k, v) in &xs {
2125             assert_eq!(map.get(&k), Some(&v));
2126         }
2127     }
2128
2129     #[test]
2130     fn test_size_hint() {
2131         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2132
2133         let map: HashMap<_, _>  = xs.iter().cloned().collect();
2134
2135         let mut iter = map.iter();
2136
2137         for _ in iter.by_ref().take(3) {}
2138
2139         assert_eq!(iter.size_hint(), (3, Some(3)));
2140     }
2141
2142     #[test]
2143     fn test_iter_len() {
2144         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2145
2146         let map: HashMap<_, _>  = xs.iter().cloned().collect();
2147
2148         let mut iter = map.iter();
2149
2150         for _ in iter.by_ref().take(3) {}
2151
2152         assert_eq!(iter.len(), 3);
2153     }
2154
2155     #[test]
2156     fn test_mut_size_hint() {
2157         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2158
2159         let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
2160
2161         let mut iter = map.iter_mut();
2162
2163         for _ in iter.by_ref().take(3) {}
2164
2165         assert_eq!(iter.size_hint(), (3, Some(3)));
2166     }
2167
2168     #[test]
2169     fn test_iter_mut_len() {
2170         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2171
2172         let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
2173
2174         let mut iter = map.iter_mut();
2175
2176         for _ in iter.by_ref().take(3) {}
2177
2178         assert_eq!(iter.len(), 3);
2179     }
2180
2181     #[test]
2182     fn test_index() {
2183         let mut map = HashMap::new();
2184
2185         map.insert(1, 2);
2186         map.insert(2, 1);
2187         map.insert(3, 4);
2188
2189         assert_eq!(map[2], 1);
2190     }
2191
2192     #[test]
2193     #[should_fail]
2194     fn test_index_nonexistent() {
2195         let mut map = HashMap::new();
2196
2197         map.insert(1, 2);
2198         map.insert(2, 1);
2199         map.insert(3, 4);
2200
2201         map[4];
2202     }
2203
2204     #[test]
2205     fn test_entry(){
2206         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2207
2208         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2209
2210         // Existing key (insert)
2211         match map.entry(1) {
2212             Vacant(_) => unreachable!(),
2213             Occupied(mut view) => {
2214                 assert_eq!(view.get(), &10);
2215                 assert_eq!(view.insert(100), 10);
2216             }
2217         }
2218         assert_eq!(map.get(&1).unwrap(), &100);
2219         assert_eq!(map.len(), 6);
2220
2221
2222         // Existing key (update)
2223         match map.entry(2) {
2224             Vacant(_) => unreachable!(),
2225             Occupied(mut view) => {
2226                 let v = view.get_mut();
2227                 let new_v = (*v) * 10;
2228                 *v = new_v;
2229             }
2230         }
2231         assert_eq!(map.get(&2).unwrap(), &200);
2232         assert_eq!(map.len(), 6);
2233
2234         // Existing key (take)
2235         match map.entry(3) {
2236             Vacant(_) => unreachable!(),
2237             Occupied(view) => {
2238                 assert_eq!(view.remove(), 30);
2239             }
2240         }
2241         assert_eq!(map.get(&3), None);
2242         assert_eq!(map.len(), 5);
2243
2244
2245         // Inexistent key (insert)
2246         match map.entry(10) {
2247             Occupied(_) => unreachable!(),
2248             Vacant(view) => {
2249                 assert_eq!(*view.insert(1000), 1000);
2250             }
2251         }
2252         assert_eq!(map.get(&10).unwrap(), &1000);
2253         assert_eq!(map.len(), 6);
2254     }
2255
2256     #[test]
2257     fn test_entry_take_doesnt_corrupt() {
2258         #![allow(deprecated)] //rand
2259         // Test for #19292
2260         fn check(m: &HashMap<isize, ()>) {
2261             for k in m.keys() {
2262                 assert!(m.contains_key(k),
2263                         "{} is in keys() but not in the map?", k);
2264             }
2265         }
2266
2267         let mut m = HashMap::new();
2268         let mut rng = weak_rng();
2269
2270         // Populate the map with some items.
2271         for _ in 0..50 {
2272             let x = rng.gen_range(-10, 10);
2273             m.insert(x, ());
2274         }
2275
2276         for i in 0..1000 {
2277             let x = rng.gen_range(-10, 10);
2278             match m.entry(x) {
2279                 Vacant(_) => {},
2280                 Occupied(e) => {
2281                     println!("{}: remove {}", i, x);
2282                     e.remove();
2283                 },
2284             }
2285
2286             check(&m);
2287         }
2288     }
2289 }