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