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)]
16 pub use self::Entry::*;
20 use core::cmp::Ordering;
21 use core::default::Default;
23 use core::hash::{Hash, Writer, Hasher};
24 use core::iter::{Enumerate, FilterMap, Map, FromIterator, IntoIterator};
26 use core::mem::replace;
27 use core::ops::{Index, IndexMut};
32 // FIXME(conventions): capacity management???
34 /// A map optimized for small integer keys.
39 /// use std::collections::VecMap;
41 /// let mut months = VecMap::new();
42 /// months.insert(1, "Jan");
43 /// months.insert(2, "Feb");
44 /// months.insert(3, "Mar");
46 /// if !months.contains_key(&12) {
47 /// println!("The end is near!");
50 /// assert_eq!(months.get(&1), Some(&"Jan"));
52 /// match months.get_mut(&3) {
53 /// Some(value) => *value = "Venus",
57 /// assert_eq!(months.get(&3), Some(&"Venus"));
59 /// // Print out all months
60 /// for (key, value) in months.iter() {
61 /// println!("month {} is {}", key, value);
65 /// assert!(months.is_empty());
67 pub struct VecMap<V> {
71 /// A view into a single entry in a map, which may either be vacant or occupied.
72 #[unstable(feature = "collections",
73 reason = "precise API still under development")]
74 pub enum Entry<'a, V:'a> {
76 Vacant(VacantEntry<'a, V>),
78 Occupied(OccupiedEntry<'a, V>),
82 #[unstable(feature = "collections",
83 reason = "precise API still under development")]
84 pub struct VacantEntry<'a, V:'a> {
85 map: &'a mut VecMap<V>,
89 /// An occupied Entry.
90 #[unstable(feature = "collections",
91 reason = "precise API still under development")]
92 pub struct OccupiedEntry<'a, V:'a> {
93 map: &'a mut VecMap<V>,
97 #[stable(feature = "rust1", since = "1.0.0")]
98 impl<V> Default for VecMap<V> {
99 #[stable(feature = "rust1", since = "1.0.0")]
101 fn default() -> VecMap<V> { VecMap::new() }
104 impl<V:Clone> Clone for VecMap<V> {
106 fn clone(&self) -> VecMap<V> {
107 VecMap { v: self.v.clone() }
111 fn clone_from(&mut self, source: &VecMap<V>) {
112 self.v.clone_from(&source.v);
116 impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> {
117 fn hash(&self, state: &mut S) {
118 // In order to not traverse the `VecMap` twice, count the elements
120 let mut count: uint = 0;
121 for elt in self.iter() {
130 /// Creates an empty `VecMap`.
135 /// use std::collections::VecMap;
136 /// let mut map: VecMap<&str> = VecMap::new();
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
141 /// Creates an empty `VecMap` with space for at least `capacity`
142 /// elements before resizing.
147 /// use std::collections::VecMap;
148 /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn with_capacity(capacity: uint) -> VecMap<V> {
152 VecMap { v: Vec::with_capacity(capacity) }
155 /// Returns the number of elements the `VecMap` can hold without
161 /// use std::collections::VecMap;
162 /// let map: VecMap<String> = VecMap::with_capacity(10);
163 /// assert!(map.capacity() >= 10);
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn capacity(&self) -> uint {
171 /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
172 /// In the case of `VecMap` this means reallocations will not occur as long
173 /// as all inserted keys are less than `len`.
175 /// The collection may reserve more space to avoid frequent reallocations.
180 /// use std::collections::VecMap;
181 /// let mut map: VecMap<&str> = VecMap::new();
182 /// map.reserve_len(10);
183 /// assert!(map.capacity() >= 10);
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn reserve_len(&mut self, len: uint) {
187 let cur_len = self.v.len();
189 self.v.reserve(len - cur_len);
193 /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
194 /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
195 /// keys are less than `len`.
197 /// Note that the allocator may give the collection more space than it requests.
198 /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer
199 /// `reserve_len` if future insertions are expected.
204 /// use std::collections::VecMap;
205 /// let mut map: VecMap<&str> = VecMap::new();
206 /// map.reserve_len_exact(10);
207 /// assert!(map.capacity() >= 10);
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn reserve_len_exact(&mut self, len: uint) {
211 let cur_len = self.v.len();
213 self.v.reserve_exact(len - cur_len);
217 /// Returns an iterator visiting all keys in ascending order of the keys.
218 /// The iterator's element type is `uint`.
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn keys<'r>(&'r self) -> Keys<'r, V> {
221 fn first<A, B>((a, _): (A, B)) -> A { a }
222 let first: fn((uint, &'r V)) -> uint = first; // coerce to fn pointer
224 Keys { iter: self.iter().map(first) }
227 /// Returns an iterator visiting all values in ascending order of the keys.
228 /// The iterator's element type is `&'r V`.
229 #[stable(feature = "rust1", since = "1.0.0")]
230 pub fn values<'r>(&'r self) -> Values<'r, V> {
231 fn second<A, B>((_, b): (A, B)) -> B { b }
232 let second: fn((uint, &'r V)) -> &'r V = second; // coerce to fn pointer
234 Values { iter: self.iter().map(second) }
237 /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
238 /// The iterator's element type is `(uint, &'r V)`.
243 /// use std::collections::VecMap;
245 /// let mut map = VecMap::new();
246 /// map.insert(1, "a");
247 /// map.insert(3, "c");
248 /// map.insert(2, "b");
250 /// // Print `1: a` then `2: b` then `3: c`
251 /// for (key, value) in map.iter() {
252 /// println!("{}: {}", key, value);
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn iter<'r>(&'r self) -> Iter<'r, V> {
264 /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
265 /// with mutable references to the values.
266 /// The iterator's element type is `(uint, &'r mut V)`.
271 /// use std::collections::VecMap;
273 /// let mut map = VecMap::new();
274 /// map.insert(1, "a");
275 /// map.insert(2, "b");
276 /// map.insert(3, "c");
278 /// for (key, value) in map.iter_mut() {
282 /// for (key, value) in map.iter() {
283 /// assert_eq!(value, &"x");
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
291 iter: self.v.iter_mut()
295 /// Returns an iterator visiting all key-value pairs in ascending order of
296 /// the keys, consuming the original `VecMap`.
297 /// The iterator's element type is `(uint, &'r V)`.
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.into_iter().collect();
311 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn into_iter(self) -> IntoIter<V> {
315 fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
318 let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
320 IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
323 /// Returns an iterator visiting all key-value pairs in ascending order of
324 /// the keys, emptying (but not consuming) the original `VecMap`.
325 /// The iterator's element type is `(uint, &'r V)`. Keeps the allocated memory for reuse.
330 /// use std::collections::VecMap;
332 /// let mut map = VecMap::new();
333 /// map.insert(1, "a");
334 /// map.insert(3, "c");
335 /// map.insert(2, "b");
337 /// let vec: Vec<(uint, &str)> = map.drain().collect();
339 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
341 #[unstable(feature = "collections",
342 reason = "matches collection reform specification, waiting for dust to settle")]
343 pub fn drain<'a>(&'a mut self) -> Drain<'a, V> {
344 fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
347 let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
349 Drain { iter: self.v.drain().enumerate().filter_map(filter) }
352 /// Return the number of elements in the map.
357 /// use std::collections::VecMap;
359 /// let mut a = VecMap::new();
360 /// assert_eq!(a.len(), 0);
361 /// a.insert(1, "a");
362 /// assert_eq!(a.len(), 1);
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn len(&self) -> uint {
366 self.v.iter().filter(|elt| elt.is_some()).count()
369 /// Return true if the map contains no elements.
374 /// use std::collections::VecMap;
376 /// let mut a = VecMap::new();
377 /// assert!(a.is_empty());
378 /// a.insert(1, "a");
379 /// assert!(!a.is_empty());
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn is_empty(&self) -> bool {
383 self.v.iter().all(|elt| elt.is_none())
386 /// Clears the map, removing all key-value pairs.
391 /// use std::collections::VecMap;
393 /// let mut a = VecMap::new();
394 /// a.insert(1, "a");
396 /// assert!(a.is_empty());
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn clear(&mut self) { self.v.clear() }
401 /// Returns a reference to the value corresponding to the key.
406 /// use std::collections::VecMap;
408 /// let mut map = VecMap::new();
409 /// map.insert(1, "a");
410 /// assert_eq!(map.get(&1), Some(&"a"));
411 /// assert_eq!(map.get(&2), None);
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn get(&self, key: &uint) -> Option<&V> {
415 if *key < self.v.len() {
417 Some(ref value) => Some(value),
425 /// Returns true if the map contains a value for the specified key.
430 /// use std::collections::VecMap;
432 /// let mut map = VecMap::new();
433 /// map.insert(1, "a");
434 /// assert_eq!(map.contains_key(&1), true);
435 /// assert_eq!(map.contains_key(&2), false);
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn contains_key(&self, key: &uint) -> bool {
440 self.get(key).is_some()
443 /// Returns a mutable reference to the value corresponding to the key.
448 /// use std::collections::VecMap;
450 /// let mut map = VecMap::new();
451 /// map.insert(1, "a");
452 /// match map.get_mut(&1) {
453 /// Some(x) => *x = "b",
456 /// assert_eq!(map[1], "b");
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
460 if *key < self.v.len() {
461 match *(&mut self.v[*key]) {
462 Some(ref mut value) => Some(value),
470 /// Inserts a key-value pair from the map. If the key already had a value
471 /// present in the map, that value is returned. Otherwise, `None` is returned.
476 /// use std::collections::VecMap;
478 /// let mut map = VecMap::new();
479 /// assert_eq!(map.insert(37, "a"), None);
480 /// assert_eq!(map.is_empty(), false);
482 /// map.insert(37, "b");
483 /// assert_eq!(map.insert(37, "c"), Some("b"));
484 /// assert_eq!(map[37], "c");
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
488 let len = self.v.len();
490 self.v.extend((0..key - len + 1).map(|_| None));
492 replace(&mut self.v[key], Some(value))
495 /// Removes a key from the map, returning the value at the key if the key
496 /// was previously in the map.
501 /// use std::collections::VecMap;
503 /// let mut map = VecMap::new();
504 /// map.insert(1, "a");
505 /// assert_eq!(map.remove(&1), Some("a"));
506 /// assert_eq!(map.remove(&1), None);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn remove(&mut self, key: &uint) -> Option<V> {
510 if *key >= self.v.len() {
513 let result = &mut self.v[*key];
517 /// Gets the given key's corresponding entry in the map for in-place manipulation.
522 /// use std::collections::VecMap;
523 /// use std::collections::vec_map::Entry;
525 /// let mut count: VecMap<u32> = VecMap::new();
527 /// // count the number of occurrences of numbers in the vec
528 /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4].iter() {
529 /// match count.entry(*x) {
530 /// Entry::Vacant(view) => {
533 /// Entry::Occupied(mut view) => {
534 /// let v = view.get_mut();
540 /// assert_eq!(count[1], 3);
542 #[unstable(feature = "collections",
543 reason = "precise API still under development")]
544 pub fn entry(&mut self, key: usize) -> Entry<V> {
545 // FIXME(Gankro): this is basically the dumbest implementation of
546 // entry possible, because weird non-lexical borrows issues make it
547 // completely insane to do any other way. That said, Entry is a border-line
548 // useless construct on VecMap, so it's hardly a big loss.
549 if self.contains_key(&key) {
550 Occupied(OccupiedEntry {
564 impl<'a, V> Entry<'a, V> {
565 #[unstable(feature = "collections",
566 reason = "matches collection reform v2 specification, waiting for dust to settle")]
567 /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
568 pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
570 Occupied(entry) => Ok(entry.into_mut()),
571 Vacant(entry) => Err(entry),
576 impl<'a, V> VacantEntry<'a, V> {
577 /// Sets the value of the entry with the VacantEntry's key,
578 /// and returns a mutable reference to it.
579 #[unstable(feature = "collections",
580 reason = "matches collection reform v2 specification, waiting for dust to settle")]
581 pub fn insert(self, value: V) -> &'a mut V {
582 let index = self.index;
583 self.map.insert(index, value);
588 impl<'a, V> OccupiedEntry<'a, V> {
589 /// Gets a reference to the value in the entry.
590 #[unstable(feature = "collections",
591 reason = "matches collection reform v2 specification, waiting for dust to settle")]
592 pub fn get(&self) -> &V {
593 let index = self.index;
597 /// Gets a mutable reference to the value in the entry.
598 #[unstable(feature = "collections",
599 reason = "matches collection reform v2 specification, waiting for dust to settle")]
600 pub fn get_mut(&mut self) -> &mut V {
601 let index = self.index;
605 /// Converts the entry into a mutable reference to its value.
606 #[unstable(feature = "collections",
607 reason = "matches collection reform v2 specification, waiting for dust to settle")]
608 pub fn into_mut(self) -> &'a mut V {
609 let index = self.index;
613 /// Sets the value of the entry with the OccupiedEntry's key,
614 /// and returns the entry's old value.
615 #[unstable(feature = "collections",
616 reason = "matches collection reform v2 specification, waiting for dust to settle")]
617 pub fn insert(&mut self, value: V) -> V {
618 let index = self.index;
619 self.map.insert(index, value).unwrap()
622 /// Takes the value of the entry out of the map, and returns it.
623 #[unstable(feature = "collections",
624 reason = "matches collection reform v2 specification, waiting for dust to settle")]
625 pub fn remove(self) -> V {
626 let index = self.index;
627 self.map.remove(&index).unwrap()
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<V: PartialEq> PartialEq for VecMap<V> {
633 fn eq(&self, other: &VecMap<V>) -> bool {
634 iter::order::eq(self.iter(), other.iter())
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl<V: Eq> Eq for VecMap<V> {}
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl<V: PartialOrd> PartialOrd for VecMap<V> {
644 fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
645 iter::order::partial_cmp(self.iter(), other.iter())
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<V: Ord> Ord for VecMap<V> {
652 fn cmp(&self, other: &VecMap<V>) -> Ordering {
653 iter::order::cmp(self.iter(), other.iter())
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660 try!(write!(f, "VecMap {{"));
662 for (i, (k, v)) in self.iter().enumerate() {
663 if i != 0 { try!(write!(f, ", ")); }
664 try!(write!(f, "{}: {:?}", k, *v));
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<V> FromIterator<(uint, V)> for VecMap<V> {
673 fn from_iter<Iter: Iterator<Item=(uint, V)>>(iter: Iter) -> VecMap<V> {
674 let mut map = VecMap::new();
680 impl<T> IntoIterator for VecMap<T> {
681 type Iter = IntoIter<T>;
683 fn into_iter(self) -> IntoIter<T> {
688 impl<'a, T> IntoIterator for &'a VecMap<T> {
689 type Iter = Iter<'a, T>;
691 fn into_iter(self) -> Iter<'a, T> {
696 impl<'a, T> IntoIterator for &'a mut VecMap<T> {
697 type Iter = IterMut<'a, T>;
699 fn into_iter(mut self) -> IterMut<'a, T> {
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl<V> Extend<(uint, V)> for VecMap<V> {
706 fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
713 impl<V> Index<uint> for VecMap<V> {
717 fn index<'a>(&'a self, i: &uint) -> &'a V {
718 self.get(i).expect("key not present")
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<V> IndexMut<uint> for VecMap<V> {
727 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
728 self.get_mut(i).expect("key not present")
732 macro_rules! iterator {
733 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<'a, V> Iterator for $name<'a, V> {
739 fn next(&mut self) -> Option<$elem> {
740 while self.front < self.back {
741 match self.iter.next() {
743 match elem$(. $getter ())+ {
745 let index = self.front;
747 return Some((index, x));
760 fn size_hint(&self) -> (uint, Option<uint>) {
761 (0, Some(self.back - self.front))
767 macro_rules! double_ended_iterator {
768 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<'a, V> DoubleEndedIterator for $name<'a, V> {
772 fn next_back(&mut self) -> Option<$elem> {
773 while self.front < self.back {
774 match self.iter.next_back() {
776 match elem$(. $getter ())+ {
779 return Some((self.back, x));
794 /// An iterator over the key-value pairs of a map.
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub struct Iter<'a, V:'a> {
799 iter: slice::Iter<'a, Option<V>>
802 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
803 impl<'a, V> Clone for Iter<'a, V> {
804 fn clone(&self) -> Iter<'a, V> {
808 iter: self.iter.clone()
813 iterator! { impl Iter -> (uint, &'a V), as_ref }
814 double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
816 /// An iterator over the key-value pairs of a map, with the
817 /// values being mutable.
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub struct IterMut<'a, V:'a> {
822 iter: slice::IterMut<'a, Option<V>>
825 iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
826 double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
828 /// An iterator over the keys of a map.
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub struct Keys<'a, V: 'a> {
831 iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
834 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
835 impl<'a, V> Clone for Keys<'a, V> {
836 fn clone(&self) -> Keys<'a, V> {
838 iter: self.iter.clone()
843 /// An iterator over the values of a map.
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct Values<'a, V: 'a> {
846 iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
849 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
850 impl<'a, V> Clone for Values<'a, V> {
851 fn clone(&self) -> Values<'a, V> {
853 iter: self.iter.clone()
858 /// A consuming iterator over the key-value pairs of a map.
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub struct IntoIter<V> {
864 Enumerate<vec::IntoIter<Option<V>>>,
865 fn((uint, Option<V>)) -> Option<(uint, V)>>
868 #[unstable(feature = "collections")]
869 pub struct Drain<'a, V> {
873 Enumerate<vec::Drain<'a, Option<V>>>,
874 fn((uint, Option<V>)) -> Option<(uint, V)>>
877 #[unstable(feature = "collections")]
878 impl<'a, V> Iterator for Drain<'a, V> {
879 type Item = (uint, V);
881 fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
882 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
885 #[unstable(feature = "collections")]
886 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
887 fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<'a, V> Iterator for Keys<'a, V> {
894 fn next(&mut self) -> Option<uint> { self.iter.next() }
895 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
899 fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a, V> Iterator for Values<'a, V> {
906 fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
907 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
911 fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<V> Iterator for IntoIter<V> {
916 type Item = (uint, V);
918 fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
919 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<V> DoubleEndedIterator for IntoIter<V> {
923 fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
929 use core::hash::{hash, SipHasher};
931 use super::{VecMap, Occupied, Vacant};
935 let mut m = VecMap::new();
936 assert!(m.insert(1, 12).is_none());
937 assert!(m.insert(2, 8).is_none());
938 assert!(m.insert(5, 14).is_none());
940 match m.get_mut(&5) {
941 None => panic!(), Some(x) => *x = new
943 assert_eq!(m.get(&5), Some(&new));
948 let mut map = VecMap::new();
949 assert_eq!(map.len(), 0);
950 assert!(map.is_empty());
951 assert!(map.insert(5, 20).is_none());
952 assert_eq!(map.len(), 1);
953 assert!(!map.is_empty());
954 assert!(map.insert(11, 12).is_none());
955 assert_eq!(map.len(), 2);
956 assert!(!map.is_empty());
957 assert!(map.insert(14, 22).is_none());
958 assert_eq!(map.len(), 3);
959 assert!(!map.is_empty());
964 let mut map = VecMap::new();
965 assert!(map.insert(5, 20).is_none());
966 assert!(map.insert(11, 12).is_none());
967 assert!(map.insert(14, 22).is_none());
969 assert!(map.is_empty());
970 assert!(map.get(&5).is_none());
971 assert!(map.get(&11).is_none());
972 assert!(map.get(&14).is_none());
977 let mut m = VecMap::new();
978 assert_eq!(m.insert(1, 2), None);
979 assert_eq!(m.insert(1, 3), Some(2));
980 assert_eq!(m.insert(1, 4), Some(3));
985 let mut m = VecMap::new();
987 assert_eq!(m.remove(&1), Some(2));
988 assert_eq!(m.remove(&1), None);
993 let mut map = VecMap::new();
997 let keys = map.keys().collect::<Vec<uint>>();
998 assert_eq!(keys.len(), 3);
999 assert!(keys.contains(&1));
1000 assert!(keys.contains(&2));
1001 assert!(keys.contains(&3));
1006 let mut map = VecMap::new();
1010 let values = map.values().map(|&v| v).collect::<Vec<char>>();
1011 assert_eq!(values.len(), 3);
1012 assert!(values.contains(&'a'));
1013 assert!(values.contains(&'b'));
1014 assert!(values.contains(&'c'));
1018 fn test_iterator() {
1019 let mut m = VecMap::new();
1021 assert!(m.insert(0, 1).is_none());
1022 assert!(m.insert(1, 2).is_none());
1023 assert!(m.insert(3, 5).is_none());
1024 assert!(m.insert(6, 10).is_none());
1025 assert!(m.insert(10, 11).is_none());
1027 let mut it = m.iter();
1028 assert_eq!(it.size_hint(), (0, Some(11)));
1029 assert_eq!(it.next().unwrap(), (0, &1));
1030 assert_eq!(it.size_hint(), (0, Some(10)));
1031 assert_eq!(it.next().unwrap(), (1, &2));
1032 assert_eq!(it.size_hint(), (0, Some(9)));
1033 assert_eq!(it.next().unwrap(), (3, &5));
1034 assert_eq!(it.size_hint(), (0, Some(7)));
1035 assert_eq!(it.next().unwrap(), (6, &10));
1036 assert_eq!(it.size_hint(), (0, Some(4)));
1037 assert_eq!(it.next().unwrap(), (10, &11));
1038 assert_eq!(it.size_hint(), (0, Some(0)));
1039 assert!(it.next().is_none());
1043 fn test_iterator_size_hints() {
1044 let mut m = VecMap::new();
1046 assert!(m.insert(0, 1).is_none());
1047 assert!(m.insert(1, 2).is_none());
1048 assert!(m.insert(3, 5).is_none());
1049 assert!(m.insert(6, 10).is_none());
1050 assert!(m.insert(10, 11).is_none());
1052 assert_eq!(m.iter().size_hint(), (0, Some(11)));
1053 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
1054 assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
1055 assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
1059 fn test_mut_iterator() {
1060 let mut m = VecMap::new();
1062 assert!(m.insert(0, 1).is_none());
1063 assert!(m.insert(1, 2).is_none());
1064 assert!(m.insert(3, 5).is_none());
1065 assert!(m.insert(6, 10).is_none());
1066 assert!(m.insert(10, 11).is_none());
1068 for (k, v) in m.iter_mut() {
1072 let mut it = m.iter();
1073 assert_eq!(it.next().unwrap(), (0, &1));
1074 assert_eq!(it.next().unwrap(), (1, &3));
1075 assert_eq!(it.next().unwrap(), (3, &8));
1076 assert_eq!(it.next().unwrap(), (6, &16));
1077 assert_eq!(it.next().unwrap(), (10, &21));
1078 assert!(it.next().is_none());
1082 fn test_rev_iterator() {
1083 let mut m = VecMap::new();
1085 assert!(m.insert(0, 1).is_none());
1086 assert!(m.insert(1, 2).is_none());
1087 assert!(m.insert(3, 5).is_none());
1088 assert!(m.insert(6, 10).is_none());
1089 assert!(m.insert(10, 11).is_none());
1091 let mut it = m.iter().rev();
1092 assert_eq!(it.next().unwrap(), (10, &11));
1093 assert_eq!(it.next().unwrap(), (6, &10));
1094 assert_eq!(it.next().unwrap(), (3, &5));
1095 assert_eq!(it.next().unwrap(), (1, &2));
1096 assert_eq!(it.next().unwrap(), (0, &1));
1097 assert!(it.next().is_none());
1101 fn test_mut_rev_iterator() {
1102 let mut m = VecMap::new();
1104 assert!(m.insert(0, 1).is_none());
1105 assert!(m.insert(1, 2).is_none());
1106 assert!(m.insert(3, 5).is_none());
1107 assert!(m.insert(6, 10).is_none());
1108 assert!(m.insert(10, 11).is_none());
1110 for (k, v) in m.iter_mut().rev() {
1114 let mut it = m.iter();
1115 assert_eq!(it.next().unwrap(), (0, &1));
1116 assert_eq!(it.next().unwrap(), (1, &3));
1117 assert_eq!(it.next().unwrap(), (3, &8));
1118 assert_eq!(it.next().unwrap(), (6, &16));
1119 assert_eq!(it.next().unwrap(), (10, &21));
1120 assert!(it.next().is_none());
1124 fn test_move_iter() {
1125 let mut m = VecMap::new();
1127 let mut called = false;
1128 for (k, v) in m.into_iter() {
1132 assert_eq!(v, box 2);
1138 fn test_drain_iterator() {
1139 let mut map = VecMap::new();
1144 let vec: Vec<(usize, &str)> = map.drain().collect();
1146 assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
1147 assert_eq!(map.len(), 0);
1152 let mut map = VecMap::new();
1153 let empty = VecMap::<int>::new();
1158 let map_str = format!("{:?}", map);
1159 assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1160 assert_eq!(format!("{:?}", empty), "VecMap {}");
1165 let mut a = VecMap::new();
1171 assert!(a.clone() == a);
1176 let mut a = VecMap::new();
1177 let mut b = VecMap::new();
1180 assert!(a.insert(0, 5).is_none());
1182 assert!(b.insert(0, 4).is_none());
1184 assert!(a.insert(5, 19).is_none());
1186 assert!(!b.insert(0, 5).is_none());
1188 assert!(b.insert(5, 19).is_none());
1192 b = VecMap::with_capacity(1);
1198 let mut a = VecMap::new();
1199 let mut b = VecMap::new();
1201 assert!(!(a < b) && !(b < a));
1202 assert!(b.insert(2u, 5).is_none());
1204 assert!(a.insert(2, 7).is_none());
1205 assert!(!(a < b) && b < a);
1206 assert!(b.insert(1, 0).is_none());
1208 assert!(a.insert(0, 6).is_none());
1210 assert!(a.insert(6, 2).is_none());
1211 assert!(a < b && !(b < a));
1216 let mut a = VecMap::new();
1217 let mut b = VecMap::new();
1219 assert!(a <= b && a >= b);
1220 assert!(a.insert(1u, 1).is_none());
1221 assert!(a > b && a >= b);
1222 assert!(b < a && b <= a);
1223 assert!(b.insert(2, 2).is_none());
1224 assert!(b > a && b >= a);
1225 assert!(a < b && a <= b);
1230 let mut x = VecMap::new();
1231 let mut y = VecMap::new();
1233 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1242 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1244 x.insert(1000, 'd');
1247 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1251 fn test_from_iter() {
1252 let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1254 let map: VecMap<char> = xs.iter().map(|&x| x).collect();
1256 for &(k, v) in xs.iter() {
1257 assert_eq!(map.get(&k), Some(&v));
1263 let mut map: VecMap<int> = VecMap::new();
1269 assert_eq!(map[3], 4);
1274 fn test_index_nonexistent() {
1275 let mut map: VecMap<int> = VecMap::new();
1286 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1288 let mut map: VecMap<i32> = xs.iter().map(|&x| x).collect();
1290 // Existing key (insert)
1291 match map.entry(1) {
1292 Vacant(_) => unreachable!(),
1293 Occupied(mut view) => {
1294 assert_eq!(view.get(), &10);
1295 assert_eq!(view.insert(100), 10);
1298 assert_eq!(map.get(&1).unwrap(), &100);
1299 assert_eq!(map.len(), 6);
1302 // Existing key (update)
1303 match map.entry(2) {
1304 Vacant(_) => unreachable!(),
1305 Occupied(mut view) => {
1306 let v = view.get_mut();
1310 assert_eq!(map.get(&2).unwrap(), &200);
1311 assert_eq!(map.len(), 6);
1313 // Existing key (take)
1314 match map.entry(3) {
1315 Vacant(_) => unreachable!(),
1317 assert_eq!(view.remove(), 30);
1320 assert_eq!(map.get(&3), None);
1321 assert_eq!(map.len(), 5);
1324 // Inexistent key (insert)
1325 match map.entry(10) {
1326 Occupied(_) => unreachable!(),
1328 assert_eq!(*view.insert(1000), 1000);
1331 assert_eq!(map.get(&10).unwrap(), &1000);
1332 assert_eq!(map.len(), 6);
1340 use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1343 pub fn insert_rand_100(b: &mut Bencher) {
1344 let mut m : VecMap<uint> = VecMap::new();
1345 insert_rand_n(100, &mut m, b,
1346 |m, i| { m.insert(i, 1); },
1347 |m, i| { m.remove(&i); });
1351 pub fn insert_rand_10_000(b: &mut Bencher) {
1352 let mut m : VecMap<uint> = VecMap::new();
1353 insert_rand_n(10_000, &mut m, b,
1354 |m, i| { m.insert(i, 1); },
1355 |m, i| { m.remove(&i); });
1360 pub fn insert_seq_100(b: &mut Bencher) {
1361 let mut m : VecMap<uint> = VecMap::new();
1362 insert_seq_n(100, &mut m, b,
1363 |m, i| { m.insert(i, 1); },
1364 |m, i| { m.remove(&i); });
1368 pub fn insert_seq_10_000(b: &mut Bencher) {
1369 let mut m : VecMap<uint> = VecMap::new();
1370 insert_seq_n(10_000, &mut m, b,
1371 |m, i| { m.insert(i, 1); },
1372 |m, i| { m.remove(&i); });
1377 pub fn find_rand_100(b: &mut Bencher) {
1378 let mut m : VecMap<uint> = VecMap::new();
1379 find_rand_n(100, &mut m, b,
1380 |m, i| { m.insert(i, 1); },
1381 |m, i| { m.get(&i); });
1385 pub fn find_rand_10_000(b: &mut Bencher) {
1386 let mut m : VecMap<uint> = VecMap::new();
1387 find_rand_n(10_000, &mut m, b,
1388 |m, i| { m.insert(i, 1); },
1389 |m, i| { m.get(&i); });
1394 pub fn find_seq_100(b: &mut Bencher) {
1395 let mut m : VecMap<uint> = VecMap::new();
1396 find_seq_n(100, &mut m, b,
1397 |m, i| { m.insert(i, 1); },
1398 |m, i| { m.get(&i); });
1402 pub fn find_seq_10_000(b: &mut Bencher) {
1403 let mut m : VecMap<uint> = VecMap::new();
1404 find_seq_n(10_000, &mut m, b,
1405 |m, i| { m.insert(i, 1); },
1406 |m, i| { m.get(&i); });