Skip to content

Commit 4dd3ce8

Browse files
authored
Rollup merge of rust-lang#63265 - JohnTitor:implement-nth-back-for-chunksexactmut, r=scottmcm
Implement `nth_back` for ChunksExactMut This is a part of rust-lang#54054. r? @scottmcm
2 parents b4fcf48 + d3019d1 commit 4dd3ce8

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
@@ -4637,6 +4637,22 @@ impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
46374637
Some(tail)
46384638
}
46394639
}
4640+
4641+
#[inline]
4642+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4643+
let len = self.len();
4644+
if n >= len {
4645+
self.v = &mut [];
4646+
None
4647+
} else {
4648+
let start = (len - 1 - n) * self.chunk_size;
4649+
let end = start + self.chunk_size;
4650+
let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4651+
let (head, nth_back) = temp.split_at_mut(start);
4652+
self.v = head;
4653+
Some(nth_back)
4654+
}
4655+
}
46404656
}
46414657

46424658
#[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)