Skip to content

Commit ce682cb

Browse files
author
blake2-ppc
committed
std: Add .consume_iter() for Option, to make it reusable
Let Option be a base for a widely useful one- or zero- item iterator. Refactor OptionIterator to support any generic element type, so the same iterator impl can be used for both &T, &mut T and T iterators.
1 parent bbda3fa commit ce682cb

File tree

1 file changed

+15
-27
lines changed

1 file changed

+15
-27
lines changed

src/libstd/option.rs

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ impl<T: ToStr> ToStr for Option<T> {
116116
impl<T> Option<T> {
117117
/// Return an iterator over the possibly contained value
118118
#[inline]
119-
pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
119+
pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
120120
match *self {
121121
Some(ref x) => OptionIterator{opt: Some(x)},
122122
None => OptionIterator{opt: None}
@@ -125,13 +125,19 @@ impl<T> Option<T> {
125125

126126
/// Return a mutable iterator over the possibly contained value
127127
#[inline]
128-
pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
128+
pub fn mut_iter<'r>(&'r mut self) -> OptionIterator<&'r mut T> {
129129
match *self {
130-
Some(ref mut x) => OptionMutIterator{opt: Some(x)},
131-
None => OptionMutIterator{opt: None}
130+
Some(ref mut x) => OptionIterator{opt: Some(x)},
131+
None => OptionIterator{opt: None}
132132
}
133133
}
134134

135+
/// Return a consuming iterator over the possibly contained value
136+
#[inline]
137+
pub fn consume_iter(self) -> OptionIterator<T> {
138+
OptionIterator{opt: self}
139+
}
140+
135141
/// Returns true if the option equals `None`
136142
#[inline]
137143
pub fn is_none(&self) -> bool {
@@ -404,31 +410,13 @@ impl<T> Zero for Option<T> {
404410
fn is_zero(&self) -> bool { self.is_none() }
405411
}
406412

407-
/// Immutable iterator over an `Option<A>`
408-
pub struct OptionIterator<'self, A> {
409-
priv opt: Option<&'self A>
410-
}
411-
412-
impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
413-
fn next(&mut self) -> Option<&'self A> {
414-
util::replace(&mut self.opt, None)
415-
}
416-
417-
fn size_hint(&self) -> (uint, Option<uint>) {
418-
match self.opt {
419-
Some(_) => (1, Some(1)),
420-
None => (0, Some(0)),
421-
}
422-
}
423-
}
424-
425-
/// Mutable iterator over an `Option<A>`
426-
pub struct OptionMutIterator<'self, A> {
427-
priv opt: Option<&'self mut A>
413+
/// Immutable iterator over an Option
414+
pub struct OptionIterator<A> {
415+
priv opt: Option<A>
428416
}
429417

430-
impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
431-
fn next(&mut self) -> Option<&'self mut A> {
418+
impl<A> Iterator<A> for OptionIterator<A> {
419+
fn next(&mut self) -> Option<A> {
432420
util::replace(&mut self.opt, None)
433421
}
434422

0 commit comments

Comments
 (0)