Skip to content

Commit 4f2f545

Browse files
committed
add Iterator implementations for Option
1 parent d1d8559 commit 4f2f545

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/libstd/option.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ use util;
4848
use num::Zero;
4949
use old_iter::{BaseIter, MutableIter, ExtendedIter};
5050
use old_iter;
51+
use iterator::Iterator;
5152
use str::StrSlice;
5253
use clone::DeepClone;
5354

@@ -146,7 +147,24 @@ impl<A> ExtendedIter<A> for Option<A> {
146147
}
147148

148149
impl<T> Option<T> {
150+
#[inline]
151+
pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
152+
match *self {
153+
Some(ref x) => OptionIterator{opt: Some(x)},
154+
None => OptionIterator{opt: None}
155+
}
156+
}
157+
158+
#[inline]
159+
pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
160+
match *self {
161+
Some(ref mut x) => OptionMutIterator{opt: Some(x)},
162+
None => OptionMutIterator{opt: None}
163+
}
164+
}
165+
149166
/// Returns true if the option equals `none`
167+
#[inline]
150168
pub fn is_none(&const self) -> bool {
151169
match *self { None => true, Some(_) => false }
152170
}
@@ -376,6 +394,26 @@ impl<T:Copy + Zero> Option<T> {
376394
}
377395
}
378396

397+
pub struct OptionIterator<'self, A> {
398+
priv opt: Option<&'self A>
399+
}
400+
401+
impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
402+
fn next(&mut self) -> Option<&'self A> {
403+
util::replace(&mut self.opt, None)
404+
}
405+
}
406+
407+
pub struct OptionMutIterator<'self, A> {
408+
priv opt: Option<&'self mut A>
409+
}
410+
411+
impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
412+
fn next(&mut self) -> Option<&'self mut A> {
413+
util::replace(&mut self.opt, None)
414+
}
415+
}
416+
379417
#[test]
380418
fn test_unwrap_ptr() {
381419
unsafe {

0 commit comments

Comments
 (0)