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.
12 * A simple map based on a vector for small integer keys. Space requirements
13 * are O(highest integer key).
16 #![allow(missing_doc)]
18 use std::iter::{Enumerate, FilterMap, Rev};
19 use std::mem::replace;
20 use std::{vec, slice};
23 pub struct SmallIntMap<T> {
27 impl<V> Container for SmallIntMap<V> {
28 /// Return the number of elements in the map
29 fn len(&self) -> uint {
30 self.v.iter().count(|elt| elt.is_some())
33 /// Return true if there are no elements in the map
34 fn is_empty(&self) -> bool {
35 self.v.iter().all(|elt| elt.is_none())
39 impl<V> Mutable for SmallIntMap<V> {
40 /// Clear the map, removing all key-value pairs.
41 fn clear(&mut self) { self.v.clear() }
44 impl<V> Map<uint, V> for SmallIntMap<V> {
45 /// Return a reference to the value corresponding to the key
46 fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
47 if *key < self.v.len() {
48 match *self.v.get(*key) {
49 Some(ref value) => Some(value),
58 impl<V> MutableMap<uint, V> for SmallIntMap<V> {
59 /// Return a mutable reference to the value corresponding to the key
60 fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
61 if *key < self.v.len() {
62 match *self.v.get_mut(*key) {
63 Some(ref mut value) => Some(value),
71 /// Insert a key-value pair into the map. An existing value for a
72 /// key is replaced by the new value. Return true if the key did
73 /// not already exist in the map.
74 fn insert(&mut self, key: uint, value: V) -> bool {
75 let exists = self.contains_key(&key);
76 let len = self.v.len();
78 self.v.grow_fn(key - len + 1, |_| None);
80 *self.v.get_mut(key) = Some(value);
84 /// Remove a key-value pair from the map. Return true if the key
85 /// was present in the map, otherwise false.
86 fn remove(&mut self, key: &uint) -> bool {
87 self.pop(key).is_some()
90 /// Insert a key-value pair from the map. If the key already had a value
91 /// present in the map, that value is returned. Otherwise None is returned.
92 fn swap(&mut self, key: uint, value: V) -> Option<V> {
93 match self.find_mut(&key) {
94 Some(loc) => { return Some(replace(loc, value)); }
97 self.insert(key, value);
101 /// Removes a key from the map, returning the value at the key if the key
102 /// was previously in the map.
103 fn pop(&mut self, key: &uint) -> Option<V> {
104 if *key >= self.v.len() {
107 self.v.get_mut(*key).take()
111 impl<V> SmallIntMap<V> {
112 /// Create an empty SmallIntMap
113 pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
115 /// Create an empty SmallIntMap with capacity `capacity`
116 pub fn with_capacity(capacity: uint) -> SmallIntMap<V> {
117 SmallIntMap { v: Vec::with_capacity(capacity) }
120 pub fn get<'a>(&'a self, key: &uint) -> &'a V {
121 self.find(key).expect("key not present")
124 /// An iterator visiting all key-value pairs in ascending order by the keys.
125 /// Iterator element type is (uint, &'r V)
126 pub fn iter<'r>(&'r self) -> Entries<'r, V> {
134 /// An iterator visiting all key-value pairs in ascending order by the keys,
135 /// with mutable references to the values
136 /// Iterator element type is (uint, &'r mut V)
137 pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
141 iter: self.v.mut_iter()
145 #[deprecated = "replaced by .iter().rev()"]
146 pub fn rev_iter<'r>(&'r self) -> Rev<Entries<'r, V>> {
150 #[deprecated = "replaced by .mut_iter().rev()"]
151 pub fn mut_rev_iter<'r>(&'r mut self) -> Rev<MutEntries<'r, V>> {
152 self.mut_iter().rev()
155 /// Empties the hash map, moving all values into the specified closure
156 pub fn move_iter(&mut self)
157 -> FilterMap<(uint, Option<V>), (uint, V),
158 Enumerate<vec::MoveItems<Option<V>>>>
160 let values = replace(&mut self.v, vec!());
161 values.move_iter().enumerate().filter_map(|(i, v)| {
167 impl<V:Clone> SmallIntMap<V> {
168 pub fn update_with_key(&mut self,
171 ff: |uint, V, V| -> V)
173 let new_val = match self.find(&key) {
175 Some(orig) => ff(key, (*orig).clone(), val)
177 self.insert(key, new_val)
180 pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
181 self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
186 macro_rules! iterator {
187 (impl $name:ident -> $elem:ty, $getter:ident) => {
188 impl<'a, T> Iterator<$elem> for $name<'a, T> {
190 fn next(&mut self) -> Option<$elem> {
191 while self.front < self.back {
192 match self.iter.next() {
195 let index = self.front;
197 return Some((index, elem. $getter ()));
208 fn size_hint(&self) -> (uint, Option<uint>) {
209 (0, Some(self.back - self.front))
215 macro_rules! double_ended_iterator {
216 (impl $name:ident -> $elem:ty, $getter:ident) => {
217 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
219 fn next_back(&mut self) -> Option<$elem> {
220 while self.front < self.back {
221 match self.iter.next_back() {
225 return Some((self.back, elem. $getter ()));
238 pub struct Entries<'a, T> {
241 iter: slice::Items<'a, Option<T>>
244 iterator!(impl Entries -> (uint, &'a T), get_ref)
245 double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
246 #[deprecated = "replaced by Rev<Entries<'a, T>>"]
247 pub type RevEntries<'a, T> = Rev<Entries<'a, T>>;
249 pub struct MutEntries<'a, T> {
252 iter: slice::MutItems<'a, Option<T>>
255 iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
256 double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
257 #[deprecated = "replaced by Rev<MutEntries<'a, T>"]
258 pub type RevMutEntries<'a, T> = Rev<MutEntries<'a, T>>;
263 use super::SmallIntMap;
267 let mut m = SmallIntMap::new();
268 assert!(m.insert(1, 12));
269 assert!(m.insert(2, 8));
270 assert!(m.insert(5, 14));
272 match m.find_mut(&5) {
273 None => fail!(), Some(x) => *x = new
275 assert_eq!(m.find(&5), Some(&new));
280 let mut map = SmallIntMap::new();
281 assert_eq!(map.len(), 0);
282 assert!(map.is_empty());
283 assert!(map.insert(5, 20));
284 assert_eq!(map.len(), 1);
285 assert!(!map.is_empty());
286 assert!(map.insert(11, 12));
287 assert_eq!(map.len(), 2);
288 assert!(!map.is_empty());
289 assert!(map.insert(14, 22));
290 assert_eq!(map.len(), 3);
291 assert!(!map.is_empty());
296 let mut map = SmallIntMap::new();
297 assert!(map.insert(5, 20));
298 assert!(map.insert(11, 12));
299 assert!(map.insert(14, 22));
301 assert!(map.is_empty());
302 assert!(map.find(&5).is_none());
303 assert!(map.find(&11).is_none());
304 assert!(map.find(&14).is_none());
308 fn test_insert_with_key() {
309 let mut map = SmallIntMap::new();
311 // given a new key, initialize it with this new count,
312 // given an existing key, add more to its count
313 fn addMoreToCount(_k: uint, v0: uint, v1: uint) -> uint {
317 fn addMoreToCount_simple(v0: uint, v1: uint) -> uint {
322 map.update(3, 1, addMoreToCount_simple);
323 map.update_with_key(9, 1, addMoreToCount);
324 map.update(3, 7, addMoreToCount_simple);
325 map.update_with_key(5, 3, addMoreToCount);
326 map.update_with_key(3, 2, addMoreToCount);
328 // check the total counts
329 assert_eq!(map.find(&3).unwrap(), &10);
330 assert_eq!(map.find(&5).unwrap(), &3);
331 assert_eq!(map.find(&9).unwrap(), &1);
333 // sadly, no sevens were counted
334 assert!(map.find(&7).is_none());
339 let mut m = SmallIntMap::new();
340 assert_eq!(m.swap(1, 2), None);
341 assert_eq!(m.swap(1, 3), Some(2));
342 assert_eq!(m.swap(1, 4), Some(3));
347 let mut m = SmallIntMap::new();
349 assert_eq!(m.pop(&1), Some(2));
350 assert_eq!(m.pop(&1), None);
355 let mut m = SmallIntMap::new();
357 assert!(m.insert(0, 1));
358 assert!(m.insert(1, 2));
359 assert!(m.insert(3, 5));
360 assert!(m.insert(6, 10));
361 assert!(m.insert(10, 11));
363 let mut it = m.iter();
364 assert_eq!(it.size_hint(), (0, Some(11)));
365 assert_eq!(it.next().unwrap(), (0, &1));
366 assert_eq!(it.size_hint(), (0, Some(10)));
367 assert_eq!(it.next().unwrap(), (1, &2));
368 assert_eq!(it.size_hint(), (0, Some(9)));
369 assert_eq!(it.next().unwrap(), (3, &5));
370 assert_eq!(it.size_hint(), (0, Some(7)));
371 assert_eq!(it.next().unwrap(), (6, &10));
372 assert_eq!(it.size_hint(), (0, Some(4)));
373 assert_eq!(it.next().unwrap(), (10, &11));
374 assert_eq!(it.size_hint(), (0, Some(0)));
375 assert!(it.next().is_none());
379 fn test_iterator_size_hints() {
380 let mut m = SmallIntMap::new();
382 assert!(m.insert(0, 1));
383 assert!(m.insert(1, 2));
384 assert!(m.insert(3, 5));
385 assert!(m.insert(6, 10));
386 assert!(m.insert(10, 11));
388 assert_eq!(m.iter().size_hint(), (0, Some(11)));
389 assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
390 assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
391 assert_eq!(m.mut_iter().rev().size_hint(), (0, Some(11)));
395 fn test_mut_iterator() {
396 let mut m = SmallIntMap::new();
398 assert!(m.insert(0, 1));
399 assert!(m.insert(1, 2));
400 assert!(m.insert(3, 5));
401 assert!(m.insert(6, 10));
402 assert!(m.insert(10, 11));
404 for (k, v) in m.mut_iter() {
408 let mut it = m.iter();
409 assert_eq!(it.next().unwrap(), (0, &1));
410 assert_eq!(it.next().unwrap(), (1, &3));
411 assert_eq!(it.next().unwrap(), (3, &8));
412 assert_eq!(it.next().unwrap(), (6, &16));
413 assert_eq!(it.next().unwrap(), (10, &21));
414 assert!(it.next().is_none());
418 fn test_rev_iterator() {
419 let mut m = SmallIntMap::new();
421 assert!(m.insert(0, 1));
422 assert!(m.insert(1, 2));
423 assert!(m.insert(3, 5));
424 assert!(m.insert(6, 10));
425 assert!(m.insert(10, 11));
427 let mut it = m.iter().rev();
428 assert_eq!(it.next().unwrap(), (10, &11));
429 assert_eq!(it.next().unwrap(), (6, &10));
430 assert_eq!(it.next().unwrap(), (3, &5));
431 assert_eq!(it.next().unwrap(), (1, &2));
432 assert_eq!(it.next().unwrap(), (0, &1));
433 assert!(it.next().is_none());
437 fn test_mut_rev_iterator() {
438 let mut m = SmallIntMap::new();
440 assert!(m.insert(0, 1));
441 assert!(m.insert(1, 2));
442 assert!(m.insert(3, 5));
443 assert!(m.insert(6, 10));
444 assert!(m.insert(10, 11));
446 for (k, v) in m.mut_iter().rev() {
450 let mut it = m.iter();
451 assert_eq!(it.next().unwrap(), (0, &1));
452 assert_eq!(it.next().unwrap(), (1, &3));
453 assert_eq!(it.next().unwrap(), (3, &8));
454 assert_eq!(it.next().unwrap(), (6, &16));
455 assert_eq!(it.next().unwrap(), (10, &21));
456 assert!(it.next().is_none());
460 fn test_move_iter() {
461 let mut m = SmallIntMap::new();
463 let mut called = false;
464 for (k, v) in m.move_iter() {
468 assert_eq!(v, box 2);
478 use self::test::Bencher;
479 use super::SmallIntMap;
480 use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
484 pub fn insert_rand_100(b: &mut Bencher) {
485 let mut m : SmallIntMap<uint> = SmallIntMap::new();
486 insert_rand_n(100, &mut m, b);
490 pub fn insert_rand_10_000(b: &mut Bencher) {
491 let mut m : SmallIntMap<uint> = SmallIntMap::new();
492 insert_rand_n(10_000, &mut m, b);
497 pub fn insert_seq_100(b: &mut Bencher) {
498 let mut m : SmallIntMap<uint> = SmallIntMap::new();
499 insert_seq_n(100, &mut m, b);
503 pub fn insert_seq_10_000(b: &mut Bencher) {
504 let mut m : SmallIntMap<uint> = SmallIntMap::new();
505 insert_seq_n(10_000, &mut m, b);
510 pub fn find_rand_100(b: &mut Bencher) {
511 let mut m : SmallIntMap<uint> = SmallIntMap::new();
512 find_rand_n(100, &mut m, b);
516 pub fn find_rand_10_000(b: &mut Bencher) {
517 let mut m : SmallIntMap<uint> = SmallIntMap::new();
518 find_rand_n(10_000, &mut m, b);
523 pub fn find_seq_100(b: &mut Bencher) {
524 let mut m : SmallIntMap<uint> = SmallIntMap::new();
525 find_seq_n(100, &mut m, b);
529 pub fn find_seq_10_000(b: &mut Bencher) {
530 let mut m : SmallIntMap<uint> = SmallIntMap::new();
531 find_seq_n(10_000, &mut m, b);