Skip to content

Commit 0b339e0

Browse files
committed
Add methods for obtaining iterators over the keys and values of a SmallIntMap
1 parent 18f7b8f commit 0b339e0

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/libcollections/smallintmap.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use core::prelude::*;
1717

1818
use core::default::Default;
1919
use core::fmt;
20+
use core::iter;
2021
use core::iter::{Enumerate, FilterMap};
2122
use core::mem::replace;
2223

@@ -194,6 +195,18 @@ impl<V> SmallIntMap<V> {
194195
self.find(key).expect("key not present")
195196
}
196197

198+
/// An iterator visiting all keys in ascending order by the keys.
199+
/// Iterator element type is `uint`.
200+
pub fn keys<'r>(&'r self) -> Keys<'r, V> {
201+
self.iter().map(|(k, _v)| k)
202+
}
203+
204+
/// An iterator visiting all values in ascending order by the keys.
205+
/// Iterator element type is `&'r V`.
206+
pub fn values<'r>(&'r self) -> Values<'r, V> {
207+
self.iter().map(|(_k, v)| v)
208+
}
209+
197210
/// An iterator visiting all key-value pairs in ascending order by the keys.
198211
/// Iterator element type is `(uint, &'r V)`.
199212
///
@@ -422,6 +435,14 @@ pub struct MutEntries<'a, T> {
422435
iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
423436
double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
424437

438+
/// Forward iterator over the keys of a map
439+
pub type Keys<'a, T> =
440+
iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;
441+
442+
/// Forward iterator over the values of a map
443+
pub type Values<'a, T> =
444+
iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;
445+
425446
#[cfg(test)]
426447
mod test_map {
427448
use std::prelude::*;
@@ -517,6 +538,32 @@ mod test_map {
517538
assert_eq!(m.pop(&1), None);
518539
}
519540

541+
#[test]
542+
fn test_keys() {
543+
let mut map = SmallIntMap::new();
544+
map.insert(1, 'a');
545+
map.insert(2, 'b');
546+
map.insert(3, 'c');
547+
let keys = map.keys().collect::<Vec<uint>>();
548+
assert_eq!(keys.len(), 3);
549+
assert!(keys.contains(&1));
550+
assert!(keys.contains(&2));
551+
assert!(keys.contains(&3));
552+
}
553+
554+
#[test]
555+
fn test_values() {
556+
let mut map = SmallIntMap::new();
557+
map.insert(1, 'a');
558+
map.insert(2, 'b');
559+
map.insert(3, 'c');
560+
let values = map.values().map(|&v| v).collect::<Vec<char>>();
561+
assert_eq!(values.len(), 3);
562+
assert!(values.contains(&'a'));
563+
assert!(values.contains(&'b'));
564+
assert!(values.contains(&'c'));
565+
}
566+
520567
#[test]
521568
fn test_iterator() {
522569
let mut m = SmallIntMap::new();

0 commit comments

Comments
 (0)