Skip to content

Commit aff83c8

Browse files
@amit.chandrawizAmit
@amit.chandra
authored andcommitted
hopefully working nth_back on chunks
Signed-off-by: wizAmit <[email protected]>
1 parent 02a148d commit aff83c8

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

src/libcore/slice/mod.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -4154,18 +4154,19 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
41544154
}
41554155

41564156
#[inline]
4157-
fn nth_back(&mut self, n: usize) {
4158-
let (end, overflow) = self.v.len().overflowing_sub(n);
4159-
if end < self.v.len() || overflow {
4160-
self.v = &[];
4157+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4158+
let (end, overflow) = self.v.len().overflowing_sub(n * self.chunk_size);
4159+
if overflow {
4160+
self.v = &mut [];
41614161
None
41624162
} else {
41634163
let start = match end.checked_sub(self.chunk_size) {
4164-
Some(sum) => cmp::min(self.v.len(), sum),
4165-
None => self.v.len(),
4164+
Some(res) => cmp::min(self.v.len(), res),
4165+
None => 0,
41664166
};
4167-
let nth = &self.v[start..end];
4168-
self.v = &self.v[end..];
4167+
let nth_back = &self.v[start..end];
4168+
self.v = &self.v[..start];
4169+
Some(nth_back)
41694170
}
41704171
}
41714172
}

src/libcore/tests/slice.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -139,12 +139,19 @@ fn test_chunks_nth_back() {
139139
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
140140
let mut c = v.chunks(2);
141141
assert_eq!(c.nth_back(1).unwrap(), &[2, 3]);
142-
assert_eq!(c.next().unwrap(), &[4, 5]);
142+
assert_eq!(c.next().unwrap(), &[0, 1]);
143+
assert_eq!(c.next(), None);
143144

144145
let v2: &[i32] = &[0, 1, 2, 3, 4];
145146
let mut c2 = v2.chunks(3);
146147
assert_eq!(c2.nth_back(1).unwrap(), &[0, 1]);
147148
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);
148155
}
149156

150157
#[test]

0 commit comments

Comments
 (0)