Skip to content

Commit

Permalink
implement nth_back for Enumerate
Browse files Browse the repository at this point in the history
  • Loading branch information
koalatux committed Apr 16, 2019
1 parent fae2a68 commit 2605537
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/libcore/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,16 @@ impl<I> DoubleEndedIterator for Enumerate<I> where
})
}

#[inline]
fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
self.iter.nth_back(n).map(|a| {
let len = self.iter.len();
// Can safely add, `ExactSizeIterator` promises that the number of
// elements fits into a `usize`.
(self.count + len, a)
})
}

#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
Expand Down
18 changes: 18 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,24 @@ fn test_iterator_enumerate_nth() {
assert_eq!(i, 3);
}

#[test]
fn test_iterator_enumerate_nth_back() {
let xs = [0, 1, 2, 3, 4, 5];
let mut it = xs.iter().enumerate();
while let Some((i, &x)) = it.nth_back(0) {
assert_eq!(i, x);
}

let mut it = xs.iter().enumerate();
while let Some((i, &x)) = it.nth_back(1) {
assert_eq!(i, x);
}

let (i, &x) = xs.iter().enumerate().nth_back(3).unwrap();
assert_eq!(i, x);
assert_eq!(i, 2);
}

#[test]
fn test_iterator_enumerate_count() {
let xs = [0, 1, 2, 3, 4, 5];
Expand Down

0 comments on commit 2605537

Please sign in to comment.