Skip to content

Commit cb8b491

Browse files
authored
Rollup merge of rust-lang#62074 - wizAmit:feature/mut_chunks_nth_back, r=scottmcm
squash of all commits for nth_back on ChunksMut wip nth_back for chunks_mut working chunksmut fixed nth_back for chunksmut Signed-off-by: wizAmit <[email protected]> r? @timvermeulen r? @scottmcm
2 parents ece18b7 + b95bde4 commit cb8b491

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/libcore/slice/mod.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4339,6 +4339,25 @@ impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
43394339
Some(tail)
43404340
}
43414341
}
4342+
4343+
#[inline]
4344+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4345+
let len = self.len();
4346+
if n >= len {
4347+
self.v = &mut [];
4348+
None
4349+
} else {
4350+
let start = (len - 1 - n) * self.chunk_size;
4351+
let end = match start.checked_add(self.chunk_size) {
4352+
Some(res) => cmp::min(res, self.v.len()),
4353+
None => self.v.len(),
4354+
};
4355+
let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4356+
let (head, nth_back) = temp.split_at_mut(start);
4357+
self.v = head;
4358+
Some(nth_back)
4359+
}
4360+
}
43424361
}
43434362

43444363
#[stable(feature = "rust1", since = "1.0.0")]

src/libcore/tests/slice.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,28 @@ fn test_chunks_mut_nth() {
222222
assert_eq!(c2.next(), None);
223223
}
224224

225+
#[test]
226+
fn test_chunks_mut_nth_back() {
227+
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
228+
let mut c = v.chunks_mut(2);
229+
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
230+
assert_eq!(c.next().unwrap(), &[0, 1]);
231+
232+
let v1: &mut [i32] = &mut [0, 1, 2, 3, 4];
233+
let mut c1 = v1.chunks_mut(3);
234+
assert_eq!(c1.nth_back(1).unwrap(), &[0, 1, 2]);
235+
assert_eq!(c1.next(), None);
236+
237+
let v3: &mut [i32] = &mut [0, 1, 2, 3, 4];
238+
let mut c3 = v3.chunks_mut(10);
239+
assert_eq!(c3.nth_back(0).unwrap(), &[0, 1, 2, 3, 4]);
240+
assert_eq!(c3.next(), None);
241+
242+
let v4: &mut [i32] = &mut [0, 1, 2];
243+
let mut c4 = v4.chunks_mut(10);
244+
assert_eq!(c4.nth_back(1_000_000_000usize), None);
245+
}
246+
225247
#[test]
226248
fn test_chunks_mut_last() {
227249
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)