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_doc)]
18 use core::default::Default;
21 use core::iter::{Enumerate, FilterMap};
22 use core::mem::replace;
24 use {Mutable, Map, MutableMap, MutableSeq};
30 /// A map optimized for small integer keys.
35 /// use std::collections::SmallIntMap;
37 /// let mut months = SmallIntMap::new();
38 /// months.insert(1, "Jan");
39 /// months.insert(2, "Feb");
40 /// months.insert(3, "Mar");
42 /// if !months.contains_key(&12) {
43 /// println!("The end is near!");
46 /// assert_eq!(months.find(&1), Some(&"Jan"));
48 /// match months.find_mut(&3) {
49 /// Some(value) => *value = "Venus",
53 /// assert_eq!(months.find(&3), Some(&"Venus"));
55 /// // Print out all months
56 /// for (key, value) in months.iter() {
57 /// println!("month {} is {}", key, value);
61 /// assert!(months.is_empty());
63 #[deriving(PartialEq, Eq)]
64 pub struct SmallIntMap<T> {
68 impl<V> Collection for SmallIntMap<V> {
69 /// Returns the number of elements in the map.
70 fn len(&self) -> uint {
71 self.v.iter().filter(|elt| elt.is_some()).count()
74 /// Returns`true` if there are no elements in the map.
75 fn is_empty(&self) -> bool {
76 self.v.iter().all(|elt| elt.is_none())
80 impl<V> Mutable for SmallIntMap<V> {
81 /// Clears the map, removing all key-value pairs.
82 fn clear(&mut self) { self.v.clear() }
85 impl<V> Map<uint, V> for SmallIntMap<V> {
86 /// Returns a reference to the value corresponding to the key.
87 fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
88 if *key < self.v.len() {
90 Some(ref value) => Some(value),
99 impl<V> MutableMap<uint, V> for SmallIntMap<V> {
100 /// Returns a mutable reference to the value corresponding to the key.
101 fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
102 if *key < self.v.len() {
103 match *self.v.get_mut(*key) {
104 Some(ref mut value) => Some(value),
112 /// Inserts a key-value pair into the map. An existing value for a
113 /// key is replaced by the new value. Returns `true` if the key did
114 /// not already exist in the map.
115 fn insert(&mut self, key: uint, value: V) -> bool {
116 let exists = self.contains_key(&key);
117 let len = self.v.len();
119 self.v.grow_fn(key - len + 1, |_| None);
121 *self.v.get_mut(key) = Some(value);
125 /// Removes a key-value pair from the map. Returns `true` if the key
126 /// was present in the map.
127 fn remove(&mut self, key: &uint) -> bool {
128 self.pop(key).is_some()
131 /// Inserts a key-value pair into the map. If the key already had a value
132 /// present in the map, that value is returned. Otherwise `None` is returned.
133 fn swap(&mut self, key: uint, value: V) -> Option<V> {
134 match self.find_mut(&key) {
135 Some(loc) => { return Some(replace(loc, value)); }
138 self.insert(key, value);
142 /// Removes a key from the map, returning the value at the key if the key
143 /// was previously in the map.
144 fn pop(&mut self, key: &uint) -> Option<V> {
145 if *key >= self.v.len() {
148 self.v.get_mut(*key).take()
152 impl<V> Default for SmallIntMap<V> {
154 fn default() -> SmallIntMap<V> { SmallIntMap::new() }
157 impl<V:Clone> Clone for SmallIntMap<V> {
159 fn clone(&self) -> SmallIntMap<V> {
160 SmallIntMap { v: self.v.clone() }
164 fn clone_from(&mut self, source: &SmallIntMap<V>) {
165 self.v.reserve(source.v.len());
166 for (i, w) in self.v.mut_iter().enumerate() {
167 *w = source.v[i].clone();
172 impl <S: hash::Writer, T: Hash<S>> Hash<S> for SmallIntMap<T> {
173 fn hash(&self, state: &mut S) {
178 impl<V> SmallIntMap<V> {
179 /// Creates an empty `SmallIntMap`.
184 /// use std::collections::SmallIntMap;
185 /// let mut map: SmallIntMap<&str> = SmallIntMap::new();
187 pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
189 /// Creates an empty `SmallIntMap` with space for at least `capacity`
190 /// elements before resizing.
195 /// use std::collections::SmallIntMap;
196 /// let mut map: SmallIntMap<&str> = SmallIntMap::with_capacity(10);
198 pub fn with_capacity(capacity: uint) -> SmallIntMap<V> {
199 SmallIntMap { v: Vec::with_capacity(capacity) }
202 /// Retrieves a value for the given key.
203 /// See [`find`](../trait.Map.html#tymethod.find) for a non-failing alternative.
207 /// Fails if the key is not present.
212 /// #![allow(deprecated)]
214 /// use std::collections::SmallIntMap;
216 /// let mut map = SmallIntMap::new();
217 /// map.insert(1, "a");
218 /// assert_eq!(map.get(&1), &"a");
220 #[deprecated = "prefer using indexing, e.g., map[0]"]
221 pub fn get<'a>(&'a self, key: &uint) -> &'a V {
222 self.find(key).expect("key not present")
225 /// Returns an iterator visiting all keys in ascending order by the keys.
226 /// The iterator's element type is `uint`.
227 pub fn keys<'r>(&'r self) -> Keys<'r, V> {
228 self.iter().map(|(k, _v)| k)
231 /// Returns an iterator visiting all values in ascending order by the keys.
232 /// The iterator's element type is `&'r V`.
233 pub fn values<'r>(&'r self) -> Values<'r, V> {
234 self.iter().map(|(_k, v)| v)
237 /// Returns an iterator visiting all key-value pairs in ascending order by the keys.
238 /// The iterator's element type is `(uint, &'r V)`.
243 /// use std::collections::SmallIntMap;
245 /// let mut map = SmallIntMap::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 pub fn iter<'r>(&'r self) -> Entries<'r, V> {
263 /// Returns an iterator visiting all key-value pairs in ascending order by the keys,
264 /// with mutable references to the values.
265 /// The iterator's element type is `(uint, &'r mut V)`.
270 /// use std::collections::SmallIntMap;
272 /// let mut map = SmallIntMap::new();
273 /// map.insert(1, "a");
274 /// map.insert(2, "b");
275 /// map.insert(3, "c");
277 /// for (key, value) in map.mut_iter() {
281 /// for (key, value) in map.iter() {
282 /// assert_eq!(value, &"x");
285 pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
289 iter: self.v.mut_iter()
293 /// Returns an iterator visiting all key-value pairs in ascending order by
294 /// the keys, emptying (but not consuming) the original `SmallIntMap`.
295 /// The iterator's element type is `(uint, &'r V)`.
300 /// use std::collections::SmallIntMap;
302 /// let mut map = SmallIntMap::new();
303 /// map.insert(1, "a");
304 /// map.insert(3, "c");
305 /// map.insert(2, "b");
307 /// // Not possible with .iter()
308 /// let vec: Vec<(uint, &str)> = map.move_iter().collect();
310 /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
312 pub fn move_iter(&mut self)
313 -> FilterMap<(uint, Option<V>), (uint, V),
314 Enumerate<vec::MoveItems<Option<V>>>>
316 let values = replace(&mut self.v, vec!());
317 values.move_iter().enumerate().filter_map(|(i, v)| {
323 impl<V:Clone> SmallIntMap<V> {
324 /// Updates a value in the map. If the key already exists in the map,
325 /// modifies the value with `ff` taking `oldval, newval`.
326 /// Otherwise, sets the value to `newval`.
327 /// Returasn `true` if the key did not already exist in the map.
332 /// use std::collections::SmallIntMap;
334 /// let mut map = SmallIntMap::new();
336 /// // Key does not exist, will do a simple insert
337 /// assert!(map.update(1, vec![1i, 2], |old, new| old.append(new.as_slice())));
338 /// assert_eq!(map[1], vec![1i, 2]);
340 /// // Key exists, update the value
341 /// assert!(!map.update(1, vec![3i, 4], |old, new| old.append(new.as_slice())));
342 /// assert_eq!(map[1], vec![1i, 2, 3, 4]);
344 pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
345 self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
348 /// Updates a value in the map. If the key already exists in the map,
349 /// modifies the value with `ff` taking `key, oldval, newval`.
350 /// Otherwise, sets the value to `newval`.
351 /// Returns `true` if the key did not already exist in the map.
356 /// use std::collections::SmallIntMap;
358 /// let mut map = SmallIntMap::new();
360 /// // Key does not exist, will do a simple insert
361 /// assert!(map.update_with_key(7, 10, |key, old, new| (old + new) % key));
362 /// assert_eq!(map[7], 10);
364 /// // Key exists, update the value
365 /// assert!(!map.update_with_key(7, 20, |key, old, new| (old + new) % key));
366 /// assert_eq!(map[7], 2);
368 pub fn update_with_key(&mut self,
371 ff: |uint, V, V| -> V)
373 let new_val = match self.find(&key) {
375 Some(orig) => ff(key, (*orig).clone(), val)
377 self.insert(key, new_val)
381 impl<V: PartialOrd> PartialOrd for SmallIntMap<V> {
383 fn partial_cmp(&self, other: &SmallIntMap<V>) -> Option<Ordering> {
384 iter::order::partial_cmp(self.iter(), other.iter())
388 impl<V: Ord> Ord for SmallIntMap<V> {
390 fn cmp(&self, other: &SmallIntMap<V>) -> Ordering {
391 iter::order::cmp(self.iter(), other.iter())
395 impl<V: fmt::Show> fmt::Show for SmallIntMap<V> {
396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
397 try!(write!(f, "{{"));
399 for (i, (k, v)) in self.iter().enumerate() {
400 if i != 0 { try!(write!(f, ", ")); }
401 try!(write!(f, "{}: {}", k, *v));
408 impl<V> FromIterator<(uint, V)> for SmallIntMap<V> {
409 fn from_iter<Iter: Iterator<(uint, V)>>(iter: Iter) -> SmallIntMap<V> {
410 let mut map = SmallIntMap::new();
416 impl<V> Extendable<(uint, V)> for SmallIntMap<V> {
417 fn extend<Iter: Iterator<(uint, V)>>(&mut self, mut iter: Iter) {
424 impl<V> Index<uint, V> for SmallIntMap<V> {
427 fn index<'a>(&'a self, i: &uint) -> &'a V {
432 // FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
433 /*impl<V> IndexMut<uint, V> for SmallIntMap<V> {
435 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
436 self.find_mut(i).expect("key not present")
440 macro_rules! iterator {
441 (impl $name:ident -> $elem:ty, $getter:ident) => {
442 impl<'a, T> Iterator<$elem> for $name<'a, T> {
444 fn next(&mut self) -> Option<$elem> {
445 while self.front < self.back {
446 match self.iter.next() {
449 let index = self.front;
451 return Some((index, elem. $getter ()));
462 fn size_hint(&self) -> (uint, Option<uint>) {
463 (0, Some(self.back - self.front))
469 macro_rules! double_ended_iterator {
470 (impl $name:ident -> $elem:ty, $getter:ident) => {
471 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
473 fn next_back(&mut self) -> Option<$elem> {
474 while self.front < self.back {
475 match self.iter.next_back() {
479 return Some((self.back, elem. $getter ()));
492 /// Forward iterator over a map.
493 pub struct Entries<'a, T> {
496 iter: slice::Items<'a, Option<T>>
499 iterator!(impl Entries -> (uint, &'a T), get_ref)
500 double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
502 /// Forward iterator over the key-value pairs of a map, with the
503 /// values being mutable.
504 pub struct MutEntries<'a, T> {
507 iter: slice::MutItems<'a, Option<T>>
510 iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
511 double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
513 /// Forward iterator over the keys of a map
514 pub type Keys<'a, T> =
515 iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;
517 /// Forward iterator over the values of a map
518 pub type Values<'a, T> =
519 iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;
527 use {Map, MutableMap, Mutable, MutableSeq};
528 use super::SmallIntMap;
532 let mut m = SmallIntMap::new();
533 assert!(m.insert(1, 12i));
534 assert!(m.insert(2, 8));
535 assert!(m.insert(5, 14));
537 match m.find_mut(&5) {
538 None => fail!(), Some(x) => *x = new
540 assert_eq!(m.find(&5), Some(&new));
545 let mut map = SmallIntMap::new();
546 assert_eq!(map.len(), 0);
547 assert!(map.is_empty());
548 assert!(map.insert(5, 20i));
549 assert_eq!(map.len(), 1);
550 assert!(!map.is_empty());
551 assert!(map.insert(11, 12));
552 assert_eq!(map.len(), 2);
553 assert!(!map.is_empty());
554 assert!(map.insert(14, 22));
555 assert_eq!(map.len(), 3);
556 assert!(!map.is_empty());
561 let mut map = SmallIntMap::new();
562 assert!(map.insert(5, 20i));
563 assert!(map.insert(11, 12));
564 assert!(map.insert(14, 22));
566 assert!(map.is_empty());
567 assert!(map.find(&5).is_none());
568 assert!(map.find(&11).is_none());
569 assert!(map.find(&14).is_none());
573 fn test_insert_with_key() {
574 let mut map = SmallIntMap::new();
576 // given a new key, initialize it with this new count,
577 // given an existing key, add more to its count
578 fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
582 fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
587 map.update(3, 1, add_more_to_count_simple);
588 map.update_with_key(9, 1, add_more_to_count);
589 map.update(3, 7, add_more_to_count_simple);
590 map.update_with_key(5, 3, add_more_to_count);
591 map.update_with_key(3, 2, add_more_to_count);
593 // check the total counts
594 assert_eq!(map.find(&3).unwrap(), &10);
595 assert_eq!(map.find(&5).unwrap(), &3);
596 assert_eq!(map.find(&9).unwrap(), &1);
598 // sadly, no sevens were counted
599 assert!(map.find(&7).is_none());
604 let mut m = SmallIntMap::new();
605 assert_eq!(m.swap(1, 2i), None);
606 assert_eq!(m.swap(1, 3i), Some(2));
607 assert_eq!(m.swap(1, 4i), Some(3));
612 let mut m = SmallIntMap::new();
614 assert_eq!(m.pop(&1), Some(2));
615 assert_eq!(m.pop(&1), None);
620 let mut map = SmallIntMap::new();
624 let keys = map.keys().collect::<Vec<uint>>();
625 assert_eq!(keys.len(), 3);
626 assert!(keys.contains(&1));
627 assert!(keys.contains(&2));
628 assert!(keys.contains(&3));
633 let mut map = SmallIntMap::new();
637 let values = map.values().map(|&v| v).collect::<Vec<char>>();
638 assert_eq!(values.len(), 3);
639 assert!(values.contains(&'a'));
640 assert!(values.contains(&'b'));
641 assert!(values.contains(&'c'));
646 let mut m = SmallIntMap::new();
648 assert!(m.insert(0, 1i));
649 assert!(m.insert(1, 2));
650 assert!(m.insert(3, 5));
651 assert!(m.insert(6, 10));
652 assert!(m.insert(10, 11));
654 let mut it = m.iter();
655 assert_eq!(it.size_hint(), (0, Some(11)));
656 assert_eq!(it.next().unwrap(), (0, &1));
657 assert_eq!(it.size_hint(), (0, Some(10)));
658 assert_eq!(it.next().unwrap(), (1, &2));
659 assert_eq!(it.size_hint(), (0, Some(9)));
660 assert_eq!(it.next().unwrap(), (3, &5));
661 assert_eq!(it.size_hint(), (0, Some(7)));
662 assert_eq!(it.next().unwrap(), (6, &10));
663 assert_eq!(it.size_hint(), (0, Some(4)));
664 assert_eq!(it.next().unwrap(), (10, &11));
665 assert_eq!(it.size_hint(), (0, Some(0)));
666 assert!(it.next().is_none());
670 fn test_iterator_size_hints() {
671 let mut m = SmallIntMap::new();
673 assert!(m.insert(0, 1i));
674 assert!(m.insert(1, 2));
675 assert!(m.insert(3, 5));
676 assert!(m.insert(6, 10));
677 assert!(m.insert(10, 11));
679 assert_eq!(m.iter().size_hint(), (0, Some(11)));
680 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
681 assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
682 assert_eq!(m.mut_iter().rev().size_hint(), (0, Some(11)));
686 fn test_mut_iterator() {
687 let mut m = SmallIntMap::new();
689 assert!(m.insert(0, 1i));
690 assert!(m.insert(1, 2));
691 assert!(m.insert(3, 5));
692 assert!(m.insert(6, 10));
693 assert!(m.insert(10, 11));
695 for (k, v) in m.mut_iter() {
699 let mut it = m.iter();
700 assert_eq!(it.next().unwrap(), (0, &1));
701 assert_eq!(it.next().unwrap(), (1, &3));
702 assert_eq!(it.next().unwrap(), (3, &8));
703 assert_eq!(it.next().unwrap(), (6, &16));
704 assert_eq!(it.next().unwrap(), (10, &21));
705 assert!(it.next().is_none());
709 fn test_rev_iterator() {
710 let mut m = SmallIntMap::new();
712 assert!(m.insert(0, 1i));
713 assert!(m.insert(1, 2));
714 assert!(m.insert(3, 5));
715 assert!(m.insert(6, 10));
716 assert!(m.insert(10, 11));
718 let mut it = m.iter().rev();
719 assert_eq!(it.next().unwrap(), (10, &11));
720 assert_eq!(it.next().unwrap(), (6, &10));
721 assert_eq!(it.next().unwrap(), (3, &5));
722 assert_eq!(it.next().unwrap(), (1, &2));
723 assert_eq!(it.next().unwrap(), (0, &1));
724 assert!(it.next().is_none());
728 fn test_mut_rev_iterator() {
729 let mut m = SmallIntMap::new();
731 assert!(m.insert(0, 1i));
732 assert!(m.insert(1, 2));
733 assert!(m.insert(3, 5));
734 assert!(m.insert(6, 10));
735 assert!(m.insert(10, 11));
737 for (k, v) in m.mut_iter().rev() {
741 let mut it = m.iter();
742 assert_eq!(it.next().unwrap(), (0, &1));
743 assert_eq!(it.next().unwrap(), (1, &3));
744 assert_eq!(it.next().unwrap(), (3, &8));
745 assert_eq!(it.next().unwrap(), (6, &16));
746 assert_eq!(it.next().unwrap(), (10, &21));
747 assert!(it.next().is_none());
751 fn test_move_iter() {
752 let mut m = SmallIntMap::new();
754 let mut called = false;
755 for (k, v) in m.move_iter() {
759 assert_eq!(v, box 2i);
767 let mut map = SmallIntMap::new();
768 let empty = SmallIntMap::<int>::new();
773 let map_str = map.to_string();
774 let map_str = map_str.as_slice();
775 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
776 assert_eq!(format!("{}", empty), "{}".to_string());
781 let mut a = SmallIntMap::new();
787 assert!(a.clone() == a);
792 let mut a = SmallIntMap::new();
793 let mut b = SmallIntMap::new();
796 assert!(a.insert(0, 5i));
798 assert!(b.insert(0, 4i));
800 assert!(a.insert(5, 19));
802 assert!(!b.insert(0, 5));
804 assert!(b.insert(5, 19));
810 let mut a = SmallIntMap::new();
811 let mut b = SmallIntMap::new();
813 assert!(!(a < b) && !(b < a));
814 assert!(b.insert(2u, 5i));
816 assert!(a.insert(2, 7));
817 assert!(!(a < b) && b < a);
818 assert!(b.insert(1, 0));
820 assert!(a.insert(0, 6));
822 assert!(a.insert(6, 2));
823 assert!(a < b && !(b < a));
828 let mut a = SmallIntMap::new();
829 let mut b = SmallIntMap::new();
831 assert!(a <= b && a >= b);
832 assert!(a.insert(1u, 1i));
833 assert!(a > b && a >= b);
834 assert!(b < a && b <= a);
835 assert!(b.insert(2, 2));
836 assert!(b > a && b >= a);
837 assert!(a < b && a <= b);
842 let mut x = SmallIntMap::new();
843 let mut y = SmallIntMap::new();
845 assert!(hash::hash(&x) == hash::hash(&y));
854 assert!(hash::hash(&x) == hash::hash(&y));
858 fn test_from_iter() {
859 let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
861 let map: SmallIntMap<char> = xs.iter().map(|&x| x).collect();
863 for &(k, v) in xs.iter() {
864 assert_eq!(map.find(&k), Some(&v));
870 let mut map: SmallIntMap<int> = SmallIntMap::new();
876 assert_eq!(map[3], 4);
881 fn test_index_nonexistent() {
882 let mut map: SmallIntMap<int> = SmallIntMap::new();
895 use self::test::Bencher;
896 use super::SmallIntMap;
897 use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
901 pub fn insert_rand_100(b: &mut Bencher) {
902 let mut m : SmallIntMap<uint> = SmallIntMap::new();
903 insert_rand_n(100, &mut m, b);
907 pub fn insert_rand_10_000(b: &mut Bencher) {
908 let mut m : SmallIntMap<uint> = SmallIntMap::new();
909 insert_rand_n(10_000, &mut m, b);
914 pub fn insert_seq_100(b: &mut Bencher) {
915 let mut m : SmallIntMap<uint> = SmallIntMap::new();
916 insert_seq_n(100, &mut m, b);
920 pub fn insert_seq_10_000(b: &mut Bencher) {
921 let mut m : SmallIntMap<uint> = SmallIntMap::new();
922 insert_seq_n(10_000, &mut m, b);
927 pub fn find_rand_100(b: &mut Bencher) {
928 let mut m : SmallIntMap<uint> = SmallIntMap::new();
929 find_rand_n(100, &mut m, b);
933 pub fn find_rand_10_000(b: &mut Bencher) {
934 let mut m : SmallIntMap<uint> = SmallIntMap::new();
935 find_rand_n(10_000, &mut m, b);
940 pub fn find_seq_100(b: &mut Bencher) {
941 let mut m : SmallIntMap<uint> = SmallIntMap::new();
942 find_seq_n(100, &mut m, b);
946 pub fn find_seq_10_000(b: &mut Bencher) {
947 let mut m : SmallIntMap<uint> = SmallIntMap::new();
948 find_seq_n(10_000, &mut m, b);