Rollup merge of #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 #54054 and nth_back() is tracked in #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.
This commit is contained in:
commit
cb2dde63d5
4 changed files with 30 additions and 0 deletions
|
|
@ -677,6 +677,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> {
|
||||
|
|
|
|||
|
|
@ -115,6 +115,7 @@
|
|||
#![feature(maybe_uninit, maybe_uninit_slice, maybe_uninit_array)]
|
||||
#![feature(alloc_layout_extra)]
|
||||
#![feature(try_trait)]
|
||||
#![feature(iter_nth_back)]
|
||||
|
||||
// Allow testing this library
|
||||
|
||||
|
|
|
|||
|
|
@ -3867,6 +3867,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")]
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue