Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom nth_back for Zip #60574

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/libcore/iter/adapters/zip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ impl<A, B> DoubleEndedIterator for Zip<A, B> 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) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default implementation of nth_back calls Iterator::next_back in a loop, which seems like it'd be just as good as this one? It looks like ZipImpl::nth exists, so I'd have expected the change here to add ZipImpl::nth_back and specialize it the same way.

if n == 0 {
return Some(x)
}
n -= 1;
}
None
}
}

// Zip specialization trait
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/iter/traits/double_ended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down