Skip to content

Commit 02a148d

Browse files
@amit.chandrawizAmit
@amit.chandra
authored andcommitted
wip nth_back on chunks
Signed-off-by: wizAmit <[email protected]>
1 parent 80e7cde commit 02a148d

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/libcore/slice/mod.rs

+16
Original file line numberDiff line numberDiff line change
@@ -4152,6 +4152,22 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
41524152
Some(snd)
41534153
}
41544154
}
4155+
4156+
#[inline]
4157+
fn nth_back(&mut self, n: usize) {
4158+
let (end, overflow) = self.v.len().overflowing_sub(n);
4159+
if end < self.v.len() || overflow {
4160+
self.v = &[];
4161+
None
4162+
} else {
4163+
let start = match end.checked_sub(self.chunk_size) {
4164+
Some(sum) => cmp::min(self.v.len(), sum),
4165+
None => self.v.len(),
4166+
};
4167+
let nth = &self.v[start..end];
4168+
self.v = &self.v[end..];
4169+
}
4170+
}
41554171
}
41564172

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

src/libcore/tests/slice.rs

+13
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ fn test_chunks_nth() {
134134
assert_eq!(c2.next(), None);
135135
}
136136

137+
#[test]
138+
fn test_chunks_nth_back() {
139+
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
140+
let mut c = v.chunks(2);
141+
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
142+
assert_eq!(c.next().unwrap(), &[4, 5]);
143+
144+
let v2: &[i32] = &[0, 1, 2, 3, 4];
145+
let mut c2 = v2.chunks(3);
146+
assert_eq!(c2.nth_back(1).unwrap(), &[0, 1]);
147+
assert_eq!(c2.next(), None);
148+
}
149+
137150
#[test]
138151
fn test_chunks_last() {
139152
let v: &[i32] = &[0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)