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