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