Skip to content

Commit 4583238

Browse files
@amit.chandrawizAmit
@amit.chandra
authored andcommittedJun 22, 2019
squash commit for nth_back on chunks exact
wip nth_back for chunks_exact working nth_back for chunks exact Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
1 parent 4a365a2 commit 4583238

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
 

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

+15
Original file line numberDiff line numberDiff line change
@@ -4453,6 +4453,21 @@ impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
44534453
Some(snd)
44544454
}
44554455
}
4456+
4457+
#[inline]
4458+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4459+
let len = self.len();
4460+
if n >= len {
4461+
self.v = &[];
4462+
None
4463+
} else {
4464+
let start = (len - 1 - n) * self.chunk_size;
4465+
let end = start + self.chunk_size;
4466+
let nth_back = &self.v[start..end];
4467+
self.v = &self.v[..start];
4468+
Some(nth_back)
4469+
}
4470+
}
44564471
}
44574472

44584473
#[stable(feature = "chunks_exact", since = "1.31.0")]

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

+19
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,25 @@ fn test_chunks_exact_nth() {
275275
assert_eq!(c2.next(), None);
276276
}
277277

278+
#[test]
279+
fn test_chunks_exact_nth_back() {
280+
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
281+
let mut c = v.chunks_exact(2);
282+
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
283+
assert_eq!(c.next().unwrap(), &[0, 1]);
284+
assert_eq!(c.next(), None);
285+
286+
let v2: &[i32] = &[0, 1, 2, 3, 4];
287+
let mut c2 = v2.chunks_exact(3);
288+
assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]);
289+
assert_eq!(c2.next(), None);
290+
assert_eq!(c2.next_back(), None);
291+
292+
let v3: &[i32] = &[0, 1, 2, 3, 4];
293+
let mut c3 = v3.chunks_exact(10);
294+
assert_eq!(c3.nth_back(0), None);
295+
}
296+
278297
#[test]
279298
fn test_chunks_exact_last() {
280299
let v: &[i32] = &[0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)
Please sign in to comment.