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.
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.
11 //! A simple map based on a vector for small integer keys. Space requirements
12 //! are O(highest integer key).
14 #![allow(missing_docs)]
18 use core::cmp::Ordering;
19 use core::default::Default;
21 use core::hash::{Hash, Writer};
22 use core::iter::{Enumerate, FilterMap, Map, FromIterator};
24 use core::mem::replace;
25 use core::ops::{Index, IndexMut};
30 // FIXME(conventions): capacity management???
32 /// A map optimized for small integer keys.
37 /// use std::collections::VecMap;
39 /// let mut months = VecMap::new();
40 /// months.insert(1, "Jan");
41 /// months.insert(2, "Feb");
42 /// months.insert(3, "Mar");
44 /// if !months.contains_key(&12) {
45 /// println!("The end is near!");
48 /// assert_eq!(months.get(&1), Some(&"Jan"));
50 /// match months.get_mut(&3) {
51 /// Some(value) => *value = "Venus",
55 /// assert_eq!(months.get(&3), Some(&"Venus"));
57 /// // Print out all months
58 /// for (key, value) in months.iter() {
59 /// println!("month {} is {}", key, value);
63 /// assert!(months.is_empty());
65 pub struct VecMap<V> {
70 impl<V> Default for VecMap<V> {
73 fn default() -> VecMap<V> { VecMap::new() }
76 impl<V:Clone> Clone for VecMap<V> {
78 fn clone(&self) -> VecMap<V> {
79 VecMap { v: self.v.clone() }
83 fn clone_from(&mut self, source: &VecMap<V>) {
84 self.v.clone_from(&source.v);
88 impl<S: Writer, V: Hash<S>> Hash<S> for VecMap<V> {
89 fn hash(&self, state: &mut S) {
90 // In order to not traverse the `VecMap` twice, count the elements
92 let mut count: uint = 0;
93 for elt in self.iter() {
102 /// Creates an empty `VecMap`.
107 /// use std::collections::VecMap;
108 /// let mut map: VecMap<&str> = VecMap::new();
111 pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
113 /// Creates an empty `VecMap` with space for at least `capacity`
114 /// elements before resizing.
119 /// use std::collections::VecMap;
120 /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
123 pub fn with_capacity(capacity: uint) -> VecMap<V> {
124 VecMap { v: Vec::with_capacity(capacity) }
127 /// Returns the number of elements the `VecMap` can hold without
133 /// use std::collections::VecMap;
134 /// let map: VecMap<String> = VecMap::with_capacity(10);
135 /// assert!(map.capacity() >= 10);
139 pub fn capacity(&self) -> uint {
143 /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
144 /// In the case of `VecMap` this means reallocations will not occur as long
145 /// as all inserted keys are less than `len`.
147 /// The collection may reserve more space to avoid frequent reallocations.
152 /// use std::collections::VecMap;
153 /// let mut map: VecMap<&str> = VecMap::new();
154 /// map.reserve_len(10);
155 /// assert!(map.capacity() >= 10);
158 pub fn reserve_len(&mut self, len: uint) {
159 let cur_len = self.v.len();
161 self.v.reserve(len - cur_len);
165 /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
166 /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
167 /// keys are less than `len`.
169 /// Note that the allocator may give the collection more space than it requests.
170 /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer
171 /// `reserve_len` if future insertions are expected.
176 /// use std::collections::VecMap;
177 /// let mut map: VecMap<&str> = VecMap::new();
178 /// map.reserve_len_exact(10);
179 /// assert!(map.capacity() >= 10);
182 pub fn reserve_len_exact(&mut self, len: uint) {
183 let cur_len = self.v.len();
185 self.v.reserve_exact(len - cur_len);
189 /// Returns an iterator visiting all keys in ascending order by the keys.
190 /// The iterator's element type is `uint`.
192 pub fn keys<'r>(&'r self) -> Keys<'r, V> {
193 fn first<A, B>((a, _): (A, B)) -> A { a }
194 let first: fn((uint, &'r V)) -> uint = first; // coerce to fn pointer
196 Keys { iter: self.iter().map(first) }
199 /// Returns an iterator visiting all values in ascending order by the keys.
200 /// The iterator's element type is `&'r V`.
202 pub fn values<'r>(&'r self) -> Values<'r, V> {
203 fn second<A, B>((_, b): (A, B)) -> B { b }
204 let second: fn((uint, &'r V)) -> &'r V = second; // coerce to fn pointer
206 Values { iter: self.iter().map(second) }
209 /// Returns an iterator visiting all key-value pairs in ascending order by the keys.
210 /// The iterator's element type is `(uint, &'r V)`.
215 /// use std::collections::VecMap;
217 /// let mut map = VecMap::new();
218 /// map.insert(1, "a");
219 /// map.insert(3, "c");
220 /// map.insert(2, "b");
222 /// // Print `1: a` then `2: b` then `3: c`
223 /// for (key, value) in map.iter() {
224 /// println!("{}: {}", key, value);
228 pub fn iter<'r>(&'r self) -> Iter<'r, V> {
236 /// Returns an iterator visiting all key-value pairs in ascending order by the keys,
237 /// with mutable references to the values.
238 /// The iterator's element type is `(uint, &'r mut V)`.
243 /// use std::collections::VecMap;
245 /// let mut map = VecMap::new();
246 /// map.insert(1, "a");
247 /// map.insert(2, "b");
248 /// map.insert(3, "c");
250 /// for (key, value) in map.iter_mut() {
254 /// for (key, value) in map.iter() {
255 /// assert_eq!(value, &"x");
259 pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
263 iter: self.v.iter_mut()
267 /// Returns an iterator visiting all key-value pairs in ascending order by
268 /// the keys, emptying (but not consuming) the original `VecMap`.
269 /// The iterator's element type is `(uint, &'r V)`.
274 /// use std::collections::VecMap;
276 /// let mut map = VecMap::new();
277 /// map.insert(1, "a");
278 /// map.insert(3, "c");
279 /// map.insert(2, "b");
281 /// // Not possible with .iter()
282 /// let vec: Vec<(uint, &str)> = map.into_iter().collect();
284 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
287 pub fn into_iter(&mut self) -> IntoIter<V> {
288 fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
291 let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
293 let values = replace(&mut self.v, vec!());
294 IntoIter { iter: values.into_iter().enumerate().filter_map(filter) }
297 /// Return the number of elements in the map.
302 /// use std::collections::VecMap;
304 /// let mut a = VecMap::new();
305 /// assert_eq!(a.len(), 0);
306 /// a.insert(1, "a");
307 /// assert_eq!(a.len(), 1);
310 pub fn len(&self) -> uint {
311 self.v.iter().filter(|elt| elt.is_some()).count()
314 /// Return true if the map contains no elements.
319 /// use std::collections::VecMap;
321 /// let mut a = VecMap::new();
322 /// assert!(a.is_empty());
323 /// a.insert(1, "a");
324 /// assert!(!a.is_empty());
327 pub fn is_empty(&self) -> bool {
328 self.v.iter().all(|elt| elt.is_none())
331 /// Clears the map, removing all key-value pairs.
336 /// use std::collections::VecMap;
338 /// let mut a = VecMap::new();
339 /// a.insert(1, "a");
341 /// assert!(a.is_empty());
344 pub fn clear(&mut self) { self.v.clear() }
346 /// Deprecated: Renamed to `get`.
347 #[deprecated = "Renamed to `get`"]
348 pub fn find(&self, key: &uint) -> Option<&V> {
352 /// Returns a reference to the value corresponding to the key.
357 /// use std::collections::VecMap;
359 /// let mut map = VecMap::new();
360 /// map.insert(1, "a");
361 /// assert_eq!(map.get(&1), Some(&"a"));
362 /// assert_eq!(map.get(&2), None);
365 pub fn get(&self, key: &uint) -> Option<&V> {
366 if *key < self.v.len() {
368 Some(ref value) => Some(value),
376 /// Returns true if the map contains a value for the specified key.
381 /// use std::collections::VecMap;
383 /// let mut map = VecMap::new();
384 /// map.insert(1, "a");
385 /// assert_eq!(map.contains_key(&1), true);
386 /// assert_eq!(map.contains_key(&2), false);
390 pub fn contains_key(&self, key: &uint) -> bool {
391 self.get(key).is_some()
394 /// Deprecated: Renamed to `get_mut`.
395 #[deprecated = "Renamed to `get_mut`"]
396 pub fn find_mut(&mut self, key: &uint) -> Option<&mut V> {
400 /// Returns a mutable reference to the value corresponding to the key.
405 /// use std::collections::VecMap;
407 /// let mut map = VecMap::new();
408 /// map.insert(1, "a");
409 /// match map.get_mut(&1) {
410 /// Some(x) => *x = "b",
413 /// assert_eq!(map[1], "b");
416 pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
417 if *key < self.v.len() {
418 match *(&mut self.v[*key]) {
419 Some(ref mut value) => Some(value),
427 /// Deprecated: Renamed to `insert`.
428 #[deprecated = "Renamed to `insert`"]
429 pub fn swap(&mut self, key: uint, value: V) -> Option<V> {
430 self.insert(key, value)
433 /// Inserts a key-value pair from the map. If the key already had a value
434 /// present in the map, that value is returned. Otherwise, `None` is returned.
439 /// use std::collections::VecMap;
441 /// let mut map = VecMap::new();
442 /// assert_eq!(map.insert(37, "a"), None);
443 /// assert_eq!(map.is_empty(), false);
445 /// map.insert(37, "b");
446 /// assert_eq!(map.insert(37, "c"), Some("b"));
447 /// assert_eq!(map[37], "c");
450 pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
451 let len = self.v.len();
453 self.v.extend(range(0, key - len + 1).map(|_| None));
455 replace(&mut self.v[key], Some(value))
458 /// Deprecated: Renamed to `remove`.
459 #[deprecated = "Renamed to `remove`"]
460 pub fn pop(&mut self, key: &uint) -> Option<V> {
464 /// Removes a key from the map, returning the value at the key if the key
465 /// was previously in the map.
470 /// use std::collections::VecMap;
472 /// let mut map = VecMap::new();
473 /// map.insert(1, "a");
474 /// assert_eq!(map.remove(&1), Some("a"));
475 /// assert_eq!(map.remove(&1), None);
478 pub fn remove(&mut self, key: &uint) -> Option<V> {
479 if *key >= self.v.len() {
486 impl<V:Clone> VecMap<V> {
487 /// Deprecated: Use the entry API when available; shouldn't matter anyway, access is cheap.
488 #[deprecated = "Use the entry API when available; shouldn't matter anyway, access is cheap"]
490 pub fn update<F>(&mut self, key: uint, newval: V, ff: F) -> bool where F: FnOnce(V, V) -> V {
491 self.update_with_key(key, newval, move |_k, v, v1| ff(v,v1))
494 /// Deprecated: Use the entry API when available; shouldn't matter anyway, access is cheap.
495 #[deprecated = "Use the entry API when available; shouldn't matter anyway, access is cheap"]
496 pub fn update_with_key<F>(&mut self, key: uint, val: V, ff: F) -> bool where
497 F: FnOnce(uint, V, V) -> V
499 let new_val = match self.get(&key) {
501 Some(orig) => ff(key, (*orig).clone(), val)
503 self.insert(key, new_val).is_none()
508 impl<V: PartialEq> PartialEq for VecMap<V> {
509 fn eq(&self, other: &VecMap<V>) -> bool {
510 iter::order::eq(self.iter(), other.iter())
515 impl<V: Eq> Eq for VecMap<V> {}
518 impl<V: PartialOrd> PartialOrd for VecMap<V> {
520 fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
521 iter::order::partial_cmp(self.iter(), other.iter())
526 impl<V: Ord> Ord for VecMap<V> {
528 fn cmp(&self, other: &VecMap<V>) -> Ordering {
529 iter::order::cmp(self.iter(), other.iter())
534 impl<V: fmt::Show> fmt::Show for VecMap<V> {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 try!(write!(f, "{{"));
538 for (i, (k, v)) in self.iter().enumerate() {
539 if i != 0 { try!(write!(f, ", ")); }
540 try!(write!(f, "{}: {}", k, *v));
548 impl<V> FromIterator<(uint, V)> for VecMap<V> {
549 fn from_iter<Iter: Iterator<Item=(uint, V)>>(iter: Iter) -> VecMap<V> {
550 let mut map = VecMap::new();
557 impl<V> Extend<(uint, V)> for VecMap<V> {
558 fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
565 // NOTE(stage0): remove impl after a snapshot
568 impl<V> Index<uint, V> for VecMap<V> {
570 fn index<'a>(&'a self, i: &uint) -> &'a V {
571 self.get(i).expect("key not present")
575 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
576 impl<V> Index<uint> for VecMap<V> {
580 fn index<'a>(&'a self, i: &uint) -> &'a V {
581 self.get(i).expect("key not present")
585 // NOTE(stage0): remove impl after a snapshot
588 impl<V> IndexMut<uint, V> for VecMap<V> {
590 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
591 self.get_mut(i).expect("key not present")
595 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
597 impl<V> IndexMut<uint> for VecMap<V> {
601 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
602 self.get_mut(i).expect("key not present")
606 macro_rules! iterator {
607 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
609 impl<'a, V> Iterator for $name<'a, V> {
613 fn next(&mut self) -> Option<$elem> {
614 while self.front < self.back {
615 match self.iter.next() {
617 match elem$(. $getter ())+ {
619 let index = self.front;
621 return Some((index, x));
634 fn size_hint(&self) -> (uint, Option<uint>) {
635 (0, Some(self.back - self.front))
641 macro_rules! double_ended_iterator {
642 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
644 impl<'a, V> DoubleEndedIterator for $name<'a, V> {
646 fn next_back(&mut self) -> Option<$elem> {
647 while self.front < self.back {
648 match self.iter.next_back() {
650 match elem$(. $getter ())+ {
653 return Some((self.back, x));
668 /// An iterator over the key-value pairs of a map.
670 pub struct Iter<'a, V:'a> {
673 iter: slice::Iter<'a, Option<V>>
676 // FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
677 impl<'a, V> Clone for Iter<'a, V> {
678 fn clone(&self) -> Iter<'a, V> {
682 iter: self.iter.clone()
687 iterator! { impl Iter -> (uint, &'a V), as_ref }
688 double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
690 /// An iterator over the key-value pairs of a map, with the
691 /// values being mutable.
693 pub struct IterMut<'a, V:'a> {
696 iter: slice::IterMut<'a, Option<V>>
699 iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
700 double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
702 /// An iterator over the keys of a map.
704 pub struct Keys<'a, V: 'a> {
705 iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
708 // FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
709 impl<'a, V> Clone for Keys<'a, V> {
710 fn clone(&self) -> Keys<'a, V> {
712 iter: self.iter.clone()
717 /// An iterator over the values of a map.
719 pub struct Values<'a, V: 'a> {
720 iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
723 // FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
724 impl<'a, V> Clone for Values<'a, V> {
725 fn clone(&self) -> Values<'a, V> {
727 iter: self.iter.clone()
732 /// A consuming iterator over the key-value pairs of a map.
734 pub struct IntoIter<V> {
738 Enumerate<vec::IntoIter<Option<V>>>,
739 fn((uint, Option<V>)) -> Option<(uint, V)>>
743 impl<'a, V> Iterator for Keys<'a, V> {
746 fn next(&mut self) -> Option<uint> { self.iter.next() }
747 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
750 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
751 fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
755 impl<'a, V> Iterator for Values<'a, V> {
758 fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
759 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
762 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
763 fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
767 impl<V> Iterator for IntoIter<V> {
768 type Item = (uint, V);
770 fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
771 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
774 impl<V> DoubleEndedIterator for IntoIter<V> {
775 fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
781 use core::hash::hash;
787 let mut m = VecMap::new();
788 assert!(m.insert(1, 12i).is_none());
789 assert!(m.insert(2, 8).is_none());
790 assert!(m.insert(5, 14).is_none());
792 match m.get_mut(&5) {
793 None => panic!(), Some(x) => *x = new
795 assert_eq!(m.get(&5), Some(&new));
800 let mut map = VecMap::new();
801 assert_eq!(map.len(), 0);
802 assert!(map.is_empty());
803 assert!(map.insert(5, 20i).is_none());
804 assert_eq!(map.len(), 1);
805 assert!(!map.is_empty());
806 assert!(map.insert(11, 12).is_none());
807 assert_eq!(map.len(), 2);
808 assert!(!map.is_empty());
809 assert!(map.insert(14, 22).is_none());
810 assert_eq!(map.len(), 3);
811 assert!(!map.is_empty());
816 let mut map = VecMap::new();
817 assert!(map.insert(5, 20i).is_none());
818 assert!(map.insert(11, 12).is_none());
819 assert!(map.insert(14, 22).is_none());
821 assert!(map.is_empty());
822 assert!(map.get(&5).is_none());
823 assert!(map.get(&11).is_none());
824 assert!(map.get(&14).is_none());
828 fn test_insert_with_key() {
829 let mut map = VecMap::new();
831 // given a new key, initialize it with this new count,
832 // given an existing key, add more to its count
833 fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
837 fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
842 map.update(3, 1, add_more_to_count_simple);
843 map.update_with_key(9, 1, add_more_to_count);
844 map.update(3, 7, add_more_to_count_simple);
845 map.update_with_key(5, 3, add_more_to_count);
846 map.update_with_key(3, 2, add_more_to_count);
848 // check the total counts
849 assert_eq!(map.get(&3).unwrap(), &10);
850 assert_eq!(map.get(&5).unwrap(), &3);
851 assert_eq!(map.get(&9).unwrap(), &1);
853 // sadly, no sevens were counted
854 assert!(map.get(&7).is_none());
859 let mut m = VecMap::new();
860 assert_eq!(m.insert(1, 2i), None);
861 assert_eq!(m.insert(1, 3i), Some(2));
862 assert_eq!(m.insert(1, 4i), Some(3));
867 let mut m = VecMap::new();
869 assert_eq!(m.remove(&1), Some(2));
870 assert_eq!(m.remove(&1), None);
875 let mut map = VecMap::new();
879 let keys = map.keys().collect::<Vec<uint>>();
880 assert_eq!(keys.len(), 3);
881 assert!(keys.contains(&1));
882 assert!(keys.contains(&2));
883 assert!(keys.contains(&3));
888 let mut map = VecMap::new();
892 let values = map.values().map(|&v| v).collect::<Vec<char>>();
893 assert_eq!(values.len(), 3);
894 assert!(values.contains(&'a'));
895 assert!(values.contains(&'b'));
896 assert!(values.contains(&'c'));
901 let mut m = VecMap::new();
903 assert!(m.insert(0, 1i).is_none());
904 assert!(m.insert(1, 2).is_none());
905 assert!(m.insert(3, 5).is_none());
906 assert!(m.insert(6, 10).is_none());
907 assert!(m.insert(10, 11).is_none());
909 let mut it = m.iter();
910 assert_eq!(it.size_hint(), (0, Some(11)));
911 assert_eq!(it.next().unwrap(), (0, &1));
912 assert_eq!(it.size_hint(), (0, Some(10)));
913 assert_eq!(it.next().unwrap(), (1, &2));
914 assert_eq!(it.size_hint(), (0, Some(9)));
915 assert_eq!(it.next().unwrap(), (3, &5));
916 assert_eq!(it.size_hint(), (0, Some(7)));
917 assert_eq!(it.next().unwrap(), (6, &10));
918 assert_eq!(it.size_hint(), (0, Some(4)));
919 assert_eq!(it.next().unwrap(), (10, &11));
920 assert_eq!(it.size_hint(), (0, Some(0)));
921 assert!(it.next().is_none());
925 fn test_iterator_size_hints() {
926 let mut m = VecMap::new();
928 assert!(m.insert(0, 1i).is_none());
929 assert!(m.insert(1, 2).is_none());
930 assert!(m.insert(3, 5).is_none());
931 assert!(m.insert(6, 10).is_none());
932 assert!(m.insert(10, 11).is_none());
934 assert_eq!(m.iter().size_hint(), (0, Some(11)));
935 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
936 assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
937 assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
941 fn test_mut_iterator() {
942 let mut m = VecMap::new();
944 assert!(m.insert(0, 1i).is_none());
945 assert!(m.insert(1, 2).is_none());
946 assert!(m.insert(3, 5).is_none());
947 assert!(m.insert(6, 10).is_none());
948 assert!(m.insert(10, 11).is_none());
950 for (k, v) in m.iter_mut() {
954 let mut it = m.iter();
955 assert_eq!(it.next().unwrap(), (0, &1));
956 assert_eq!(it.next().unwrap(), (1, &3));
957 assert_eq!(it.next().unwrap(), (3, &8));
958 assert_eq!(it.next().unwrap(), (6, &16));
959 assert_eq!(it.next().unwrap(), (10, &21));
960 assert!(it.next().is_none());
964 fn test_rev_iterator() {
965 let mut m = VecMap::new();
967 assert!(m.insert(0, 1i).is_none());
968 assert!(m.insert(1, 2).is_none());
969 assert!(m.insert(3, 5).is_none());
970 assert!(m.insert(6, 10).is_none());
971 assert!(m.insert(10, 11).is_none());
973 let mut it = m.iter().rev();
974 assert_eq!(it.next().unwrap(), (10, &11));
975 assert_eq!(it.next().unwrap(), (6, &10));
976 assert_eq!(it.next().unwrap(), (3, &5));
977 assert_eq!(it.next().unwrap(), (1, &2));
978 assert_eq!(it.next().unwrap(), (0, &1));
979 assert!(it.next().is_none());
983 fn test_mut_rev_iterator() {
984 let mut m = VecMap::new();
986 assert!(m.insert(0, 1i).is_none());
987 assert!(m.insert(1, 2).is_none());
988 assert!(m.insert(3, 5).is_none());
989 assert!(m.insert(6, 10).is_none());
990 assert!(m.insert(10, 11).is_none());
992 for (k, v) in m.iter_mut().rev() {
996 let mut it = m.iter();
997 assert_eq!(it.next().unwrap(), (0, &1));
998 assert_eq!(it.next().unwrap(), (1, &3));
999 assert_eq!(it.next().unwrap(), (3, &8));
1000 assert_eq!(it.next().unwrap(), (6, &16));
1001 assert_eq!(it.next().unwrap(), (10, &21));
1002 assert!(it.next().is_none());
1006 fn test_move_iter() {
1007 let mut m = VecMap::new();
1008 m.insert(1, box 2i);
1009 let mut called = false;
1010 for (k, v) in m.into_iter() {
1014 assert_eq!(v, box 2i);
1017 m.insert(2, box 1i);
1022 let mut map = VecMap::new();
1023 let empty = VecMap::<int>::new();
1028 let map_str = map.to_string();
1029 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1030 assert_eq!(format!("{}", empty), "{}");
1035 let mut a = VecMap::new();
1041 assert!(a.clone() == a);
1046 let mut a = VecMap::new();
1047 let mut b = VecMap::new();
1050 assert!(a.insert(0, 5i).is_none());
1052 assert!(b.insert(0, 4i).is_none());
1054 assert!(a.insert(5, 19).is_none());
1056 assert!(!b.insert(0, 5).is_none());
1058 assert!(b.insert(5, 19).is_none());
1062 b = VecMap::with_capacity(1);
1068 let mut a = VecMap::new();
1069 let mut b = VecMap::new();
1071 assert!(!(a < b) && !(b < a));
1072 assert!(b.insert(2u, 5i).is_none());
1074 assert!(a.insert(2, 7).is_none());
1075 assert!(!(a < b) && b < a);
1076 assert!(b.insert(1, 0).is_none());
1078 assert!(a.insert(0, 6).is_none());
1080 assert!(a.insert(6, 2).is_none());
1081 assert!(a < b && !(b < a));
1086 let mut a = VecMap::new();
1087 let mut b = VecMap::new();
1089 assert!(a <= b && a >= b);
1090 assert!(a.insert(1u, 1i).is_none());
1091 assert!(a > b && a >= b);
1092 assert!(b < a && b <= a);
1093 assert!(b.insert(2, 2).is_none());
1094 assert!(b > a && b >= a);
1095 assert!(a < b && a <= b);
1100 let mut x = VecMap::new();
1101 let mut y = VecMap::new();
1103 assert!(hash(&x) == hash(&y));
1112 assert!(hash(&x) == hash(&y));
1114 x.insert(1000, 'd');
1117 assert!(hash(&x) == hash(&y));
1121 fn test_from_iter() {
1122 let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1124 let map: VecMap<char> = xs.iter().map(|&x| x).collect();
1126 for &(k, v) in xs.iter() {
1127 assert_eq!(map.get(&k), Some(&v));
1133 let mut map: VecMap<int> = VecMap::new();
1139 assert_eq!(map[3], 4);
1144 fn test_index_nonexistent() {
1145 let mut map: VecMap<int> = VecMap::new();
1159 use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1162 pub fn insert_rand_100(b: &mut Bencher) {
1163 let mut m : VecMap<uint> = VecMap::new();
1164 insert_rand_n(100, &mut m, b,
1165 |m, i| { m.insert(i, 1); },
1166 |m, i| { m.remove(&i); });
1170 pub fn insert_rand_10_000(b: &mut Bencher) {
1171 let mut m : VecMap<uint> = VecMap::new();
1172 insert_rand_n(10_000, &mut m, b,
1173 |m, i| { m.insert(i, 1); },
1174 |m, i| { m.remove(&i); });
1179 pub fn insert_seq_100(b: &mut Bencher) {
1180 let mut m : VecMap<uint> = VecMap::new();
1181 insert_seq_n(100, &mut m, b,
1182 |m, i| { m.insert(i, 1); },
1183 |m, i| { m.remove(&i); });
1187 pub fn insert_seq_10_000(b: &mut Bencher) {
1188 let mut m : VecMap<uint> = VecMap::new();
1189 insert_seq_n(10_000, &mut m, b,
1190 |m, i| { m.insert(i, 1); },
1191 |m, i| { m.remove(&i); });
1196 pub fn find_rand_100(b: &mut Bencher) {
1197 let mut m : VecMap<uint> = VecMap::new();
1198 find_rand_n(100, &mut m, b,
1199 |m, i| { m.insert(i, 1); },
1200 |m, i| { m.get(&i); });
1204 pub fn find_rand_10_000(b: &mut Bencher) {
1205 let mut m : VecMap<uint> = VecMap::new();
1206 find_rand_n(10_000, &mut m, b,
1207 |m, i| { m.insert(i, 1); },
1208 |m, i| { m.get(&i); });
1213 pub fn find_seq_100(b: &mut Bencher) {
1214 let mut m : VecMap<uint> = VecMap::new();
1215 find_seq_n(100, &mut m, b,
1216 |m, i| { m.insert(i, 1); },
1217 |m, i| { m.get(&i); });
1221 pub fn find_seq_10_000(b: &mut Bencher) {
1222 let mut m : VecMap<uint> = VecMap::new();
1223 find_seq_n(10_000, &mut m, b,
1224 |m, i| { m.insert(i, 1); },
1225 |m, i| { m.get(&i); });