about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorDaniel Micay <danielmicay@gmail.com>2013-06-10 17:45:59 -0400
committerDaniel Micay <danielmicay@gmail.com>2013-06-11 14:05:27 -0400
commit4f2f545ac2ce19034b138006e7ac76e502b3188b (patch)
treee2e8749d451448a3f8b340ec4af67e5ba809acc8 /src/libstd
parentd1d855993d0386fc13ad1b74df565b5ba6f6e4ea (diff)
downloadrust-4f2f545ac2ce19034b138006e7ac76e502b3188b.tar.gz
rust-4f2f545ac2ce19034b138006e7ac76e502b3188b.zip
add Iterator implementations for Option
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/option.rs38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/libstd/option.rs b/src/libstd/option.rs
index 2386a779235..8855ad0e30f 100644
--- a/src/libstd/option.rs
+++ b/src/libstd/option.rs
@@ -48,6 +48,7 @@ use util;
 use num::Zero;
 use old_iter::{BaseIter, MutableIter, ExtendedIter};
 use old_iter;
+use iterator::Iterator;
 use str::StrSlice;
 use clone::DeepClone;
 
@@ -146,7 +147,24 @@ impl<A> ExtendedIter<A> for Option<A> {
 }
 
 impl<T> Option<T> {
+    #[inline]
+    pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
+        match *self {
+            Some(ref x) => OptionIterator{opt: Some(x)},
+            None => OptionIterator{opt: None}
+        }
+    }
+
+    #[inline]
+    pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
+        match *self {
+            Some(ref mut x) => OptionMutIterator{opt: Some(x)},
+            None => OptionMutIterator{opt: None}
+        }
+    }
+
     /// Returns true if the option equals `none`
+    #[inline]
     pub fn is_none(&const self) -> bool {
         match *self { None => true, Some(_) => false }
     }
@@ -376,6 +394,26 @@ impl<T:Copy + Zero> Option<T> {
     }
 }
 
+pub struct OptionIterator<'self, A> {
+    priv opt: Option<&'self A>
+}
+
+impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
+    fn next(&mut self) -> Option<&'self A> {
+        util::replace(&mut self.opt, None)
+    }
+}
+
+pub struct OptionMutIterator<'self, A> {
+    priv opt: Option<&'self mut A>
+}
+
+impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
+    fn next(&mut self) -> Option<&'self mut A> {
+        util::replace(&mut self.opt, None)
+    }
+}
+
 #[test]
 fn test_unwrap_ptr() {
     unsafe {