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.
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.
11 // ignore-lexer-test FIXME #15883
14 use self::SearchResult::*;
15 use self::VacantEntryState::*;
19 use cmp::{max, Eq, PartialEq};
21 use fmt::{self, Debug};
22 use hash::{Hash, SipHasher};
23 use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
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};
42 use super::table::BucketState::{
46 use super::state::HashState;
48 const INITIAL_LOG2_CAP: usize = 5;
49 #[unstable(feature = "std_misc")]
50 pub const INITIAL_CAPACITY: usize = 1 << INITIAL_LOG2_CAP; // 2^5
52 /// The default behavior of HashMap implements a load factor of 90.9%.
53 /// This behavior is characterized by the following condition:
55 /// - if size > 0.909 * capacity: grow the map
57 struct DefaultResizePolicy;
59 impl DefaultResizePolicy {
60 fn new() -> DefaultResizePolicy {
65 fn min_capacity(&self, usable_size: usize) -> usize {
66 // Here, we are rephrasing the logic by specifying the lower limit
69 // - if `cap < size * 1.1`: grow the map
73 /// An inverse of `min_capacity`, approximately.
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
83 // This doesn't have to be checked for overflow since allocation size
84 // in bytes will overflow earlier than multiplication by 10.
90 fn test_resize_policy() {
91 let rp = DefaultResizePolicy;
93 assert!(rp.min_capacity(rp.usable_capacity(n)) <= n);
94 assert!(rp.usable_capacity(rp.min_capacity(n)) <= n);
98 // The main performance trick in this hashmap is called Robin Hood Hashing.
99 // It gains its excellent performance from one essential operation:
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.
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
109 // > Why a load factor of approximately 90%?
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.
121 // > Wait, what? Where did you get 1-α^k from?
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.
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.
137 // ## Future Improvements (FIXME!)
139 // Allow the load factor to be changed dynamically and/or at initialization.
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.
145 // ## Future Optimizations (FIXME!)
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.
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).
161 // Shrinking the table could simply reallocate in place after moving buckets
162 // to the first half.
164 // The growth algorithm (fragment of the Proof of Correctness)
165 // --------------------
167 // The growth algorithm is basically a fast path of the naive reinsertion-
168 // during-resize algorithm. Other paths should never be taken.
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.
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:
194 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
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
202 // Theorem: A linear robin hood reinsertion from the first ideal element
203 // produces identical results to a linear naive reinsertion from the same
206 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
208 /// A hash map implementation which uses linear probing with Robin
209 /// Hood bucket stealing.
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.
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)]`.
220 /// Relevant papers/articles:
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/)
231 /// use std::collections::HashMap;
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();
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.");
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());
249 /// // oops, this review has a lot of spelling mistakes, let's delete it.
250 /// book_reviews.remove(&("The Adventures of Sherlock Holmes"));
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)
261 /// // iterate over everything.
262 /// for (book, review) in book_reviews.iter() {
263 /// println!("{}: \"{}\"", *book, *review);
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`.
271 /// use std::collections::HashMap;
273 /// #[derive(Hash, Eq, PartialEq, Debug)]
280 /// /// Create a new Viking.
281 /// fn new(name: &str, country: &str) -> Viking {
282 /// Viking { name: name.to_string(), country: country.to_string() }
286 /// // Use a HashMap to store the vikings' health points.
287 /// let mut vikings = HashMap::new();
289 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
290 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
291 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
293 /// // Use derived implementation to print the status of the vikings.
294 /// for (viking, health) in vikings.iter() {
295 /// println!("{:?} has {} hp", viking, health);
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub struct HashMap<K, V, S = RandomState> {
301 // All hashes are keyed on these values, to prevent hash collision attacks.
304 table: RawTable<K, V>,
306 resize_policy: DefaultResizePolicy,
309 /// Search for a pre-hashed key.
310 fn search_hashed<K, V, M, F>(table: M,
313 -> SearchResult<K, V, M> where
314 M: Deref<Target=RawTable<K, V>>,
315 F: FnMut(&K) -> bool,
317 // This is the only function where capacity can be zero. To avoid
318 // undefined behaviour when Bucket::new gets the raw bucket in this
319 // case, immediately return the appropriate search result.
320 if table.capacity() == 0 {
321 return TableRef(table);
324 let size = table.size();
325 let mut probe = Bucket::new(table, hash);
326 let ib = probe.index();
328 while probe.index() != ib + size {
329 let full = match probe.peek() {
330 Empty(b) => return TableRef(b.into_table()), // hit an empty bucket
334 if full.distance() + ib < full.index() {
335 // We can finish the search early if we hit any bucket
336 // with a lower distance to initial bucket than we've probed.
337 return TableRef(full.into_table());
340 // If the hash doesn't match, it can't be this one..
341 if hash == full.hash() {
342 // If the key doesn't match, it can't be this one..
343 if is_match(full.read().0) {
344 return FoundExisting(full);
351 TableRef(probe.into_table())
354 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
355 let (empty, retkey, retval) = starting_bucket.take();
356 let mut gap = match empty.gap_peek() {
358 None => return (retkey, retval)
361 while gap.full().distance() != 0 {
362 gap = match gap.shift() {
368 // Now we've done all our shifting. Return the value we grabbed earlier.
372 /// Perform robin hood bucket stealing at the given `bucket`. You must
373 /// also pass the position of that bucket's initial bucket so we don't have
374 /// to recalculate it.
376 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
377 fn robin_hood<'a, K: 'a, V: 'a>(mut bucket: FullBucketMut<'a, K, V>,
383 let starting_index = bucket.index();
385 let table = bucket.table(); // FIXME "lifetime too short".
388 // There can be at most `size - dib` buckets to displace, because
389 // in the worst case, there are `size` elements and we already are
390 // `distance` buckets away from the initial one.
391 let idx_end = starting_index + size - bucket.distance();
394 let (old_hash, old_key, old_val) = bucket.replace(hash, k, v);
396 let probe = bucket.next();
397 assert!(probe.index() != idx_end);
399 let full_bucket = match probe.peek() {
402 let b = bucket.put(old_hash, old_key, old_val);
403 // Now that it's stolen, just read the value's pointer
404 // right out of the table!
405 return Bucket::at_index(b.into_table(), starting_index)
411 Full(bucket) => bucket
414 let probe_ib = full_bucket.index() - full_bucket.distance();
416 bucket = full_bucket;
418 // Robin hood! Steal the spot.
430 /// A result that works like Option<FullBucket<..>> but preserves
431 /// the reference that grants us access to the table in any case.
432 enum SearchResult<K, V, M> {
433 // This is an entry that holds the given key:
434 FoundExisting(FullBucket<K, V, M>),
436 // There was no such entry. The reference is given back:
440 impl<K, V, M> SearchResult<K, V, M> {
441 fn into_option(self) -> Option<FullBucket<K, V, M>> {
443 FoundExisting(bucket) => Some(bucket),
449 impl<K, V, S> HashMap<K, V, S>
450 where K: Eq + Hash, S: HashState
452 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
453 table::make_hash(&self.hash_state, x)
456 /// Search for a key, yielding the index if it's found in the hashtable.
457 /// If you already have the hash for the key lying around, use
459 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>>
460 where K: Borrow<Q>, Q: Eq + Hash
462 let hash = self.make_hash(q);
463 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
467 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>>
468 where K: Borrow<Q>, Q: Eq + Hash
470 let hash = self.make_hash(q);
471 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
475 // The caller should ensure that invariants by Robin Hood Hashing hold.
476 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
477 let cap = self.table.capacity();
478 let mut buckets = Bucket::new(&mut self.table, hash);
479 let ib = buckets.index();
481 while buckets.index() != ib + cap {
482 // We don't need to compare hashes for value swap.
483 // Not even DIBs for Robin Hood.
484 buckets = match buckets.peek() {
486 empty.put(hash, k, v);
489 Full(b) => b.into_bucket()
493 panic!("Internal HashMap error: Out of space.");
497 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
498 /// Create an empty HashMap.
503 /// use std::collections::HashMap;
504 /// let mut map: HashMap<&str, int> = HashMap::new();
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn new() -> HashMap<K, V, RandomState> {
512 /// Creates an empty hash map with the given initial capacity.
517 /// use std::collections::HashMap;
518 /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
523 HashMap::with_capacity_and_hash_state(capacity, Default::default())
527 impl<K, V, S> HashMap<K, V, S>
528 where K: Eq + Hash, S: HashState
530 /// Creates an empty hashmap which will use the given hasher to hash keys.
532 /// The creates map has the default initial capacity.
537 /// use std::collections::HashMap;
538 /// use std::collections::hash_map::RandomState;
540 /// let s = RandomState::new();
541 /// let mut map = HashMap::with_hash_state(s);
542 /// map.insert(1, 2);
545 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
546 pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> {
548 hash_state: hash_state,
549 resize_policy: DefaultResizePolicy::new(),
550 table: RawTable::new(0),
554 /// Create an empty HashMap with space for at least `capacity`
555 /// elements, using `hasher` to hash the keys.
557 /// Warning: `hasher` is normally randomly generated, and
558 /// is designed to allow HashMaps to be resistant to attacks that
559 /// cause many collisions and very poor performance. Setting it
560 /// manually using this function can expose a DoS attack vector.
565 /// use std::collections::HashMap;
566 /// use std::collections::hash_map::RandomState;
568 /// let s = RandomState::new();
569 /// let mut map = HashMap::with_capacity_and_hash_state(10, s);
570 /// map.insert(1, 2);
573 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
574 pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
575 -> HashMap<K, V, S> {
576 let resize_policy = DefaultResizePolicy::new();
577 let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
578 let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
579 assert!(internal_cap >= capacity, "capacity overflow");
581 hash_state: hash_state,
582 resize_policy: resize_policy,
583 table: RawTable::new(internal_cap),
587 /// Returns the number of elements the map can hold without reallocating.
592 /// use std::collections::HashMap;
593 /// let map: HashMap<int, int> = HashMap::with_capacity(100);
594 /// assert!(map.capacity() >= 100);
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub fn capacity(&self) -> usize {
599 self.resize_policy.usable_capacity(self.table.capacity())
602 /// Reserves capacity for at least `additional` more elements to be inserted
603 /// in the `HashMap`. The collection may reserve more space to avoid
604 /// frequent reallocations.
608 /// Panics if the new allocation size overflows `usize`.
613 /// use std::collections::HashMap;
614 /// let mut map: HashMap<&str, int> = HashMap::new();
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn reserve(&mut self, additional: usize) {
619 let new_size = self.len().checked_add(additional).expect("capacity overflow");
620 let min_cap = self.resize_policy.min_capacity(new_size);
622 // An invalid value shouldn't make us run out of space. This includes
623 // an overflow check.
624 assert!(new_size <= min_cap);
626 if self.table.capacity() < min_cap {
627 let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
628 self.resize(new_capacity);
632 /// Resizes the internal vectors to a new capacity. It's your responsibility to:
633 /// 1) Make sure the new capacity is enough for all the elements, accounting
634 /// for the load factor.
635 /// 2) Ensure new_capacity is a power of two or zero.
636 fn resize(&mut self, new_capacity: usize) {
637 assert!(self.table.size() <= new_capacity);
638 assert!(new_capacity.is_power_of_two() || new_capacity == 0);
640 let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
641 let old_size = old_table.size();
643 if old_table.capacity() == 0 || old_table.size() == 0 {
648 // Specialization of the other branch.
649 let mut bucket = Bucket::first(&mut old_table);
651 // "So a few of the first shall be last: for many be called,
654 // We'll most likely encounter a few buckets at the beginning that
655 // have their initial buckets near the end of the table. They were
656 // placed at the beginning as the probe wrapped around the table
657 // during insertion. We must skip forward to a bucket that won't
658 // get reinserted too early and won't unfairly steal others spot.
659 // This eliminates the need for robin hood.
661 bucket = match bucket.peek() {
663 if full.distance() == 0 {
664 // This bucket occupies its ideal spot.
665 // It indicates the start of another "cluster".
666 bucket = full.into_bucket();
669 // Leaving this bucket in the last cluster for later.
673 // Encountered a hole between clusters.
680 // This is how the buckets might be laid out in memory:
681 // ($ marks an initialized bucket)
683 // |$$$_$$$$$$_$$$$$|
685 // But we've skipped the entire initial cluster of buckets
686 // and will continue iteration in this order:
689 // ^ wrap around once end is reached
692 // ^ exit once table.size == 0
694 bucket = match bucket.peek() {
696 let h = bucket.hash();
697 let (b, k, v) = bucket.take();
698 self.insert_hashed_ordered(h, k, v);
700 let t = b.table(); // FIXME "lifetime too short".
701 if t.size() == 0 { break }
705 Empty(b) => b.into_bucket()
710 assert_eq!(self.table.size(), old_size);
713 /// Shrinks the capacity of the map as much as possible. It will drop
714 /// down as much as possible while maintaining the internal rules
715 /// and possibly leaving some space in accordance with the resize policy.
720 /// use std::collections::HashMap;
722 /// let mut map: HashMap<int, int> = HashMap::with_capacity(100);
723 /// map.insert(1, 2);
724 /// map.insert(3, 4);
725 /// assert!(map.capacity() >= 100);
726 /// map.shrink_to_fit();
727 /// assert!(map.capacity() >= 2);
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn shrink_to_fit(&mut self) {
731 let min_capacity = self.resize_policy.min_capacity(self.len());
732 let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
734 // An invalid value shouldn't make us run out of space.
735 debug_assert!(self.len() <= min_capacity);
737 if self.table.capacity() != min_capacity {
738 let old_table = replace(&mut self.table, RawTable::new(min_capacity));
739 let old_size = old_table.size();
741 // Shrink the table. Naive algorithm for resizing:
742 for (h, k, v) in old_table.into_iter() {
743 self.insert_hashed_nocheck(h, k, v);
746 debug_assert_eq!(self.table.size(), old_size);
750 /// Insert a pre-hashed key-value pair, without first checking
751 /// that there's enough room in the buckets. Returns a reference to the
752 /// newly insert value.
754 /// If the key already exists, the hashtable will be returned untouched
755 /// and a reference to the existing element will be returned.
756 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> &mut V {
757 self.insert_or_replace_with(hash, k, v, |_, _, _| ())
760 fn insert_or_replace_with<'a, F>(&'a mut self,
764 mut found_existing: F)
766 F: FnMut(&mut K, &mut V, V),
768 // Worst case, we'll find one empty bucket among `size + 1` buckets.
769 let size = self.table.size();
770 let mut probe = Bucket::new(&mut self.table, hash);
771 let ib = probe.index();
774 let mut bucket = match probe.peek() {
777 return bucket.put(hash, k, v).into_mut_refs().1;
779 Full(bucket) => bucket
783 if bucket.hash() == hash {
785 if k == *bucket.read_mut().0 {
786 let (bucket_k, bucket_v) = bucket.into_mut_refs();
787 debug_assert!(k == *bucket_k);
788 // Key already exists. Get its reference.
789 found_existing(bucket_k, bucket_v, v);
794 let robin_ib = bucket.index() as int - bucket.distance() as int;
796 if (ib as int) < robin_ib {
797 // Found a luckier bucket than me. Better steal his spot.
798 return robin_hood(bucket, robin_ib as usize, hash, k, v);
801 probe = bucket.next();
802 assert!(probe.index() != ib + size + 1);
806 /// An iterator visiting all keys in arbitrary order.
807 /// Iterator element type is `&'a K`.
812 /// use std::collections::HashMap;
814 /// let mut map = HashMap::new();
815 /// map.insert("a", 1);
816 /// map.insert("b", 2);
817 /// map.insert("c", 3);
819 /// for key in map.keys() {
820 /// println!("{}", key);
823 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
825 fn first<A, B>((a, _): (A, B)) -> A { a }
826 let first: fn((&'a K,&'a V)) -> &'a K = first; // coerce to fn ptr
828 Keys { inner: self.iter().map(first) }
831 /// An iterator visiting all values in arbitrary order.
832 /// Iterator element type is `&'a V`.
837 /// use std::collections::HashMap;
839 /// let mut map = HashMap::new();
840 /// map.insert("a", 1);
841 /// map.insert("b", 2);
842 /// map.insert("c", 3);
844 /// for val in map.values() {
845 /// println!("{}", val);
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
850 fn second<A, B>((_, b): (A, B)) -> B { b }
851 let second: fn((&'a K,&'a V)) -> &'a V = second; // coerce to fn ptr
853 Values { inner: self.iter().map(second) }
856 /// An iterator visiting all key-value pairs in arbitrary order.
857 /// Iterator element type is `(&'a K, &'a V)`.
862 /// use std::collections::HashMap;
864 /// let mut map = HashMap::new();
865 /// map.insert("a", 1);
866 /// map.insert("b", 2);
867 /// map.insert("c", 3);
869 /// for (key, val) in map.iter() {
870 /// println!("key: {} val: {}", key, val);
873 #[stable(feature = "rust1", since = "1.0.0")]
874 pub fn iter(&self) -> Iter<K, V> {
875 Iter { inner: self.table.iter() }
878 /// An iterator visiting all key-value pairs in arbitrary order,
879 /// with mutable references to the values.
880 /// Iterator element type is `(&'a K, &'a mut V)`.
885 /// use std::collections::HashMap;
887 /// let mut map = HashMap::new();
888 /// map.insert("a", 1);
889 /// map.insert("b", 2);
890 /// map.insert("c", 3);
892 /// // Update all values
893 /// for (_, val) in map.iter_mut() {
897 /// for (key, val) in map.iter() {
898 /// println!("key: {} val: {}", key, val);
901 #[stable(feature = "rust1", since = "1.0.0")]
902 pub fn iter_mut(&mut self) -> IterMut<K, V> {
903 IterMut { inner: self.table.iter_mut() }
906 /// Creates a consuming iterator, that is, one that moves each key-value
907 /// pair out of the map in arbitrary order. The map cannot be used after
913 /// use std::collections::HashMap;
915 /// let mut map = HashMap::new();
916 /// map.insert("a", 1);
917 /// map.insert("b", 2);
918 /// map.insert("c", 3);
920 /// // Not possible with .iter()
921 /// let vec: Vec<(&str, int)> = map.into_iter().collect();
923 #[stable(feature = "rust1", since = "1.0.0")]
924 pub fn into_iter(self) -> IntoIter<K, V> {
925 fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
926 let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two;
929 inner: self.table.into_iter().map(last_two)
933 /// Gets the given key's corresponding entry in the map for in-place manipulation.
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub fn entry(&mut self, key: K) -> Entry<K, V> {
939 let hash = self.make_hash(&key);
940 search_entry_hashed(&mut self.table, hash, key)
943 /// Returns the number of elements in the map.
948 /// use std::collections::HashMap;
950 /// let mut a = HashMap::new();
951 /// assert_eq!(a.len(), 0);
952 /// a.insert(1, "a");
953 /// assert_eq!(a.len(), 1);
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn len(&self) -> usize { self.table.size() }
958 /// Returns true if the map contains no elements.
963 /// use std::collections::HashMap;
965 /// let mut a = HashMap::new();
966 /// assert!(a.is_empty());
967 /// a.insert(1, "a");
968 /// assert!(!a.is_empty());
971 #[stable(feature = "rust1", since = "1.0.0")]
972 pub fn is_empty(&self) -> bool { self.len() == 0 }
974 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
975 /// allocated memory for reuse.
980 /// use std::collections::HashMap;
982 /// let mut a = HashMap::new();
983 /// a.insert(1, "a");
984 /// a.insert(2, "b");
986 /// for (k, v) in a.drain().take(1) {
987 /// assert!(k == 1 || k == 2);
988 /// assert!(v == "a" || v == "b");
991 /// assert!(a.is_empty());
994 #[unstable(feature = "std_misc",
995 reason = "matches collection reform specification, waiting for dust to settle")]
996 pub fn drain(&mut self) -> Drain<K, V> {
997 fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
998 let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two; // coerce to fn pointer
1001 inner: self.table.drain().map(last_two),
1005 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1011 /// use std::collections::HashMap;
1013 /// let mut a = HashMap::new();
1014 /// a.insert(1, "a");
1016 /// assert!(a.is_empty());
1018 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn clear(&mut self) {
1024 /// Returns a reference to the value corresponding to the key.
1026 /// The key may be any borrowed form of the map's key type, but
1027 /// `Hash` and `Eq` on the borrowed form *must* match those for
1033 /// use std::collections::HashMap;
1035 /// let mut map = HashMap::new();
1036 /// map.insert(1, "a");
1037 /// assert_eq!(map.get(&1), Some(&"a"));
1038 /// assert_eq!(map.get(&2), None);
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1042 where K: Borrow<Q>, Q: Hash + Eq
1044 self.search(k).map(|bucket| bucket.into_refs().1)
1047 /// Returns true if the map contains a value for the specified key.
1049 /// The key may be any borrowed form of the map's key type, but
1050 /// `Hash` and `Eq` on the borrowed form *must* match those for
1056 /// use std::collections::HashMap;
1058 /// let mut map = HashMap::new();
1059 /// map.insert(1, "a");
1060 /// assert_eq!(map.contains_key(&1), true);
1061 /// assert_eq!(map.contains_key(&2), false);
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1065 where K: Borrow<Q>, Q: Hash + Eq
1067 self.search(k).is_some()
1070 /// Returns a mutable reference to the value corresponding to the key.
1072 /// The key may be any borrowed form of the map's key type, but
1073 /// `Hash` and `Eq` on the borrowed form *must* match those for
1079 /// use std::collections::HashMap;
1081 /// let mut map = HashMap::new();
1082 /// map.insert(1, "a");
1083 /// match map.get_mut(&1) {
1084 /// Some(x) => *x = "b",
1087 /// assert_eq!(map[1], "b");
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1091 where K: Borrow<Q>, Q: Hash + Eq
1093 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1096 /// Inserts a key-value pair from the map. If the key already had a value
1097 /// present in the map, that value is returned. Otherwise, `None` is returned.
1102 /// use std::collections::HashMap;
1104 /// let mut map = HashMap::new();
1105 /// assert_eq!(map.insert(37, "a"), None);
1106 /// assert_eq!(map.is_empty(), false);
1108 /// map.insert(37, "b");
1109 /// assert_eq!(map.insert(37, "c"), Some("b"));
1110 /// assert_eq!(map[37], "c");
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1114 let hash = self.make_hash(&k);
1117 let mut retval = None;
1118 self.insert_or_replace_with(hash, k, v, |_, val_ref, val| {
1119 retval = Some(replace(val_ref, val));
1124 /// Removes a key from the map, returning the value at the key if the key
1125 /// was previously in the map.
1127 /// The key may be any borrowed form of the map's key type, but
1128 /// `Hash` and `Eq` on the borrowed form *must* match those for
1134 /// use std::collections::HashMap;
1136 /// let mut map = HashMap::new();
1137 /// map.insert(1, "a");
1138 /// assert_eq!(map.remove(&1), Some("a"));
1139 /// assert_eq!(map.remove(&1), None);
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1143 where K: Borrow<Q>, Q: Hash + Eq
1145 if self.table.size() == 0 {
1149 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1153 fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)
1156 // Worst case, we'll find one empty bucket among `size + 1` buckets.
1157 let size = table.size();
1158 let mut probe = Bucket::new(table, hash);
1159 let ib = probe.index();
1162 let bucket = match probe.peek() {
1165 return Vacant(VacantEntry {
1168 elem: NoElem(bucket),
1171 Full(bucket) => bucket
1175 if bucket.hash() == hash {
1177 if k == *bucket.read().0 {
1178 return Occupied(OccupiedEntry{
1184 let robin_ib = bucket.index() as int - bucket.distance() as int;
1186 if (ib as int) < robin_ib {
1187 // Found a luckier bucket than me. Better steal his spot.
1188 return Vacant(VacantEntry {
1191 elem: NeqElem(bucket, robin_ib as usize),
1195 probe = bucket.next();
1196 assert!(probe.index() != ib + size + 1);
1200 impl<K, V, S> PartialEq for HashMap<K, V, S>
1201 where K: Eq + Hash, V: PartialEq, S: HashState
1203 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1204 if self.len() != other.len() { return false; }
1206 self.iter().all(|(key, value)|
1207 other.get(key).map_or(false, |v| *value == *v)
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl<K, V, S> Eq for HashMap<K, V, S>
1214 where K: Eq + Hash, V: Eq, S: HashState
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<K, V, S> Debug for HashMap<K, V, S>
1219 where K: Eq + Hash + Debug, V: Debug, S: HashState
1221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1222 try!(write!(f, "{{"));
1224 for (i, (k, v)) in self.iter().enumerate() {
1225 if i != 0 { try!(write!(f, ", ")); }
1226 try!(write!(f, "{:?}: {:?}", *k, *v));
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<K, V, S> Default for HashMap<K, V, S>
1236 S: HashState + Default,
1238 fn default() -> HashMap<K, V, S> {
1239 HashMap::with_hash_state(Default::default())
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<K, Q: ?Sized, V, S> Index<Q> for HashMap<K, V, S>
1245 where K: Eq + Hash + Borrow<Q>,
1252 fn index<'a>(&'a self, index: &Q) -> &'a V {
1253 self.get(index).expect("no entry found for key")
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 impl<K, V, S, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
1259 where K: Eq + Hash + Borrow<Q>,
1264 fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
1265 self.get_mut(index).expect("no entry found for key")
1269 /// HashMap iterator.
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 pub struct Iter<'a, K: 'a, V: 'a> {
1272 inner: table::Iter<'a, K, V>
1275 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1276 impl<'a, K, V> Clone for Iter<'a, K, V> {
1277 fn clone(&self) -> Iter<'a, K, V> {
1279 inner: self.inner.clone()
1284 /// HashMap mutable values iterator.
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub struct IterMut<'a, K: 'a, V: 'a> {
1287 inner: table::IterMut<'a, K, V>
1290 /// HashMap move iterator.
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub struct IntoIter<K, V> {
1293 inner: iter::Map<table::IntoIter<K, V>, fn((SafeHash, K, V)) -> (K, V)>
1296 /// HashMap keys iterator.
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 pub struct Keys<'a, K: 'a, V: 'a> {
1299 inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
1302 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1303 impl<'a, K, V> Clone for Keys<'a, K, V> {
1304 fn clone(&self) -> Keys<'a, K, V> {
1306 inner: self.inner.clone()
1311 /// HashMap values iterator.
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 pub struct Values<'a, K: 'a, V: 'a> {
1314 inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
1317 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1318 impl<'a, K, V> Clone for Values<'a, K, V> {
1319 fn clone(&self) -> Values<'a, K, V> {
1321 inner: self.inner.clone()
1326 /// HashMap drain iterator.
1327 #[unstable(feature = "std_misc",
1328 reason = "matches collection reform specification, waiting for dust to settle")]
1329 pub struct Drain<'a, K: 'a, V: 'a> {
1330 inner: iter::Map<table::Drain<'a, K, V>, fn((SafeHash, K, V)) -> (K, V)>
1333 /// A view into a single occupied location in a HashMap.
1334 #[unstable(feature = "std_misc",
1335 reason = "precise API still being fleshed out")]
1336 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1337 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1340 /// A view into a single empty location in a HashMap.
1341 #[unstable(feature = "std_misc",
1342 reason = "precise API still being fleshed out")]
1343 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1346 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1349 /// A view into a single location in a map, which may be vacant or occupied.
1350 #[unstable(feature = "std_misc",
1351 reason = "precise API still being fleshed out")]
1352 pub enum Entry<'a, K: 'a, V: 'a> {
1353 /// An occupied Entry.
1354 Occupied(OccupiedEntry<'a, K, V>),
1356 Vacant(VacantEntry<'a, K, V>),
1359 /// Possible states of a VacantEntry.
1360 enum VacantEntryState<K, V, M> {
1361 /// The index is occupied, but the key to insert has precedence,
1362 /// and will kick the current one out on insertion.
1363 NeqElem(FullBucket<K, V, M>, usize),
1364 /// The index is genuinely vacant.
1365 NoElem(EmptyBucket<K, V, M>),
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1370 where K: Eq + Hash, S: HashState
1372 type Item = (&'a K, &'a V);
1373 type IntoIter = Iter<'a, K, V>;
1375 fn into_iter(self) -> Iter<'a, K, V> {
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1382 where K: Eq + Hash, S: HashState
1384 type Item = (&'a K, &'a mut V);
1385 type IntoIter = IterMut<'a, K, V>;
1387 fn into_iter(mut self) -> IterMut<'a, K, V> {
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1394 where K: Eq + Hash, S: HashState
1397 type IntoIter = IntoIter<K, V>;
1399 fn into_iter(self) -> IntoIter<K, V> {
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1406 type Item = (&'a K, &'a V);
1408 #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1409 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1413 #[inline] fn len(&self) -> usize { self.inner.len() }
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1418 type Item = (&'a K, &'a mut V);
1420 #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1421 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1425 #[inline] fn len(&self) -> usize { self.inner.len() }
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<K, V> Iterator for IntoIter<K, V> {
1432 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1433 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1437 #[inline] fn len(&self) -> usize { self.inner.len() }
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1444 #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1445 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1449 #[inline] fn len(&self) -> usize { self.inner.len() }
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<'a, K, V> Iterator for Values<'a, K, V> {
1456 #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1457 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1461 #[inline] fn len(&self) -> usize { self.inner.len() }
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1468 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1469 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1473 #[inline] fn len(&self) -> usize { self.inner.len() }
1476 #[unstable(feature = "std_misc",
1477 reason = "matches collection reform v2 specification, waiting for dust to settle")]
1478 impl<'a, K, V> Entry<'a, K, V> {
1479 /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant.
1480 pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1482 Occupied(entry) => Ok(entry.into_mut()),
1483 Vacant(entry) => Err(entry),
1488 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1489 /// Gets a reference to the value in the entry.
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 pub fn get(&self) -> &V {
1495 /// Gets a mutable reference to the value in the entry.
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn get_mut(&mut self) -> &mut V {
1498 self.elem.read_mut().1
1501 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1502 /// with a lifetime bound to the map itself
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub fn into_mut(self) -> &'a mut V {
1505 self.elem.into_mut_refs().1
1508 /// Sets the value of the entry, and returns the entry's old value
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 pub fn insert(&mut self, mut value: V) -> V {
1511 let old_value = self.get_mut();
1512 mem::swap(&mut value, old_value);
1516 /// Takes the value out of the entry, and returns it
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 pub fn remove(self) -> V {
1519 pop_internal(self.elem).1
1523 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1524 /// Sets the value of the entry with the VacantEntry's key,
1525 /// and returns a mutable reference to it
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 pub fn insert(self, value: V) -> &'a mut V {
1529 NeqElem(bucket, ib) => {
1530 robin_hood(bucket, ib, self.hash, self.key, value)
1533 bucket.put(self.hash, self.key, value).into_mut_refs().1
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1541 where K: Eq + Hash, S: HashState + Default
1543 fn from_iter<T: IntoIterator<Item=(K, V)>>(iterable: T) -> HashMap<K, V, S> {
1544 let iter = iterable.into_iter();
1545 let lower = iter.size_hint().0;
1546 let mut map = HashMap::with_capacity_and_hash_state(lower,
1547 Default::default());
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1555 where K: Eq + Hash, S: HashState
1557 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1558 for (k, v) in iter {
1565 /// `RandomState` is the default state for `HashMap` types.
1567 /// A particular instance `RandomState` will create the same instances of
1568 /// `Hasher`, but the hashers created by two different `RandomState`
1569 /// instances are unlikely to produce the same result for the same values.
1571 #[unstable(feature = "std_misc",
1572 reason = "hashing an hash maps may be altered")]
1573 pub struct RandomState {
1578 #[unstable(feature = "std_misc",
1579 reason = "hashing an hash maps may be altered")]
1581 /// Construct a new `RandomState` that is initialized with random keys.
1583 #[allow(deprecated)]
1584 pub fn new() -> RandomState {
1585 let mut r = rand::thread_rng();
1586 RandomState { k0: r.gen(), k1: r.gen() }
1590 #[unstable(feature = "std_misc",
1591 reason = "hashing an hash maps may be altered")]
1592 impl HashState for RandomState {
1593 type Hasher = SipHasher;
1594 fn hasher(&self) -> SipHasher {
1595 SipHasher::new_with_keys(self.k0, self.k1)
1599 #[unstable(feature = "std_misc",
1600 reason = "hashing an hash maps may be altered")]
1601 impl Default for RandomState {
1603 fn default() -> RandomState {
1613 use super::Entry::{Occupied, Vacant};
1614 use iter::{range_inclusive, range_step_inclusive, repeat};
1616 use rand::{weak_rng, Rng};
1619 fn test_create_capacity_zero() {
1620 let mut m = HashMap::with_capacity(0);
1622 assert!(m.insert(1, 1).is_none());
1624 assert!(m.contains_key(&1));
1625 assert!(!m.contains_key(&0));
1630 let mut m = HashMap::new();
1631 assert_eq!(m.len(), 0);
1632 assert!(m.insert(1, 2).is_none());
1633 assert_eq!(m.len(), 1);
1634 assert!(m.insert(2, 4).is_none());
1635 assert_eq!(m.len(), 2);
1636 assert_eq!(*m.get(&1).unwrap(), 2);
1637 assert_eq!(*m.get(&2).unwrap(), 4);
1640 thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
1642 #[derive(Hash, PartialEq, Eq)]
1648 fn new(k: usize) -> Dropable {
1649 DROP_VECTOR.with(|slot| {
1650 slot.borrow_mut()[k] += 1;
1657 impl Drop for Dropable {
1658 fn drop(&mut self) {
1659 DROP_VECTOR.with(|slot| {
1660 slot.borrow_mut()[self.k] -= 1;
1665 impl Clone for Dropable {
1666 fn clone(&self) -> Dropable {
1667 Dropable::new(self.k)
1673 DROP_VECTOR.with(|slot| {
1674 *slot.borrow_mut() = repeat(0).take(200).collect();
1678 let mut m = HashMap::new();
1680 DROP_VECTOR.with(|v| {
1682 assert_eq!(v.borrow()[i], 0);
1687 let d1 = Dropable::new(i);
1688 let d2 = Dropable::new(i+100);
1692 DROP_VECTOR.with(|v| {
1694 assert_eq!(v.borrow()[i], 1);
1699 let k = Dropable::new(i);
1700 let v = m.remove(&k);
1702 assert!(v.is_some());
1704 DROP_VECTOR.with(|v| {
1705 assert_eq!(v.borrow()[i], 1);
1706 assert_eq!(v.borrow()[i+100], 1);
1710 DROP_VECTOR.with(|v| {
1712 assert_eq!(v.borrow()[i], 0);
1713 assert_eq!(v.borrow()[i+100], 0);
1717 assert_eq!(v.borrow()[i], 1);
1718 assert_eq!(v.borrow()[i+100], 1);
1723 DROP_VECTOR.with(|v| {
1725 assert_eq!(v.borrow()[i], 0);
1731 fn test_move_iter_drops() {
1732 DROP_VECTOR.with(|v| {
1733 *v.borrow_mut() = repeat(0).take(200).collect();
1737 let mut hm = HashMap::new();
1739 DROP_VECTOR.with(|v| {
1741 assert_eq!(v.borrow()[i], 0);
1746 let d1 = Dropable::new(i);
1747 let d2 = Dropable::new(i+100);
1751 DROP_VECTOR.with(|v| {
1753 assert_eq!(v.borrow()[i], 1);
1760 // By the way, ensure that cloning doesn't screw up the dropping.
1764 let mut half = hm.into_iter().take(50);
1766 DROP_VECTOR.with(|v| {
1768 assert_eq!(v.borrow()[i], 1);
1772 for _ in half.by_ref() {}
1774 DROP_VECTOR.with(|v| {
1775 let nk = (0..100).filter(|&i| {
1779 let nv = (0..100).filter(|&i| {
1780 v.borrow()[i+100] == 1
1788 DROP_VECTOR.with(|v| {
1790 assert_eq!(v.borrow()[i], 0);
1796 fn test_empty_pop() {
1797 let mut m: HashMap<int, bool> = HashMap::new();
1798 assert_eq!(m.remove(&0), None);
1802 fn test_lots_of_insertions() {
1803 let mut m = HashMap::new();
1805 // Try this a few times to make sure we never screw up the hashmap's
1808 assert!(m.is_empty());
1810 for i in range_inclusive(1, 1000) {
1811 assert!(m.insert(i, i).is_none());
1813 for j in range_inclusive(1, i) {
1815 assert_eq!(r, Some(&j));
1818 for j in range_inclusive(i+1, 1000) {
1820 assert_eq!(r, None);
1824 for i in range_inclusive(1001, 2000) {
1825 assert!(!m.contains_key(&i));
1829 for i in range_inclusive(1, 1000) {
1830 assert!(m.remove(&i).is_some());
1832 for j in range_inclusive(1, i) {
1833 assert!(!m.contains_key(&j));
1836 for j in range_inclusive(i+1, 1000) {
1837 assert!(m.contains_key(&j));
1841 for i in range_inclusive(1, 1000) {
1842 assert!(!m.contains_key(&i));
1845 for i in range_inclusive(1, 1000) {
1846 assert!(m.insert(i, i).is_none());
1850 for i in range_step_inclusive(1000, 1, -1) {
1851 assert!(m.remove(&i).is_some());
1853 for j in range_inclusive(i, 1000) {
1854 assert!(!m.contains_key(&j));
1857 for j in range_inclusive(1, i-1) {
1858 assert!(m.contains_key(&j));
1865 fn test_find_mut() {
1866 let mut m = HashMap::new();
1867 assert!(m.insert(1, 12).is_none());
1868 assert!(m.insert(2, 8).is_none());
1869 assert!(m.insert(5, 14).is_none());
1871 match m.get_mut(&5) {
1872 None => panic!(), Some(x) => *x = new
1874 assert_eq!(m.get(&5), Some(&new));
1878 fn test_insert_overwrite() {
1879 let mut m = HashMap::new();
1880 assert!(m.insert(1, 2).is_none());
1881 assert_eq!(*m.get(&1).unwrap(), 2);
1882 assert!(!m.insert(1, 3).is_none());
1883 assert_eq!(*m.get(&1).unwrap(), 3);
1887 fn test_insert_conflicts() {
1888 let mut m = HashMap::with_capacity(4);
1889 assert!(m.insert(1, 2).is_none());
1890 assert!(m.insert(5, 3).is_none());
1891 assert!(m.insert(9, 4).is_none());
1892 assert_eq!(*m.get(&9).unwrap(), 4);
1893 assert_eq!(*m.get(&5).unwrap(), 3);
1894 assert_eq!(*m.get(&1).unwrap(), 2);
1898 fn test_conflict_remove() {
1899 let mut m = HashMap::with_capacity(4);
1900 assert!(m.insert(1, 2).is_none());
1901 assert_eq!(*m.get(&1).unwrap(), 2);
1902 assert!(m.insert(5, 3).is_none());
1903 assert_eq!(*m.get(&1).unwrap(), 2);
1904 assert_eq!(*m.get(&5).unwrap(), 3);
1905 assert!(m.insert(9, 4).is_none());
1906 assert_eq!(*m.get(&1).unwrap(), 2);
1907 assert_eq!(*m.get(&5).unwrap(), 3);
1908 assert_eq!(*m.get(&9).unwrap(), 4);
1909 assert!(m.remove(&1).is_some());
1910 assert_eq!(*m.get(&9).unwrap(), 4);
1911 assert_eq!(*m.get(&5).unwrap(), 3);
1915 fn test_is_empty() {
1916 let mut m = HashMap::with_capacity(4);
1917 assert!(m.insert(1, 2).is_none());
1918 assert!(!m.is_empty());
1919 assert!(m.remove(&1).is_some());
1920 assert!(m.is_empty());
1925 let mut m = HashMap::new();
1927 assert_eq!(m.remove(&1), Some(2));
1928 assert_eq!(m.remove(&1), None);
1933 let mut m = HashMap::with_capacity(4);
1935 assert!(m.insert(i, i*2).is_none());
1937 assert_eq!(m.len(), 32);
1939 let mut observed: u32 = 0;
1942 assert_eq!(*v, *k * 2);
1943 observed |= 1 << *k;
1945 assert_eq!(observed, 0xFFFF_FFFF);
1950 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1951 let map: HashMap<_, _> = vec.into_iter().collect();
1952 let keys: Vec<_> = map.keys().cloned().collect();
1953 assert_eq!(keys.len(), 3);
1954 assert!(keys.contains(&1));
1955 assert!(keys.contains(&2));
1956 assert!(keys.contains(&3));
1961 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1962 let map: HashMap<_, _> = vec.into_iter().collect();
1963 let values: Vec<_> = map.values().cloned().collect();
1964 assert_eq!(values.len(), 3);
1965 assert!(values.contains(&'a'));
1966 assert!(values.contains(&'b'));
1967 assert!(values.contains(&'c'));
1972 let mut m = HashMap::new();
1973 assert!(m.get(&1).is_none());
1977 Some(v) => assert_eq!(*v, 2)
1983 let mut m1 = HashMap::new();
1988 let mut m2 = HashMap::new();
2001 let mut map = HashMap::new();
2002 let empty: HashMap<i32, i32> = HashMap::new();
2007 let map_str = format!("{:?}", map);
2009 assert!(map_str == "{1: 2, 3: 4}" ||
2010 map_str == "{3: 4, 1: 2}");
2011 assert_eq!(format!("{:?}", empty), "{}");
2016 let mut m = HashMap::new();
2018 assert_eq!(m.len(), 0);
2019 assert!(m.is_empty());
2022 let old_cap = m.table.capacity();
2023 while old_cap == m.table.capacity() {
2028 assert_eq!(m.len(), i);
2029 assert!(!m.is_empty());
2033 fn test_behavior_resize_policy() {
2034 let mut m = HashMap::new();
2036 assert_eq!(m.len(), 0);
2037 assert_eq!(m.table.capacity(), 0);
2038 assert!(m.is_empty());
2042 assert!(m.is_empty());
2043 let initial_cap = m.table.capacity();
2044 m.reserve(initial_cap);
2045 let cap = m.table.capacity();
2047 assert_eq!(cap, initial_cap * 2);
2050 for _ in 0..cap * 3 / 4 {
2054 // three quarters full
2056 assert_eq!(m.len(), i);
2057 assert_eq!(m.table.capacity(), cap);
2059 for _ in 0..cap / 4 {
2065 let new_cap = m.table.capacity();
2066 assert_eq!(new_cap, cap * 2);
2068 for _ in 0..cap / 2 - 1 {
2071 assert_eq!(m.table.capacity(), new_cap);
2073 // A little more than one quarter full.
2075 assert_eq!(m.table.capacity(), cap);
2076 // again, a little more than half full
2077 for _ in 0..cap / 2 - 1 {
2083 assert_eq!(m.len(), i);
2084 assert!(!m.is_empty());
2085 assert_eq!(m.table.capacity(), initial_cap);
2089 fn test_reserve_shrink_to_fit() {
2090 let mut m = HashMap::new();
2093 assert!(m.capacity() >= m.len());
2099 let usable_cap = m.capacity();
2100 for i in 128..(128 + 256) {
2102 assert_eq!(m.capacity(), usable_cap);
2105 for i in 100..(128 + 256) {
2106 assert_eq!(m.remove(&i), Some(i));
2110 assert_eq!(m.len(), 100);
2111 assert!(!m.is_empty());
2112 assert!(m.capacity() >= m.len());
2115 assert_eq!(m.remove(&i), Some(i));
2120 assert_eq!(m.len(), 1);
2121 assert!(m.capacity() >= m.len());
2122 assert_eq!(m.remove(&0), Some(0));
2126 fn test_from_iter() {
2127 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2129 let map: HashMap<_, _> = xs.iter().cloned().collect();
2131 for &(k, v) in &xs {
2132 assert_eq!(map.get(&k), Some(&v));
2137 fn test_size_hint() {
2138 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2140 let map: HashMap<_, _> = xs.iter().cloned().collect();
2142 let mut iter = map.iter();
2144 for _ in iter.by_ref().take(3) {}
2146 assert_eq!(iter.size_hint(), (3, Some(3)));
2150 fn test_iter_len() {
2151 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2153 let map: HashMap<_, _> = xs.iter().cloned().collect();
2155 let mut iter = map.iter();
2157 for _ in iter.by_ref().take(3) {}
2159 assert_eq!(iter.len(), 3);
2163 fn test_mut_size_hint() {
2164 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2166 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2168 let mut iter = map.iter_mut();
2170 for _ in iter.by_ref().take(3) {}
2172 assert_eq!(iter.size_hint(), (3, Some(3)));
2176 fn test_iter_mut_len() {
2177 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2179 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2181 let mut iter = map.iter_mut();
2183 for _ in iter.by_ref().take(3) {}
2185 assert_eq!(iter.len(), 3);
2190 let mut map = HashMap::new();
2196 assert_eq!(map[2], 1);
2201 fn test_index_nonexistent() {
2202 let mut map = HashMap::new();
2213 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2215 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2217 // Existing key (insert)
2218 match map.entry(1) {
2219 Vacant(_) => unreachable!(),
2220 Occupied(mut view) => {
2221 assert_eq!(view.get(), &10);
2222 assert_eq!(view.insert(100), 10);
2225 assert_eq!(map.get(&1).unwrap(), &100);
2226 assert_eq!(map.len(), 6);
2229 // Existing key (update)
2230 match map.entry(2) {
2231 Vacant(_) => unreachable!(),
2232 Occupied(mut view) => {
2233 let v = view.get_mut();
2234 let new_v = (*v) * 10;
2238 assert_eq!(map.get(&2).unwrap(), &200);
2239 assert_eq!(map.len(), 6);
2241 // Existing key (take)
2242 match map.entry(3) {
2243 Vacant(_) => unreachable!(),
2245 assert_eq!(view.remove(), 30);
2248 assert_eq!(map.get(&3), None);
2249 assert_eq!(map.len(), 5);
2252 // Inexistent key (insert)
2253 match map.entry(10) {
2254 Occupied(_) => unreachable!(),
2256 assert_eq!(*view.insert(1000), 1000);
2259 assert_eq!(map.get(&10).unwrap(), &1000);
2260 assert_eq!(map.len(), 6);
2264 fn test_entry_take_doesnt_corrupt() {
2265 #![allow(deprecated)] //rand
2267 fn check(m: &HashMap<isize, ()>) {
2269 assert!(m.contains_key(k),
2270 "{} is in keys() but not in the map?", k);
2274 let mut m = HashMap::new();
2275 let mut rng = weak_rng();
2277 // Populate the map with some items.
2279 let x = rng.gen_range(-10, 10);
2284 let x = rng.gen_range(-10, 10);
2288 println!("{}: remove {}", i, x);