about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2013-06-23 17:40:56 -0700
committerbors <bors@rust-lang.org>2013-06-23 17:40:56 -0700
commitac4211ef52a3577f901ed4dc7f370b05ca4e638d (patch)
treed2a3dce9cc7c3bdcda7330eadd2de77c61d7db22 /src/libstd
parentf82756180bec5a8405e1fc6ee1b22949db24861f (diff)
parentf3966e4a08c17c1610a21e0b343f69369ad0eb31 (diff)
downloadrust-ac4211ef52a3577f901ed4dc7f370b05ca4e638d.tar.gz
rust-ac4211ef52a3577f901ed4dc7f370b05ca4e638d.zip
auto merge of #7279 : hanny24/rust/master, r=msullivan
This commit adds filtered method for Option type. It is not exactly necessary (chain method can be used instead), however I believe that this approach using extra filtered method is more convinient.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/option.rs17
1 files changed, 17 insertions, 0 deletions
diff --git a/src/libstd/option.rs b/src/libstd/option.rs
index 7dc6b7fe4b1..88a66249c96 100644
--- a/src/libstd/option.rs
+++ b/src/libstd/option.rs
@@ -159,6 +159,15 @@ impl<T> Option<T> {
         }
     }
 
+    /// Filters an optional value using given function.
+    #[inline(always)]
+    pub fn filtered<'a>(self, f: &fn(t: &'a T) -> bool) -> Option<T> {
+        match self {
+            Some(x) => if(f(&x)) {Some(x)} else {None},
+            None => None
+        }
+    }
+
     /// Maps a `some` value from one type to another by reference
     #[inline]
     pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
@@ -464,3 +473,11 @@ fn test_get_or_zero() {
     let no_stuff: Option<int> = None;
     assert_eq!(no_stuff.get_or_zero(), 0);
 }
+
+#[test]
+fn test_filtered() {
+    let some_stuff = Some(42);
+    let modified_stuff = some_stuff.filtered(|&x| {x < 10});
+    assert_eq!(some_stuff.get(), 42);
+    assert!(modified_stuff.is_none());
+}