1
Fork 0

wip nth_back on chunks

Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
This commit is contained in:
@amit.chandra 2019-04-26 19:53:18 +05:30 committed by wizAmit
parent 80e7cde223
commit 02a148dba2
2 changed files with 29 additions and 0 deletions

View file

@ -4152,6 +4152,22 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
Some(snd)
}
}
#[inline]
fn nth_back(&mut self, n: usize) {
let (end, overflow) = self.v.len().overflowing_sub(n);
if end < self.v.len() || overflow {
self.v = &[];
None
} else {
let start = match end.checked_sub(self.chunk_size) {
Some(sum) => cmp::min(self.v.len(), sum),
None => self.v.len(),
};
let nth = &self.v[start..end];
self.v = &self.v[end..];
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]

View file

@ -134,6 +134,19 @@ fn test_chunks_nth() {
assert_eq!(c2.next(), None);
}
#[test]
fn test_chunks_nth_back() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
let mut c = v.chunks(2);
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
assert_eq!(c.next().unwrap(), &[4, 5]);
let v2: &[i32] = &[0, 1, 2, 3, 4];
let mut c2 = v2.chunks(3);
assert_eq!(c2.nth_back(1).unwrap(), &[0, 1]);
assert_eq!(c2.next(), None);
}
#[test]
fn test_chunks_last() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];