Skip to content

Commit

Permalink
make skip a double ended iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
oli-obk committed Mar 4, 2016
1 parent 8e261d1 commit 25e5de3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/libcore/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3851,6 +3851,17 @@ impl<I> Iterator for Skip<I> where I: Iterator {
#[stable(feature = "rust1", since = "1.0.0")]
impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}

#[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
fn next_back(&mut self) -> Option<Self::Item> {
if self.len() > 0 {
self.iter.next_back()
} else {
None
}
}
}

/// An iterator that only iterates over the first `n` iterations of `iter`.
///
/// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
Expand Down
38 changes: 38 additions & 0 deletions src/libcoretest/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,44 @@ fn test_iterator_skip() {
assert_eq!(it.len(), 0);
}

#[test]
fn test_iterator_skip_doubleended() {
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
let mut it = xs.iter().rev().skip(5);
assert_eq!(it.next(), Some(&15));
assert_eq!(it.by_ref().rev().next(), Some(&0));
assert_eq!(it.next(), Some(&13));
assert_eq!(it.by_ref().rev().next(), Some(&1));
assert_eq!(it.next(), Some(&5));
assert_eq!(it.by_ref().rev().next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), None);
let mut it = xs.iter().rev().skip(5).rev();
assert_eq!(it.next(), Some(&0));
assert_eq!(it.rev().next(), Some(&15));
let mut it_base = xs.iter();
{
let mut it = it_base.by_ref().skip(5).rev();
assert_eq!(it.next(), Some(&30));
assert_eq!(it.next(), Some(&20));
assert_eq!(it.next(), Some(&19));
assert_eq!(it.next(), Some(&17));
assert_eq!(it.next(), Some(&16));
assert_eq!(it.next(), Some(&15));
assert_eq!(it.next(), Some(&13));
assert_eq!(it.next(), None);
}
// make sure the skipped parts have not been consumed
assert_eq!(it_base.next(), Some(&0));
assert_eq!(it_base.next(), Some(&1));
assert_eq!(it_base.next(), Some(&2));
assert_eq!(it_base.next(), Some(&3));
assert_eq!(it_base.next(), Some(&5));
assert_eq!(it_base.next(), None);
let it = xs.iter().skip(5).rev();
assert_eq!(it.last(), Some(&13));
}

#[test]
fn test_iterator_skip_nth() {
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
Expand Down

0 comments on commit 25e5de3

Please sign in to comment.