Skip to content

Commit d3019d1

Browse files
committed
Implement nth_back for ChunksExactMut
1 parent 2c13edc commit d3019d1

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/libcore/slice/mod.rs

+16
Original file line numberDiff line numberDiff line change
@@ -4612,6 +4612,22 @@ impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
46124612
Some(tail)
46134613
}
46144614
}
4615+
4616+
#[inline]
4617+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4618+
let len = self.len();
4619+
if n >= len {
4620+
self.v = &mut [];
4621+
None
4622+
} else {
4623+
let start = (len - 1 - n) * self.chunk_size;
4624+
let end = start + self.chunk_size;
4625+
let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4626+
let (head, nth_back) = temp.split_at_mut(start);
4627+
self.v = head;
4628+
Some(nth_back)
4629+
}
4630+
}
46154631
}
46164632

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

src/libcore/tests/slice.rs

+19
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,25 @@ fn test_chunks_exact_mut_nth() {
374374
assert_eq!(c2.next(), None);
375375
}
376376

377+
#[test]
378+
fn test_chunks_exact_mut_nth_back() {
379+
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
380+
let mut c = v.chunks_exact_mut(2);
381+
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
382+
assert_eq!(c.next().unwrap(), &[0, 1]);
383+
assert_eq!(c.next(), None);
384+
385+
let v2: &mut [i32] = &mut [0, 1, 2, 3, 4];
386+
let mut c2 = v2.chunks_exact_mut(3);
387+
assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]);
388+
assert_eq!(c2.next(), None);
389+
assert_eq!(c2.next_back(), None);
390+
391+
let v3: &mut [i32] = &mut [0, 1, 2, 3, 4];
392+
let mut c3 = v3.chunks_exact_mut(10);
393+
assert_eq!(c3.nth_back(0), None);
394+
}
395+
377396
#[test]
378397
fn test_chunks_exact_mut_last() {
379398
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)