]> git.lizzy.rs Git - rust.git/blob - src/libcollections/smallintmap.rs
auto merge of #16767 : SiegeLord/rust/reexported_methods, r=cmr
[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 /// Note: stage0-specific version that lacks bound on A.
493 #[cfg(stage0)]
494 pub struct Entries<'a, T> {
495     front: uint,
496     back: uint,
497     iter: slice::Items<'a, Option<T>>
498 }
499
500 /// Forward iterator over a map.
501 #[cfg(not(stage0))]
502 pub struct Entries<'a, T:'a> {
503     front: uint,
504     back: uint,
505     iter: slice::Items<'a, Option<T>>
506 }
507
508 iterator!(impl Entries -> (uint, &'a T), get_ref)
509 double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
510
511 /// Note: stage0-specific version that lacks bound on A.
512 #[cfg(stage0)]
513 pub struct MutEntries<'a, T> {
514     front: uint,
515     back: uint,
516     iter: slice::MutItems<'a, Option<T>>
517 }
518
519 /// Forward iterator over the key-value pairs of a map, with the
520 /// values being mutable.
521 #[cfg(not(stage0))]
522 pub struct MutEntries<'a, T:'a> {
523     front: uint,
524     back: uint,
525     iter: slice::MutItems<'a, Option<T>>
526 }
527
528 iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
529 double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
530
531 /// Forward iterator over the keys of a map
532 pub type Keys<'a, T> =
533     iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;
534
535 /// Forward iterator over the values of a map
536 pub type Values<'a, T> =
537     iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;
538
539 #[cfg(test)]
540 mod test_map {
541     use std::prelude::*;
542     use vec::Vec;
543     use hash;
544
545     use {Map, MutableMap, Mutable, MutableSeq};
546     use super::SmallIntMap;
547
548     #[test]
549     fn test_find_mut() {
550         let mut m = SmallIntMap::new();
551         assert!(m.insert(1, 12i));
552         assert!(m.insert(2, 8));
553         assert!(m.insert(5, 14));
554         let new = 100;
555         match m.find_mut(&5) {
556             None => fail!(), Some(x) => *x = new
557         }
558         assert_eq!(m.find(&5), Some(&new));
559     }
560
561     #[test]
562     fn test_len() {
563         let mut map = SmallIntMap::new();
564         assert_eq!(map.len(), 0);
565         assert!(map.is_empty());
566         assert!(map.insert(5, 20i));
567         assert_eq!(map.len(), 1);
568         assert!(!map.is_empty());
569         assert!(map.insert(11, 12));
570         assert_eq!(map.len(), 2);
571         assert!(!map.is_empty());
572         assert!(map.insert(14, 22));
573         assert_eq!(map.len(), 3);
574         assert!(!map.is_empty());
575     }
576
577     #[test]
578     fn test_clear() {
579         let mut map = SmallIntMap::new();
580         assert!(map.insert(5, 20i));
581         assert!(map.insert(11, 12));
582         assert!(map.insert(14, 22));
583         map.clear();
584         assert!(map.is_empty());
585         assert!(map.find(&5).is_none());
586         assert!(map.find(&11).is_none());
587         assert!(map.find(&14).is_none());
588     }
589
590     #[test]
591     fn test_insert_with_key() {
592         let mut map = SmallIntMap::new();
593
594         // given a new key, initialize it with this new count,
595         // given an existing key, add more to its count
596         fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
597             v0 + v1
598         }
599
600         fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
601             v0 + v1
602         }
603
604         // count integers
605         map.update(3, 1, add_more_to_count_simple);
606         map.update_with_key(9, 1, add_more_to_count);
607         map.update(3, 7, add_more_to_count_simple);
608         map.update_with_key(5, 3, add_more_to_count);
609         map.update_with_key(3, 2, add_more_to_count);
610
611         // check the total counts
612         assert_eq!(map.find(&3).unwrap(), &10);
613         assert_eq!(map.find(&5).unwrap(), &3);
614         assert_eq!(map.find(&9).unwrap(), &1);
615
616         // sadly, no sevens were counted
617         assert!(map.find(&7).is_none());
618     }
619
620     #[test]
621     fn test_swap() {
622         let mut m = SmallIntMap::new();
623         assert_eq!(m.swap(1, 2i), None);
624         assert_eq!(m.swap(1, 3i), Some(2));
625         assert_eq!(m.swap(1, 4i), Some(3));
626     }
627
628     #[test]
629     fn test_pop() {
630         let mut m = SmallIntMap::new();
631         m.insert(1, 2i);
632         assert_eq!(m.pop(&1), Some(2));
633         assert_eq!(m.pop(&1), None);
634     }
635
636     #[test]
637     fn test_keys() {
638         let mut map = SmallIntMap::new();
639         map.insert(1, 'a');
640         map.insert(2, 'b');
641         map.insert(3, 'c');
642         let keys = map.keys().collect::<Vec<uint>>();
643         assert_eq!(keys.len(), 3);
644         assert!(keys.contains(&1));
645         assert!(keys.contains(&2));
646         assert!(keys.contains(&3));
647     }
648
649     #[test]
650     fn test_values() {
651         let mut map = SmallIntMap::new();
652         map.insert(1, 'a');
653         map.insert(2, 'b');
654         map.insert(3, 'c');
655         let values = map.values().map(|&v| v).collect::<Vec<char>>();
656         assert_eq!(values.len(), 3);
657         assert!(values.contains(&'a'));
658         assert!(values.contains(&'b'));
659         assert!(values.contains(&'c'));
660     }
661
662     #[test]
663     fn test_iterator() {
664         let mut m = SmallIntMap::new();
665
666         assert!(m.insert(0, 1i));
667         assert!(m.insert(1, 2));
668         assert!(m.insert(3, 5));
669         assert!(m.insert(6, 10));
670         assert!(m.insert(10, 11));
671
672         let mut it = m.iter();
673         assert_eq!(it.size_hint(), (0, Some(11)));
674         assert_eq!(it.next().unwrap(), (0, &1));
675         assert_eq!(it.size_hint(), (0, Some(10)));
676         assert_eq!(it.next().unwrap(), (1, &2));
677         assert_eq!(it.size_hint(), (0, Some(9)));
678         assert_eq!(it.next().unwrap(), (3, &5));
679         assert_eq!(it.size_hint(), (0, Some(7)));
680         assert_eq!(it.next().unwrap(), (6, &10));
681         assert_eq!(it.size_hint(), (0, Some(4)));
682         assert_eq!(it.next().unwrap(), (10, &11));
683         assert_eq!(it.size_hint(), (0, Some(0)));
684         assert!(it.next().is_none());
685     }
686
687     #[test]
688     fn test_iterator_size_hints() {
689         let mut m = SmallIntMap::new();
690
691         assert!(m.insert(0, 1i));
692         assert!(m.insert(1, 2));
693         assert!(m.insert(3, 5));
694         assert!(m.insert(6, 10));
695         assert!(m.insert(10, 11));
696
697         assert_eq!(m.iter().size_hint(), (0, Some(11)));
698         assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
699         assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
700         assert_eq!(m.mut_iter().rev().size_hint(), (0, Some(11)));
701     }
702
703     #[test]
704     fn test_mut_iterator() {
705         let mut m = SmallIntMap::new();
706
707         assert!(m.insert(0, 1i));
708         assert!(m.insert(1, 2));
709         assert!(m.insert(3, 5));
710         assert!(m.insert(6, 10));
711         assert!(m.insert(10, 11));
712
713         for (k, v) in m.mut_iter() {
714             *v += k as int;
715         }
716
717         let mut it = m.iter();
718         assert_eq!(it.next().unwrap(), (0, &1));
719         assert_eq!(it.next().unwrap(), (1, &3));
720         assert_eq!(it.next().unwrap(), (3, &8));
721         assert_eq!(it.next().unwrap(), (6, &16));
722         assert_eq!(it.next().unwrap(), (10, &21));
723         assert!(it.next().is_none());
724     }
725
726     #[test]
727     fn test_rev_iterator() {
728         let mut m = SmallIntMap::new();
729
730         assert!(m.insert(0, 1i));
731         assert!(m.insert(1, 2));
732         assert!(m.insert(3, 5));
733         assert!(m.insert(6, 10));
734         assert!(m.insert(10, 11));
735
736         let mut it = m.iter().rev();
737         assert_eq!(it.next().unwrap(), (10, &11));
738         assert_eq!(it.next().unwrap(), (6, &10));
739         assert_eq!(it.next().unwrap(), (3, &5));
740         assert_eq!(it.next().unwrap(), (1, &2));
741         assert_eq!(it.next().unwrap(), (0, &1));
742         assert!(it.next().is_none());
743     }
744
745     #[test]
746     fn test_mut_rev_iterator() {
747         let mut m = SmallIntMap::new();
748
749         assert!(m.insert(0, 1i));
750         assert!(m.insert(1, 2));
751         assert!(m.insert(3, 5));
752         assert!(m.insert(6, 10));
753         assert!(m.insert(10, 11));
754
755         for (k, v) in m.mut_iter().rev() {
756             *v += k as int;
757         }
758
759         let mut it = m.iter();
760         assert_eq!(it.next().unwrap(), (0, &1));
761         assert_eq!(it.next().unwrap(), (1, &3));
762         assert_eq!(it.next().unwrap(), (3, &8));
763         assert_eq!(it.next().unwrap(), (6, &16));
764         assert_eq!(it.next().unwrap(), (10, &21));
765         assert!(it.next().is_none());
766     }
767
768     #[test]
769     fn test_move_iter() {
770         let mut m = SmallIntMap::new();
771         m.insert(1, box 2i);
772         let mut called = false;
773         for (k, v) in m.move_iter() {
774             assert!(!called);
775             called = true;
776             assert_eq!(k, 1);
777             assert_eq!(v, box 2i);
778         }
779         assert!(called);
780         m.insert(2, box 1i);
781     }
782
783     #[test]
784     fn test_show() {
785         let mut map = SmallIntMap::new();
786         let empty = SmallIntMap::<int>::new();
787
788         map.insert(1, 2i);
789         map.insert(3, 4i);
790
791         let map_str = map.to_string();
792         let map_str = map_str.as_slice();
793         assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
794         assert_eq!(format!("{}", empty), "{}".to_string());
795     }
796
797     #[test]
798     fn test_clone() {
799         let mut a = SmallIntMap::new();
800
801         a.insert(1, 'x');
802         a.insert(4, 'y');
803         a.insert(6, 'z');
804
805         assert!(a.clone() == a);
806     }
807
808     #[test]
809     fn test_eq() {
810         let mut a = SmallIntMap::new();
811         let mut b = SmallIntMap::new();
812
813         assert!(a == b);
814         assert!(a.insert(0, 5i));
815         assert!(a != b);
816         assert!(b.insert(0, 4i));
817         assert!(a != b);
818         assert!(a.insert(5, 19));
819         assert!(a != b);
820         assert!(!b.insert(0, 5));
821         assert!(a != b);
822         assert!(b.insert(5, 19));
823         assert!(a == b);
824     }
825
826     #[test]
827     fn test_lt() {
828         let mut a = SmallIntMap::new();
829         let mut b = SmallIntMap::new();
830
831         assert!(!(a < b) && !(b < a));
832         assert!(b.insert(2u, 5i));
833         assert!(a < b);
834         assert!(a.insert(2, 7));
835         assert!(!(a < b) && b < a);
836         assert!(b.insert(1, 0));
837         assert!(b < a);
838         assert!(a.insert(0, 6));
839         assert!(a < b);
840         assert!(a.insert(6, 2));
841         assert!(a < b && !(b < a));
842     }
843
844     #[test]
845     fn test_ord() {
846         let mut a = SmallIntMap::new();
847         let mut b = SmallIntMap::new();
848
849         assert!(a <= b && a >= b);
850         assert!(a.insert(1u, 1i));
851         assert!(a > b && a >= b);
852         assert!(b < a && b <= a);
853         assert!(b.insert(2, 2));
854         assert!(b > a && b >= a);
855         assert!(a < b && a <= b);
856     }
857
858     #[test]
859     fn test_hash() {
860         let mut x = SmallIntMap::new();
861         let mut y = SmallIntMap::new();
862
863         assert!(hash::hash(&x) == hash::hash(&y));
864         x.insert(1, 'a');
865         x.insert(2, 'b');
866         x.insert(3, 'c');
867
868         y.insert(3, 'c');
869         y.insert(2, 'b');
870         y.insert(1, 'a');
871
872         assert!(hash::hash(&x) == hash::hash(&y));
873     }
874
875     #[test]
876     fn test_from_iter() {
877         let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
878
879         let map: SmallIntMap<char> = xs.iter().map(|&x| x).collect();
880
881         for &(k, v) in xs.iter() {
882             assert_eq!(map.find(&k), Some(&v));
883         }
884     }
885
886     #[test]
887     fn test_index() {
888         let mut map: SmallIntMap<int> = SmallIntMap::new();
889
890         map.insert(1, 2);
891         map.insert(2, 1);
892         map.insert(3, 4);
893
894         assert_eq!(map[3], 4);
895     }
896
897     #[test]
898     #[should_fail]
899     fn test_index_nonexistent() {
900         let mut map: SmallIntMap<int> = SmallIntMap::new();
901
902         map.insert(1, 2);
903         map.insert(2, 1);
904         map.insert(3, 4);
905
906         map[4];
907     }
908 }
909
910 #[cfg(test)]
911 mod bench {
912     extern crate test;
913     use self::test::Bencher;
914     use super::SmallIntMap;
915     use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
916
917     // Find seq
918     #[bench]
919     pub fn insert_rand_100(b: &mut Bencher) {
920         let mut m : SmallIntMap<uint> = SmallIntMap::new();
921         insert_rand_n(100, &mut m, b);
922     }
923
924     #[bench]
925     pub fn insert_rand_10_000(b: &mut Bencher) {
926         let mut m : SmallIntMap<uint> = SmallIntMap::new();
927         insert_rand_n(10_000, &mut m, b);
928     }
929
930     // Insert seq
931     #[bench]
932     pub fn insert_seq_100(b: &mut Bencher) {
933         let mut m : SmallIntMap<uint> = SmallIntMap::new();
934         insert_seq_n(100, &mut m, b);
935     }
936
937     #[bench]
938     pub fn insert_seq_10_000(b: &mut Bencher) {
939         let mut m : SmallIntMap<uint> = SmallIntMap::new();
940         insert_seq_n(10_000, &mut m, b);
941     }
942
943     // Find rand
944     #[bench]
945     pub fn find_rand_100(b: &mut Bencher) {
946         let mut m : SmallIntMap<uint> = SmallIntMap::new();
947         find_rand_n(100, &mut m, b);
948     }
949
950     #[bench]
951     pub fn find_rand_10_000(b: &mut Bencher) {
952         let mut m : SmallIntMap<uint> = SmallIntMap::new();
953         find_rand_n(10_000, &mut m, b);
954     }
955
956     // Find seq
957     #[bench]
958     pub fn find_seq_100(b: &mut Bencher) {
959         let mut m : SmallIntMap<uint> = SmallIntMap::new();
960         find_seq_n(100, &mut m, b);
961     }
962
963     #[bench]
964     pub fn find_seq_10_000(b: &mut Bencher) {
965         let mut m : SmallIntMap<uint> = SmallIntMap::new();
966         find_seq_n(10_000, &mut m, b);
967     }
968 }