Skip to content

Commit

Permalink
Adaptor .while_some()
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Jun 9, 2015
1 parent 541a21c commit d461775
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/adaptors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,40 @@ impl<'a, I, F> Iterator for TakeWhileRef<'a, I, F> where
}
}

/// An iterator adaptor that filters **Option\<A\>** iterator elements
/// and produces **A**. Stops on the first **None** encountered.
///
/// See [*.while_some()*](trait.Itertools.html#method.while_some) for more information.
#[derive(Clone)]
pub struct WhileSome<I> {
iter: I,
}

impl<I> WhileSome<I> {

This comment has been minimized.

Copy link
@DanielKeep

DanielKeep Jun 10, 2015

Contributor

Shouldn't this have type constraints on it? Otherwise, wouldn't you be able to create a WhileSome that you can't do anything with (WhileSome::new("lolwut")).

/// Create a new **WhileSome\<I\>**.
pub fn new(iter: I) -> Self {
WhileSome { iter: iter }
}
}

impl<I, A> Iterator for WhileSome<I> where
I: Iterator<Item=Option<A>>
{
type Item = A;

fn next(&mut self) -> Option<A> {
match self.iter.next() {
None | Some(None) => None,
Some(elt) => elt,
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
let sh = self.iter.size_hint();
(0, sh.1)
}
}

/// An iterator to iterate through all the combinations of pairs in a **Clone**-able iterator.
///
/// See [*.combinations()*](trait.Itertools.html#method.combinations) for more information.
Expand Down
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pub use adaptors::{
Merge,
MultiPeek,
TakeWhileRef,
WhileSome,
Coalesce,
CoalesceFn,
Combinations,
Expand Down Expand Up @@ -674,6 +675,16 @@ pub trait Itertools : Iterator {
TakeWhileRef::new(self, f)
}

/// Return an iterator adaptor that filters **Option\<A\>** iterator elements
/// and produces **A**. Stops on the first **None** encountered.
///
/// Iterator element type is **A**, the unwrapped element.
fn while_some<A>(self) -> WhileSome<Self> where
Self: Sized + Iterator<Item=Option<A>>,
{
WhileSome::new(self)
}

/// Return an iterator adaptor that iterates over the combinations of
/// the elements from an iterator.
///
Expand Down
4 changes: 4 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,3 +594,7 @@ fn pad_using() {
let r: Vec<_> = v.into_iter().pad_using(1, |_| panic!()).collect();
assert_eq!(r, vec![0, 1, 2]);
}

#[test]
fn while_some() {
}

0 comments on commit d461775

Please sign in to comment.