diff --git a/src/libcore/iter/adapters/zip.rs b/src/libcore/iter/adapters/zip.rs index 06f047d92872e..35fc1ea7e64b6 100644 --- a/src/libcore/iter/adapters/zip.rs +++ b/src/libcore/iter/adapters/zip.rs @@ -62,6 +62,17 @@ impl DoubleEndedIterator for Zip where fn next_back(&mut self) -> Option<(A::Item, B::Item)> { ZipImpl::next_back(self) } + + #[inline] + fn nth_back(&mut self, mut n: usize) -> Option<(A::Item, B::Item)> { + while let Some(x) = ZipImpl::next_back(self) { + if n == 0 { + return Some(x) + } + n -= 1; + } + None + } } // Zip specialization trait diff --git a/src/libcore/iter/traits/double_ended.rs b/src/libcore/iter/traits/double_ended.rs index 06de95c082724..aa46c26e72d9b 100644 --- a/src/libcore/iter/traits/double_ended.rs +++ b/src/libcore/iter/traits/double_ended.rs @@ -69,7 +69,7 @@ pub trait DoubleEndedIterator: Iterator { /// Returns the `n`th element from the end of the iterator. /// /// This is essentially the reversed version of [`nth`]. Although like most indexing - /// operations, the count starts from zero, so `nth_back(0)` returns the first value fro + /// operations, the count starts from zero, so `nth_back(0)` returns the first value from /// the end, `nth_back(1)` the second, and so on. /// /// Note that all elements between the end and the returned element will be diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index 7dfb1adad9eed..df89713c3cca4 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -153,6 +153,22 @@ fn test_zip_nth() { assert_eq!(it.nth(3), None); } +#[test] +fn test_zip_nth_back() { + let xs = [0, 1, 2, 4, 5]; + let ys = [10, 11, 12]; + let mut it = xs.iter().zip(&ys); + assert_eq!(it.nth_back(0), Some((&2, &12))); + assert_eq!(it.nth_back(1), Some((&0, &10))); + assert_eq!(it.nth_back(0), None); + + let mut it = xs.iter().zip(&ys); + assert_eq!(it.nth_back(3), None); + + let mut it = ys.iter().zip(&xs); + assert_eq!(it.nth_back(3), None); +} + #[test] fn test_zip_nth_side_effects() { let mut a = Vec::new();