Skip to content

Commit 2605537

Browse files
committed
implement nth_back for Enumerate
1 parent fae2a68 commit 2605537

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/libcore/iter/adapters/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,16 @@ impl<I> DoubleEndedIterator for Enumerate<I> where
980980
})
981981
}
982982

983+
#[inline]
984+
fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
985+
self.iter.nth_back(n).map(|a| {
986+
let len = self.iter.len();
987+
// Can safely add, `ExactSizeIterator` promises that the number of
988+
// elements fits into a `usize`.
989+
(self.count + len, a)
990+
})
991+
}
992+
983993
#[inline]
984994
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
985995
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>

src/libcore/tests/iter.rs

+18
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,24 @@ fn test_iterator_enumerate_nth() {
389389
assert_eq!(i, 3);
390390
}
391391

392+
#[test]
393+
fn test_iterator_enumerate_nth_back() {
394+
let xs = [0, 1, 2, 3, 4, 5];
395+
let mut it = xs.iter().enumerate();
396+
while let Some((i, &x)) = it.nth_back(0) {
397+
assert_eq!(i, x);
398+
}
399+
400+
let mut it = xs.iter().enumerate();
401+
while let Some((i, &x)) = it.nth_back(1) {
402+
assert_eq!(i, x);
403+
}
404+
405+
let (i, &x) = xs.iter().enumerate().nth_back(3).unwrap();
406+
assert_eq!(i, x);
407+
assert_eq!(i, 2);
408+
}
409+
392410
#[test]
393411
fn test_iterator_enumerate_count() {
394412
let xs = [0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)