about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDaniel Micay <danielmicay@gmail.com>2013-03-24 20:35:23 -0400
committerDaniel Micay <danielmicay@gmail.com>2013-03-24 21:40:13 -0400
commitf0f4a00e88fc374b2b3096789a11bf429d42c3a9 (patch)
tree814ff9413332ef136f7a52f4516dbd266927bfac
parent89e2578a9d1cd18270b7148a5d5d6b8bee051ac5 (diff)
downloadrust-f0f4a00e88fc374b2b3096789a11bf429d42c3a9.tar.gz
rust-f0f4a00e88fc374b2b3096789a11bf429d42c3a9.zip
smallintmap: add find_mut method
-rw-r--r--src/libstd/smallintmap.rs30
1 files changed, 28 insertions, 2 deletions
diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs
index a559e7540d4..fffd6c9ee4f 100644
--- a/src/libstd/smallintmap.rs
+++ b/src/libstd/smallintmap.rs
@@ -86,7 +86,7 @@ impl<V> Map<uint, V> for SmallIntMap<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) {
         for uint::range(0, self.v.len()) |i| {
             match self.v[i] {
@@ -96,7 +96,7 @@ impl<V> Map<uint, V> for SmallIntMap<V> {
         }
     }
 
-    /// 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> {
         if *key < self.v.len() {
             match self.v[*key] {
@@ -140,6 +140,18 @@ pub impl<V> SmallIntMap<V> {
     fn get(&self, key: &uint) -> &'self V {
         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> {
@@ -160,6 +172,20 @@ pub impl<V:Copy> SmallIntMap<V> {
 #[cfg(test)]
 mod tests {
     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]
     fn test_len() {