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, Hasher};
22 use core::iter::{Enumerate, FilterMap, Map, FromIterator, IntoIterator};
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> {
69 #[stable(feature = "rust1", since = "1.0.0")]
70 impl<V> Default for VecMap<V> {
71 #[stable(feature = "rust1", since = "1.0.0")]
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 + Hasher, 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();
110 #[stable(feature = "rust1", since = "1.0.0")]
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);
122 #[stable(feature = "rust1", since = "1.0.0")]
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);
138 #[stable(feature = "rust1", since = "1.0.0")]
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);
157 #[stable(feature = "rust1", since = "1.0.0")]
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);
181 #[stable(feature = "rust1", since = "1.0.0")]
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 of the keys.
190 /// The iterator's element type is `uint`.
191 #[stable(feature = "rust1", since = "1.0.0")]
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 of the keys.
200 /// The iterator's element type is `&'r V`.
201 #[stable(feature = "rust1", since = "1.0.0")]
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 of 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);
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn iter<'r>(&'r self) -> Iter<'r, V> {
236 /// Returns an iterator visiting all key-value pairs in ascending order of 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");
258 #[stable(feature = "rust1", since = "1.0.0")]
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 of
268 /// the keys, 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 /// let vec: Vec<(uint, &str)> = map.into_iter().collect();
283 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn into_iter(self) -> IntoIter<V> {
287 fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
290 let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
292 IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
295 /// Returns an iterator visiting all key-value pairs in ascending order of
296 /// the keys, emptying (but not consuming) the original `VecMap`.
297 /// The iterator's element type is `(uint, &'r V)`. Keeps the allocated memory for reuse.
302 /// use std::collections::VecMap;
304 /// let mut map = VecMap::new();
305 /// map.insert(1, "a");
306 /// map.insert(3, "c");
307 /// map.insert(2, "b");
309 /// let vec: Vec<(uint, &str)> = map.drain().collect();
311 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
313 #[unstable(feature = "collections",
314 reason = "matches collection reform specification, waiting for dust to settle")]
315 pub fn drain<'a>(&'a mut self) -> Drain<'a, V> {
316 fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
319 let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
321 Drain { iter: self.v.drain().enumerate().filter_map(filter) }
324 /// Return the number of elements in the map.
329 /// use std::collections::VecMap;
331 /// let mut a = VecMap::new();
332 /// assert_eq!(a.len(), 0);
333 /// a.insert(1, "a");
334 /// assert_eq!(a.len(), 1);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn len(&self) -> uint {
338 self.v.iter().filter(|elt| elt.is_some()).count()
341 /// Return true if the map contains no elements.
346 /// use std::collections::VecMap;
348 /// let mut a = VecMap::new();
349 /// assert!(a.is_empty());
350 /// a.insert(1, "a");
351 /// assert!(!a.is_empty());
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn is_empty(&self) -> bool {
355 self.v.iter().all(|elt| elt.is_none())
358 /// Clears the map, removing all key-value pairs.
363 /// use std::collections::VecMap;
365 /// let mut a = VecMap::new();
366 /// a.insert(1, "a");
368 /// assert!(a.is_empty());
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn clear(&mut self) { self.v.clear() }
373 /// Returns a reference to the value corresponding to the key.
378 /// use std::collections::VecMap;
380 /// let mut map = VecMap::new();
381 /// map.insert(1, "a");
382 /// assert_eq!(map.get(&1), Some(&"a"));
383 /// assert_eq!(map.get(&2), None);
385 #[stable(feature = "rust1", since = "1.0.0")]
386 pub fn get(&self, key: &uint) -> Option<&V> {
387 if *key < self.v.len() {
389 Some(ref value) => Some(value),
397 /// Returns true if the map contains a value for the specified key.
402 /// use std::collections::VecMap;
404 /// let mut map = VecMap::new();
405 /// map.insert(1, "a");
406 /// assert_eq!(map.contains_key(&1), true);
407 /// assert_eq!(map.contains_key(&2), false);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn contains_key(&self, key: &uint) -> bool {
412 self.get(key).is_some()
415 /// Returns a mutable reference to the value corresponding to the key.
420 /// use std::collections::VecMap;
422 /// let mut map = VecMap::new();
423 /// map.insert(1, "a");
424 /// match map.get_mut(&1) {
425 /// Some(x) => *x = "b",
428 /// assert_eq!(map[1], "b");
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
432 if *key < self.v.len() {
433 match *(&mut self.v[*key]) {
434 Some(ref mut value) => Some(value),
442 /// Inserts a key-value pair from the map. If the key already had a value
443 /// present in the map, that value is returned. Otherwise, `None` is returned.
448 /// use std::collections::VecMap;
450 /// let mut map = VecMap::new();
451 /// assert_eq!(map.insert(37, "a"), None);
452 /// assert_eq!(map.is_empty(), false);
454 /// map.insert(37, "b");
455 /// assert_eq!(map.insert(37, "c"), Some("b"));
456 /// assert_eq!(map[37], "c");
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
460 let len = self.v.len();
462 self.v.extend((0..key - len + 1).map(|_| None));
464 replace(&mut self.v[key], Some(value))
467 /// Removes a key from the map, returning the value at the key if the key
468 /// was previously in the map.
473 /// use std::collections::VecMap;
475 /// let mut map = VecMap::new();
476 /// map.insert(1, "a");
477 /// assert_eq!(map.remove(&1), Some("a"));
478 /// assert_eq!(map.remove(&1), None);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn remove(&mut self, key: &uint) -> Option<V> {
482 if *key >= self.v.len() {
485 let result = &mut self.v[*key];
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<V: PartialEq> PartialEq for VecMap<V> {
492 fn eq(&self, other: &VecMap<V>) -> bool {
493 iter::order::eq(self.iter(), other.iter())
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<V: Eq> Eq for VecMap<V> {}
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<V: PartialOrd> PartialOrd for VecMap<V> {
503 fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
504 iter::order::partial_cmp(self.iter(), other.iter())
508 #[stable(feature = "rust1", since = "1.0.0")]
509 impl<V: Ord> Ord for VecMap<V> {
511 fn cmp(&self, other: &VecMap<V>) -> Ordering {
512 iter::order::cmp(self.iter(), other.iter())
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519 try!(write!(f, "VecMap {{"));
521 for (i, (k, v)) in self.iter().enumerate() {
522 if i != 0 { try!(write!(f, ", ")); }
523 try!(write!(f, "{}: {:?}", k, *v));
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl<V> FromIterator<(uint, V)> for VecMap<V> {
532 fn from_iter<Iter: Iterator<Item=(uint, V)>>(iter: Iter) -> VecMap<V> {
533 let mut map = VecMap::new();
539 impl<T> IntoIterator for VecMap<T> {
540 type Iter = IntoIter<T>;
542 fn into_iter(self) -> IntoIter<T> {
547 impl<'a, T> IntoIterator for &'a VecMap<T> {
548 type Iter = Iter<'a, T>;
550 fn into_iter(self) -> Iter<'a, T> {
555 impl<'a, T> IntoIterator for &'a mut VecMap<T> {
556 type Iter = IterMut<'a, T>;
558 fn into_iter(mut self) -> IterMut<'a, T> {
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl<V> Extend<(uint, V)> for VecMap<V> {
565 fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
572 impl<V> Index<uint> for VecMap<V> {
576 fn index<'a>(&'a self, i: &uint) -> &'a V {
577 self.get(i).expect("key not present")
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<V> IndexMut<uint> for VecMap<V> {
586 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
587 self.get_mut(i).expect("key not present")
591 macro_rules! iterator {
592 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
593 #[stable(feature = "rust1", since = "1.0.0")]
594 impl<'a, V> Iterator for $name<'a, V> {
598 fn next(&mut self) -> Option<$elem> {
599 while self.front < self.back {
600 match self.iter.next() {
602 match elem$(. $getter ())+ {
604 let index = self.front;
606 return Some((index, x));
619 fn size_hint(&self) -> (uint, Option<uint>) {
620 (0, Some(self.back - self.front))
626 macro_rules! double_ended_iterator {
627 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl<'a, V> DoubleEndedIterator for $name<'a, V> {
631 fn next_back(&mut self) -> Option<$elem> {
632 while self.front < self.back {
633 match self.iter.next_back() {
635 match elem$(. $getter ())+ {
638 return Some((self.back, x));
653 /// An iterator over the key-value pairs of a map.
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub struct Iter<'a, V:'a> {
658 iter: slice::Iter<'a, Option<V>>
661 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
662 impl<'a, V> Clone for Iter<'a, V> {
663 fn clone(&self) -> Iter<'a, V> {
667 iter: self.iter.clone()
672 iterator! { impl Iter -> (uint, &'a V), as_ref }
673 double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
675 /// An iterator over the key-value pairs of a map, with the
676 /// values being mutable.
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub struct IterMut<'a, V:'a> {
681 iter: slice::IterMut<'a, Option<V>>
684 iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
685 double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
687 /// An iterator over the keys of a map.
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub struct Keys<'a, V: 'a> {
690 iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
693 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
694 impl<'a, V> Clone for Keys<'a, V> {
695 fn clone(&self) -> Keys<'a, V> {
697 iter: self.iter.clone()
702 /// An iterator over the values of a map.
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub struct Values<'a, V: 'a> {
705 iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
708 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
709 impl<'a, V> Clone for Values<'a, V> {
710 fn clone(&self) -> Values<'a, V> {
712 iter: self.iter.clone()
717 /// A consuming iterator over the key-value pairs of a map.
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub struct IntoIter<V> {
723 Enumerate<vec::IntoIter<Option<V>>>,
724 fn((uint, Option<V>)) -> Option<(uint, V)>>
727 #[unstable(feature = "collections")]
728 pub struct Drain<'a, V> {
732 Enumerate<vec::Drain<'a, Option<V>>>,
733 fn((uint, Option<V>)) -> Option<(uint, V)>>
736 #[unstable(feature = "collections")]
737 impl<'a, V> Iterator for Drain<'a, V> {
738 type Item = (uint, V);
740 fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
741 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
744 #[unstable(feature = "collections")]
745 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
746 fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<'a, V> Iterator for Keys<'a, V> {
753 fn next(&mut self) -> Option<uint> { self.iter.next() }
754 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
756 #[stable(feature = "rust1", since = "1.0.0")]
757 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
758 fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl<'a, V> Iterator for Values<'a, V> {
765 fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
766 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
770 fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
773 #[stable(feature = "rust1", since = "1.0.0")]
774 impl<V> Iterator for IntoIter<V> {
775 type Item = (uint, V);
777 fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
778 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
780 #[stable(feature = "rust1", since = "1.0.0")]
781 impl<V> DoubleEndedIterator for IntoIter<V> {
782 fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
788 use core::hash::{hash, SipHasher};
794 let mut m = VecMap::new();
795 assert!(m.insert(1, 12i).is_none());
796 assert!(m.insert(2, 8).is_none());
797 assert!(m.insert(5, 14).is_none());
799 match m.get_mut(&5) {
800 None => panic!(), Some(x) => *x = new
802 assert_eq!(m.get(&5), Some(&new));
807 let mut map = VecMap::new();
808 assert_eq!(map.len(), 0);
809 assert!(map.is_empty());
810 assert!(map.insert(5, 20i).is_none());
811 assert_eq!(map.len(), 1);
812 assert!(!map.is_empty());
813 assert!(map.insert(11, 12).is_none());
814 assert_eq!(map.len(), 2);
815 assert!(!map.is_empty());
816 assert!(map.insert(14, 22).is_none());
817 assert_eq!(map.len(), 3);
818 assert!(!map.is_empty());
823 let mut map = VecMap::new();
824 assert!(map.insert(5, 20i).is_none());
825 assert!(map.insert(11, 12).is_none());
826 assert!(map.insert(14, 22).is_none());
828 assert!(map.is_empty());
829 assert!(map.get(&5).is_none());
830 assert!(map.get(&11).is_none());
831 assert!(map.get(&14).is_none());
836 let mut m = VecMap::new();
837 assert_eq!(m.insert(1, 2i), None);
838 assert_eq!(m.insert(1, 3i), Some(2));
839 assert_eq!(m.insert(1, 4i), Some(3));
844 let mut m = VecMap::new();
846 assert_eq!(m.remove(&1), Some(2));
847 assert_eq!(m.remove(&1), None);
852 let mut map = VecMap::new();
856 let keys = map.keys().collect::<Vec<uint>>();
857 assert_eq!(keys.len(), 3);
858 assert!(keys.contains(&1));
859 assert!(keys.contains(&2));
860 assert!(keys.contains(&3));
865 let mut map = VecMap::new();
869 let values = map.values().map(|&v| v).collect::<Vec<char>>();
870 assert_eq!(values.len(), 3);
871 assert!(values.contains(&'a'));
872 assert!(values.contains(&'b'));
873 assert!(values.contains(&'c'));
878 let mut m = VecMap::new();
880 assert!(m.insert(0, 1i).is_none());
881 assert!(m.insert(1, 2).is_none());
882 assert!(m.insert(3, 5).is_none());
883 assert!(m.insert(6, 10).is_none());
884 assert!(m.insert(10, 11).is_none());
886 let mut it = m.iter();
887 assert_eq!(it.size_hint(), (0, Some(11)));
888 assert_eq!(it.next().unwrap(), (0, &1));
889 assert_eq!(it.size_hint(), (0, Some(10)));
890 assert_eq!(it.next().unwrap(), (1, &2));
891 assert_eq!(it.size_hint(), (0, Some(9)));
892 assert_eq!(it.next().unwrap(), (3, &5));
893 assert_eq!(it.size_hint(), (0, Some(7)));
894 assert_eq!(it.next().unwrap(), (6, &10));
895 assert_eq!(it.size_hint(), (0, Some(4)));
896 assert_eq!(it.next().unwrap(), (10, &11));
897 assert_eq!(it.size_hint(), (0, Some(0)));
898 assert!(it.next().is_none());
902 fn test_iterator_size_hints() {
903 let mut m = VecMap::new();
905 assert!(m.insert(0, 1i).is_none());
906 assert!(m.insert(1, 2).is_none());
907 assert!(m.insert(3, 5).is_none());
908 assert!(m.insert(6, 10).is_none());
909 assert!(m.insert(10, 11).is_none());
911 assert_eq!(m.iter().size_hint(), (0, Some(11)));
912 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
913 assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
914 assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
918 fn test_mut_iterator() {
919 let mut m = VecMap::new();
921 assert!(m.insert(0, 1i).is_none());
922 assert!(m.insert(1, 2).is_none());
923 assert!(m.insert(3, 5).is_none());
924 assert!(m.insert(6, 10).is_none());
925 assert!(m.insert(10, 11).is_none());
927 for (k, v) in m.iter_mut() {
931 let mut it = m.iter();
932 assert_eq!(it.next().unwrap(), (0, &1));
933 assert_eq!(it.next().unwrap(), (1, &3));
934 assert_eq!(it.next().unwrap(), (3, &8));
935 assert_eq!(it.next().unwrap(), (6, &16));
936 assert_eq!(it.next().unwrap(), (10, &21));
937 assert!(it.next().is_none());
941 fn test_rev_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 let mut it = m.iter().rev();
951 assert_eq!(it.next().unwrap(), (10, &11));
952 assert_eq!(it.next().unwrap(), (6, &10));
953 assert_eq!(it.next().unwrap(), (3, &5));
954 assert_eq!(it.next().unwrap(), (1, &2));
955 assert_eq!(it.next().unwrap(), (0, &1));
956 assert!(it.next().is_none());
960 fn test_mut_rev_iterator() {
961 let mut m = VecMap::new();
963 assert!(m.insert(0, 1i).is_none());
964 assert!(m.insert(1, 2).is_none());
965 assert!(m.insert(3, 5).is_none());
966 assert!(m.insert(6, 10).is_none());
967 assert!(m.insert(10, 11).is_none());
969 for (k, v) in m.iter_mut().rev() {
973 let mut it = m.iter();
974 assert_eq!(it.next().unwrap(), (0, &1));
975 assert_eq!(it.next().unwrap(), (1, &3));
976 assert_eq!(it.next().unwrap(), (3, &8));
977 assert_eq!(it.next().unwrap(), (6, &16));
978 assert_eq!(it.next().unwrap(), (10, &21));
979 assert!(it.next().is_none());
983 fn test_move_iter() {
984 let mut m = VecMap::new();
986 let mut called = false;
987 for (k, v) in m.into_iter() {
991 assert_eq!(v, box 2i);
997 fn test_drain_iterator() {
998 let mut map = VecMap::new();
1003 let vec: Vec<(usize, &str)> = map.drain().collect();
1005 assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
1006 assert_eq!(map.len(), 0);
1011 let mut map = VecMap::new();
1012 let empty = VecMap::<int>::new();
1017 let map_str = format!("{:?}", map);
1018 assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1019 assert_eq!(format!("{:?}", empty), "VecMap {}");
1024 let mut a = VecMap::new();
1030 assert!(a.clone() == a);
1035 let mut a = VecMap::new();
1036 let mut b = VecMap::new();
1039 assert!(a.insert(0, 5i).is_none());
1041 assert!(b.insert(0, 4i).is_none());
1043 assert!(a.insert(5, 19).is_none());
1045 assert!(!b.insert(0, 5).is_none());
1047 assert!(b.insert(5, 19).is_none());
1051 b = VecMap::with_capacity(1);
1057 let mut a = VecMap::new();
1058 let mut b = VecMap::new();
1060 assert!(!(a < b) && !(b < a));
1061 assert!(b.insert(2u, 5i).is_none());
1063 assert!(a.insert(2, 7).is_none());
1064 assert!(!(a < b) && b < a);
1065 assert!(b.insert(1, 0).is_none());
1067 assert!(a.insert(0, 6).is_none());
1069 assert!(a.insert(6, 2).is_none());
1070 assert!(a < b && !(b < a));
1075 let mut a = VecMap::new();
1076 let mut b = VecMap::new();
1078 assert!(a <= b && a >= b);
1079 assert!(a.insert(1u, 1i).is_none());
1080 assert!(a > b && a >= b);
1081 assert!(b < a && b <= a);
1082 assert!(b.insert(2, 2).is_none());
1083 assert!(b > a && b >= a);
1084 assert!(a < b && a <= b);
1089 let mut x = VecMap::new();
1090 let mut y = VecMap::new();
1092 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1101 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1103 x.insert(1000, 'd');
1106 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1110 fn test_from_iter() {
1111 let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1113 let map: VecMap<char> = xs.iter().map(|&x| x).collect();
1115 for &(k, v) in xs.iter() {
1116 assert_eq!(map.get(&k), Some(&v));
1122 let mut map: VecMap<int> = VecMap::new();
1128 assert_eq!(map[3], 4);
1133 fn test_index_nonexistent() {
1134 let mut map: VecMap<int> = VecMap::new();
1148 use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1151 pub fn insert_rand_100(b: &mut Bencher) {
1152 let mut m : VecMap<uint> = VecMap::new();
1153 insert_rand_n(100, &mut m, b,
1154 |m, i| { m.insert(i, 1); },
1155 |m, i| { m.remove(&i); });
1159 pub fn insert_rand_10_000(b: &mut Bencher) {
1160 let mut m : VecMap<uint> = VecMap::new();
1161 insert_rand_n(10_000, &mut m, b,
1162 |m, i| { m.insert(i, 1); },
1163 |m, i| { m.remove(&i); });
1168 pub fn insert_seq_100(b: &mut Bencher) {
1169 let mut m : VecMap<uint> = VecMap::new();
1170 insert_seq_n(100, &mut m, b,
1171 |m, i| { m.insert(i, 1); },
1172 |m, i| { m.remove(&i); });
1176 pub fn insert_seq_10_000(b: &mut Bencher) {
1177 let mut m : VecMap<uint> = VecMap::new();
1178 insert_seq_n(10_000, &mut m, b,
1179 |m, i| { m.insert(i, 1); },
1180 |m, i| { m.remove(&i); });
1185 pub fn find_rand_100(b: &mut Bencher) {
1186 let mut m : VecMap<uint> = VecMap::new();
1187 find_rand_n(100, &mut m, b,
1188 |m, i| { m.insert(i, 1); },
1189 |m, i| { m.get(&i); });
1193 pub fn find_rand_10_000(b: &mut Bencher) {
1194 let mut m : VecMap<uint> = VecMap::new();
1195 find_rand_n(10_000, &mut m, b,
1196 |m, i| { m.insert(i, 1); },
1197 |m, i| { m.get(&i); });
1202 pub fn find_seq_100(b: &mut Bencher) {
1203 let mut m : VecMap<uint> = VecMap::new();
1204 find_seq_n(100, &mut m, b,
1205 |m, i| { m.insert(i, 1); },
1206 |m, i| { m.get(&i); });
1210 pub fn find_seq_10_000(b: &mut Bencher) {
1211 let mut m : VecMap<uint> = VecMap::new();
1212 find_seq_n(10_000, &mut m, b,
1213 |m, i| { m.insert(i, 1); },
1214 |m, i| { m.get(&i); });