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