Skip to content

Commit

Permalink
Add cycle
Browse files Browse the repository at this point in the history
  • Loading branch information
sfackler committed Mar 10, 2019
1 parent d269d1f commit a3243e4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
43 changes: 43 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,18 @@ pub trait FallibleIterator {
Cloned(self)
}

/// Returns an iterator which repeas this iterator endlessly.
#[inline]
fn cycle(self) -> Cycle<Self>
where
Self: Sized + Clone,
{
Cycle {
it: self.clone(),
cur: self,
}
}

/// Lexicographically compares the elements of this iterator to that of
/// another.
#[inline]
Expand Down Expand Up @@ -2064,6 +2076,37 @@ where
}
}

/// An iterator which cycles another endlessly.
#[derive(Clone, Debug)]
pub struct Cycle<I> {
it: I,
cur: I,
}

impl<I> FallibleIterator for Cycle<I>
where
I: FallibleIterator + Clone,
{
type Item = I::Item;
type Error = I::Error;

#[inline]
fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
match self.cur.next()? {
None => {
self.cur = self.it.clone();
self.cur.next()
}
Some(v) => Ok(Some(v)),
}
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::max_value(), None)
}
}

/// An iterator that yields pairs of this iterator's and another iterator's
/// values.
#[derive(Clone, Debug)]
Expand Down
12 changes: 11 additions & 1 deletion src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,18 @@ fn find_map() {

#[test]
fn unzip() {
let it = convert(vec![(0, 0), (1, -1), (2, -2), (3, -3)].into_iter().map(Ok::<_, ()>));
let it = convert(
vec![(0, 0), (1, -1), (2, -2), (3, -3)]
.into_iter()
.map(Ok::<_, ()>),
);
let (pos, neg): (Vec<i32>, Vec<i32>) = it.unzip().unwrap();
assert_eq!(pos, vec![0, 1, 2, 3]);
assert_eq!(neg, vec![0, -1, -2, -3]);
}

#[test]
fn cycle() {
let it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::<i32, ()>)).cycle();
assert_eq!(it.take(6).clone().collect::<Vec<_>>(), Ok(vec![0, 1, 2, 3, 0, 1]));
}

0 comments on commit a3243e4

Please sign in to comment.