Skip to content

Commit 25e5de3

Browse files
committed
make skip a double ended iterator
1 parent 8e261d1 commit 25e5de3

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/libcore/iter.rs

+11
Original file line numberDiff line numberDiff line change
@@ -3851,6 +3851,17 @@ impl<I> Iterator for Skip<I> where I: Iterator {
38513851
#[stable(feature = "rust1", since = "1.0.0")]
38523852
impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
38533853

3854+
#[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
3855+
impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
3856+
fn next_back(&mut self) -> Option<Self::Item> {
3857+
if self.len() > 0 {
3858+
self.iter.next_back()
3859+
} else {
3860+
None
3861+
}
3862+
}
3863+
}
3864+
38543865
/// An iterator that only iterates over the first `n` iterations of `iter`.
38553866
///
38563867
/// This `struct` is created by the [`take()`] method on [`Iterator`]. See its

src/libcoretest/iter.rs

+38
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,44 @@ fn test_iterator_skip() {
303303
assert_eq!(it.len(), 0);
304304
}
305305

306+
#[test]
307+
fn test_iterator_skip_doubleended() {
308+
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
309+
let mut it = xs.iter().rev().skip(5);
310+
assert_eq!(it.next(), Some(&15));
311+
assert_eq!(it.by_ref().rev().next(), Some(&0));
312+
assert_eq!(it.next(), Some(&13));
313+
assert_eq!(it.by_ref().rev().next(), Some(&1));
314+
assert_eq!(it.next(), Some(&5));
315+
assert_eq!(it.by_ref().rev().next(), Some(&2));
316+
assert_eq!(it.next(), Some(&3));
317+
assert_eq!(it.next(), None);
318+
let mut it = xs.iter().rev().skip(5).rev();
319+
assert_eq!(it.next(), Some(&0));
320+
assert_eq!(it.rev().next(), Some(&15));
321+
let mut it_base = xs.iter();
322+
{
323+
let mut it = it_base.by_ref().skip(5).rev();
324+
assert_eq!(it.next(), Some(&30));
325+
assert_eq!(it.next(), Some(&20));
326+
assert_eq!(it.next(), Some(&19));
327+
assert_eq!(it.next(), Some(&17));
328+
assert_eq!(it.next(), Some(&16));
329+
assert_eq!(it.next(), Some(&15));
330+
assert_eq!(it.next(), Some(&13));
331+
assert_eq!(it.next(), None);
332+
}
333+
// make sure the skipped parts have not been consumed
334+
assert_eq!(it_base.next(), Some(&0));
335+
assert_eq!(it_base.next(), Some(&1));
336+
assert_eq!(it_base.next(), Some(&2));
337+
assert_eq!(it_base.next(), Some(&3));
338+
assert_eq!(it_base.next(), Some(&5));
339+
assert_eq!(it_base.next(), None);
340+
let it = xs.iter().skip(5).rev();
341+
assert_eq!(it.last(), Some(&13));
342+
}
343+
306344
#[test]
307345
fn test_iterator_skip_nth() {
308346
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];

0 commit comments

Comments
 (0)