提交 f0f4a00e 编写于 作者: D Daniel Micay

smallintmap: add find_mut method

上级 89e2578a
...@@ -86,7 +86,7 @@ fn each_value(&self, blk: &fn(value: &V) -> bool) { ...@@ -86,7 +86,7 @@ fn each_value(&self, blk: &fn(value: &V) -> bool) {
self.each(|&(_, v)| blk(v)) self.each(|&(_, v)| blk(v))
} }
/// Visit all key-value pairs in order /// Iterate over the map and mutate the contained values
fn mutate_values(&mut self, it: &fn(&uint, &'self mut V) -> bool) { fn mutate_values(&mut self, it: &fn(&uint, &'self mut V) -> bool) {
for uint::range(0, self.v.len()) |i| { for uint::range(0, self.v.len()) |i| {
match self.v[i] { match self.v[i] {
...@@ -96,7 +96,7 @@ fn mutate_values(&mut self, it: &fn(&uint, &'self mut V) -> bool) { ...@@ -96,7 +96,7 @@ fn mutate_values(&mut self, it: &fn(&uint, &'self mut V) -> bool) {
} }
} }
/// Iterate over the map and mutate the contained values /// Return a reference to the value corresponding to the key
fn find(&self, key: &uint) -> Option<&'self V> { fn find(&self, key: &uint) -> Option<&'self V> {
if *key < self.v.len() { if *key < self.v.len() {
match self.v[*key] { match self.v[*key] {
...@@ -140,6 +140,18 @@ fn new() -> SmallIntMap<V> { SmallIntMap{v: ~[]} } ...@@ -140,6 +140,18 @@ fn new() -> SmallIntMap<V> { SmallIntMap{v: ~[]} }
fn get(&self, key: &uint) -> &'self V { fn get(&self, key: &uint) -> &'self V {
self.find(key).expect("key not present") self.find(key).expect("key not present")
} }
/// Return a mutable reference to the value corresponding to the key
fn find_mut(&mut self, key: &uint) -> Option<&'self mut V> {
if *key < self.v.len() {
match self.v[*key] {
Some(ref mut value) => Some(value),
None => None
}
} else {
None
}
}
} }
pub impl<V:Copy> SmallIntMap<V> { pub impl<V:Copy> SmallIntMap<V> {
...@@ -160,6 +172,20 @@ fn update(&mut self, key: uint, newval: V, ff: &fn(V, V) -> V) -> bool { ...@@ -160,6 +172,20 @@ fn update(&mut self, key: uint, newval: V, ff: &fn(V, V) -> V) -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::SmallIntMap; use super::SmallIntMap;
use core::prelude::*;
#[test]
fn test_find_mut() {
let mut m = SmallIntMap::new();
fail_unless!(m.insert(1, 12));
fail_unless!(m.insert(2, 8));
fail_unless!(m.insert(5, 14));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
}
assert_eq!(m.find(&5), Some(&new));
}
#[test] #[test]
fn test_len() { fn test_len() {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册