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

Implement specialized nth_back() for Box and Windows. #59328

Merged
merged 2 commits into from
Mar 24, 2019
Merged
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
3 changes: 3 additions & 0 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,9 @@ impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> {
(**self).next_back()
}
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
(**self).nth_back(n)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
Expand Down
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
#![feature(maybe_uninit)]
#![feature(alloc_layout_extra)]
#![feature(try_trait)]
#![feature(iter_nth_back)]

// Allow testing this library

Expand Down
13 changes: 13 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3835,6 +3835,19 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
ret
}
}

#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
let (end, overflow) = self.v.len().overflowing_sub(n);
if end < self.size || overflow {
self.v = &[];
None
} else {
let ret = &self.v[end-self.size..end];
self.v = &self.v[..end-1];
Some(ret)
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
13 changes: 13 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,19 @@ fn test_windows_nth() {
assert_eq!(c2.next(), None);
}

#[test]
fn test_windows_nth_back() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
let mut c = v.windows(2);
assert_eq!(c.nth_back(2).unwrap()[0], 2);
assert_eq!(c.next_back().unwrap()[1], 2);

let v2: &[i32] = &[0, 1, 2, 3, 4];
let mut c2 = v2.windows(4);
assert_eq!(c2.nth_back(1).unwrap()[1], 1);
assert_eq!(c2.next_back(), None);
}

#[test]
fn test_windows_last() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
Expand Down