Skip to content

Instantly share code, notes, and snippets.

@gavinb
Last active December 19, 2015 23:28
Show Gist options
  • Save gavinb/6034521 to your computer and use it in GitHub Desktop.
Save gavinb/6034521 to your computer and use it in GitHub Desktop.
Experimental repeat() iterator for Rust
// iterator.rs
pub trait IteratorUtil<A> {
// ...
fn repeat_(&mut self) -> RepeatIterator<A, Self>;
}
//...
#[inline]
fn repeat_(&mut self) -> RepeatIterator<A, T> {
RepeatIterator{iter: self, iter_orig: copy self}
}
//...
/// An iterator which repeats the same sequence forever, looping around
/// back to the start when it reaches the end.
pub struct RepeatIterator<A, T> {
priv iter_orig: T, // State of original iterator for restart
priv iter: T, // Current iterator
}
impl<A, T: Iterator<A>> Iterator<A> for RepeatIterator<A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
match self.iter.next() {
Some(x) => {
Some(x)
}
None => {
self.iter = copy self.iter_orig;
return self.next();
}
}
}
}
#[cfg(test)]
mod tests {
// ...
#[test]
fn test_repeat() {
let a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let mut it = a.iter().repeat_();
for uint::range(0,21) |n| {
assert_eq!(*it.next().get(), (n%10 as int));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment