Skip to content

Commit dc82626

Browse files
@amit.chandrawizAmit
@amit.chandra
authored andcommitted
wip nth_back on chunks
Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
1 parent 37ff5d3 commit dc82626

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/libcore/slice/mod.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4178,6 +4178,22 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
41784178
Some(snd)
41794179
}
41804180
}
4181+
4182+
#[inline]
4183+
fn nth_back(&mut self, n: usize) {
4184+
let (end, overflow) = self.v.len().overflowing_sub(n);
4185+
if end < self.v.len() || overflow {
4186+
self.v = &[];
4187+
None
4188+
} else {
4189+
let start = match end.checked_sub(self.chunk_size) {
4190+
Some(sum) => cmp::min(self.v.len(), sum),
4191+
None => self.v.len(),
4192+
};
4193+
let nth = &self.v[start..end];
4194+
self.v = &self.v[end..];
4195+
}
4196+
}
41814197
}
41824198

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

src/libcore/tests/slice.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ 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(), &[4, 5]);
143+
144+
let v2: &[i32] = &[0, 1, 2, 3, 4];
145+
let mut c2 = v2.chunks(3);
146+
assert_eq!(c2.nth_back(1).unwrap(), &[0, 1]);
147+
assert_eq!(c2.next(), None);
148+
}
149+
137150
#[test]
138151
fn test_chunks_last() {
139152
let v: &[i32] = &[0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)