Skip to content

Commit

Permalink
Rollup merge of rust-lang#63265 - JohnTitor:implement-nth-back-for-ch…
Browse files Browse the repository at this point in the history
…unksexactmut, r=scottmcm

Implement `nth_back` for ChunksExactMut

This is a part of rust-lang#54054.

r? @scottmcm
  • Loading branch information
Centril authored Aug 20, 2019
2 parents b4fcf48 + d3019d1 commit 4dd3ce8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4637,6 +4637,22 @@ impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
Some(tail)
}
}

#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
let len = self.len();
if n >= len {
self.v = &mut [];
None
} else {
let start = (len - 1 - n) * self.chunk_size;
let end = start + self.chunk_size;
let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
let (head, nth_back) = temp.split_at_mut(start);
self.v = head;
Some(nth_back)
}
}
}

#[stable(feature = "chunks_exact", since = "1.31.0")]
Expand Down
19 changes: 19 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,25 @@ fn test_chunks_exact_mut_nth() {
assert_eq!(c2.next(), None);
}

#[test]
fn test_chunks_exact_mut_nth_back() {
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
let mut c = v.chunks_exact_mut(2);
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
assert_eq!(c.next().unwrap(), &[0, 1]);
assert_eq!(c.next(), None);

let v2: &mut [i32] = &mut [0, 1, 2, 3, 4];
let mut c2 = v2.chunks_exact_mut(3);
assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]);
assert_eq!(c2.next(), None);
assert_eq!(c2.next_back(), None);

let v3: &mut [i32] = &mut [0, 1, 2, 3, 4];
let mut c3 = v3.chunks_exact_mut(10);
assert_eq!(c3.nth_back(0), None);
}

#[test]
fn test_chunks_exact_mut_last() {
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
Expand Down

0 comments on commit 4dd3ce8

Please sign in to comment.