Skip to content

Commit aad084a

Browse files
authored
Rollup merge of rust-lang#61048 - wizAmit:feature/nth_back_chunks, r=scottmcm
Feature/nth back chunks A succinct implementation for nth_back on chunks. Thank you @timvermeulen for the guidance. r? @timvermeulen
2 parents c98841b + bcfd1f3 commit aad084a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/libcore/slice/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4158,6 +4158,24 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
41584158
Some(snd)
41594159
}
41604160
}
4161+
4162+
#[inline]
4163+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4164+
let len = self.len();
4165+
if n >= len {
4166+
self.v = &[];
4167+
None
4168+
} else {
4169+
let start = (len - 1 - n) * self.chunk_size;
4170+
let end = match start.checked_add(self.chunk_size) {
4171+
Some(res) => cmp::min(res, self.v.len()),
4172+
None => self.v.len(),
4173+
};
4174+
let nth_back = &self.v[start..end];
4175+
self.v = &self.v[..start];
4176+
Some(nth_back)
4177+
}
4178+
}
41614179
}
41624180

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

src/libcore/tests/slice.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,30 @@ fn test_chunks_nth() {
134134
assert_eq!(c2.next(), None);
135135
}
136136

137+
#[test]
138+
fn test_chunks_nth_back() {
139+
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
140+
let mut c = v.chunks(2);
141+
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
142+
assert_eq!(c.next().unwrap(), &[0, 1]);
143+
assert_eq!(c.next(), None);
144+
145+
let v2: &[i32] = &[0, 1, 2, 3, 4];
146+
let mut c2 = v2.chunks(3);
147+
assert_eq!(c2.nth_back(1).unwrap(), &[0, 1, 2]);
148+
assert_eq!(c2.next(), None);
149+
assert_eq!(c2.next_back(), None);
150+
151+
let v3: &[i32] = &[0, 1, 2, 3, 4];
152+
let mut c3 = v3.chunks(10);
153+
assert_eq!(c3.nth_back(0).unwrap(), &[0, 1, 2, 3, 4]);
154+
assert_eq!(c3.next(), None);
155+
156+
let v4: &[i32] = &[0, 1, 2];
157+
let mut c4 = v4.chunks(10);
158+
assert_eq!(c4.nth_back(1_000_000_000usize), None);
159+
}
160+
137161
#[test]
138162
fn test_chunks_last() {
139163
let v: &[i32] = &[0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)