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