]> git.lizzy.rs Git - rust.git/blob - src/libcollections/smallintmap.rs
rollup merge of #16716 : tshepang/temp
[rust.git] / src / libcollections / smallintmap.rs
1 // Copyright 2012-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 //! A simple map based on a vector for small integer keys. Space requirements
12 //! are O(highest integer key).
13
14 #![allow(missing_doc)]
15
16 use core::prelude::*;
17
18 use core::default::Default;
19 use core::fmt;
20 use core::iter;
21 use core::iter::{Enumerate, FilterMap};
22 use core::mem::replace;
23
24 use {Mutable, Map, MutableMap, MutableSeq};
25 use {vec, slice};
26 use vec::Vec;
27 use hash;
28 use hash::Hash;
29
30 /// A map optimized for small integer keys.
31 ///
32 /// # Example
33 ///
34 /// ```
35 /// use std::collections::SmallIntMap;
36 ///
37 /// let mut months = SmallIntMap::new();
38 /// months.insert(1, "Jan");
39 /// months.insert(2, "Feb");
40 /// months.insert(3, "Mar");
41 ///
42 /// if !months.contains_key(&12) {
43 ///     println!("The end is near!");
44 /// }
45 ///
46 /// assert_eq!(months.find(&1), Some(&"Jan"));
47 ///
48 /// match months.find_mut(&3) {
49 ///     Some(value) => *value = "Venus",
50 ///     None => (),
51 /// }
52 ///
53 /// assert_eq!(months.find(&3), Some(&"Venus"));
54 ///
55 /// // Print out all months
56 /// for (key, value) in months.iter() {
57 ///     println!("month {} is {}", key, value);
58 /// }
59 ///
60 /// months.clear();
61 /// assert!(months.is_empty());
62 /// ```
63 #[deriving(PartialEq, Eq)]
64 pub struct SmallIntMap<T> {
65     v: Vec<Option<T>>,
66 }
67
68 impl<V> Collection for SmallIntMap<V> {
69     /// Returns the number of elements in the map.
70     fn len(&self) -> uint {
71         self.v.iter().filter(|elt| elt.is_some()).count()
72     }
73
74     /// Returns`true` if there are no elements in the map.
75     fn is_empty(&self) -> bool {
76         self.v.iter().all(|elt| elt.is_none())
77     }
78 }
79
80 impl<V> Mutable for SmallIntMap<V> {
81     /// Clears the map, removing all key-value pairs.
82     fn clear(&mut self) { self.v.clear() }
83 }
84
85 impl<V> Map<uint, V> for SmallIntMap<V> {
86     /// Returns a reference to the value corresponding to the key.
87     fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
88         if *key < self.v.len() {
89             match self.v[*key] {
90               Some(ref value) => Some(value),
91               None => None
92             }
93         } else {
94             None
95         }
96     }
97 }
98
99 impl<V> MutableMap<uint, V> for SmallIntMap<V> {
100     /// Returns a mutable reference to the value corresponding to the key.
101     fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
102         if *key < self.v.len() {
103             match *self.v.get_mut(*key) {
104               Some(ref mut value) => Some(value),
105               None => None
106             }
107         } else {
108             None
109         }
110     }
111
112     /// Inserts a key-value pair into the map. An existing value for a
113     /// key is replaced by the new value. Returns `true` if the key did
114     /// not already exist in the map.
115     fn insert(&mut self, key: uint, value: V) -> bool {
116         let exists = self.contains_key(&key);
117         let len = self.v.len();
118         if len <= key {
119             self.v.grow_fn(key - len + 1, |_| None);
120         }
121         *self.v.get_mut(key) = Some(value);
122         !exists
123     }
124
125     /// Removes a key-value pair from the map. Returns `true` if the key
126     /// was present in the map.
127     fn remove(&mut self, key: &uint) -> bool {
128         self.pop(key).is_some()
129     }
130
131     /// Inserts a key-value pair into the map. If the key already had a value
132     /// present in the map, that value is returned. Otherwise `None` is returned.
133     fn swap(&mut self, key: uint, value: V) -> Option<V> {
134         match self.find_mut(&key) {
135             Some(loc) => { return Some(replace(loc, value)); }
136             None => ()
137         }
138         self.insert(key, value);
139         return None;
140     }
141
142     /// Removes a key from the map, returning the value at the key if the key
143     /// was previously in the map.
144     fn pop(&mut self, key: &uint) -> Option<V> {
145         if *key >= self.v.len() {
146             return None;
147         }
148         self.v.get_mut(*key).take()
149     }
150 }
151
152 impl<V> Default for SmallIntMap<V> {
153     #[inline]
154     fn default() -> SmallIntMap<V> { SmallIntMap::new() }
155 }
156
157 impl<V:Clone> Clone for SmallIntMap<V> {
158     #[inline]
159     fn clone(&self) -> SmallIntMap<V> {
160         SmallIntMap { v: self.v.clone() }
161     }
162
163     #[inline]
164     fn clone_from(&mut self, source: &SmallIntMap<V>) {
165         self.v.reserve(source.v.len());
166         for (i, w) in self.v.mut_iter().enumerate() {
167             *w = source.v[i].clone();
168         }
169     }
170 }
171
172 impl <S: hash::Writer, T: Hash<S>> Hash<S> for SmallIntMap<T> {
173     fn hash(&self, state: &mut S) {
174         self.v.hash(state)
175     }
176 }
177
178 impl<V> SmallIntMap<V> {
179     /// Creates an empty `SmallIntMap`.
180     ///
181     /// # Example
182     ///
183     /// ```
184     /// use std::collections::SmallIntMap;
185     /// let mut map: SmallIntMap<&str> = SmallIntMap::new();
186     /// ```
187     pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
188
189     /// Creates an empty `SmallIntMap` with space for at least `capacity`
190     /// elements before resizing.
191     ///
192     /// # Example
193     ///
194     /// ```
195     /// use std::collections::SmallIntMap;
196     /// let mut map: SmallIntMap<&str> = SmallIntMap::with_capacity(10);
197     /// ```
198     pub fn with_capacity(capacity: uint) -> SmallIntMap<V> {
199         SmallIntMap { v: Vec::with_capacity(capacity) }
200     }
201
202     /// Retrieves a value for the given key.
203     /// See [`find`](../trait.Map.html#tymethod.find) for a non-failing alternative.
204     ///
205     /// # Failure
206     ///
207     /// Fails if the key is not present.
208     ///
209     /// # Example
210     ///
211     /// ```
212     /// #![allow(deprecated)]
213     ///
214     /// use std::collections::SmallIntMap;
215     ///
216     /// let mut map = SmallIntMap::new();
217     /// map.insert(1, "a");
218     /// assert_eq!(map.get(&1), &"a");
219     /// ```
220     #[deprecated = "prefer using indexing, e.g., map[0]"]
221     pub fn get<'a>(&'a self, key: &uint) -> &'a V {
222         self.find(key).expect("key not present")
223     }
224
225     /// Returns an iterator visiting all keys in ascending order by the keys.
226     /// The iterator's element type is `uint`.
227     pub fn keys<'r>(&'r self) -> Keys<'r, V> {
228         self.iter().map(|(k, _v)| k)
229     }
230
231     /// Returns an iterator visiting all values in ascending order by the keys.
232     /// The iterator's element type is `&'r V`.
233     pub fn values<'r>(&'r self) -> Values<'r, V> {
234         self.iter().map(|(_k, v)| v)
235     }
236
237     /// Returns an iterator visiting all key-value pairs in ascending order by the keys.
238     /// The iterator's element type is `(uint, &'r V)`.
239     ///
240     /// # Example
241     ///
242     /// ```
243     /// use std::collections::SmallIntMap;
244     ///
245     /// let mut map = SmallIntMap::new();
246     /// map.insert(1, "a");
247     /// map.insert(3, "c");
248     /// map.insert(2, "b");
249     ///
250     /// // Print `1: a` then `2: b` then `3: c`
251     /// for (key, value) in map.iter() {
252     ///     println!("{}: {}", key, value);
253     /// }
254     /// ```
255     pub fn iter<'r>(&'r self) -> Entries<'r, V> {
256         Entries {
257             front: 0,
258             back: self.v.len(),
259             iter: self.v.iter()
260         }
261     }
262
263     /// Returns an iterator visiting all key-value pairs in ascending order by the keys,
264     /// with mutable references to the values.
265     /// The iterator's element type is `(uint, &'r mut V)`.
266     ///
267     /// # Example
268     ///
269     /// ```
270     /// use std::collections::SmallIntMap;
271     ///
272     /// let mut map = SmallIntMap::new();
273     /// map.insert(1, "a");
274     /// map.insert(2, "b");
275     /// map.insert(3, "c");
276     ///
277     /// for (key, value) in map.mut_iter() {
278     ///     *value = "x";
279     /// }
280     ///
281     /// for (key, value) in map.iter() {
282     ///     assert_eq!(value, &"x");
283     /// }
284     /// ```
285     pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
286         MutEntries {
287             front: 0,
288             back: self.v.len(),
289             iter: self.v.mut_iter()
290         }
291     }
292
293     /// Returns an iterator visiting all key-value pairs in ascending order by
294     /// the keys, emptying (but not consuming) the original `SmallIntMap`.
295     /// The iterator's element type is `(uint, &'r V)`.
296     ///
297     /// # Example
298     ///
299     /// ```
300     /// use std::collections::SmallIntMap;
301     ///
302     /// let mut map = SmallIntMap::new();
303     /// map.insert(1, "a");
304     /// map.insert(3, "c");
305     /// map.insert(2, "b");
306     ///
307     /// // Not possible with .iter()
308     /// let vec: Vec<(uint, &str)> = map.move_iter().collect();
309     ///
310     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
311     /// ```
312     pub fn move_iter(&mut self)
313         -> FilterMap<(uint, Option<V>), (uint, V),
314                 Enumerate<vec::MoveItems<Option<V>>>>
315     {
316         let values = replace(&mut self.v, vec!());
317         values.move_iter().enumerate().filter_map(|(i, v)| {
318             v.map(|v| (i, v))
319         })
320     }
321 }
322
323 impl<V:Clone> SmallIntMap<V> {
324     /// Updates a value in the map. If the key already exists in the map,
325     /// modifies the value with `ff` taking `oldval, newval`.
326     /// Otherwise, sets the value to `newval`.
327     /// Returasn `true` if the key did not already exist in the map.
328     ///
329     /// # Example
330     ///
331     /// ```
332     /// use std::collections::SmallIntMap;
333     ///
334     /// let mut map = SmallIntMap::new();
335     ///
336     /// // Key does not exist, will do a simple insert
337     /// assert!(map.update(1, vec![1i, 2], |old, new| old.append(new.as_slice())));
338     /// assert_eq!(map[1], vec![1i, 2]);
339     ///
340     /// // Key exists, update the value
341     /// assert!(!map.update(1, vec![3i, 4], |old, new| old.append(new.as_slice())));
342     /// assert_eq!(map[1], vec![1i, 2, 3, 4]);
343     /// ```
344     pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
345         self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
346     }
347
348     /// Updates a value in the map. If the key already exists in the map,
349     /// modifies the value with `ff` taking `key, oldval, newval`.
350     /// Otherwise, sets the value to `newval`.
351     /// Returns `true` if the key did not already exist in the map.
352     ///
353     /// # Example
354     ///
355     /// ```
356     /// use std::collections::SmallIntMap;
357     ///
358     /// let mut map = SmallIntMap::new();
359     ///
360     /// // Key does not exist, will do a simple insert
361     /// assert!(map.update_with_key(7, 10, |key, old, new| (old + new) % key));
362     /// assert_eq!(map[7], 10);
363     ///
364     /// // Key exists, update the value
365     /// assert!(!map.update_with_key(7, 20, |key, old, new| (old + new) % key));
366     /// assert_eq!(map[7], 2);
367     /// ```
368     pub fn update_with_key(&mut self,
369                            key: uint,
370                            val: V,
371                            ff: |uint, V, V| -> V)
372                            -> bool {
373         let new_val = match self.find(&key) {
374             None => val,
375             Some(orig) => ff(key, (*orig).clone(), val)
376         };
377         self.insert(key, new_val)
378     }
379 }
380
381 impl<V: PartialOrd> PartialOrd for SmallIntMap<V> {
382     #[inline]
383     fn partial_cmp(&self, other: &SmallIntMap<V>) -> Option<Ordering> {
384         iter::order::partial_cmp(self.iter(), other.iter())
385     }
386 }
387
388 impl<V: Ord> Ord for SmallIntMap<V> {
389     #[inline]
390     fn cmp(&self, other: &SmallIntMap<V>) -> Ordering {
391         iter::order::cmp(self.iter(), other.iter())
392     }
393 }
394
395 impl<V: fmt::Show> fmt::Show for SmallIntMap<V> {
396     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
397         try!(write!(f, "{{"));
398
399         for (i, (k, v)) in self.iter().enumerate() {
400             if i != 0 { try!(write!(f, ", ")); }
401             try!(write!(f, "{}: {}", k, *v));
402         }
403
404         write!(f, "}}")
405     }
406 }
407
408 impl<V> FromIterator<(uint, V)> for SmallIntMap<V> {
409     fn from_iter<Iter: Iterator<(uint, V)>>(iter: Iter) -> SmallIntMap<V> {
410         let mut map = SmallIntMap::new();
411         map.extend(iter);
412         map
413     }
414 }
415
416 impl<V> Extendable<(uint, V)> for SmallIntMap<V> {
417     fn extend<Iter: Iterator<(uint, V)>>(&mut self, mut iter: Iter) {
418         for (k, v) in iter {
419             self.insert(k, v);
420         }
421     }
422 }
423
424 impl<V> Index<uint, V> for SmallIntMap<V> {
425     #[inline]
426     #[allow(deprecated)]
427     fn index<'a>(&'a self, i: &uint) -> &'a V {
428         self.get(i)
429     }
430 }
431
432 // FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
433 /*impl<V> IndexMut<uint, V> for SmallIntMap<V> {
434     #[inline]
435     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
436         self.find_mut(i).expect("key not present")
437     }
438 }*/
439
440 macro_rules! iterator {
441     (impl $name:ident -> $elem:ty, $getter:ident) => {
442         impl<'a, T> Iterator<$elem> for $name<'a, T> {
443             #[inline]
444             fn next(&mut self) -> Option<$elem> {
445                 while self.front < self.back {
446                     match self.iter.next() {
447                         Some(elem) => {
448                             if elem.is_some() {
449                                 let index = self.front;
450                                 self.front += 1;
451                                 return Some((index, elem. $getter ()));
452                             }
453                         }
454                         _ => ()
455                     }
456                     self.front += 1;
457                 }
458                 None
459             }
460
461             #[inline]
462             fn size_hint(&self) -> (uint, Option<uint>) {
463                 (0, Some(self.back - self.front))
464             }
465         }
466     }
467 }
468
469 macro_rules! double_ended_iterator {
470     (impl $name:ident -> $elem:ty, $getter:ident) => {
471         impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
472             #[inline]
473             fn next_back(&mut self) -> Option<$elem> {
474                 while self.front < self.back {
475                     match self.iter.next_back() {
476                         Some(elem) => {
477                             if elem.is_some() {
478                                 self.back -= 1;
479                                 return Some((self.back, elem. $getter ()));
480                             }
481                         }
482                         _ => ()
483                     }
484                     self.back -= 1;
485                 }
486                 None
487             }
488         }
489     }
490 }
491
492 /// Forward iterator over a map.
493 pub struct Entries<'a, T:'a> {
494     front: uint,
495     back: uint,
496     iter: slice::Items<'a, Option<T>>
497 }
498
499 iterator!(impl Entries -> (uint, &'a T), get_ref)
500 double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
501
502 /// Forward iterator over the key-value pairs of a map, with the
503 /// values being mutable.
504 pub struct MutEntries<'a, T:'a> {
505     front: uint,
506     back: uint,
507     iter: slice::MutItems<'a, Option<T>>
508 }
509
510 iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
511 double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
512
513 /// Forward iterator over the keys of a map
514 pub type Keys<'a, T> =
515     iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;
516
517 /// Forward iterator over the values of a map
518 pub type Values<'a, T> =
519     iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;
520
521 #[cfg(test)]
522 mod test_map {
523     use std::prelude::*;
524     use vec::Vec;
525     use hash;
526
527     use {Map, MutableMap, Mutable, MutableSeq};
528     use super::SmallIntMap;
529
530     #[test]
531     fn test_find_mut() {
532         let mut m = SmallIntMap::new();
533         assert!(m.insert(1, 12i));
534         assert!(m.insert(2, 8));
535         assert!(m.insert(5, 14));
536         let new = 100;
537         match m.find_mut(&5) {
538             None => fail!(), Some(x) => *x = new
539         }
540         assert_eq!(m.find(&5), Some(&new));
541     }
542
543     #[test]
544     fn test_len() {
545         let mut map = SmallIntMap::new();
546         assert_eq!(map.len(), 0);
547         assert!(map.is_empty());
548         assert!(map.insert(5, 20i));
549         assert_eq!(map.len(), 1);
550         assert!(!map.is_empty());
551         assert!(map.insert(11, 12));
552         assert_eq!(map.len(), 2);
553         assert!(!map.is_empty());
554         assert!(map.insert(14, 22));
555         assert_eq!(map.len(), 3);
556         assert!(!map.is_empty());
557     }
558
559     #[test]
560     fn test_clear() {
561         let mut map = SmallIntMap::new();
562         assert!(map.insert(5, 20i));
563         assert!(map.insert(11, 12));
564         assert!(map.insert(14, 22));
565         map.clear();
566         assert!(map.is_empty());
567         assert!(map.find(&5).is_none());
568         assert!(map.find(&11).is_none());
569         assert!(map.find(&14).is_none());
570     }
571
572     #[test]
573     fn test_insert_with_key() {
574         let mut map = SmallIntMap::new();
575
576         // given a new key, initialize it with this new count,
577         // given an existing key, add more to its count
578         fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
579             v0 + v1
580         }
581
582         fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
583             v0 + v1
584         }
585
586         // count integers
587         map.update(3, 1, add_more_to_count_simple);
588         map.update_with_key(9, 1, add_more_to_count);
589         map.update(3, 7, add_more_to_count_simple);
590         map.update_with_key(5, 3, add_more_to_count);
591         map.update_with_key(3, 2, add_more_to_count);
592
593         // check the total counts
594         assert_eq!(map.find(&3).unwrap(), &10);
595         assert_eq!(map.find(&5).unwrap(), &3);
596         assert_eq!(map.find(&9).unwrap(), &1);
597
598         // sadly, no sevens were counted
599         assert!(map.find(&7).is_none());
600     }
601
602     #[test]
603     fn test_swap() {
604         let mut m = SmallIntMap::new();
605         assert_eq!(m.swap(1, 2i), None);
606         assert_eq!(m.swap(1, 3i), Some(2));
607         assert_eq!(m.swap(1, 4i), Some(3));
608     }
609
610     #[test]
611     fn test_pop() {
612         let mut m = SmallIntMap::new();
613         m.insert(1, 2i);
614         assert_eq!(m.pop(&1), Some(2));
615         assert_eq!(m.pop(&1), None);
616     }
617
618     #[test]
619     fn test_keys() {
620         let mut map = SmallIntMap::new();
621         map.insert(1, 'a');
622         map.insert(2, 'b');
623         map.insert(3, 'c');
624         let keys = map.keys().collect::<Vec<uint>>();
625         assert_eq!(keys.len(), 3);
626         assert!(keys.contains(&1));
627         assert!(keys.contains(&2));
628         assert!(keys.contains(&3));
629     }
630
631     #[test]
632     fn test_values() {
633         let mut map = SmallIntMap::new();
634         map.insert(1, 'a');
635         map.insert(2, 'b');
636         map.insert(3, 'c');
637         let values = map.values().map(|&v| v).collect::<Vec<char>>();
638         assert_eq!(values.len(), 3);
639         assert!(values.contains(&'a'));
640         assert!(values.contains(&'b'));
641         assert!(values.contains(&'c'));
642     }
643
644     #[test]
645     fn test_iterator() {
646         let mut m = SmallIntMap::new();
647
648         assert!(m.insert(0, 1i));
649         assert!(m.insert(1, 2));
650         assert!(m.insert(3, 5));
651         assert!(m.insert(6, 10));
652         assert!(m.insert(10, 11));
653
654         let mut it = m.iter();
655         assert_eq!(it.size_hint(), (0, Some(11)));
656         assert_eq!(it.next().unwrap(), (0, &1));
657         assert_eq!(it.size_hint(), (0, Some(10)));
658         assert_eq!(it.next().unwrap(), (1, &2));
659         assert_eq!(it.size_hint(), (0, Some(9)));
660         assert_eq!(it.next().unwrap(), (3, &5));
661         assert_eq!(it.size_hint(), (0, Some(7)));
662         assert_eq!(it.next().unwrap(), (6, &10));
663         assert_eq!(it.size_hint(), (0, Some(4)));
664         assert_eq!(it.next().unwrap(), (10, &11));
665         assert_eq!(it.size_hint(), (0, Some(0)));
666         assert!(it.next().is_none());
667     }
668
669     #[test]
670     fn test_iterator_size_hints() {
671         let mut m = SmallIntMap::new();
672
673         assert!(m.insert(0, 1i));
674         assert!(m.insert(1, 2));
675         assert!(m.insert(3, 5));
676         assert!(m.insert(6, 10));
677         assert!(m.insert(10, 11));
678
679         assert_eq!(m.iter().size_hint(), (0, Some(11)));
680         assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
681         assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
682         assert_eq!(m.mut_iter().rev().size_hint(), (0, Some(11)));
683     }
684
685     #[test]
686     fn test_mut_iterator() {
687         let mut m = SmallIntMap::new();
688
689         assert!(m.insert(0, 1i));
690         assert!(m.insert(1, 2));
691         assert!(m.insert(3, 5));
692         assert!(m.insert(6, 10));
693         assert!(m.insert(10, 11));
694
695         for (k, v) in m.mut_iter() {
696             *v += k as int;
697         }
698
699         let mut it = m.iter();
700         assert_eq!(it.next().unwrap(), (0, &1));
701         assert_eq!(it.next().unwrap(), (1, &3));
702         assert_eq!(it.next().unwrap(), (3, &8));
703         assert_eq!(it.next().unwrap(), (6, &16));
704         assert_eq!(it.next().unwrap(), (10, &21));
705         assert!(it.next().is_none());
706     }
707
708     #[test]
709     fn test_rev_iterator() {
710         let mut m = SmallIntMap::new();
711
712         assert!(m.insert(0, 1i));
713         assert!(m.insert(1, 2));
714         assert!(m.insert(3, 5));
715         assert!(m.insert(6, 10));
716         assert!(m.insert(10, 11));
717
718         let mut it = m.iter().rev();
719         assert_eq!(it.next().unwrap(), (10, &11));
720         assert_eq!(it.next().unwrap(), (6, &10));
721         assert_eq!(it.next().unwrap(), (3, &5));
722         assert_eq!(it.next().unwrap(), (1, &2));
723         assert_eq!(it.next().unwrap(), (0, &1));
724         assert!(it.next().is_none());
725     }
726
727     #[test]
728     fn test_mut_rev_iterator() {
729         let mut m = SmallIntMap::new();
730
731         assert!(m.insert(0, 1i));
732         assert!(m.insert(1, 2));
733         assert!(m.insert(3, 5));
734         assert!(m.insert(6, 10));
735         assert!(m.insert(10, 11));
736
737         for (k, v) in m.mut_iter().rev() {
738             *v += k as int;
739         }
740
741         let mut it = m.iter();
742         assert_eq!(it.next().unwrap(), (0, &1));
743         assert_eq!(it.next().unwrap(), (1, &3));
744         assert_eq!(it.next().unwrap(), (3, &8));
745         assert_eq!(it.next().unwrap(), (6, &16));
746         assert_eq!(it.next().unwrap(), (10, &21));
747         assert!(it.next().is_none());
748     }
749
750     #[test]
751     fn test_move_iter() {
752         let mut m = SmallIntMap::new();
753         m.insert(1, box 2i);
754         let mut called = false;
755         for (k, v) in m.move_iter() {
756             assert!(!called);
757             called = true;
758             assert_eq!(k, 1);
759             assert_eq!(v, box 2i);
760         }
761         assert!(called);
762         m.insert(2, box 1i);
763     }
764
765     #[test]
766     fn test_show() {
767         let mut map = SmallIntMap::new();
768         let empty = SmallIntMap::<int>::new();
769
770         map.insert(1, 2i);
771         map.insert(3, 4i);
772
773         let map_str = map.to_string();
774         let map_str = map_str.as_slice();
775         assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
776         assert_eq!(format!("{}", empty), "{}".to_string());
777     }
778
779     #[test]
780     fn test_clone() {
781         let mut a = SmallIntMap::new();
782
783         a.insert(1, 'x');
784         a.insert(4, 'y');
785         a.insert(6, 'z');
786
787         assert!(a.clone() == a);
788     }
789
790     #[test]
791     fn test_eq() {
792         let mut a = SmallIntMap::new();
793         let mut b = SmallIntMap::new();
794
795         assert!(a == b);
796         assert!(a.insert(0, 5i));
797         assert!(a != b);
798         assert!(b.insert(0, 4i));
799         assert!(a != b);
800         assert!(a.insert(5, 19));
801         assert!(a != b);
802         assert!(!b.insert(0, 5));
803         assert!(a != b);
804         assert!(b.insert(5, 19));
805         assert!(a == b);
806     }
807
808     #[test]
809     fn test_lt() {
810         let mut a = SmallIntMap::new();
811         let mut b = SmallIntMap::new();
812
813         assert!(!(a < b) && !(b < a));
814         assert!(b.insert(2u, 5i));
815         assert!(a < b);
816         assert!(a.insert(2, 7));
817         assert!(!(a < b) && b < a);
818         assert!(b.insert(1, 0));
819         assert!(b < a);
820         assert!(a.insert(0, 6));
821         assert!(a < b);
822         assert!(a.insert(6, 2));
823         assert!(a < b && !(b < a));
824     }
825
826     #[test]
827     fn test_ord() {
828         let mut a = SmallIntMap::new();
829         let mut b = SmallIntMap::new();
830
831         assert!(a <= b && a >= b);
832         assert!(a.insert(1u, 1i));
833         assert!(a > b && a >= b);
834         assert!(b < a && b <= a);
835         assert!(b.insert(2, 2));
836         assert!(b > a && b >= a);
837         assert!(a < b && a <= b);
838     }
839
840     #[test]
841     fn test_hash() {
842         let mut x = SmallIntMap::new();
843         let mut y = SmallIntMap::new();
844
845         assert!(hash::hash(&x) == hash::hash(&y));
846         x.insert(1, 'a');
847         x.insert(2, 'b');
848         x.insert(3, 'c');
849
850         y.insert(3, 'c');
851         y.insert(2, 'b');
852         y.insert(1, 'a');
853
854         assert!(hash::hash(&x) == hash::hash(&y));
855     }
856
857     #[test]
858     fn test_from_iter() {
859         let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
860
861         let map: SmallIntMap<char> = xs.iter().map(|&x| x).collect();
862
863         for &(k, v) in xs.iter() {
864             assert_eq!(map.find(&k), Some(&v));
865         }
866     }
867
868     #[test]
869     fn test_index() {
870         let mut map: SmallIntMap<int> = SmallIntMap::new();
871
872         map.insert(1, 2);
873         map.insert(2, 1);
874         map.insert(3, 4);
875
876         assert_eq!(map[3], 4);
877     }
878
879     #[test]
880     #[should_fail]
881     fn test_index_nonexistent() {
882         let mut map: SmallIntMap<int> = SmallIntMap::new();
883
884         map.insert(1, 2);
885         map.insert(2, 1);
886         map.insert(3, 4);
887
888         map[4];
889     }
890 }
891
892 #[cfg(test)]
893 mod bench {
894     extern crate test;
895     use self::test::Bencher;
896     use super::SmallIntMap;
897     use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
898
899     // Find seq
900     #[bench]
901     pub fn insert_rand_100(b: &mut Bencher) {
902         let mut m : SmallIntMap<uint> = SmallIntMap::new();
903         insert_rand_n(100, &mut m, b);
904     }
905
906     #[bench]
907     pub fn insert_rand_10_000(b: &mut Bencher) {
908         let mut m : SmallIntMap<uint> = SmallIntMap::new();
909         insert_rand_n(10_000, &mut m, b);
910     }
911
912     // Insert seq
913     #[bench]
914     pub fn insert_seq_100(b: &mut Bencher) {
915         let mut m : SmallIntMap<uint> = SmallIntMap::new();
916         insert_seq_n(100, &mut m, b);
917     }
918
919     #[bench]
920     pub fn insert_seq_10_000(b: &mut Bencher) {
921         let mut m : SmallIntMap<uint> = SmallIntMap::new();
922         insert_seq_n(10_000, &mut m, b);
923     }
924
925     // Find rand
926     #[bench]
927     pub fn find_rand_100(b: &mut Bencher) {
928         let mut m : SmallIntMap<uint> = SmallIntMap::new();
929         find_rand_n(100, &mut m, b);
930     }
931
932     #[bench]
933     pub fn find_rand_10_000(b: &mut Bencher) {
934         let mut m : SmallIntMap<uint> = SmallIntMap::new();
935         find_rand_n(10_000, &mut m, b);
936     }
937
938     // Find seq
939     #[bench]
940     pub fn find_seq_100(b: &mut Bencher) {
941         let mut m : SmallIntMap<uint> = SmallIntMap::new();
942         find_seq_n(100, &mut m, b);
943     }
944
945     #[bench]
946     pub fn find_seq_10_000(b: &mut Bencher) {
947         let mut m : SmallIntMap<uint> = SmallIntMap::new();
948         find_seq_n(10_000, &mut m, b);
949     }
950 }