Skip to content

Commit cb2dde6

Browse files
committed
Rollup merge of rust-lang#59328 - koalatux:iter-nth-back, r=scottmcm
Implement specialized nth_back() for Box and Windows. Hi there, this is my first pull request to rust :-) I started implementing some specializations for DoubleEndedIterator::nth_back() and these are the first two. The problem has been discussed in rust-lang#54054 and nth_back() is tracked in rust-lang#56995. I'm stuck with the next implementation so I though I do a PR for the ones I'm confident with to get some feedback.
2 parents 1d286f7 + 739ba04 commit cb2dde6

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

Diff for: src/liballoc/boxed.rs

+3
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,9 @@ impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
677677
fn next_back(&mut self) -> Option<I::Item> {
678678
(**self).next_back()
679679
}
680+
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
681+
(**self).nth_back(n)
682+
}
680683
}
681684
#[stable(feature = "rust1", since = "1.0.0")]
682685
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {

Diff for: src/liballoc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@
115115
#![feature(maybe_uninit, maybe_uninit_slice, maybe_uninit_array)]
116116
#![feature(alloc_layout_extra)]
117117
#![feature(try_trait)]
118+
#![feature(iter_nth_back)]
118119

119120
// Allow testing this library
120121

Diff for: src/libcore/slice/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -3867,6 +3867,19 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
38673867
ret
38683868
}
38693869
}
3870+
3871+
#[inline]
3872+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
3873+
let (end, overflow) = self.v.len().overflowing_sub(n);
3874+
if end < self.size || overflow {
3875+
self.v = &[];
3876+
None
3877+
} else {
3878+
let ret = &self.v[end-self.size..end];
3879+
self.v = &self.v[..end-1];
3880+
Some(ret)
3881+
}
3882+
}
38703883
}
38713884

38723885
#[stable(feature = "rust1", since = "1.0.0")]

Diff for: src/libcore/tests/slice.rs

+13
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,19 @@ fn test_windows_nth() {
578578
assert_eq!(c2.next(), None);
579579
}
580580

581+
#[test]
582+
fn test_windows_nth_back() {
583+
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
584+
let mut c = v.windows(2);
585+
assert_eq!(c.nth_back(2).unwrap()[0], 2);
586+
assert_eq!(c.next_back().unwrap()[1], 2);
587+
588+
let v2: &[i32] = &[0, 1, 2, 3, 4];
589+
let mut c2 = v2.windows(4);
590+
assert_eq!(c2.nth_back(1).unwrap()[1], 1);
591+
assert_eq!(c2.next_back(), None);
592+
}
593+
581594
#[test]
582595
fn test_windows_last() {
583596
let v: &[i32] = &[0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)