Skip to content

Commit

Permalink
squash of all commits for nth_back on ChunksMut
Browse files Browse the repository at this point in the history
wip nth_back for chunks_mut

working chunksmut

fixed nth_back for chunksmut

Signed-off-by: wizAmit <[email protected]>
  • Loading branch information
@amit.chandra authored and wizAmit committed Jun 23, 2019
1 parent a96ba96 commit b95bde4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4330,6 +4330,25 @@ impl<'a, T> DoubleEndedIterator for ChunksMut<'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 = match start.checked_add(self.chunk_size) {
Some(res) => cmp::min(res, self.v.len()),
None => self.v.len(),
};
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 = "rust1", since = "1.0.0")]
Expand Down
22 changes: 22 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,28 @@ fn test_chunks_mut_nth() {
assert_eq!(c2.next(), None);
}

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

let v1: &mut [i32] = &mut [0, 1, 2, 3, 4];
let mut c1 = v1.chunks_mut(3);
assert_eq!(c1.nth_back(1).unwrap(), &[0, 1, 2]);
assert_eq!(c1.next(), None);

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

let v4: &mut [i32] = &mut [0, 1, 2];
let mut c4 = v4.chunks_mut(10);
assert_eq!(c4.nth_back(1_000_000_000usize), None);
}

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

0 comments on commit b95bde4

Please sign in to comment.