diff --git a/src/libcore/iter/adapters/mod.rs b/src/libcore/iter/adapters/mod.rs index ce18b4b97ad6..d6c5c3a2b094 100644 --- a/src/libcore/iter/adapters/mod.rs +++ b/src/libcore/iter/adapters/mod.rs @@ -981,6 +981,16 @@ impl DoubleEndedIterator for Enumerate where }) } + #[inline] + fn nth_back(&mut self, n: usize) -> Option<(usize, ::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(&mut self, init: Acc, mut fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try @@ -1790,6 +1800,17 @@ impl DoubleEndedIterator for Fuse where I: DoubleEndedIterator { } } + #[inline] + default fn nth_back(&mut self, n: usize) -> Option<::Item> { + if self.done { + None + } else { + let nth = self.iter.nth_back(n); + self.done = nth.is_none(); + nth + } + } + #[inline] default fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try @@ -1878,6 +1899,11 @@ impl DoubleEndedIterator for Fuse self.iter.next_back() } + #[inline] + fn nth_back(&mut self, n: usize) -> Option<::Item> { + self.iter.nth_back(n) + } + #[inline] fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index f4bb887dd294..b7e2825dd9cc 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -795,6 +795,11 @@ impl DoubleEndedIterator for Bytes<'_> { self.0.next_back() } + #[inline] + fn nth_back(&mut self, n: usize) -> Option { + self.0.nth_back(n) + } + #[inline] fn rfind

(&mut self, predicate: P) -> Option where P: FnMut(&Self::Item) -> bool diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index d5b581d336d2..5247331fba24 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -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];