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)]
20 use core::cmp::Ordering;
21 use core::default::Default;
23 use core::hash::{Hash, Hasher};
24 #[cfg(stage0)] use core::hash::Writer;
25 use core::iter::{Enumerate, FilterMap, Map, FromIterator, IntoIterator};
27 use core::mem::replace;
28 use core::ops::{Index, IndexMut};
33 /// A map optimized for small integer keys.
38 /// use std::collections::VecMap;
40 /// let mut months = VecMap::new();
41 /// months.insert(1, "Jan");
42 /// months.insert(2, "Feb");
43 /// months.insert(3, "Mar");
45 /// if !months.contains_key(&12) {
46 /// println!("The end is near!");
49 /// assert_eq!(months.get(&1), Some(&"Jan"));
51 /// match months.get_mut(&3) {
52 /// Some(value) => *value = "Venus",
56 /// assert_eq!(months.get(&3), Some(&"Venus"));
58 /// // Print out all months
59 /// for (key, value) in months.iter() {
60 /// println!("month {} is {}", key, value);
64 /// assert!(months.is_empty());
66 pub struct VecMap<V> {
70 /// A view into a single entry in a map, which may either be vacant or occupied.
71 #[unstable(feature = "collections",
72 reason = "precise API still under development")]
73 pub enum Entry<'a, V:'a> {
75 Vacant(VacantEntry<'a, V>),
77 Occupied(OccupiedEntry<'a, V>),
81 #[unstable(feature = "collections",
82 reason = "precise API still under development")]
83 pub struct VacantEntry<'a, V:'a> {
84 map: &'a mut VecMap<V>,
88 /// An occupied Entry.
89 #[unstable(feature = "collections",
90 reason = "precise API still under development")]
91 pub struct OccupiedEntry<'a, V:'a> {
92 map: &'a mut VecMap<V>,
96 #[stable(feature = "rust1", since = "1.0.0")]
97 impl<V> Default for VecMap<V> {
98 #[stable(feature = "rust1", since = "1.0.0")]
100 fn default() -> VecMap<V> { VecMap::new() }
103 #[stable(feature = "rust1", since = "1.0.0")]
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);
117 impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> {
118 fn hash(&self, state: &mut S) {
119 // In order to not traverse the `VecMap` twice, count the elements
121 let mut count: usize = 0;
129 #[stable(feature = "rust1", since = "1.0.0")]
131 impl<V: Hash> Hash for VecMap<V> {
132 fn hash<H: Hasher>(&self, state: &mut H) {
133 // In order to not traverse the `VecMap` twice, count the elements
135 let mut count: usize = 0;
145 /// Creates an empty `VecMap`.
150 /// use std::collections::VecMap;
151 /// let mut map: VecMap<&str> = VecMap::new();
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
156 /// Creates an empty `VecMap` with space for at least `capacity`
157 /// elements before resizing.
162 /// use std::collections::VecMap;
163 /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub fn with_capacity(capacity: usize) -> VecMap<V> {
167 VecMap { v: Vec::with_capacity(capacity) }
170 /// Returns the number of elements the `VecMap` can hold without
176 /// use std::collections::VecMap;
177 /// let map: VecMap<String> = VecMap::with_capacity(10);
178 /// assert!(map.capacity() >= 10);
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn capacity(&self) -> usize {
186 /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
187 /// In the case of `VecMap` this means reallocations will not occur as long
188 /// as all inserted keys are less than `len`.
190 /// The collection may reserve more space to avoid frequent reallocations.
195 /// use std::collections::VecMap;
196 /// let mut map: VecMap<&str> = VecMap::new();
197 /// map.reserve_len(10);
198 /// assert!(map.capacity() >= 10);
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn reserve_len(&mut self, len: usize) {
202 let cur_len = self.v.len();
204 self.v.reserve(len - cur_len);
208 /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
209 /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
210 /// keys are less than `len`.
212 /// Note that the allocator may give the collection more space than it requests.
213 /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer
214 /// `reserve_len` if future insertions are expected.
219 /// use std::collections::VecMap;
220 /// let mut map: VecMap<&str> = VecMap::new();
221 /// map.reserve_len_exact(10);
222 /// assert!(map.capacity() >= 10);
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn reserve_len_exact(&mut self, len: usize) {
226 let cur_len = self.v.len();
228 self.v.reserve_exact(len - cur_len);
232 /// Returns an iterator visiting all keys in ascending order of the keys.
233 /// The iterator's element type is `usize`.
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn keys<'r>(&'r self) -> Keys<'r, V> {
236 fn first<A, B>((a, _): (A, B)) -> A { a }
237 let first: fn((usize, &'r V)) -> usize = first; // coerce to fn pointer
239 Keys { iter: self.iter().map(first) }
242 /// Returns an iterator visiting all values in ascending order of the keys.
243 /// The iterator's element type is `&'r V`.
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn values<'r>(&'r self) -> Values<'r, V> {
246 fn second<A, B>((_, b): (A, B)) -> B { b }
247 let second: fn((usize, &'r V)) -> &'r V = second; // coerce to fn pointer
249 Values { iter: self.iter().map(second) }
252 /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
253 /// The iterator's element type is `(usize, &'r V)`.
258 /// use std::collections::VecMap;
260 /// let mut map = VecMap::new();
261 /// map.insert(1, "a");
262 /// map.insert(3, "c");
263 /// map.insert(2, "b");
265 /// // Print `1: a` then `2: b` then `3: c`
266 /// for (key, value) in map.iter() {
267 /// println!("{}: {}", key, value);
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn iter<'r>(&'r self) -> Iter<'r, V> {
279 /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
280 /// with mutable references to the values.
281 /// The iterator's element type is `(usize, &'r mut V)`.
286 /// use std::collections::VecMap;
288 /// let mut map = VecMap::new();
289 /// map.insert(1, "a");
290 /// map.insert(2, "b");
291 /// map.insert(3, "c");
293 /// for (key, value) in map.iter_mut() {
297 /// for (key, value) in map.iter() {
298 /// assert_eq!(value, &"x");
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
306 iter: self.v.iter_mut()
310 /// Returns an iterator visiting all key-value pairs in ascending order of
311 /// the keys, consuming the original `VecMap`.
312 /// The iterator's element type is `(usize, &'r V)`.
317 /// use std::collections::VecMap;
319 /// let mut map = VecMap::new();
320 /// map.insert(1, "a");
321 /// map.insert(3, "c");
322 /// map.insert(2, "b");
324 /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
326 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub fn into_iter(self) -> IntoIter<V> {
330 fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
333 let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
335 IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
338 /// Returns an iterator visiting all key-value pairs in ascending order of
339 /// the keys, emptying (but not consuming) the original `VecMap`.
340 /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
345 /// use std::collections::VecMap;
347 /// let mut map = VecMap::new();
348 /// map.insert(1, "a");
349 /// map.insert(3, "c");
350 /// map.insert(2, "b");
352 /// let vec: Vec<(usize, &str)> = map.drain().collect();
354 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
356 #[unstable(feature = "collections",
357 reason = "matches collection reform specification, waiting for dust to settle")]
358 pub fn drain<'a>(&'a mut self) -> Drain<'a, V> {
359 fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
362 let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
364 Drain { iter: self.v.drain().enumerate().filter_map(filter) }
367 /// Return the number of elements in the map.
372 /// use std::collections::VecMap;
374 /// let mut a = VecMap::new();
375 /// assert_eq!(a.len(), 0);
376 /// a.insert(1, "a");
377 /// assert_eq!(a.len(), 1);
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn len(&self) -> usize {
381 self.v.iter().filter(|elt| elt.is_some()).count()
384 /// Return true if the map contains no elements.
389 /// use std::collections::VecMap;
391 /// let mut a = VecMap::new();
392 /// assert!(a.is_empty());
393 /// a.insert(1, "a");
394 /// assert!(!a.is_empty());
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn is_empty(&self) -> bool {
398 self.v.iter().all(|elt| elt.is_none())
401 /// Clears the map, removing all key-value pairs.
406 /// use std::collections::VecMap;
408 /// let mut a = VecMap::new();
409 /// a.insert(1, "a");
411 /// assert!(a.is_empty());
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn clear(&mut self) { self.v.clear() }
416 /// Returns a reference to the value corresponding to the key.
421 /// use std::collections::VecMap;
423 /// let mut map = VecMap::new();
424 /// map.insert(1, "a");
425 /// assert_eq!(map.get(&1), Some(&"a"));
426 /// assert_eq!(map.get(&2), None);
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn get(&self, key: &usize) -> Option<&V> {
430 if *key < self.v.len() {
432 Some(ref value) => Some(value),
440 /// Returns true if the map contains a value for the specified key.
445 /// use std::collections::VecMap;
447 /// let mut map = VecMap::new();
448 /// map.insert(1, "a");
449 /// assert_eq!(map.contains_key(&1), true);
450 /// assert_eq!(map.contains_key(&2), false);
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn contains_key(&self, key: &usize) -> bool {
455 self.get(key).is_some()
458 /// Returns a mutable reference to the value corresponding to the key.
463 /// use std::collections::VecMap;
465 /// let mut map = VecMap::new();
466 /// map.insert(1, "a");
467 /// match map.get_mut(&1) {
468 /// Some(x) => *x = "b",
471 /// assert_eq!(map[1], "b");
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn get_mut(&mut self, key: &usize) -> Option<&mut V> {
475 if *key < self.v.len() {
476 match *(&mut self.v[*key]) {
477 Some(ref mut value) => Some(value),
485 /// Inserts a key-value pair from the map. If the key already had a value
486 /// present in the map, that value is returned. Otherwise, `None` is returned.
491 /// use std::collections::VecMap;
493 /// let mut map = VecMap::new();
494 /// assert_eq!(map.insert(37, "a"), None);
495 /// assert_eq!(map.is_empty(), false);
497 /// map.insert(37, "b");
498 /// assert_eq!(map.insert(37, "c"), Some("b"));
499 /// assert_eq!(map[37], "c");
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
503 let len = self.v.len();
505 self.v.extend((0..key - len + 1).map(|_| None));
507 replace(&mut self.v[key], Some(value))
510 /// Removes a key from the map, returning the value at the key if the key
511 /// was previously in the map.
516 /// use std::collections::VecMap;
518 /// let mut map = VecMap::new();
519 /// map.insert(1, "a");
520 /// assert_eq!(map.remove(&1), Some("a"));
521 /// assert_eq!(map.remove(&1), None);
523 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn remove(&mut self, key: &usize) -> Option<V> {
525 if *key >= self.v.len() {
528 let result = &mut self.v[*key];
532 /// Gets the given key's corresponding entry in the map for in-place manipulation.
537 /// use std::collections::VecMap;
538 /// use std::collections::vec_map::Entry;
540 /// let mut count: VecMap<u32> = VecMap::new();
542 /// // count the number of occurrences of numbers in the vec
543 /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4].iter() {
544 /// match count.entry(*x) {
545 /// Entry::Vacant(view) => {
548 /// Entry::Occupied(mut view) => {
549 /// let v = view.get_mut();
555 /// assert_eq!(count[1], 3);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn entry(&mut self, key: usize) -> Entry<V> {
559 // FIXME(Gankro): this is basically the dumbest implementation of
560 // entry possible, because weird non-lexical borrows issues make it
561 // completely insane to do any other way. That said, Entry is a border-line
562 // useless construct on VecMap, so it's hardly a big loss.
563 if self.contains_key(&key) {
564 Occupied(OccupiedEntry {
578 impl<'a, V> Entry<'a, V> {
579 #[unstable(feature = "collections",
580 reason = "matches collection reform v2 specification, waiting for dust to settle")]
581 /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
582 pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
584 Occupied(entry) => Ok(entry.into_mut()),
585 Vacant(entry) => Err(entry),
590 impl<'a, V> VacantEntry<'a, V> {
591 /// Sets the value of the entry with the VacantEntry's key,
592 /// and returns a mutable reference to it.
593 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn insert(self, value: V) -> &'a mut V {
595 let index = self.index;
596 self.map.insert(index, value);
601 impl<'a, V> OccupiedEntry<'a, V> {
602 /// Gets a reference to the value in the entry.
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn get(&self) -> &V {
605 let index = self.index;
609 /// Gets a mutable reference to the value in the entry.
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn get_mut(&mut self) -> &mut V {
612 let index = self.index;
616 /// Converts the entry into a mutable reference to its value.
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn into_mut(self) -> &'a mut V {
619 let index = self.index;
623 /// Sets the value of the entry with the OccupiedEntry's key,
624 /// and returns the entry's old value.
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn insert(&mut self, value: V) -> V {
627 let index = self.index;
628 self.map.insert(index, value).unwrap()
631 /// Takes the value of the entry out of the map, and returns it.
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn remove(self) -> V {
634 let index = self.index;
635 self.map.remove(&index).unwrap()
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<V: PartialEq> PartialEq for VecMap<V> {
641 fn eq(&self, other: &VecMap<V>) -> bool {
642 iter::order::eq(self.iter(), other.iter())
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl<V: Eq> Eq for VecMap<V> {}
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<V: PartialOrd> PartialOrd for VecMap<V> {
652 fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
653 iter::order::partial_cmp(self.iter(), other.iter())
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl<V: Ord> Ord for VecMap<V> {
660 fn cmp(&self, other: &VecMap<V>) -> Ordering {
661 iter::order::cmp(self.iter(), other.iter())
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668 try!(write!(f, "VecMap {{"));
670 for (i, (k, v)) in self.iter().enumerate() {
671 if i != 0 { try!(write!(f, ", ")); }
672 try!(write!(f, "{}: {:?}", k, *v));
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<V> FromIterator<(usize, V)> for VecMap<V> {
681 fn from_iter<I: IntoIterator<Item=(usize, V)>>(iter: I) -> VecMap<V> {
682 let mut map = VecMap::new();
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl<T> IntoIterator for VecMap<T> {
690 type Item = (usize, T);
691 type IntoIter = IntoIter<T>;
693 fn into_iter(self) -> IntoIter<T> {
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<'a, T> IntoIterator for &'a VecMap<T> {
700 type Item = (usize, &'a T);
701 type IntoIter = Iter<'a, T>;
703 fn into_iter(self) -> Iter<'a, T> {
708 #[stable(feature = "rust1", since = "1.0.0")]
709 impl<'a, T> IntoIterator for &'a mut VecMap<T> {
710 type Item = (usize, &'a mut T);
711 type IntoIter = IterMut<'a, T>;
713 fn into_iter(mut self) -> IterMut<'a, T> {
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<V> Extend<(usize, V)> for VecMap<V> {
720 fn extend<I: IntoIterator<Item=(usize, V)>>(&mut self, iter: I) {
727 impl<V> Index<usize> for VecMap<V> {
731 fn index<'a>(&'a self, i: &usize) -> &'a V {
732 self.get(i).expect("key not present")
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<V> IndexMut<usize> for VecMap<V> {
739 fn index_mut<'a>(&'a mut self, i: &usize) -> &'a mut V {
740 self.get_mut(i).expect("key not present")
744 macro_rules! iterator {
745 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
746 #[stable(feature = "rust1", since = "1.0.0")]
747 impl<'a, V> Iterator for $name<'a, V> {
751 fn next(&mut self) -> Option<$elem> {
752 while self.front < self.back {
753 match self.iter.next() {
755 match elem$(. $getter ())+ {
757 let index = self.front;
759 return Some((index, x));
772 fn size_hint(&self) -> (usize, Option<usize>) {
773 (0, Some(self.back - self.front))
779 macro_rules! double_ended_iterator {
780 (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<'a, V> DoubleEndedIterator for $name<'a, V> {
784 fn next_back(&mut self) -> Option<$elem> {
785 while self.front < self.back {
786 match self.iter.next_back() {
788 match elem$(. $getter ())+ {
791 return Some((self.back, x));
806 /// An iterator over the key-value pairs of a map.
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub struct Iter<'a, V:'a> {
811 iter: slice::Iter<'a, Option<V>>
814 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
815 impl<'a, V> Clone for Iter<'a, V> {
816 fn clone(&self) -> Iter<'a, V> {
820 iter: self.iter.clone()
825 iterator! { impl Iter -> (usize, &'a V), as_ref }
826 double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
828 /// An iterator over the key-value pairs of a map, with the
829 /// values being mutable.
830 #[stable(feature = "rust1", since = "1.0.0")]
831 pub struct IterMut<'a, V:'a> {
834 iter: slice::IterMut<'a, Option<V>>
837 iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
838 double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
840 /// An iterator over the keys of a map.
841 #[stable(feature = "rust1", since = "1.0.0")]
842 pub struct Keys<'a, V: 'a> {
843 iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> usize>
846 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
847 impl<'a, V> Clone for Keys<'a, V> {
848 fn clone(&self) -> Keys<'a, V> {
850 iter: self.iter.clone()
855 /// An iterator over the values of a map.
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub struct Values<'a, V: 'a> {
858 iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> &'a V>
861 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
862 impl<'a, V> Clone for Values<'a, V> {
863 fn clone(&self) -> Values<'a, V> {
865 iter: self.iter.clone()
870 /// A consuming iterator over the key-value pairs of a map.
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub struct IntoIter<V> {
874 Enumerate<vec::IntoIter<Option<V>>>,
875 fn((usize, Option<V>)) -> Option<(usize, V)>>
878 #[unstable(feature = "collections")]
879 pub struct Drain<'a, V:'a> {
881 Enumerate<vec::Drain<'a, Option<V>>>,
882 fn((usize, Option<V>)) -> Option<(usize, V)>>
885 #[unstable(feature = "collections")]
886 impl<'a, V> Iterator for Drain<'a, V> {
887 type Item = (usize, V);
889 fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
890 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
893 #[unstable(feature = "collections")]
894 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
895 fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a, V> Iterator for Keys<'a, V> {
902 fn next(&mut self) -> Option<usize> { self.iter.next() }
903 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
907 fn next_back(&mut self) -> Option<usize> { self.iter.next_back() }
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl<'a, V> Iterator for Values<'a, V> {
914 fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
915 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
919 fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<V> Iterator for IntoIter<V> {
924 type Item = (usize, V);
926 fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
927 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl<V> DoubleEndedIterator for IntoIter<V> {
931 fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
937 use core::hash::{hash, SipHasher};
940 use super::Entry::{Occupied, Vacant};
944 let mut m = VecMap::new();
945 assert!(m.insert(1, 12).is_none());
946 assert!(m.insert(2, 8).is_none());
947 assert!(m.insert(5, 14).is_none());
949 match m.get_mut(&5) {
950 None => panic!(), Some(x) => *x = new
952 assert_eq!(m.get(&5), Some(&new));
957 let mut map = VecMap::new();
958 assert_eq!(map.len(), 0);
959 assert!(map.is_empty());
960 assert!(map.insert(5, 20).is_none());
961 assert_eq!(map.len(), 1);
962 assert!(!map.is_empty());
963 assert!(map.insert(11, 12).is_none());
964 assert_eq!(map.len(), 2);
965 assert!(!map.is_empty());
966 assert!(map.insert(14, 22).is_none());
967 assert_eq!(map.len(), 3);
968 assert!(!map.is_empty());
973 let mut map = VecMap::new();
974 assert!(map.insert(5, 20).is_none());
975 assert!(map.insert(11, 12).is_none());
976 assert!(map.insert(14, 22).is_none());
978 assert!(map.is_empty());
979 assert!(map.get(&5).is_none());
980 assert!(map.get(&11).is_none());
981 assert!(map.get(&14).is_none());
986 let mut m = VecMap::new();
987 assert_eq!(m.insert(1, 2), None);
988 assert_eq!(m.insert(1, 3), Some(2));
989 assert_eq!(m.insert(1, 4), Some(3));
994 let mut m = VecMap::new();
996 assert_eq!(m.remove(&1), Some(2));
997 assert_eq!(m.remove(&1), None);
1002 let mut map = VecMap::new();
1006 let keys: Vec<_> = map.keys().collect();
1007 assert_eq!(keys.len(), 3);
1008 assert!(keys.contains(&1));
1009 assert!(keys.contains(&2));
1010 assert!(keys.contains(&3));
1015 let mut map = VecMap::new();
1019 let values: Vec<_> = map.values().cloned().collect();
1020 assert_eq!(values.len(), 3);
1021 assert!(values.contains(&'a'));
1022 assert!(values.contains(&'b'));
1023 assert!(values.contains(&'c'));
1027 fn test_iterator() {
1028 let mut m = VecMap::new();
1030 assert!(m.insert(0, 1).is_none());
1031 assert!(m.insert(1, 2).is_none());
1032 assert!(m.insert(3, 5).is_none());
1033 assert!(m.insert(6, 10).is_none());
1034 assert!(m.insert(10, 11).is_none());
1036 let mut it = m.iter();
1037 assert_eq!(it.size_hint(), (0, Some(11)));
1038 assert_eq!(it.next().unwrap(), (0, &1));
1039 assert_eq!(it.size_hint(), (0, Some(10)));
1040 assert_eq!(it.next().unwrap(), (1, &2));
1041 assert_eq!(it.size_hint(), (0, Some(9)));
1042 assert_eq!(it.next().unwrap(), (3, &5));
1043 assert_eq!(it.size_hint(), (0, Some(7)));
1044 assert_eq!(it.next().unwrap(), (6, &10));
1045 assert_eq!(it.size_hint(), (0, Some(4)));
1046 assert_eq!(it.next().unwrap(), (10, &11));
1047 assert_eq!(it.size_hint(), (0, Some(0)));
1048 assert!(it.next().is_none());
1052 fn test_iterator_size_hints() {
1053 let mut m = VecMap::new();
1055 assert!(m.insert(0, 1).is_none());
1056 assert!(m.insert(1, 2).is_none());
1057 assert!(m.insert(3, 5).is_none());
1058 assert!(m.insert(6, 10).is_none());
1059 assert!(m.insert(10, 11).is_none());
1061 assert_eq!(m.iter().size_hint(), (0, Some(11)));
1062 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
1063 assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
1064 assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
1068 fn test_mut_iterator() {
1069 let mut m = VecMap::new();
1071 assert!(m.insert(0, 1).is_none());
1072 assert!(m.insert(1, 2).is_none());
1073 assert!(m.insert(3, 5).is_none());
1074 assert!(m.insert(6, 10).is_none());
1075 assert!(m.insert(10, 11).is_none());
1077 for (k, v) in &mut m {
1081 let mut it = m.iter();
1082 assert_eq!(it.next().unwrap(), (0, &1));
1083 assert_eq!(it.next().unwrap(), (1, &3));
1084 assert_eq!(it.next().unwrap(), (3, &8));
1085 assert_eq!(it.next().unwrap(), (6, &16));
1086 assert_eq!(it.next().unwrap(), (10, &21));
1087 assert!(it.next().is_none());
1091 fn test_rev_iterator() {
1092 let mut m = VecMap::new();
1094 assert!(m.insert(0, 1).is_none());
1095 assert!(m.insert(1, 2).is_none());
1096 assert!(m.insert(3, 5).is_none());
1097 assert!(m.insert(6, 10).is_none());
1098 assert!(m.insert(10, 11).is_none());
1100 let mut it = m.iter().rev();
1101 assert_eq!(it.next().unwrap(), (10, &11));
1102 assert_eq!(it.next().unwrap(), (6, &10));
1103 assert_eq!(it.next().unwrap(), (3, &5));
1104 assert_eq!(it.next().unwrap(), (1, &2));
1105 assert_eq!(it.next().unwrap(), (0, &1));
1106 assert!(it.next().is_none());
1110 fn test_mut_rev_iterator() {
1111 let mut m = VecMap::new();
1113 assert!(m.insert(0, 1).is_none());
1114 assert!(m.insert(1, 2).is_none());
1115 assert!(m.insert(3, 5).is_none());
1116 assert!(m.insert(6, 10).is_none());
1117 assert!(m.insert(10, 11).is_none());
1119 for (k, v) in m.iter_mut().rev() {
1123 let mut it = m.iter();
1124 assert_eq!(it.next().unwrap(), (0, &1));
1125 assert_eq!(it.next().unwrap(), (1, &3));
1126 assert_eq!(it.next().unwrap(), (3, &8));
1127 assert_eq!(it.next().unwrap(), (6, &16));
1128 assert_eq!(it.next().unwrap(), (10, &21));
1129 assert!(it.next().is_none());
1133 fn test_move_iter() {
1134 let mut m = VecMap::new();
1136 let mut called = false;
1141 assert_eq!(v, box 2);
1147 fn test_drain_iterator() {
1148 let mut map = VecMap::new();
1153 let vec: Vec<_> = map.drain().collect();
1155 assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
1156 assert_eq!(map.len(), 0);
1161 let mut map = VecMap::new();
1162 let empty = VecMap::<i32>::new();
1167 let map_str = format!("{:?}", map);
1168 assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1169 assert_eq!(format!("{:?}", empty), "VecMap {}");
1174 let mut a = VecMap::new();
1180 assert!(a.clone() == a);
1185 let mut a = VecMap::new();
1186 let mut b = VecMap::new();
1189 assert!(a.insert(0, 5).is_none());
1191 assert!(b.insert(0, 4).is_none());
1193 assert!(a.insert(5, 19).is_none());
1195 assert!(!b.insert(0, 5).is_none());
1197 assert!(b.insert(5, 19).is_none());
1201 b = VecMap::with_capacity(1);
1207 let mut a = VecMap::new();
1208 let mut b = VecMap::new();
1210 assert!(!(a < b) && !(b < a));
1211 assert!(b.insert(2, 5).is_none());
1213 assert!(a.insert(2, 7).is_none());
1214 assert!(!(a < b) && b < a);
1215 assert!(b.insert(1, 0).is_none());
1217 assert!(a.insert(0, 6).is_none());
1219 assert!(a.insert(6, 2).is_none());
1220 assert!(a < b && !(b < a));
1225 let mut a = VecMap::new();
1226 let mut b = VecMap::new();
1228 assert!(a <= b && a >= b);
1229 assert!(a.insert(1, 1).is_none());
1230 assert!(a > b && a >= b);
1231 assert!(b < a && b <= a);
1232 assert!(b.insert(2, 2).is_none());
1233 assert!(b > a && b >= a);
1234 assert!(a < b && a <= b);
1239 let mut x = VecMap::new();
1240 let mut y = VecMap::new();
1242 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1251 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1253 x.insert(1000, 'd');
1256 assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1260 fn test_from_iter() {
1261 let xs = vec![(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1263 let map: VecMap<_> = xs.iter().cloned().collect();
1265 for &(k, v) in &xs {
1266 assert_eq!(map.get(&k), Some(&v));
1272 let mut map = VecMap::new();
1278 assert_eq!(map[3], 4);
1283 fn test_index_nonexistent() {
1284 let mut map = VecMap::new();
1295 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1297 let mut map: VecMap<_> = xs.iter().cloned().collect();
1299 // Existing key (insert)
1300 match map.entry(1) {
1301 Vacant(_) => unreachable!(),
1302 Occupied(mut view) => {
1303 assert_eq!(view.get(), &10);
1304 assert_eq!(view.insert(100), 10);
1307 assert_eq!(map.get(&1).unwrap(), &100);
1308 assert_eq!(map.len(), 6);
1311 // Existing key (update)
1312 match map.entry(2) {
1313 Vacant(_) => unreachable!(),
1314 Occupied(mut view) => {
1315 let v = view.get_mut();
1319 assert_eq!(map.get(&2).unwrap(), &200);
1320 assert_eq!(map.len(), 6);
1322 // Existing key (take)
1323 match map.entry(3) {
1324 Vacant(_) => unreachable!(),
1326 assert_eq!(view.remove(), 30);
1329 assert_eq!(map.get(&3), None);
1330 assert_eq!(map.len(), 5);
1333 // Inexistent key (insert)
1334 match map.entry(10) {
1335 Occupied(_) => unreachable!(),
1337 assert_eq!(*view.insert(1000), 1000);
1340 assert_eq!(map.get(&10).unwrap(), &1000);
1341 assert_eq!(map.len(), 6);
1349 map_insert_rand_bench!{insert_rand_100, 100, VecMap}
1350 map_insert_rand_bench!{insert_rand_10_000, 10_000, VecMap}
1352 map_insert_seq_bench!{insert_seq_100, 100, VecMap}
1353 map_insert_seq_bench!{insert_seq_10_000, 10_000, VecMap}
1355 map_find_rand_bench!{find_rand_100, 100, VecMap}
1356 map_find_rand_bench!{find_rand_10_000, 10_000, VecMap}
1358 map_find_seq_bench!{find_seq_100, 100, VecMap}
1359 map_find_seq_bench!{find_seq_10_000, 10_000, VecMap}