]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hashmap.rs
auto merge of #15789 : steveklabnik/rust/guide_pointers, r=cmr
[rust.git] / src / libstd / collections / hashmap.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15883
12
13 //! Unordered containers, implemented as hash-tables (`HashSet` and `HashMap` types)
14
15 use clone::Clone;
16 use cmp::{max, Eq, Equiv, PartialEq};
17 use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap};
18 use default::Default;
19 use fmt::Show;
20 use fmt;
21 use hash::{Hash, Hasher, RandomSipHasher};
22 use iter::{Iterator, FilterMap, Chain, Repeat, Zip, Extendable};
23 use iter::{range, range_inclusive, FromIterator};
24 use iter;
25 use mem::replace;
26 use num;
27 use option::{Some, None, Option};
28 use result::{Ok, Err};
29
30 mod table {
31     use clone::Clone;
32     use cmp;
33     use hash::{Hash, Hasher};
34     use iter::range_step_inclusive;
35     use iter::{Iterator, range};
36     use kinds::marker;
37     use mem::{min_align_of, size_of};
38     use mem::{overwrite, transmute};
39     use num::{CheckedMul, is_power_of_two};
40     use ops::Drop;
41     use option::{Some, None, Option};
42     use ptr::RawPtr;
43     use ptr::set_memory;
44     use ptr;
45     use rt::heap::{allocate, deallocate};
46
47     static EMPTY_BUCKET: u64 = 0u64;
48
49     /// The raw hashtable, providing safe-ish access to the unzipped and highly
50     /// optimized arrays of hashes, keys, and values.
51     ///
52     /// This design uses less memory and is a lot faster than the naive
53     /// `Vec<Option<u64, K, V>>`, because we don't pay for the overhead of an
54     /// option on every element, and we get a generally more cache-aware design.
55     ///
56     /// Key invariants of this structure:
57     ///
58     ///   - if hashes[i] == EMPTY_BUCKET, then keys[i] and vals[i] have
59     ///     'undefined' contents. Don't read from them. This invariant is
60     ///     enforced outside this module with the `EmptyIndex`, `FullIndex`,
61     ///     and `SafeHash` types.
62     ///
63     ///   - An `EmptyIndex` is only constructed for a bucket at an index with
64     ///     a hash of EMPTY_BUCKET.
65     ///
66     ///   - A `FullIndex` is only constructed for a bucket at an index with a
67     ///     non-EMPTY_BUCKET hash.
68     ///
69     ///   - A `SafeHash` is only constructed for non-`EMPTY_BUCKET` hash. We get
70     ///     around hashes of zero by changing them to 0x8000_0000_0000_0000,
71     ///     which will likely map to the same bucket, while not being confused
72     ///     with "empty".
73     ///
74     ///   - All three "arrays represented by pointers" are the same length:
75     ///     `capacity`. This is set at creation and never changes. The arrays
76     ///     are unzipped to save space (we don't have to pay for the padding
77     ///     between odd sized elements, such as in a map from u64 to u8), and
78     ///     be more cache aware (scanning through 8 hashes brings in 2 cache
79     ///     lines, since they're all right beside each other).
80     ///
81     /// You can kind of think of this module/data structure as a safe wrapper
82     /// around just the "table" part of the hashtable. It enforces some
83     /// invariants at the type level and employs some performance trickery,
84     /// but in general is just a tricked out `Vec<Option<u64, K, V>>`.
85     ///
86     /// FIXME(cgaebel):
87     ///
88     /// Feb 11, 2014: This hashtable was just implemented, and, hard as I tried,
89     /// isn't yet totally safe. There's a "known exploit" that you can create
90     /// multiple FullIndexes for a bucket, `take` one, and then still `take`
91     /// the other causing undefined behavior. Currently, there's no story
92     /// for how to protect against this statically. Therefore, there are asserts
93     /// on `take`, `get`, `get_mut`, and `put` which check the bucket state.
94     /// With time, and when we're confident this works correctly, they should
95     /// be removed. Also, the bounds check in `peek` is especially painful,
96     /// as that's called in the innermost loops of the hashtable and has the
97     /// potential to be a major performance drain. Remove this too.
98     ///
99     /// Or, better than remove, only enable these checks for debug builds.
100     /// There's currently no "debug-only" asserts in rust, so if you're reading
101     /// this and going "what? of course there are debug-only asserts!", then
102     /// please make this use them!
103     #[unsafe_no_drop_flag]
104     pub struct RawTable<K, V> {
105         capacity: uint,
106         size:     uint,
107         hashes:   *mut u64,
108         keys:     *mut K,
109         vals:     *mut V,
110     }
111
112     /// Represents an index into a `RawTable` with no key or value in it.
113     pub struct EmptyIndex {
114         idx:    int,
115         nocopy: marker::NoCopy,
116     }
117
118     /// Represents an index into a `RawTable` with a key, value, and hash
119     /// in it.
120     pub struct FullIndex {
121         idx:    int,
122         hash:   SafeHash,
123         nocopy: marker::NoCopy,
124     }
125
126     impl FullIndex {
127         /// Since we get the hash for free whenever we check the bucket state,
128         /// this function is provided for fast access, letting us avoid
129         /// redundant trips back to the hashtable.
130         #[inline(always)]
131         pub fn hash(&self) -> SafeHash { self.hash }
132
133         /// Same comment as with `hash`.
134         #[inline(always)]
135         pub fn raw_index(&self) -> uint { self.idx as uint }
136     }
137
138     /// Represents the state of a bucket: it can either have a key/value
139     /// pair (be full) or not (be empty). You cannot `take` empty buckets,
140     /// and you cannot `put` into full buckets.
141     pub enum BucketState {
142         Empty(EmptyIndex),
143         Full(FullIndex),
144     }
145
146     /// A hash that is not zero, since we use a hash of zero to represent empty
147     /// buckets.
148     #[deriving(PartialEq)]
149     pub struct SafeHash {
150         hash: u64,
151     }
152
153     impl SafeHash {
154         /// Peek at the hash value, which is guaranteed to be non-zero.
155         #[inline(always)]
156         pub fn inspect(&self) -> u64 { self.hash }
157     }
158
159     /// We need to remove hashes of 0. That's reserved for empty buckets.
160     /// This function wraps up `hash_keyed` to be the only way outside this
161     /// module to generate a SafeHash.
162     pub fn make_hash<T: Hash<S>, S, H: Hasher<S>>(hasher: &H, t: &T) -> SafeHash {
163         match hasher.hash(t) {
164             // This constant is exceedingly likely to hash to the same
165             // bucket, but it won't be counted as empty!
166             EMPTY_BUCKET => SafeHash { hash: 0x8000_0000_0000_0000 },
167             h            => SafeHash { hash: h },
168         }
169     }
170
171     fn round_up_to_next(unrounded: uint, target_alignment: uint) -> uint {
172         assert!(is_power_of_two(target_alignment));
173         (unrounded + target_alignment - 1) & !(target_alignment - 1)
174     }
175
176     #[test]
177     fn test_rounding() {
178         assert_eq!(round_up_to_next(0, 4), 0);
179         assert_eq!(round_up_to_next(1, 4), 4);
180         assert_eq!(round_up_to_next(2, 4), 4);
181         assert_eq!(round_up_to_next(3, 4), 4);
182         assert_eq!(round_up_to_next(4, 4), 4);
183         assert_eq!(round_up_to_next(5, 4), 8);
184     }
185
186     // Returns a tuple of (minimum required malloc alignment, hash_offset,
187     // key_offset, val_offset, array_size), from the start of a mallocated array.
188     fn calculate_offsets(
189         hash_size: uint, hash_align: uint,
190         keys_size: uint, keys_align: uint,
191         vals_size: uint, vals_align: uint) -> (uint, uint, uint, uint, uint) {
192
193         let hash_offset   = 0;
194         let end_of_hashes = hash_offset + hash_size;
195
196         let keys_offset   = round_up_to_next(end_of_hashes, keys_align);
197         let end_of_keys   = keys_offset + keys_size;
198
199         let vals_offset   = round_up_to_next(end_of_keys, vals_align);
200         let end_of_vals   = vals_offset + vals_size;
201
202         let min_align = cmp::max(hash_align, cmp::max(keys_align, vals_align));
203
204         (min_align, hash_offset, keys_offset, vals_offset, end_of_vals)
205     }
206
207     #[test]
208     fn test_offset_calculation() {
209         assert_eq!(calculate_offsets(128, 8, 15, 1, 4, 4 ), (8, 0, 128, 144, 148));
210         assert_eq!(calculate_offsets(3,   1, 2,  1, 1, 1 ), (1, 0, 3,   5,   6));
211         assert_eq!(calculate_offsets(6,   2, 12, 4, 24, 8), (8, 0, 8,   24,  48));
212     }
213
214     impl<K, V> RawTable<K, V> {
215
216         /// Does not initialize the buckets. The caller should ensure they,
217         /// at the very least, set every hash to EMPTY_BUCKET.
218         unsafe fn new_uninitialized(capacity: uint) -> RawTable<K, V> {
219             let hashes_size = capacity.checked_mul(&size_of::<u64>())
220                                       .expect("capacity overflow");
221             let keys_size = capacity.checked_mul(&size_of::< K >())
222                                     .expect("capacity overflow");
223             let vals_size = capacity.checked_mul(&size_of::< V >())
224                                     .expect("capacity overflow");
225
226             // Allocating hashmaps is a little tricky. We need to allocate three
227             // arrays, but since we know their sizes and alignments up front,
228             // we just allocate a single array, and then have the subarrays
229             // point into it.
230             //
231             // This is great in theory, but in practice getting the alignment
232             // right is a little subtle. Therefore, calculating offsets has been
233             // factored out into a different function.
234             let (malloc_alignment, hash_offset, keys_offset, vals_offset, size) =
235                 calculate_offsets(
236                     hashes_size, min_align_of::<u64>(),
237                     keys_size,   min_align_of::< K >(),
238                     vals_size,   min_align_of::< V >());
239
240             let buffer = allocate(size, malloc_alignment);
241
242             let hashes = buffer.offset(hash_offset as int) as *mut u64;
243             let keys   = buffer.offset(keys_offset as int) as *mut K;
244             let vals   = buffer.offset(vals_offset as int) as *mut V;
245
246             RawTable {
247                 capacity: capacity,
248                 size:     0,
249                 hashes:   hashes,
250                 keys:     keys,
251                 vals:     vals,
252             }
253         }
254
255         /// Creates a new raw table from a given capacity. All buckets are
256         /// initially empty.
257         #[allow(experimental)]
258         pub fn new(capacity: uint) -> RawTable<K, V> {
259             unsafe {
260                 let ret = RawTable::new_uninitialized(capacity);
261                 set_memory(ret.hashes, 0u8, capacity);
262                 ret
263             }
264         }
265
266         /// Reads a bucket at a given index, returning an enum indicating whether
267         /// there's anything there or not. You need to match on this enum to get
268         /// the appropriate types to pass on to most of the other functions in
269         /// this module.
270         pub fn peek(&self, index: uint) -> BucketState {
271             debug_assert!(index < self.capacity);
272
273             let idx  = index as int;
274             let hash = unsafe { *self.hashes.offset(idx) };
275
276             let nocopy = marker::NoCopy;
277
278             match hash {
279                 EMPTY_BUCKET =>
280                     Empty(EmptyIndex {
281                         idx:    idx,
282                         nocopy: nocopy
283                     }),
284                 full_hash =>
285                     Full(FullIndex {
286                         idx:    idx,
287                         hash:   SafeHash { hash: full_hash },
288                         nocopy: nocopy,
289                     })
290             }
291         }
292
293         /// Gets references to the key and value at a given index.
294         pub fn read<'a>(&'a self, index: &FullIndex) -> (&'a K, &'a V) {
295             let idx = index.idx;
296
297             unsafe {
298                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
299                 (&*self.keys.offset(idx), &*self.vals.offset(idx))
300             }
301         }
302
303         /// Gets references to the key and value at a given index, with the
304         /// value's reference being mutable.
305         pub fn read_mut<'a>(&'a mut self, index: &FullIndex) -> (&'a K, &'a mut V) {
306             let idx = index.idx;
307
308             unsafe {
309                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
310                 (&*self.keys.offset(idx), &mut *self.vals.offset(idx))
311             }
312         }
313
314         /// Read everything, mutably.
315         pub fn read_all_mut<'a>(&'a mut self, index: &FullIndex)
316             -> (&'a mut SafeHash, &'a mut K, &'a mut V) {
317             let idx = index.idx;
318
319             unsafe {
320                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
321                 (transmute(self.hashes.offset(idx)),
322                  &mut *self.keys.offset(idx), &mut *self.vals.offset(idx))
323             }
324         }
325
326         /// Puts a key and value pair, along with the key's hash, into a given
327         /// index in the hashtable. Note how the `EmptyIndex` is 'moved' into this
328         /// function, because that slot will no longer be empty when we return!
329         /// A FullIndex is returned for later use, pointing to the newly-filled
330         /// slot in the hashtable.
331         ///
332         /// Use `make_hash` to construct a `SafeHash` to pass to this function.
333         pub fn put(&mut self, index: EmptyIndex, hash: SafeHash, k: K, v: V) -> FullIndex {
334             let idx = index.idx;
335
336             unsafe {
337                 debug_assert_eq!(*self.hashes.offset(idx), EMPTY_BUCKET);
338                 *self.hashes.offset(idx) = hash.inspect();
339                 overwrite(&mut *self.keys.offset(idx), k);
340                 overwrite(&mut *self.vals.offset(idx), v);
341             }
342
343             self.size += 1;
344
345             FullIndex { idx: idx, hash: hash, nocopy: marker::NoCopy }
346         }
347
348         /// Removes a key and value from the hashtable.
349         ///
350         /// This works similarly to `put`, building an `EmptyIndex` out of the
351         /// taken FullIndex.
352         pub fn take(&mut self, index: FullIndex) -> (EmptyIndex, K, V) {
353             let idx  = index.idx;
354
355             unsafe {
356                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
357
358                 *self.hashes.offset(idx) = EMPTY_BUCKET;
359
360                 // Drop the mutable constraint.
361                 let keys = self.keys as *const K;
362                 let vals = self.vals as *const V;
363
364                 let k = ptr::read(keys.offset(idx));
365                 let v = ptr::read(vals.offset(idx));
366
367                 self.size -= 1;
368
369                 (EmptyIndex { idx: idx, nocopy: marker::NoCopy }, k, v)
370             }
371         }
372
373         /// The hashtable's capacity, similar to a vector's.
374         pub fn capacity(&self) -> uint {
375             self.capacity
376         }
377
378         /// The number of elements ever `put` in the hashtable, minus the number
379         /// of elements ever `take`n.
380         pub fn size(&self) -> uint {
381             self.size
382         }
383
384         pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
385             Entries { table: self, idx: 0, elems_seen: 0 }
386         }
387
388         pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
389             MutEntries { table: self, idx: 0, elems_seen: 0 }
390         }
391
392         pub fn move_iter(self) -> MoveEntries<K, V> {
393             MoveEntries { table: self, idx: 0 }
394         }
395     }
396
397     // `read_all_mut` casts a `*u64` to a `*SafeHash`. Since we statically
398     // ensure that a `FullIndex` points to an index with a non-zero hash,
399     // and a `SafeHash` is just a `u64` with a different name, this is
400     // safe.
401     //
402     // This test ensures that a `SafeHash` really IS the same size as a
403     // `u64`. If you need to change the size of `SafeHash` (and
404     // consequently made this test fail), `read_all_mut` needs to be
405     // modified to no longer assume this.
406     #[test]
407     fn can_alias_safehash_as_u64() {
408         assert_eq!(size_of::<SafeHash>(), size_of::<u64>())
409     }
410
411     /// Iterator over shared references to entries in a table.
412     pub struct Entries<'a, K, V> {
413         table: &'a RawTable<K, V>,
414         idx: uint,
415         elems_seen: uint,
416     }
417
418     /// Iterator over mutable references to entries in a table.
419     pub struct MutEntries<'a, K, V> {
420         table: &'a mut RawTable<K, V>,
421         idx: uint,
422         elems_seen: uint,
423     }
424
425     /// Iterator over the entries in a table, consuming the table.
426     pub struct MoveEntries<K, V> {
427         table: RawTable<K, V>,
428         idx: uint
429     }
430
431     impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
432         fn next(&mut self) -> Option<(&'a K, &'a V)> {
433             while self.idx < self.table.capacity() {
434                 let i = self.idx;
435                 self.idx += 1;
436
437                 match self.table.peek(i) {
438                     Empty(_)  => {},
439                     Full(idx) => {
440                         self.elems_seen += 1;
441                         return Some(self.table.read(&idx));
442                     }
443                 }
444             }
445
446             None
447         }
448
449         fn size_hint(&self) -> (uint, Option<uint>) {
450             let size = self.table.size() - self.elems_seen;
451             (size, Some(size))
452         }
453     }
454
455     impl<'a, K, V> Iterator<(&'a K, &'a mut V)> for MutEntries<'a, K, V> {
456         fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
457             while self.idx < self.table.capacity() {
458                 let i = self.idx;
459                 self.idx += 1;
460
461                 match self.table.peek(i) {
462                     Empty(_)  => {},
463                     // the transmute here fixes:
464                     // error: lifetime of `self` is too short to guarantee its contents
465                     //        can be safely reborrowed
466                     Full(idx) => unsafe {
467                         self.elems_seen += 1;
468                         return Some(transmute(self.table.read_mut(&idx)));
469                     }
470                 }
471             }
472
473             None
474         }
475
476         fn size_hint(&self) -> (uint, Option<uint>) {
477             let size = self.table.size() - self.elems_seen;
478             (size, Some(size))
479         }
480     }
481
482     impl<K, V> Iterator<(SafeHash, K, V)> for MoveEntries<K, V> {
483         fn next(&mut self) -> Option<(SafeHash, K, V)> {
484             while self.idx < self.table.capacity() {
485                 let i = self.idx;
486                 self.idx += 1;
487
488                 match self.table.peek(i) {
489                     Empty(_) => {},
490                     Full(idx) => {
491                         let h = idx.hash();
492                         let (_, k, v) = self.table.take(idx);
493                         return Some((h, k, v));
494                     }
495                 }
496             }
497
498             None
499         }
500
501         fn size_hint(&self) -> (uint, Option<uint>) {
502             let size = self.table.size();
503             (size, Some(size))
504         }
505     }
506
507     impl<K: Clone, V: Clone> Clone for RawTable<K, V> {
508         fn clone(&self) -> RawTable<K, V> {
509             unsafe {
510                 let mut new_ht = RawTable::new_uninitialized(self.capacity());
511
512                 for i in range(0, self.capacity()) {
513                     match self.peek(i) {
514                         Empty(_)  => {
515                             *new_ht.hashes.offset(i as int) = EMPTY_BUCKET;
516                         },
517                         Full(idx) => {
518                             let hash = idx.hash().inspect();
519                             let (k, v) = self.read(&idx);
520                             *new_ht.hashes.offset(i as int) = hash;
521                             overwrite(&mut *new_ht.keys.offset(i as int), (*k).clone());
522                             overwrite(&mut *new_ht.vals.offset(i as int), (*v).clone());
523                         }
524                     }
525                 }
526
527                 new_ht.size = self.size();
528
529                 new_ht
530             }
531         }
532     }
533
534     #[unsafe_destructor]
535     impl<K, V> Drop for RawTable<K, V> {
536         fn drop(&mut self) {
537             // This is in reverse because we're likely to have partially taken
538             // some elements out with `.move_iter()` from the front.
539             for i in range_step_inclusive(self.capacity as int - 1, 0, -1) {
540                 // Check if the size is 0, so we don't do a useless scan when
541                 // dropping empty tables such as on resize.
542                 if self.size == 0 { break }
543
544                 match self.peek(i as uint) {
545                     Empty(_)  => {},
546                     Full(idx) => { self.take(idx); }
547                 }
548             }
549
550             assert_eq!(self.size, 0);
551
552             if self.hashes.is_not_null() {
553                 let hashes_size = self.capacity * size_of::<u64>();
554                 let keys_size = self.capacity * size_of::<K>();
555                 let vals_size = self.capacity * size_of::<V>();
556                 let (align, _, _, _, size) = calculate_offsets(hashes_size, min_align_of::<u64>(),
557                                                                keys_size, min_align_of::<K>(),
558                                                                vals_size, min_align_of::<V>());
559
560                 unsafe {
561                     deallocate(self.hashes as *mut u8, size, align);
562                     // Remember how everything was allocated out of one buffer
563                     // during initialization? We only need one call to free here.
564                 }
565
566                 self.hashes = RawPtr::null();
567             }
568         }
569     }
570 }
571
572 static INITIAL_LOG2_CAP: uint = 5;
573 static INITIAL_CAPACITY: uint = 1 << INITIAL_LOG2_CAP; // 2^5
574
575 /// The default behavior of HashMap implements a load factor of 90.9%.
576 /// This behavior is characterized by the following conditions:
577 ///
578 /// - if `size * 1.1 < cap < size * 4` then shouldn't resize
579 /// - if `cap < minimum_capacity * 2` then shouldn't shrink
580 #[deriving(Clone)]
581 struct DefaultResizePolicy {
582     /// Doubled minimal capacity. The capacity must never drop below
583     /// the minimum capacity. (The check happens before the capacity
584     /// is potentially halved.)
585     minimum_capacity2: uint
586 }
587
588 impl DefaultResizePolicy {
589     fn new(new_capacity: uint) -> DefaultResizePolicy {
590         DefaultResizePolicy {
591             minimum_capacity2: new_capacity << 1
592         }
593     }
594
595     #[inline]
596     fn capacity_range(&self, new_size: uint) -> (uint, uint) {
597         ((new_size * 11) / 10, max(new_size << 3, self.minimum_capacity2))
598     }
599
600     #[inline]
601     fn reserve(&mut self, new_capacity: uint) {
602         self.minimum_capacity2 = new_capacity << 1;
603     }
604 }
605
606 // The main performance trick in this hashmap is called Robin Hood Hashing.
607 // It gains its excellent performance from one key invariant:
608 //
609 //    If an insertion collides with an existing element, and that elements
610 //    "probe distance" (how far away the element is from its ideal location)
611 //    is higher than how far we've already probed, swap the elements.
612 //
613 // This massively lowers variance in probe distance, and allows us to get very
614 // high load factors with good performance. The 90% load factor I use is rather
615 // conservative.
616 //
617 // > Why a load factor of approximately 90%?
618 //
619 // In general, all the distances to initial buckets will converge on the mean.
620 // At a load factor of Î±, the odds of finding the target bucket after k
621 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
622 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), Î±=0.92. I round
623 // this down to make the math easier on the CPU and avoid its FPU.
624 // Since on average we start the probing in the middle of a cache line, this
625 // strategy pulls in two cache lines of hashes on every lookup. I think that's
626 // pretty good, but if you want to trade off some space, it could go down to one
627 // cache line on average with an Î± of 0.84.
628 //
629 // > Wait, what? Where did you get 1-α^k from?
630 //
631 // On the first probe, your odds of a collision with an existing element is Î±.
632 // The odds of doing this twice in a row is approximately Î±^2. For three times,
633 // Î±^3, etc. Therefore, the odds of colliding k times is Î±^k. The odds of NOT
634 // colliding after k tries is 1-α^k.
635 //
636 // Future Improvements (FIXME!)
637 // ============================
638 //
639 // Allow the load factor to be changed dynamically and/or at initialization.
640 //
641 // Also, would it be possible for us to reuse storage when growing the
642 // underlying table? This is exactly the use case for 'realloc', and may
643 // be worth exploring.
644 //
645 // Future Optimizations (FIXME!)
646 // =============================
647 //
648 // The paper cited below mentions an implementation which keeps track of the
649 // distance-to-initial-bucket histogram. I'm suspicious of this approach because
650 // it requires maintaining an internal map. If this map were replaced with a
651 // hashmap, it would be faster, but now our data structure is self-referential
652 // and blows up. Also, this allows very good first guesses, but array accesses
653 // are no longer linear and in one direction, as we have now. There is also
654 // memory and cache pressure that this map would entail that would be very
655 // difficult to properly see in a microbenchmark.
656 //
657 // Another possible design choice that I made without any real reason is
658 // parameterizing the raw table over keys and values. Technically, all we need
659 // is the size and alignment of keys and values, and the code should be just as
660 // efficient (well, we might need one for power-of-two size and one for not...).
661 // This has the potential to reduce code bloat in rust executables, without
662 // really losing anything except 4 words (key size, key alignment, val size,
663 // val alignment) which can be passed in to every call of a `RawTable` function.
664 // This would definitely be an avenue worth exploring if people start complaining
665 // about the size of rust executables.
666 //
667 // There's also an "optimization" that has been omitted regarding how the
668 // hashtable allocates. The vector type has set the expectation that a hashtable
669 // which never has an element inserted should not allocate. I'm suspicious of
670 // implementing this for hashtables, because supporting it has no performance
671 // benefit over using an `Option<HashMap<K, V>>`, and is significantly more
672 // complicated.
673
674 /// A hash map implementation which uses linear probing with Robin
675 /// Hood bucket stealing.
676 ///
677 /// The hashes are all keyed by the task-local random number generator
678 /// on creation by default, this means the ordering of the keys is
679 /// randomized, but makes the tables more resistant to
680 /// denial-of-service attacks (Hash DoS). This behaviour can be
681 /// overridden with one of the constructors.
682 ///
683 /// It is required that the keys implement the `Eq` and `Hash` traits, although
684 /// this can frequently be achieved by using `#[deriving(Eq, Hash)]`.
685 ///
686 /// Relevant papers/articles:
687 ///
688 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
689 /// 2. Emmanuel Goossaert. ["Robin Hood
690 ///    hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
691 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
692 ///    deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
693 ///
694 /// # Example
695 ///
696 /// ```
697 /// use std::collections::HashMap;
698 ///
699 /// // type inference lets us omit an explicit type signature (which
700 /// // would be `HashMap<&str, &str>` in this example).
701 /// let mut book_reviews = HashMap::new();
702 ///
703 /// // review some books.
704 /// book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.");
705 /// book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
706 /// book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
707 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
708 ///
709 /// // check for a specific one.
710 /// if !book_reviews.contains_key(&("Les Misérables")) {
711 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
712 ///              book_reviews.len());
713 /// }
714 ///
715 /// // oops, this review has a lot of spelling mistakes, let's delete it.
716 /// book_reviews.remove(&("The Adventures of Sherlock Holmes"));
717 ///
718 /// // look up the values associated with some keys.
719 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
720 /// for book in to_find.iter() {
721 ///     match book_reviews.find(book) {
722 ///         Some(review) => println!("{}: {}", *book, *review),
723 ///         None => println!("{} is unreviewed.", *book)
724 ///     }
725 /// }
726 ///
727 /// // iterate over everything.
728 /// for (book, review) in book_reviews.iter() {
729 ///     println!("{}: \"{}\"", *book, *review);
730 /// }
731 /// ```
732 ///
733 /// The easiest way to use `HashMap` with a custom type is to derive `Eq` and `Hash`.
734 /// We must also derive `PartialEq`.
735 ///
736 /// ```
737 /// use std::collections::HashMap;
738 ///
739 /// #[deriving(Hash, Eq, PartialEq, Show)]
740 /// struct Viking<'a> {
741 ///     name: &'a str,
742 ///     power: uint,
743 /// }
744 ///
745 /// let mut vikings = HashMap::new();
746 ///
747 /// vikings.insert("Norway", Viking { name: "Einar", power: 9u });
748 /// vikings.insert("Denmark", Viking { name: "Olaf", power: 4u });
749 /// vikings.insert("Iceland", Viking { name: "Harald", power: 8u });
750 ///
751 /// // Use derived implementation to print the vikings.
752 /// for (land, viking) in vikings.iter() {
753 ///     println!("{} at {}", viking, land);
754 /// }
755 /// ```
756 #[deriving(Clone)]
757 pub struct HashMap<K, V, H = RandomSipHasher> {
758     // All hashes are keyed on these values, to prevent hash collision attacks.
759     hasher: H,
760
761     table: table::RawTable<K, V>,
762
763     // We keep this at the end since it might as well have tail padding.
764     resize_policy: DefaultResizePolicy,
765 }
766
767 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
768     // Probe the `idx`th bucket for a given hash, returning the index of the
769     // target bucket.
770     //
771     // This exploits the power-of-two size of the hashtable. As long as this
772     // is always true, we can use a bitmask of cap-1 to do modular arithmetic.
773     //
774     // Prefer using this with increasing values of `idx` rather than repeatedly
775     // calling `probe_next`. This reduces data-dependencies between loops, which
776     // can help the optimizer, and certainly won't hurt it. `probe_next` is
777     // simply for convenience, and is no more efficient than `probe`.
778     fn probe(&self, hash: &table::SafeHash, idx: uint) -> uint {
779         let hash_mask = self.table.capacity() - 1;
780
781         // So I heard a rumor that unsigned overflow is safe in rust..
782         ((hash.inspect() as uint) + idx) & hash_mask
783     }
784
785     // Generate the next probe in a sequence. Prefer using 'probe' by itself,
786     // but this can sometimes be useful.
787     fn probe_next(&self, probe: uint) -> uint {
788         let hash_mask = self.table.capacity() - 1;
789         (probe + 1) & hash_mask
790     }
791
792     fn make_hash<X: Hash<S>>(&self, x: &X) -> table::SafeHash {
793         table::make_hash(&self.hasher, x)
794     }
795
796     /// Get the distance of the bucket at the given index that it lies
797     /// from its 'ideal' location.
798     ///
799     /// In the cited blog posts above, this is called the "distance to
800     /// initial bucket", or DIB.
801     fn bucket_distance(&self, index_of_elem: &table::FullIndex) -> uint {
802         // where the hash of the element that happens to reside at
803         // `index_of_elem` tried to place itself first.
804         let first_probe_index = self.probe(&index_of_elem.hash(), 0);
805
806         let raw_index = index_of_elem.raw_index();
807
808         if first_probe_index <= raw_index {
809              // probe just went forward
810             raw_index - first_probe_index
811         } else {
812             // probe wrapped around the hashtable
813             raw_index + (self.table.capacity() - first_probe_index)
814         }
815     }
816
817     /// Search for a pre-hashed key.
818     fn search_hashed_generic(&self, hash: &table::SafeHash, is_match: |&K| -> bool)
819         -> Option<table::FullIndex> {
820         for num_probes in range(0u, self.table.size()) {
821             let probe = self.probe(hash, num_probes);
822
823             let idx = match self.table.peek(probe) {
824                 table::Empty(_)  => return None, // hit an empty bucket
825                 table::Full(idx) => idx
826             };
827
828             // We can finish the search early if we hit any bucket
829             // with a lower distance to initial bucket than we've probed.
830             if self.bucket_distance(&idx) < num_probes { return None }
831
832             // If the hash doesn't match, it can't be this one..
833             if *hash != idx.hash() { continue }
834
835             let (k, _) = self.table.read(&idx);
836
837             // If the key doesn't match, it can't be this one..
838             if !is_match(k) { continue }
839
840             return Some(idx);
841         }
842
843         return None
844     }
845
846     fn search_hashed(&self, hash: &table::SafeHash, k: &K) -> Option<table::FullIndex> {
847         self.search_hashed_generic(hash, |k_| *k == *k_)
848     }
849
850     fn search_equiv<Q: Hash<S> + Equiv<K>>(&self, q: &Q) -> Option<table::FullIndex> {
851         self.search_hashed_generic(&self.make_hash(q), |k| q.equiv(k))
852     }
853
854     /// Search for a key, yielding the index if it's found in the hashtable.
855     /// If you already have the hash for the key lying around, use
856     /// search_hashed.
857     fn search(&self, k: &K) -> Option<table::FullIndex> {
858         self.search_hashed(&self.make_hash(k), k)
859     }
860
861     fn pop_internal(&mut self, starting_index: table::FullIndex) -> Option<V> {
862         let starting_probe = starting_index.raw_index();
863
864         let ending_probe = {
865             let mut probe = self.probe_next(starting_probe);
866             for _ in range(0u, self.table.size()) {
867                 match self.table.peek(probe) {
868                     table::Empty(_) => {}, // empty bucket. this is the end of our shifting.
869                     table::Full(idx) => {
870                         // Bucket that isn't us, which has a non-zero probe distance.
871                         // This isn't the ending index, so keep searching.
872                         if self.bucket_distance(&idx) != 0 {
873                             probe = self.probe_next(probe);
874                             continue;
875                         }
876
877                         // if we do have a bucket_distance of zero, we're at the end
878                         // of what we need to shift.
879                     }
880                 }
881                 break;
882             }
883
884             probe
885         };
886
887         let (_, _, retval) = self.table.take(starting_index);
888
889         let mut      probe = starting_probe;
890         let mut next_probe = self.probe_next(probe);
891
892         // backwards-shift all the elements after our newly-deleted one.
893         while next_probe != ending_probe {
894             match self.table.peek(next_probe) {
895                 table::Empty(_) => {
896                     // nothing to shift in. just empty it out.
897                     match self.table.peek(probe) {
898                         table::Empty(_) => {},
899                         table::Full(idx) => { self.table.take(idx); }
900                     }
901                 },
902                 table::Full(next_idx) => {
903                     // something to shift. move it over!
904                     let next_hash = next_idx.hash();
905                     let (_, next_key, next_val) = self.table.take(next_idx);
906                     match self.table.peek(probe) {
907                         table::Empty(idx) => {
908                             self.table.put(idx, next_hash, next_key, next_val);
909                         },
910                         table::Full(idx) => {
911                             let (emptyidx, _, _) = self.table.take(idx);
912                             self.table.put(emptyidx, next_hash, next_key, next_val);
913                         }
914                     }
915                 }
916             }
917
918             probe = next_probe;
919             next_probe = self.probe_next(next_probe);
920         }
921
922         // Done the backwards shift, but there's still an element left!
923         // Empty it out.
924         match self.table.peek(probe) {
925             table::Empty(_) => {},
926             table::Full(idx) => { self.table.take(idx); }
927         }
928
929         // Now we're done all our shifting. Return the value we grabbed
930         // earlier.
931         return Some(retval);
932     }
933 }
934
935 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Collection for HashMap<K, V, H> {
936     /// Return the number of elements in the map.
937     fn len(&self) -> uint { self.table.size() }
938 }
939
940 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Mutable for HashMap<K, V, H> {
941     /// Clear the map, removing all key-value pairs. Keeps the allocated memory
942     /// for reuse.
943     fn clear(&mut self) {
944         // Prevent reallocations from happening from now on. Makes it possible
945         // for the map to be reused but has a downside: reserves permanently.
946         self.resize_policy.reserve(self.table.size());
947
948         for i in range(0, self.table.capacity()) {
949             match self.table.peek(i) {
950                 table::Empty(_)  => {},
951                 table::Full(idx) => { self.table.take(idx); }
952             }
953         }
954     }
955 }
956
957 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Map<K, V> for HashMap<K, V, H> {
958     fn find<'a>(&'a self, k: &K) -> Option<&'a V> {
959         self.search(k).map(|idx| {
960             let (_, v) = self.table.read(&idx);
961             v
962         })
963     }
964
965     fn contains_key(&self, k: &K) -> bool {
966         self.search(k).is_some()
967     }
968 }
969
970 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> MutableMap<K, V> for HashMap<K, V, H> {
971     fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> {
972         match self.search(k) {
973             None => None,
974             Some(idx) => {
975                 let (_, v) = self.table.read_mut(&idx);
976                 Some(v)
977             }
978         }
979     }
980
981     fn swap(&mut self, k: K, v: V) -> Option<V> {
982         let hash = self.make_hash(&k);
983         let potential_new_size = self.table.size() + 1;
984         self.make_some_room(potential_new_size);
985
986         for dib in range_inclusive(0u, self.table.size()) {
987             let probe = self.probe(&hash, dib);
988
989             let idx = match self.table.peek(probe) {
990                 table::Empty(idx) => {
991                     // Found a hole!
992                     self.table.put(idx, hash, k, v);
993                     return None;
994                 },
995                 table::Full(idx) => idx
996             };
997
998             if idx.hash() == hash {
999                 let (bucket_k, bucket_v) = self.table.read_mut(&idx);
1000                 if k == *bucket_k {
1001                     // Found an existing value.
1002                     return Some(replace(bucket_v, v));
1003                 }
1004             }
1005
1006             let probe_dib = self.bucket_distance(&idx);
1007
1008             if probe_dib < dib {
1009                 // Found a luckier bucket. This implies that the key does not
1010                 // already exist in the hashtable. Just do a robin hood
1011                 // insertion, then.
1012                 self.robin_hood(idx, probe_dib, hash, k, v);
1013                 return None;
1014             }
1015         }
1016
1017         // We really shouldn't be here.
1018         fail!("Internal HashMap error: Out of space.");
1019     }
1020
1021     fn pop(&mut self, k: &K) -> Option<V> {
1022         if self.table.size() == 0 {
1023             return None
1024         }
1025
1026         let potential_new_size = self.table.size() - 1;
1027         self.make_some_room(potential_new_size);
1028
1029         let starting_index = match self.search(k) {
1030             Some(idx) => idx,
1031             None      => return None,
1032         };
1033
1034         self.pop_internal(starting_index)
1035     }
1036
1037 }
1038
1039 impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> {
1040     /// Create an empty HashMap.
1041     ///
1042     /// # Example
1043     ///
1044     /// ```
1045     /// use std::collections::HashMap;
1046     /// let mut map: HashMap<&str, int> = HashMap::new();
1047     /// ```
1048     #[inline]
1049     pub fn new() -> HashMap<K, V, RandomSipHasher> {
1050         HashMap::with_capacity(INITIAL_CAPACITY)
1051     }
1052
1053     /// Creates an empty hash map with the given initial capacity.
1054     ///
1055     /// # Example
1056     ///
1057     /// ```
1058     /// use std::collections::HashMap;
1059     /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
1060     /// ```
1061     #[inline]
1062     pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomSipHasher> {
1063         let hasher = RandomSipHasher::new();
1064         HashMap::with_capacity_and_hasher(capacity, hasher)
1065     }
1066 }
1067
1068 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
1069     /// Creates an empty hashmap which will use the given hasher to hash keys.
1070     ///
1071     /// The creates map has the default initial capacity.
1072     ///
1073     /// # Example
1074     ///
1075     /// ```
1076     /// use std::collections::HashMap;
1077     /// use std::hash::sip::SipHasher;
1078     ///
1079     /// let h = SipHasher::new();
1080     /// let mut map = HashMap::with_hasher(h);
1081     /// map.insert(1i, 2u);
1082     /// ```
1083     #[inline]
1084     pub fn with_hasher(hasher: H) -> HashMap<K, V, H> {
1085         HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
1086     }
1087
1088     /// Create an empty HashMap with space for at least `capacity`
1089     /// elements, using `hasher` to hash the keys.
1090     ///
1091     /// Warning: `hasher` is normally randomly generated, and
1092     /// is designed to allow HashMaps to be resistant to attacks that
1093     /// cause many collisions and very poor performance. Setting it
1094     /// manually using this function can expose a DoS attack vector.
1095     ///
1096     /// # Example
1097     ///
1098     /// ```
1099     /// use std::collections::HashMap;
1100     /// use std::hash::sip::SipHasher;
1101     ///
1102     /// let h = SipHasher::new();
1103     /// let mut map = HashMap::with_capacity_and_hasher(10, h);
1104     /// map.insert(1i, 2u);
1105     /// ```
1106     #[inline]
1107     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap<K, V, H> {
1108         let cap = num::next_power_of_two(max(INITIAL_CAPACITY, capacity));
1109         HashMap {
1110             hasher:        hasher,
1111             resize_policy: DefaultResizePolicy::new(cap),
1112             table:         table::RawTable::new(cap),
1113         }
1114     }
1115
1116     /// The hashtable will never try to shrink below this size. You can use
1117     /// this function to reduce reallocations if your hashtable frequently
1118     /// grows and shrinks by large amounts.
1119     ///
1120     /// This function has no effect on the operational semantics of the
1121     /// hashtable, only on performance.
1122     ///
1123     /// ```
1124     /// use std::collections::HashMap;
1125     /// let mut map: HashMap<&str, int> = HashMap::new();
1126     /// map.reserve(10);
1127     /// ```
1128     pub fn reserve(&mut self, new_minimum_capacity: uint) {
1129         let cap = num::next_power_of_two(
1130             max(INITIAL_CAPACITY, new_minimum_capacity));
1131
1132         self.resize_policy.reserve(cap);
1133
1134         if self.table.capacity() < cap {
1135             self.resize(cap);
1136         }
1137     }
1138
1139     /// Resizes the internal vectors to a new capacity. It's your responsibility to:
1140     ///   1) Make sure the new capacity is enough for all the elements, accounting
1141     ///      for the load factor.
1142     ///   2) Ensure new_capacity is a power of two.
1143     fn resize(&mut self, new_capacity: uint) {
1144         assert!(self.table.size() <= new_capacity);
1145         assert!(num::is_power_of_two(new_capacity));
1146
1147         let old_table = replace(&mut self.table, table::RawTable::new(new_capacity));
1148         let old_size  = old_table.size();
1149
1150         for (h, k, v) in old_table.move_iter() {
1151             self.insert_hashed_nocheck(h, k, v);
1152         }
1153
1154         assert_eq!(self.table.size(), old_size);
1155     }
1156
1157     /// Performs any necessary resize operations, such that there's space for
1158     /// new_size elements.
1159     fn make_some_room(&mut self, new_size: uint) {
1160         let (grow_at, shrink_at) = self.resize_policy.capacity_range(new_size);
1161         let cap = self.table.capacity();
1162
1163         // An invalid value shouldn't make us run out of space.
1164         debug_assert!(grow_at >= new_size);
1165
1166         if cap <= grow_at {
1167             let new_capacity = cap << 1;
1168             self.resize(new_capacity);
1169         } else if shrink_at <= cap {
1170             let new_capacity = cap >> 1;
1171             self.resize(new_capacity);
1172         }
1173     }
1174
1175     /// Perform robin hood bucket stealing at the given 'index'. You must
1176     /// also pass that probe's "distance to initial bucket" so we don't have
1177     /// to recalculate it, as well as the total number of probes already done
1178     /// so we have some sort of upper bound on the number of probes to do.
1179     ///
1180     /// 'hash', 'k', and 'v' are the elements to robin hood into the hashtable.
1181     fn robin_hood(&mut self, mut index: table::FullIndex, mut dib_param: uint,
1182                   mut hash: table::SafeHash, mut k: K, mut v: V) {
1183         'outer: loop {
1184             let (old_hash, old_key, old_val) = {
1185                 let (old_hash_ref, old_key_ref, old_val_ref) =
1186                         self.table.read_all_mut(&index);
1187
1188                 let old_hash = replace(old_hash_ref, hash);
1189                 let old_key  = replace(old_key_ref,  k);
1190                 let old_val  = replace(old_val_ref,  v);
1191
1192                 (old_hash, old_key, old_val)
1193             };
1194
1195             let mut probe = self.probe_next(index.raw_index());
1196
1197             for dib in range(dib_param + 1, self.table.size()) {
1198                 let full_index = match self.table.peek(probe) {
1199                     table::Empty(idx) => {
1200                         // Finally. A hole!
1201                         self.table.put(idx, old_hash, old_key, old_val);
1202                         return;
1203                     },
1204                     table::Full(idx) => idx
1205                 };
1206
1207                 let probe_dib = self.bucket_distance(&full_index);
1208
1209                 // Robin hood! Steal the spot.
1210                 if probe_dib < dib {
1211                     index = full_index;
1212                     dib_param = probe_dib;
1213                     hash = old_hash;
1214                     k = old_key;
1215                     v = old_val;
1216                     continue 'outer;
1217                 }
1218
1219                 probe = self.probe_next(probe);
1220             }
1221
1222             fail!("HashMap fatal error: 100% load factor?");
1223         }
1224     }
1225
1226     /// Insert a pre-hashed key-value pair, without first checking
1227     /// that there's enough room in the buckets. Returns a reference to the
1228     /// newly insert value.
1229     ///
1230     /// If the key already exists, the hashtable will be returned untouched
1231     /// and a reference to the existing element will be returned.
1232     fn insert_hashed_nocheck<'a>(
1233         &'a mut self, hash: table::SafeHash, k: K, v: V) -> &'a mut V {
1234
1235         for dib in range_inclusive(0u, self.table.size()) {
1236             let probe = self.probe(&hash, dib);
1237
1238             let idx = match self.table.peek(probe) {
1239                 table::Empty(idx) => {
1240                     // Found a hole!
1241                     let fullidx  = self.table.put(idx, hash, k, v);
1242                     let (_, val) = self.table.read_mut(&fullidx);
1243                     return val;
1244                 },
1245                 table::Full(idx) => idx
1246             };
1247
1248             if idx.hash() == hash {
1249                 let (bucket_k, bucket_v) = self.table.read_mut(&idx);
1250                 // FIXME #12147 the conditional return confuses
1251                 // borrowck if we return bucket_v directly
1252                 let bv: *mut V = bucket_v;
1253                 if k == *bucket_k {
1254                     // Key already exists. Get its reference.
1255                     return unsafe {&mut *bv};
1256                 }
1257             }
1258
1259             let probe_dib = self.bucket_distance(&idx);
1260
1261             if  probe_dib < dib {
1262                 // Found a luckier bucket than me. Better steal his spot.
1263                 self.robin_hood(idx, probe_dib, hash, k, v);
1264
1265                 // Now that it's stolen, just read the value's pointer
1266                 // right out of the table!
1267                 match self.table.peek(probe) {
1268                     table::Empty(_)  => fail!("Just stole a spot, but now that spot's empty."),
1269                     table::Full(idx) => {
1270                         let (_, v) = self.table.read_mut(&idx);
1271                         return v;
1272                     }
1273                 }
1274             }
1275         }
1276
1277         // We really shouldn't be here.
1278         fail!("Internal HashMap error: Out of space.");
1279     }
1280
1281     /// Inserts an element which has already been hashed, returning a reference
1282     /// to that element inside the hashtable. This is more efficient that using
1283     /// `insert`, since the key will not be rehashed.
1284     fn insert_hashed<'a>(&'a mut self, hash: table::SafeHash, k: K, v: V) -> &'a mut V {
1285         let potential_new_size = self.table.size() + 1;
1286         self.make_some_room(potential_new_size);
1287         self.insert_hashed_nocheck(hash, k, v)
1288     }
1289
1290     /// Return the value corresponding to the key in the map, or insert
1291     /// and return the value if it doesn't exist.
1292     ///
1293     /// # Example
1294     ///
1295     /// ```
1296     /// use std::collections::HashMap;
1297     /// let mut map = HashMap::new();
1298     ///
1299     /// // Insert 1i with key "a"
1300     /// assert_eq!(*map.find_or_insert("a", 1i), 1);
1301     ///
1302     /// // Find the existing key
1303     /// assert_eq!(*map.find_or_insert("a", -2), 1);
1304     /// ```
1305     pub fn find_or_insert<'a>(&'a mut self, k: K, v: V) -> &'a mut V {
1306         self.find_with_or_insert_with(k, v, |_k, _v, _a| (), |_k, a| a)
1307     }
1308
1309     /// Return the value corresponding to the key in the map, or create,
1310     /// insert, and return a new value if it doesn't exist.
1311     ///
1312     /// # Example
1313     ///
1314     /// ```
1315     /// use std::collections::HashMap;
1316     /// let mut map = HashMap::new();
1317     ///
1318     /// // Insert 10 with key 2
1319     /// assert_eq!(*map.find_or_insert_with(2i, |&key| 5 * key as uint), 10u);
1320     ///
1321     /// // Find the existing key
1322     /// assert_eq!(*map.find_or_insert_with(2, |&key| key as uint), 10);
1323     /// ```
1324     pub fn find_or_insert_with<'a>(&'a mut self, k: K, f: |&K| -> V)
1325                                -> &'a mut V {
1326         self.find_with_or_insert_with(k, (), |_k, _v, _a| (), |k, _a| f(k))
1327     }
1328
1329     /// Insert a key-value pair into the map if the key is not already present.
1330     /// Otherwise, modify the existing value for the key.
1331     /// Returns the new or modified value for the key.
1332     ///
1333     /// # Example
1334     ///
1335     /// ```
1336     /// use std::collections::HashMap;
1337     /// let mut map = HashMap::new();
1338     ///
1339     /// // Insert 2 with key "a"
1340     /// assert_eq!(*map.insert_or_update_with("a", 2u, |_key, val| *val = 3), 2);
1341     ///
1342     /// // Update and return the existing value
1343     /// assert_eq!(*map.insert_or_update_with("a", 9, |_key, val| *val = 7), 7);
1344     /// assert_eq!(map.get(&"a"), &7);
1345     /// ```
1346     pub fn insert_or_update_with<'a>(
1347                                  &'a mut self,
1348                                  k: K,
1349                                  v: V,
1350                                  f: |&K, &mut V|)
1351                                  -> &'a mut V {
1352         self.find_with_or_insert_with(k, v, |k, v, _a| f(k, v), |_k, a| a)
1353     }
1354
1355     /// Modify and return the value corresponding to the key in the map, or
1356     /// insert and return a new value if it doesn't exist.
1357     ///
1358     /// This method allows for all insertion behaviours of a hashmap;
1359     /// see methods like
1360     /// [`insert`](../trait.MutableMap.html#tymethod.insert),
1361     /// [`find_or_insert`](#method.find_or_insert) and
1362     /// [`insert_or_update_with`](#method.insert_or_update_with)
1363     /// for less general and more friendly variations of this.
1364     ///
1365     /// # Example
1366     ///
1367     /// ```
1368     /// use std::collections::HashMap;
1369     ///
1370     /// // map some strings to vectors of strings
1371     /// let mut map = HashMap::new();
1372     /// map.insert("a key", vec!["value"]);
1373     /// map.insert("z key", vec!["value"]);
1374     ///
1375     /// let new = vec!["a key", "b key", "z key"];
1376     ///
1377     /// for k in new.move_iter() {
1378     ///     map.find_with_or_insert_with(
1379     ///         k, "new value",
1380     ///         // if the key does exist either prepend or append this
1381     ///         // new value based on the first letter of the key.
1382     ///         |key, already, new| {
1383     ///             if key.as_slice().starts_with("z") {
1384     ///                 already.insert(0, new);
1385     ///             } else {
1386     ///                 already.push(new);
1387     ///             }
1388     ///         },
1389     ///         // if the key doesn't exist in the map yet, add it in
1390     ///         // the obvious way.
1391     ///         |_k, v| vec![v]);
1392     /// }
1393     ///
1394     /// assert_eq!(map.len(), 3);
1395     /// assert_eq!(map.get(&"a key"), &vec!["value", "new value"]);
1396     /// assert_eq!(map.get(&"b key"), &vec!["new value"]);
1397     /// assert_eq!(map.get(&"z key"), &vec!["new value", "value"]);
1398     /// ```
1399     pub fn find_with_or_insert_with<'a, A>(&'a mut self,
1400                                            k: K,
1401                                            a: A,
1402                                            found: |&K, &mut V, A|,
1403                                            not_found: |&K, A| -> V)
1404                                           -> &'a mut V {
1405         let hash = self.make_hash(&k);
1406         match self.search_hashed(&hash, &k) {
1407             None => {
1408                 let v = not_found(&k, a);
1409                 self.insert_hashed(hash, k, v)
1410             },
1411             Some(idx) => {
1412                 let (_, v_ref) = self.table.read_mut(&idx);
1413                 found(&k, v_ref, a);
1414                 v_ref
1415             }
1416         }
1417     }
1418
1419     /// Retrieves a value for the given key.
1420     /// See [`find`](../trait.Map.html#tymethod.find) for a non-failing alternative.
1421     ///
1422     /// # Failure
1423     ///
1424     /// Fails if the key is not present.
1425     ///
1426     /// # Example
1427     ///
1428     /// ```
1429     /// use std::collections::HashMap;
1430     ///
1431     /// let mut map = HashMap::new();
1432     /// map.insert("a", 1i);
1433     /// assert_eq!(map.get(&"a"), &1);
1434     /// ```
1435     pub fn get<'a>(&'a self, k: &K) -> &'a V {
1436         match self.find(k) {
1437             Some(v) => v,
1438             None => fail!("no entry found for key")
1439         }
1440     }
1441
1442     /// Retrieves a mutable value for the given key.
1443     /// See [`find_mut`](../trait.MutableMap.html#tymethod.find_mut) for a non-failing alternative.
1444     ///
1445     /// # Failure
1446     ///
1447     /// Fails if the key is not present.
1448     ///
1449     /// # Example
1450     ///
1451     /// ```
1452     /// use std::collections::HashMap;
1453     ///
1454     /// let mut map = HashMap::new();
1455     /// map.insert("a", 1i);
1456     /// {
1457     ///     // val will freeze map to prevent usage during its lifetime
1458     ///     let val = map.get_mut(&"a");
1459     ///     *val = 40;
1460     /// }
1461     /// assert_eq!(map.get(&"a"), &40);
1462     ///
1463     /// // A more direct way could be:
1464     /// *map.get_mut(&"a") = -2;
1465     /// assert_eq!(map.get(&"a"), &-2);
1466     /// ```
1467     pub fn get_mut<'a>(&'a mut self, k: &K) -> &'a mut V {
1468         match self.find_mut(k) {
1469             Some(v) => v,
1470             None => fail!("no entry found for key")
1471         }
1472     }
1473
1474     /// Return true if the map contains a value for the specified key,
1475     /// using equivalence.
1476     ///
1477     /// See [pop_equiv](#method.pop_equiv) for an extended example.
1478     pub fn contains_key_equiv<Q: Hash<S> + Equiv<K>>(&self, key: &Q) -> bool {
1479         self.search_equiv(key).is_some()
1480     }
1481
1482     /// Return the value corresponding to the key in the map, using
1483     /// equivalence.
1484     ///
1485     /// See [pop_equiv](#method.pop_equiv) for an extended example.
1486     pub fn find_equiv<'a, Q: Hash<S> + Equiv<K>>(&'a self, k: &Q) -> Option<&'a V> {
1487         match self.search_equiv(k) {
1488             None      => None,
1489             Some(idx) => {
1490                 let (_, v_ref) = self.table.read(&idx);
1491                 Some(v_ref)
1492             }
1493         }
1494     }
1495
1496     /// Remove an equivalent key from the map, returning the value at the
1497     /// key if the key was previously in the map.
1498     ///
1499     /// # Example
1500     ///
1501     /// This is a slightly silly example where we define the number's parity as
1502     /// the equivalence class. It is important that the values hash the same,
1503     /// which is why we override `Hash`.
1504     ///
1505     /// ```
1506     /// use std::collections::HashMap;
1507     /// use std::hash::Hash;
1508     /// use std::hash::sip::SipState;
1509     ///
1510     /// #[deriving(Eq, PartialEq)]
1511     /// struct EvenOrOdd {
1512     ///     num: uint
1513     /// };
1514     ///
1515     /// impl Hash for EvenOrOdd {
1516     ///     fn hash(&self, state: &mut SipState) {
1517     ///         let parity = self.num % 2;
1518     ///         parity.hash(state);
1519     ///     }
1520     /// }
1521     ///
1522     /// impl Equiv<EvenOrOdd> for EvenOrOdd {
1523     ///     fn equiv(&self, other: &EvenOrOdd) -> bool {
1524     ///         self.num % 2 == other.num % 2
1525     ///     }
1526     /// }
1527     ///
1528     /// let mut map = HashMap::new();
1529     /// map.insert(EvenOrOdd { num: 3 }, "foo");
1530     ///
1531     /// assert!(map.contains_key_equiv(&EvenOrOdd { num: 1 }));
1532     /// assert!(!map.contains_key_equiv(&EvenOrOdd { num: 4 }));
1533     ///
1534     /// assert_eq!(map.find_equiv(&EvenOrOdd { num: 5 }), Some(&"foo"));
1535     /// assert_eq!(map.find_equiv(&EvenOrOdd { num: 2 }), None);
1536     ///
1537     /// assert_eq!(map.pop_equiv(&EvenOrOdd { num: 1 }), Some("foo"));
1538     /// assert_eq!(map.pop_equiv(&EvenOrOdd { num: 2 }), None);
1539     ///
1540     /// ```
1541     #[experimental]
1542     pub fn pop_equiv<Q:Hash<S> + Equiv<K>>(&mut self, k: &Q) -> Option<V> {
1543         if self.table.size() == 0 {
1544             return None
1545         }
1546
1547         let potential_new_size = self.table.size() - 1;
1548         self.make_some_room(potential_new_size);
1549
1550         let starting_index = match self.search_equiv(k) {
1551             Some(idx) => idx,
1552             None      => return None,
1553         };
1554
1555         self.pop_internal(starting_index)
1556     }
1557
1558     /// An iterator visiting all keys in arbitrary order.
1559     /// Iterator element type is `&'a K`.
1560     ///
1561     /// # Example
1562     ///
1563     /// ```
1564     /// use std::collections::HashMap;
1565     ///
1566     /// let mut map = HashMap::new();
1567     /// map.insert("a", 1i);
1568     /// map.insert("b", 2);
1569     /// map.insert("c", 3);
1570     ///
1571     /// for key in map.keys() {
1572     ///     println!("{}", key);
1573     /// }
1574     /// ```
1575     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1576         self.iter().map(|(k, _v)| k)
1577     }
1578
1579     /// An iterator visiting all values in arbitrary order.
1580     /// Iterator element type is `&'a V`.
1581     ///
1582     /// # Example
1583     ///
1584     /// ```
1585     /// use std::collections::HashMap;
1586     ///
1587     /// let mut map = HashMap::new();
1588     /// map.insert("a", 1i);
1589     /// map.insert("b", 2);
1590     /// map.insert("c", 3);
1591     ///
1592     /// for key in map.values() {
1593     ///     println!("{}", key);
1594     /// }
1595     /// ```
1596     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1597         self.iter().map(|(_k, v)| v)
1598     }
1599
1600     /// An iterator visiting all key-value pairs in arbitrary order.
1601     /// Iterator element type is `(&'a K, &'a V)`.
1602     ///
1603     /// # Example
1604     ///
1605     /// ```
1606     /// use std::collections::HashMap;
1607     ///
1608     /// let mut map = HashMap::new();
1609     /// map.insert("a", 1i);
1610     /// map.insert("b", 2);
1611     /// map.insert("c", 3);
1612     ///
1613     /// for (key, val) in map.iter() {
1614     ///     println!("key: {} val: {}", key, val);
1615     /// }
1616     /// ```
1617     pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
1618         self.table.iter()
1619     }
1620
1621     /// An iterator visiting all key-value pairs in arbitrary order,
1622     /// with mutable references to the values.
1623     /// Iterator element type is `(&'a K, &'a mut V)`.
1624     ///
1625     /// # Example
1626     ///
1627     /// ```
1628     /// use std::collections::HashMap;
1629     ///
1630     /// let mut map = HashMap::new();
1631     /// map.insert("a", 1i);
1632     /// map.insert("b", 2);
1633     /// map.insert("c", 3);
1634     ///
1635     /// // Update all values
1636     /// for (_, val) in map.mut_iter() {
1637     ///     *val *= 2;
1638     /// }
1639     ///
1640     /// for (key, val) in map.iter() {
1641     ///     println!("key: {} val: {}", key, val);
1642     /// }
1643     /// ```
1644     pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
1645         self.table.mut_iter()
1646     }
1647
1648     /// Creates a consuming iterator, that is, one that moves each key-value
1649     /// pair out of the map in arbitrary order. The map cannot be used after
1650     /// calling this.
1651     ///
1652     /// # Example
1653     ///
1654     /// ```
1655     /// use std::collections::HashMap;
1656     ///
1657     /// let mut map = HashMap::new();
1658     /// map.insert("a", 1i);
1659     /// map.insert("b", 2);
1660     /// map.insert("c", 3);
1661     ///
1662     /// // Not possible with .iter()
1663     /// let vec: Vec<(&str, int)> = map.move_iter().collect();
1664     /// ```
1665     pub fn move_iter(self) -> MoveEntries<K, V> {
1666         self.table.move_iter().map(|(_, k, v)| (k, v))
1667     }
1668 }
1669
1670 impl<K: Eq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
1671     /// Return a copy of the value corresponding to the key.
1672     ///
1673     /// # Example
1674     ///
1675     /// ```
1676     /// use std::collections::HashMap;
1677     ///
1678     /// let mut map: HashMap<uint, String> = HashMap::new();
1679     /// map.insert(1u, "foo".to_string());
1680     /// let s: String = map.find_copy(&1).unwrap();
1681     /// ```
1682     pub fn find_copy(&self, k: &K) -> Option<V> {
1683         self.find(k).map(|v| (*v).clone())
1684     }
1685
1686     /// Return a copy of the value corresponding to the key.
1687     ///
1688     /// # Failure
1689     ///
1690     /// Fails if the key is not present.
1691     ///
1692     /// # Example
1693     ///
1694     /// ```
1695     /// use std::collections::HashMap;
1696     ///
1697     /// let mut map: HashMap<uint, String> = HashMap::new();
1698     /// map.insert(1u, "foo".to_string());
1699     /// let s: String = map.get_copy(&1);
1700     /// ```
1701     pub fn get_copy(&self, k: &K) -> V {
1702         (*self.get(k)).clone()
1703     }
1704 }
1705
1706 impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, H> {
1707     fn eq(&self, other: &HashMap<K, V, H>) -> bool {
1708         if self.len() != other.len() { return false; }
1709
1710         self.iter()
1711           .all(|(key, value)| {
1712             match other.find(key) {
1713                 None    => false,
1714                 Some(v) => *value == *v
1715             }
1716         })
1717     }
1718 }
1719
1720 impl<K: Eq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {}
1721
1722 impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> {
1723     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1724         try!(write!(f, "{{"));
1725
1726         for (i, (k, v)) in self.iter().enumerate() {
1727             if i != 0 { try!(write!(f, ", ")); }
1728             try!(write!(f, "{}: {}", *k, *v));
1729         }
1730
1731         write!(f, "}}")
1732     }
1733 }
1734
1735 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> {
1736     fn default() -> HashMap<K, V, H> {
1737         HashMap::with_hasher(Default::default())
1738     }
1739 }
1740
1741 /// HashMap iterator
1742 pub type Entries<'a, K, V> = table::Entries<'a, K, V>;
1743
1744 /// HashMap mutable values iterator
1745 pub type MutEntries<'a, K, V> = table::MutEntries<'a, K, V>;
1746
1747 /// HashMap move iterator
1748 pub type MoveEntries<K, V> =
1749     iter::Map<'static, (table::SafeHash, K, V), (K, V), table::MoveEntries<K, V>>;
1750
1751 /// HashMap keys iterator
1752 pub type Keys<'a, K, V> =
1753     iter::Map<'static, (&'a K, &'a V), &'a K, Entries<'a, K, V>>;
1754
1755 /// HashMap values iterator
1756 pub type Values<'a, K, V> =
1757     iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>;
1758
1759 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> {
1760     fn from_iter<T: Iterator<(K, V)>>(iter: T) -> HashMap<K, V, H> {
1761         let (lower, _) = iter.size_hint();
1762         let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
1763         map.extend(iter);
1764         map
1765     }
1766 }
1767
1768 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Extendable<(K, V)> for HashMap<K, V, H> {
1769     fn extend<T: Iterator<(K, V)>>(&mut self, mut iter: T) {
1770         for (k, v) in iter {
1771             self.insert(k, v);
1772         }
1773     }
1774 }
1775
1776 /// HashSet iterator
1777 pub type SetItems<'a, K> =
1778     iter::Map<'static, (&'a K, &'a ()), &'a K, Entries<'a, K, ()>>;
1779
1780 /// HashSet move iterator
1781 pub type SetMoveItems<K> =
1782     iter::Map<'static, (K, ()), K, MoveEntries<K, ()>>;
1783
1784 /// An implementation of a hash set using the underlying representation of a
1785 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
1786 /// requires that the elements implement the `Eq` and `Hash` traits.
1787 ///
1788 /// # Example
1789 ///
1790 /// ```
1791 /// use std::collections::HashSet;
1792 ///
1793 /// // Type inference lets us omit an explicit type signature (which
1794 /// // would be `HashSet<&str>` in this example).
1795 /// let mut books = HashSet::new();
1796 ///
1797 /// // Add some books.
1798 /// books.insert("A Dance With Dragons");
1799 /// books.insert("To Kill a Mockingbird");
1800 /// books.insert("The Odyssey");
1801 /// books.insert("The Great Gatsby");
1802 ///
1803 /// // Check for a specific one.
1804 /// if !books.contains(&("The Winds of Winter")) {
1805 ///     println!("We have {} books, but The Winds of Winter ain't one.",
1806 ///              books.len());
1807 /// }
1808 ///
1809 /// // Remove a book.
1810 /// books.remove(&"The Odyssey");
1811 ///
1812 /// // Iterate over everything.
1813 /// for book in books.iter() {
1814 ///     println!("{}", *book);
1815 /// }
1816 /// ```
1817 ///
1818 /// The easiest way to use `HashSet` with a custom type is to derive
1819 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
1820 /// future be implied by `Eq`.
1821 ///
1822 /// ```rust
1823 /// use std::collections::HashSet;
1824 ///
1825 /// #[deriving(Hash, Eq, PartialEq, Show)]
1826 /// struct Viking<'a> {
1827 ///     name: &'a str,
1828 ///     power: uint,
1829 /// }
1830 ///
1831 /// let mut vikings = HashSet::new();
1832 ///
1833 /// vikings.insert(Viking { name: "Einar", power: 9u });
1834 /// vikings.insert(Viking { name: "Einar", power: 9u });
1835 /// vikings.insert(Viking { name: "Olaf", power: 4u });
1836 /// vikings.insert(Viking { name: "Harald", power: 8u });
1837 ///
1838 /// // Use derived implementation to print the vikings.
1839 /// for x in vikings.iter() {
1840 ///     println!("{}", x);
1841 /// }
1842 /// ```
1843 #[deriving(Clone)]
1844 pub struct HashSet<T, H = RandomSipHasher> {
1845     map: HashMap<T, (), H>
1846 }
1847
1848 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
1849     /// Create an empty HashSet.
1850     ///
1851     /// # Example
1852     ///
1853     /// use std::collections::HashSet;
1854     /// let mut set: HashSet<int> = HashSet::new();
1855     /// ```
1856     #[inline]
1857     pub fn new() -> HashSet<T, RandomSipHasher> {
1858         HashSet::with_capacity(INITIAL_CAPACITY)
1859     }
1860
1861     /// Create an empty HashSet with space for at least `n` elements in
1862     /// the hash table.
1863     ///
1864     /// # Example
1865     ///
1866     /// use std::collections::HashSet;
1867     /// let mut set: HashSet<int> = HashSet::with_capacity(10);
1868     /// ```
1869     #[inline]
1870     pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
1871         HashSet { map: HashMap::with_capacity(capacity) }
1872     }
1873 }
1874
1875 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
1876     /// Creates a new empty hash set which will use the given hasher to hash
1877     /// keys.
1878     ///
1879     /// The hash set is also created with the default initial capacity.
1880     ///
1881     /// # Example
1882     ///
1883     /// ```rust
1884     /// use std::collections::HashSet;
1885     /// use std::hash::sip::SipHasher;
1886     ///
1887     /// let h = SipHasher::new();
1888     /// let mut set = HashSet::with_hasher(h);
1889     /// set.insert(2u);
1890     /// ```
1891     #[inline]
1892     pub fn with_hasher(hasher: H) -> HashSet<T, H> {
1893         HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
1894     }
1895
1896     /// Create an empty HashSet with space for at least `capacity`
1897     /// elements in the hash table, using `hasher` to hash the keys.
1898     ///
1899     /// Warning: `hasher` is normally randomly generated, and
1900     /// is designed to allow `HashSet`s to be resistant to attacks that
1901     /// cause many collisions and very poor performance. Setting it
1902     /// manually using this function can expose a DoS attack vector.
1903     ///
1904     /// # Example
1905     ///
1906     /// ```rust
1907     /// use std::collections::HashSet;
1908     /// use std::hash::sip::SipHasher;
1909     ///
1910     /// let h = SipHasher::new();
1911     /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
1912     /// set.insert(1i);
1913     /// ```
1914     #[inline]
1915     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
1916         HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
1917     }
1918
1919     /// Reserve space for at least `n` elements in the hash table.
1920     ///
1921     /// # Example
1922     ///
1923     /// use std::collections::HashSet;
1924     /// let mut set: HashSet<int> = HashSet::new();
1925     /// set.reserve(10);
1926     /// ```
1927     pub fn reserve(&mut self, n: uint) {
1928         self.map.reserve(n)
1929     }
1930
1931     /// Returns true if the hash set contains a value equivalent to the
1932     /// given query value.
1933     ///
1934     /// # Example
1935     ///
1936     /// This is a slightly silly example where we define the number's
1937     /// parity as the equivilance class. It is important that the
1938     /// values hash the same, which is why we implement `Hash`.
1939     ///
1940     /// ```rust
1941     /// use std::collections::HashSet;
1942     /// use std::hash::Hash;
1943     /// use std::hash::sip::SipState;
1944     ///
1945     /// #[deriving(Eq, PartialEq)]
1946     /// struct EvenOrOdd {
1947     ///     num: uint
1948     /// };
1949     ///
1950     /// impl Hash for EvenOrOdd {
1951     ///     fn hash(&self, state: &mut SipState) {
1952     ///         let parity = self.num % 2;
1953     ///         parity.hash(state);
1954     ///     }
1955     /// }
1956     ///
1957     /// impl Equiv<EvenOrOdd> for EvenOrOdd {
1958     ///     fn equiv(&self, other: &EvenOrOdd) -> bool {
1959     ///         self.num % 2 == other.num % 2
1960     ///     }
1961     /// }
1962     ///
1963     /// let mut set = HashSet::new();
1964     /// set.insert(EvenOrOdd { num: 3u });
1965     ///
1966     /// assert!(set.contains_equiv(&EvenOrOdd { num: 3u }));
1967     /// assert!(set.contains_equiv(&EvenOrOdd { num: 5u }));
1968     /// assert!(!set.contains_equiv(&EvenOrOdd { num: 4u }));
1969     /// assert!(!set.contains_equiv(&EvenOrOdd { num: 2u }));
1970     ///
1971     /// ```
1972     pub fn contains_equiv<Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
1973       self.map.contains_key_equiv(value)
1974     }
1975
1976     /// An iterator visiting all elements in arbitrary order.
1977     /// Iterator element type is &'a T.
1978     ///
1979     /// # Example
1980     ///
1981     /// ```
1982     /// use std::collections::HashSet;
1983     /// let mut set = HashSet::new();
1984     /// set.insert("a");
1985     /// set.insert("b");
1986     ///
1987     /// // Will print in an arbitrary order.
1988     /// for x in set.iter() {
1989     ///     println!("{}", x);
1990     /// }
1991     /// ```
1992     pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
1993         self.map.keys()
1994     }
1995
1996     /// Creates a consuming iterator, that is, one that moves each value out
1997     /// of the set in arbitrary order. The set cannot be used after calling
1998     /// this.
1999     ///
2000     /// # Example
2001     ///
2002     /// ```
2003     /// use std::collections::HashSet;
2004     /// let mut set = HashSet::new();
2005     /// set.insert("a".to_string());
2006     /// set.insert("b".to_string());
2007     ///
2008     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
2009     /// let v: Vec<String> = set.move_iter().collect();
2010     ///
2011     /// // Will print in an arbitrary order.
2012     /// for x in v.iter() {
2013     ///     println!("{}", x);
2014     /// }
2015     /// ```
2016     pub fn move_iter(self) -> SetMoveItems<T> {
2017         self.map.move_iter().map(|(k, _)| k)
2018     }
2019
2020     /// Visit the values representing the difference.
2021     ///
2022     /// # Example
2023     ///
2024     /// ```
2025     /// use std::collections::HashSet;
2026     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
2027     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
2028     ///
2029     /// // Can be seen as `a - b`.
2030     /// for x in a.difference(&b) {
2031     ///     println!("{}", x); // Print 1
2032     /// }
2033     ///
2034     /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
2035     /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
2036     ///
2037     /// // Note that difference is not symmetric,
2038     /// // and `b - a` means something else:
2039     /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
2040     /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
2041     /// ```
2042     pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> SetAlgebraItems<'a, T, H> {
2043         Repeat::new(other).zip(self.iter())
2044             .filter_map(|(other, elt)| {
2045                 if !other.contains(elt) { Some(elt) } else { None }
2046             })
2047     }
2048
2049     /// Visit the values representing the symmetric difference.
2050     ///
2051     /// # Example
2052     ///
2053     /// ```
2054     /// use std::collections::HashSet;
2055     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
2056     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
2057     ///
2058     /// // Print 1, 4 in arbitrary order.
2059     /// for x in a.symmetric_difference(&b) {
2060     ///     println!("{}", x);
2061     /// }
2062     ///
2063     /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
2064     /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
2065     ///
2066     /// assert_eq!(diff1, diff2);
2067     /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
2068     /// ```
2069     pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
2070         -> Chain<SetAlgebraItems<'a, T, H>, SetAlgebraItems<'a, T, H>> {
2071         self.difference(other).chain(other.difference(self))
2072     }
2073
2074     /// Visit the values representing the intersection.
2075     ///
2076     /// # Example
2077     ///
2078     /// ```
2079     /// use std::collections::HashSet;
2080     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
2081     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
2082     ///
2083     /// // Print 2, 3 in arbitrary order.
2084     /// for x in a.intersection(&b) {
2085     ///     println!("{}", x);
2086     /// }
2087     ///
2088     /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
2089     /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
2090     /// ```
2091     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>)
2092         -> SetAlgebraItems<'a, T, H> {
2093         Repeat::new(other).zip(self.iter())
2094             .filter_map(|(other, elt)| {
2095                 if other.contains(elt) { Some(elt) } else { None }
2096             })
2097     }
2098
2099     /// Visit the values representing the union.
2100     ///
2101     /// # Example
2102     ///
2103     /// ```
2104     /// use std::collections::HashSet;
2105     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
2106     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
2107     ///
2108     /// // Print 1, 2, 3, 4 in arbitrary order.
2109     /// for x in a.union(&b) {
2110     ///     println!("{}", x);
2111     /// }
2112     ///
2113     /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
2114     /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
2115     /// ```
2116     pub fn union<'a>(&'a self, other: &'a HashSet<T, H>)
2117         -> Chain<SetItems<'a, T>, SetAlgebraItems<'a, T, H>> {
2118         self.iter().chain(other.difference(self))
2119     }
2120 }
2121
2122 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
2123     fn eq(&self, other: &HashSet<T, H>) -> bool {
2124         if self.len() != other.len() { return false; }
2125
2126         self.iter().all(|key| other.contains(key))
2127     }
2128 }
2129
2130 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
2131
2132 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Collection for HashSet<T, H> {
2133     fn len(&self) -> uint { self.map.len() }
2134 }
2135
2136 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
2137     fn clear(&mut self) { self.map.clear() }
2138 }
2139
2140 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
2141     fn contains(&self, value: &T) -> bool { self.map.contains_key(value) }
2142
2143     fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
2144         self.iter().all(|v| !other.contains(v))
2145     }
2146
2147     fn is_subset(&self, other: &HashSet<T, H>) -> bool {
2148         self.iter().all(|v| other.contains(v))
2149     }
2150 }
2151
2152 impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
2153     fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
2154
2155     fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
2156 }
2157
2158
2159 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
2160     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2161         try!(write!(f, "{{"));
2162
2163         for (i, x) in self.iter().enumerate() {
2164             if i != 0 { try!(write!(f, ", ")); }
2165             try!(write!(f, "{}", *x));
2166         }
2167
2168         write!(f, "}}")
2169     }
2170 }
2171
2172 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
2173     fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
2174         let (lower, _) = iter.size_hint();
2175         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
2176         set.extend(iter);
2177         set
2178     }
2179 }
2180
2181 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
2182     fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
2183         for k in iter {
2184             self.insert(k);
2185         }
2186     }
2187 }
2188
2189 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
2190     fn default() -> HashSet<T, H> {
2191         HashSet::with_hasher(Default::default())
2192     }
2193 }
2194
2195 // `Repeat` is used to feed the filter closure an explicit capture
2196 // of a reference to the other set
2197 /// Set operations iterator
2198 pub type SetAlgebraItems<'a, T, H> =
2199     FilterMap<'static, (&'a HashSet<T, H>, &'a T), &'a T,
2200               Zip<Repeat<&'a HashSet<T, H>>, SetItems<'a, T>>>;
2201
2202 #[cfg(test)]
2203 mod test_map {
2204     use prelude::*;
2205
2206     use super::HashMap;
2207     use cmp::Equiv;
2208     use hash;
2209     use iter::{Iterator,range_inclusive,range_step_inclusive};
2210     use cell::RefCell;
2211
2212     struct KindaIntLike(int);
2213
2214     impl Equiv<int> for KindaIntLike {
2215         fn equiv(&self, other: &int) -> bool {
2216             let KindaIntLike(this) = *self;
2217             this == *other
2218         }
2219     }
2220     impl<S: hash::Writer> hash::Hash<S> for KindaIntLike {
2221         fn hash(&self, state: &mut S) {
2222             let KindaIntLike(this) = *self;
2223             this.hash(state)
2224         }
2225     }
2226
2227     #[test]
2228     fn test_create_capacity_zero() {
2229         let mut m = HashMap::with_capacity(0);
2230
2231         assert!(m.insert(1i, 1i));
2232
2233         assert!(m.contains_key(&1));
2234         assert!(!m.contains_key(&0));
2235     }
2236
2237     #[test]
2238     fn test_insert() {
2239         let mut m = HashMap::new();
2240         assert_eq!(m.len(), 0);
2241         assert!(m.insert(1i, 2i));
2242         assert_eq!(m.len(), 1);
2243         assert!(m.insert(2i, 4i));
2244         assert_eq!(m.len(), 2);
2245         assert_eq!(*m.find(&1).unwrap(), 2);
2246         assert_eq!(*m.find(&2).unwrap(), 4);
2247     }
2248
2249     local_data_key!(drop_vector: RefCell<Vec<int>>)
2250
2251     #[deriving(Hash, PartialEq, Eq)]
2252     struct Dropable {
2253         k: uint
2254     }
2255
2256
2257     impl Dropable {
2258         fn new(k: uint) -> Dropable {
2259             let v = drop_vector.get().unwrap();
2260             v.borrow_mut().as_mut_slice()[k] += 1;
2261
2262             Dropable { k: k }
2263         }
2264     }
2265
2266     impl Drop for Dropable {
2267         fn drop(&mut self) {
2268             let v = drop_vector.get().unwrap();
2269             v.borrow_mut().as_mut_slice()[self.k] -= 1;
2270         }
2271     }
2272
2273     #[test]
2274     fn test_drops() {
2275         drop_vector.replace(Some(RefCell::new(Vec::from_elem(200, 0i))));
2276
2277         {
2278             let mut m = HashMap::new();
2279
2280             let v = drop_vector.get().unwrap();
2281             for i in range(0u, 200) {
2282                 assert_eq!(v.borrow().as_slice()[i], 0);
2283             }
2284             drop(v);
2285
2286             for i in range(0u, 100) {
2287                 let d1 = Dropable::new(i);
2288                 let d2 = Dropable::new(i+100);
2289                 m.insert(d1, d2);
2290             }
2291
2292             let v = drop_vector.get().unwrap();
2293             for i in range(0u, 200) {
2294                 assert_eq!(v.borrow().as_slice()[i], 1);
2295             }
2296             drop(v);
2297
2298             for i in range(0u, 50) {
2299                 let k = Dropable::new(i);
2300                 let v = m.pop(&k);
2301
2302                 assert!(v.is_some());
2303
2304                 let v = drop_vector.get().unwrap();
2305                 assert_eq!(v.borrow().as_slice()[i], 1);
2306                 assert_eq!(v.borrow().as_slice()[i+100], 1);
2307             }
2308
2309             let v = drop_vector.get().unwrap();
2310             for i in range(0u, 50) {
2311                 assert_eq!(v.borrow().as_slice()[i], 0);
2312                 assert_eq!(v.borrow().as_slice()[i+100], 0);
2313             }
2314
2315             for i in range(50u, 100) {
2316                 assert_eq!(v.borrow().as_slice()[i], 1);
2317                 assert_eq!(v.borrow().as_slice()[i+100], 1);
2318             }
2319         }
2320
2321         let v = drop_vector.get().unwrap();
2322         for i in range(0u, 200) {
2323             assert_eq!(v.borrow().as_slice()[i], 0);
2324         }
2325     }
2326
2327     #[test]
2328     fn test_empty_pop() {
2329         let mut m: HashMap<int, bool> = HashMap::new();
2330         assert_eq!(m.pop(&0), None);
2331     }
2332
2333     #[test]
2334     fn test_lots_of_insertions() {
2335         let mut m = HashMap::new();
2336
2337         // Try this a few times to make sure we never screw up the hashmap's
2338         // internal state.
2339         for _ in range(0i, 10) {
2340             assert!(m.is_empty());
2341
2342             for i in range_inclusive(1i, 1000) {
2343                 assert!(m.insert(i, i));
2344
2345                 for j in range_inclusive(1, i) {
2346                     let r = m.find(&j);
2347                     assert_eq!(r, Some(&j));
2348                 }
2349
2350                 for j in range_inclusive(i+1, 1000) {
2351                     let r = m.find(&j);
2352                     assert_eq!(r, None);
2353                 }
2354             }
2355
2356             for i in range_inclusive(1001i, 2000) {
2357                 assert!(!m.contains_key(&i));
2358             }
2359
2360             // remove forwards
2361             for i in range_inclusive(1i, 1000) {
2362                 assert!(m.remove(&i));
2363
2364                 for j in range_inclusive(1, i) {
2365                     assert!(!m.contains_key(&j));
2366                 }
2367
2368                 for j in range_inclusive(i+1, 1000) {
2369                     assert!(m.contains_key(&j));
2370                 }
2371             }
2372
2373             for i in range_inclusive(1i, 1000) {
2374                 assert!(!m.contains_key(&i));
2375             }
2376
2377             for i in range_inclusive(1i, 1000) {
2378                 assert!(m.insert(i, i));
2379             }
2380
2381             // remove backwards
2382             for i in range_step_inclusive(1000i, 1, -1) {
2383                 assert!(m.remove(&i));
2384
2385                 for j in range_inclusive(i, 1000) {
2386                     assert!(!m.contains_key(&j));
2387                 }
2388
2389                 for j in range_inclusive(1, i-1) {
2390                     assert!(m.contains_key(&j));
2391                 }
2392             }
2393         }
2394     }
2395
2396     #[test]
2397     fn test_find_mut() {
2398         let mut m = HashMap::new();
2399         assert!(m.insert(1i, 12i));
2400         assert!(m.insert(2i, 8i));
2401         assert!(m.insert(5i, 14i));
2402         let new = 100;
2403         match m.find_mut(&5) {
2404             None => fail!(), Some(x) => *x = new
2405         }
2406         assert_eq!(m.find(&5), Some(&new));
2407     }
2408
2409     #[test]
2410     fn test_insert_overwrite() {
2411         let mut m = HashMap::new();
2412         assert!(m.insert(1i, 2i));
2413         assert_eq!(*m.find(&1).unwrap(), 2);
2414         assert!(!m.insert(1i, 3i));
2415         assert_eq!(*m.find(&1).unwrap(), 3);
2416     }
2417
2418     #[test]
2419     fn test_insert_conflicts() {
2420         let mut m = HashMap::with_capacity(4);
2421         assert!(m.insert(1i, 2i));
2422         assert!(m.insert(5i, 3i));
2423         assert!(m.insert(9i, 4i));
2424         assert_eq!(*m.find(&9).unwrap(), 4);
2425         assert_eq!(*m.find(&5).unwrap(), 3);
2426         assert_eq!(*m.find(&1).unwrap(), 2);
2427     }
2428
2429     #[test]
2430     fn test_conflict_remove() {
2431         let mut m = HashMap::with_capacity(4);
2432         assert!(m.insert(1i, 2i));
2433         assert_eq!(*m.find(&1).unwrap(), 2);
2434         assert!(m.insert(5, 3));
2435         assert_eq!(*m.find(&1).unwrap(), 2);
2436         assert_eq!(*m.find(&5).unwrap(), 3);
2437         assert!(m.insert(9, 4));
2438         assert_eq!(*m.find(&1).unwrap(), 2);
2439         assert_eq!(*m.find(&5).unwrap(), 3);
2440         assert_eq!(*m.find(&9).unwrap(), 4);
2441         assert!(m.remove(&1));
2442         assert_eq!(*m.find(&9).unwrap(), 4);
2443         assert_eq!(*m.find(&5).unwrap(), 3);
2444     }
2445
2446     #[test]
2447     fn test_is_empty() {
2448         let mut m = HashMap::with_capacity(4);
2449         assert!(m.insert(1i, 2i));
2450         assert!(!m.is_empty());
2451         assert!(m.remove(&1));
2452         assert!(m.is_empty());
2453     }
2454
2455     #[test]
2456     fn test_pop() {
2457         let mut m = HashMap::new();
2458         m.insert(1i, 2i);
2459         assert_eq!(m.pop(&1), Some(2));
2460         assert_eq!(m.pop(&1), None);
2461     }
2462
2463     #[test]
2464     #[allow(experimental)]
2465     fn test_pop_equiv() {
2466         let mut m = HashMap::new();
2467         m.insert(1i, 2i);
2468         assert_eq!(m.pop_equiv(&KindaIntLike(1)), Some(2));
2469         assert_eq!(m.pop_equiv(&KindaIntLike(1)), None);
2470     }
2471
2472     #[test]
2473     fn test_swap() {
2474         let mut m = HashMap::new();
2475         assert_eq!(m.swap(1i, 2i), None);
2476         assert_eq!(m.swap(1i, 3i), Some(2));
2477         assert_eq!(m.swap(1i, 4i), Some(3));
2478     }
2479
2480     #[test]
2481     fn test_move_iter() {
2482         let hm = {
2483             let mut hm = HashMap::new();
2484
2485             hm.insert('a', 1i);
2486             hm.insert('b', 2i);
2487
2488             hm
2489         };
2490
2491         let v = hm.move_iter().collect::<Vec<(char, int)>>();
2492         assert!([('a', 1), ('b', 2)] == v.as_slice() || [('b', 2), ('a', 1)] == v.as_slice());
2493     }
2494
2495     #[test]
2496     fn test_iterate() {
2497         let mut m = HashMap::with_capacity(4);
2498         for i in range(0u, 32) {
2499             assert!(m.insert(i, i*2));
2500         }
2501         assert_eq!(m.len(), 32);
2502
2503         let mut observed: u32 = 0;
2504
2505         for (k, v) in m.iter() {
2506             assert_eq!(*v, *k * 2);
2507             observed |= 1 << *k;
2508         }
2509         assert_eq!(observed, 0xFFFF_FFFF);
2510     }
2511
2512     #[test]
2513     fn test_keys() {
2514         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
2515         let map = vec.move_iter().collect::<HashMap<int, char>>();
2516         let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
2517         assert_eq!(keys.len(), 3);
2518         assert!(keys.contains(&1));
2519         assert!(keys.contains(&2));
2520         assert!(keys.contains(&3));
2521     }
2522
2523     #[test]
2524     fn test_values() {
2525         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
2526         let map = vec.move_iter().collect::<HashMap<int, char>>();
2527         let values = map.values().map(|&v| v).collect::<Vec<char>>();
2528         assert_eq!(values.len(), 3);
2529         assert!(values.contains(&'a'));
2530         assert!(values.contains(&'b'));
2531         assert!(values.contains(&'c'));
2532     }
2533
2534     #[test]
2535     fn test_find() {
2536         let mut m = HashMap::new();
2537         assert!(m.find(&1i).is_none());
2538         m.insert(1i, 2i);
2539         match m.find(&1) {
2540             None => fail!(),
2541             Some(v) => assert_eq!(*v, 2)
2542         }
2543     }
2544
2545     #[test]
2546     fn test_eq() {
2547         let mut m1 = HashMap::new();
2548         m1.insert(1i, 2i);
2549         m1.insert(2i, 3i);
2550         m1.insert(3i, 4i);
2551
2552         let mut m2 = HashMap::new();
2553         m2.insert(1i, 2i);
2554         m2.insert(2i, 3i);
2555
2556         assert!(m1 != m2);
2557
2558         m2.insert(3i, 4i);
2559
2560         assert_eq!(m1, m2);
2561     }
2562
2563     #[test]
2564     fn test_show() {
2565         let mut map: HashMap<int, int> = HashMap::new();
2566         let empty: HashMap<int, int> = HashMap::new();
2567
2568         map.insert(1i, 2i);
2569         map.insert(3i, 4i);
2570
2571         let map_str = format!("{}", map);
2572
2573         assert!(map_str == "{1: 2, 3: 4}".to_string() || map_str == "{3: 4, 1: 2}".to_string());
2574         assert_eq!(format!("{}", empty), "{}".to_string());
2575     }
2576
2577     #[test]
2578     fn test_expand() {
2579         let mut m = HashMap::new();
2580
2581         assert_eq!(m.len(), 0);
2582         assert!(m.is_empty());
2583
2584         let mut i = 0u;
2585         let old_cap = m.table.capacity();
2586         while old_cap == m.table.capacity() {
2587             m.insert(i, i);
2588             i += 1;
2589         }
2590
2591         assert_eq!(m.len(), i);
2592         assert!(!m.is_empty());
2593     }
2594
2595     #[test]
2596     fn test_resize_policy() {
2597         let mut m = HashMap::new();
2598
2599         assert_eq!(m.len(), 0);
2600         assert!(m.is_empty());
2601
2602         let initial_cap = m.table.capacity();
2603         m.reserve(initial_cap * 2);
2604         let cap = m.table.capacity();
2605
2606         assert_eq!(cap, initial_cap * 2);
2607
2608         let mut i = 0u;
2609         for _ in range(0, cap * 3 / 4) {
2610             m.insert(i, i);
2611             i += 1;
2612         }
2613
2614         assert_eq!(m.len(), i);
2615         assert_eq!(m.table.capacity(), cap);
2616
2617         for _ in range(0, cap / 4) {
2618             m.insert(i, i);
2619             i += 1;
2620         }
2621
2622         let new_cap = m.table.capacity();
2623         assert_eq!(new_cap, cap * 2);
2624
2625         for _ in range(0, cap / 2) {
2626             i -= 1;
2627             m.remove(&i);
2628             assert_eq!(m.table.capacity(), new_cap);
2629         }
2630
2631         for _ in range(0, cap / 2 - 1) {
2632             i -= 1;
2633             m.remove(&i);
2634         }
2635
2636         assert_eq!(m.table.capacity(), cap);
2637         assert_eq!(m.len(), i);
2638         assert!(!m.is_empty());
2639     }
2640
2641     #[test]
2642     fn test_find_equiv() {
2643         let mut m = HashMap::new();
2644
2645         let (foo, bar, baz) = (1i,2i,3i);
2646         m.insert("foo".to_string(), foo);
2647         m.insert("bar".to_string(), bar);
2648         m.insert("baz".to_string(), baz);
2649
2650
2651         assert_eq!(m.find_equiv(&("foo")), Some(&foo));
2652         assert_eq!(m.find_equiv(&("bar")), Some(&bar));
2653         assert_eq!(m.find_equiv(&("baz")), Some(&baz));
2654
2655         assert_eq!(m.find_equiv(&("qux")), None);
2656     }
2657
2658     #[test]
2659     fn test_from_iter() {
2660         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2661
2662         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2663
2664         for &(k, v) in xs.iter() {
2665             assert_eq!(map.find(&k), Some(&v));
2666         }
2667     }
2668
2669     #[test]
2670     fn test_size_hint() {
2671         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2672
2673         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2674
2675         let mut iter = map.iter();
2676
2677         for _ in iter.by_ref().take(3) {}
2678
2679         assert_eq!(iter.size_hint(), (3, Some(3)));
2680     }
2681
2682     #[test]
2683     fn test_mut_size_hint() {
2684         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2685
2686         let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2687
2688         let mut iter = map.mut_iter();
2689
2690         for _ in iter.by_ref().take(3) {}
2691
2692         assert_eq!(iter.size_hint(), (3, Some(3)));
2693     }
2694 }
2695
2696 #[cfg(test)]
2697 mod test_set {
2698     use prelude::*;
2699
2700     use super::HashSet;
2701     use slice::ImmutableEqVector;
2702     use collections::Collection;
2703
2704     #[test]
2705     fn test_disjoint() {
2706         let mut xs = HashSet::new();
2707         let mut ys = HashSet::new();
2708         assert!(xs.is_disjoint(&ys));
2709         assert!(ys.is_disjoint(&xs));
2710         assert!(xs.insert(5i));
2711         assert!(ys.insert(11i));
2712         assert!(xs.is_disjoint(&ys));
2713         assert!(ys.is_disjoint(&xs));
2714         assert!(xs.insert(7));
2715         assert!(xs.insert(19));
2716         assert!(xs.insert(4));
2717         assert!(ys.insert(2));
2718         assert!(ys.insert(-11));
2719         assert!(xs.is_disjoint(&ys));
2720         assert!(ys.is_disjoint(&xs));
2721         assert!(ys.insert(7));
2722         assert!(!xs.is_disjoint(&ys));
2723         assert!(!ys.is_disjoint(&xs));
2724     }
2725
2726     #[test]
2727     fn test_subset_and_superset() {
2728         let mut a = HashSet::new();
2729         assert!(a.insert(0i));
2730         assert!(a.insert(5));
2731         assert!(a.insert(11));
2732         assert!(a.insert(7));
2733
2734         let mut b = HashSet::new();
2735         assert!(b.insert(0i));
2736         assert!(b.insert(7));
2737         assert!(b.insert(19));
2738         assert!(b.insert(250));
2739         assert!(b.insert(11));
2740         assert!(b.insert(200));
2741
2742         assert!(!a.is_subset(&b));
2743         assert!(!a.is_superset(&b));
2744         assert!(!b.is_subset(&a));
2745         assert!(!b.is_superset(&a));
2746
2747         assert!(b.insert(5));
2748
2749         assert!(a.is_subset(&b));
2750         assert!(!a.is_superset(&b));
2751         assert!(!b.is_subset(&a));
2752         assert!(b.is_superset(&a));
2753     }
2754
2755     #[test]
2756     fn test_iterate() {
2757         let mut a = HashSet::new();
2758         for i in range(0u, 32) {
2759             assert!(a.insert(i));
2760         }
2761         let mut observed: u32 = 0;
2762         for k in a.iter() {
2763             observed |= 1 << *k;
2764         }
2765         assert_eq!(observed, 0xFFFF_FFFF);
2766     }
2767
2768     #[test]
2769     fn test_intersection() {
2770         let mut a = HashSet::new();
2771         let mut b = HashSet::new();
2772
2773         assert!(a.insert(11i));
2774         assert!(a.insert(1));
2775         assert!(a.insert(3));
2776         assert!(a.insert(77));
2777         assert!(a.insert(103));
2778         assert!(a.insert(5));
2779         assert!(a.insert(-5));
2780
2781         assert!(b.insert(2i));
2782         assert!(b.insert(11));
2783         assert!(b.insert(77));
2784         assert!(b.insert(-9));
2785         assert!(b.insert(-42));
2786         assert!(b.insert(5));
2787         assert!(b.insert(3));
2788
2789         let mut i = 0;
2790         let expected = [3, 5, 11, 77];
2791         for x in a.intersection(&b) {
2792             assert!(expected.contains(x));
2793             i += 1
2794         }
2795         assert_eq!(i, expected.len());
2796     }
2797
2798     #[test]
2799     fn test_difference() {
2800         let mut a = HashSet::new();
2801         let mut b = HashSet::new();
2802
2803         assert!(a.insert(1i));
2804         assert!(a.insert(3));
2805         assert!(a.insert(5));
2806         assert!(a.insert(9));
2807         assert!(a.insert(11));
2808
2809         assert!(b.insert(3i));
2810         assert!(b.insert(9));
2811
2812         let mut i = 0;
2813         let expected = [1, 5, 11];
2814         for x in a.difference(&b) {
2815             assert!(expected.contains(x));
2816             i += 1
2817         }
2818         assert_eq!(i, expected.len());
2819     }
2820
2821     #[test]
2822     fn test_symmetric_difference() {
2823         let mut a = HashSet::new();
2824         let mut b = HashSet::new();
2825
2826         assert!(a.insert(1i));
2827         assert!(a.insert(3));
2828         assert!(a.insert(5));
2829         assert!(a.insert(9));
2830         assert!(a.insert(11));
2831
2832         assert!(b.insert(-2i));
2833         assert!(b.insert(3));
2834         assert!(b.insert(9));
2835         assert!(b.insert(14));
2836         assert!(b.insert(22));
2837
2838         let mut i = 0;
2839         let expected = [-2, 1, 5, 11, 14, 22];
2840         for x in a.symmetric_difference(&b) {
2841             assert!(expected.contains(x));
2842             i += 1
2843         }
2844         assert_eq!(i, expected.len());
2845     }
2846
2847     #[test]
2848     fn test_union() {
2849         let mut a = HashSet::new();
2850         let mut b = HashSet::new();
2851
2852         assert!(a.insert(1i));
2853         assert!(a.insert(3));
2854         assert!(a.insert(5));
2855         assert!(a.insert(9));
2856         assert!(a.insert(11));
2857         assert!(a.insert(16));
2858         assert!(a.insert(19));
2859         assert!(a.insert(24));
2860
2861         assert!(b.insert(-2i));
2862         assert!(b.insert(1));
2863         assert!(b.insert(5));
2864         assert!(b.insert(9));
2865         assert!(b.insert(13));
2866         assert!(b.insert(19));
2867
2868         let mut i = 0;
2869         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
2870         for x in a.union(&b) {
2871             assert!(expected.contains(x));
2872             i += 1
2873         }
2874         assert_eq!(i, expected.len());
2875     }
2876
2877     #[test]
2878     fn test_from_iter() {
2879         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
2880
2881         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
2882
2883         for x in xs.iter() {
2884             assert!(set.contains(x));
2885         }
2886     }
2887
2888     #[test]
2889     fn test_move_iter() {
2890         let hs = {
2891             let mut hs = HashSet::new();
2892
2893             hs.insert('a');
2894             hs.insert('b');
2895
2896             hs
2897         };
2898
2899         let v = hs.move_iter().collect::<Vec<char>>();
2900         assert!(['a', 'b'] == v.as_slice() || ['b', 'a'] == v.as_slice());
2901     }
2902
2903     #[test]
2904     fn test_eq() {
2905         // These constants once happened to expose a bug in insert().
2906         // I'm keeping them around to prevent a regression.
2907         let mut s1 = HashSet::new();
2908
2909         s1.insert(1i);
2910         s1.insert(2);
2911         s1.insert(3);
2912
2913         let mut s2 = HashSet::new();
2914
2915         s2.insert(1i);
2916         s2.insert(2);
2917
2918         assert!(s1 != s2);
2919
2920         s2.insert(3);
2921
2922         assert_eq!(s1, s2);
2923     }
2924
2925     #[test]
2926     fn test_show() {
2927         let mut set: HashSet<int> = HashSet::new();
2928         let empty: HashSet<int> = HashSet::new();
2929
2930         set.insert(1i);
2931         set.insert(2);
2932
2933         let set_str = format!("{}", set);
2934
2935         assert!(set_str == "{1, 2}".to_string() || set_str == "{2, 1}".to_string());
2936         assert_eq!(format!("{}", empty), "{}".to_string());
2937     }
2938 }
2939
2940 #[cfg(test)]
2941 mod bench {
2942     extern crate test;
2943     use prelude::*;
2944
2945     use self::test::Bencher;
2946     use iter::{range_inclusive};
2947
2948     #[bench]
2949     fn new_drop(b : &mut Bencher) {
2950         use super::HashMap;
2951
2952         b.iter(|| {
2953             let m : HashMap<int, int> = HashMap::new();
2954             assert_eq!(m.len(), 0);
2955         })
2956     }
2957
2958     #[bench]
2959     fn new_insert_drop(b : &mut Bencher) {
2960         use super::HashMap;
2961
2962         b.iter(|| {
2963             let mut m = HashMap::new();
2964             m.insert(0i, 0i);
2965             assert_eq!(m.len(), 1);
2966         })
2967     }
2968
2969     #[bench]
2970     fn insert(b: &mut Bencher) {
2971         use super::HashMap;
2972
2973         let mut m = HashMap::new();
2974
2975         for i in range_inclusive(1i, 1000) {
2976             m.insert(i, i);
2977         }
2978
2979         let mut k = 1001;
2980
2981         b.iter(|| {
2982             m.insert(k, k);
2983             k += 1;
2984         });
2985     }
2986
2987     #[bench]
2988     fn find_existing(b: &mut Bencher) {
2989         use super::HashMap;
2990
2991         let mut m = HashMap::new();
2992
2993         for i in range_inclusive(1i, 1000) {
2994             m.insert(i, i);
2995         }
2996
2997         b.iter(|| {
2998             for i in range_inclusive(1i, 1000) {
2999                 m.contains_key(&i);
3000             }
3001         });
3002     }
3003
3004     #[bench]
3005     fn find_nonexisting(b: &mut Bencher) {
3006         use super::HashMap;
3007
3008         let mut m = HashMap::new();
3009
3010         for i in range_inclusive(1i, 1000) {
3011             m.insert(i, i);
3012         }
3013
3014         b.iter(|| {
3015             for i in range_inclusive(1001i, 2000) {
3016                 m.contains_key(&i);
3017             }
3018         });
3019     }
3020
3021     #[bench]
3022     fn hashmap_as_queue(b: &mut Bencher) {
3023         use super::HashMap;
3024
3025         let mut m = HashMap::new();
3026
3027         for i in range_inclusive(1i, 1000) {
3028             m.insert(i, i);
3029         }
3030
3031         let mut k = 1i;
3032
3033         b.iter(|| {
3034             m.pop(&k);
3035             m.insert(k + 1000, k + 1000);
3036             k += 1;
3037         });
3038     }
3039
3040     #[bench]
3041     fn find_pop_insert(b: &mut Bencher) {
3042         use super::HashMap;
3043
3044         let mut m = HashMap::new();
3045
3046         for i in range_inclusive(1i, 1000) {
3047             m.insert(i, i);
3048         }
3049
3050         let mut k = 1i;
3051
3052         b.iter(|| {
3053             m.find(&(k + 400));
3054             m.find(&(k + 2000));
3055             m.pop(&k);
3056             m.insert(k + 1000, k + 1000);
3057             k += 1;
3058         })
3059     }
3060 }