diff options
| author | @amit.chandra <@amit.chandra> | 2019-04-26 19:53:18 +0530 |
|---|---|---|
| committer | wizAmit <amitforfriends_dns@yahoo.com> | 2019-05-22 21:58:57 +0530 |
| commit | dc82626262605665bbcea8f24925442e48dc897c (patch) | |
| tree | 6ee192d0f1e4e0bf943fbe93d3a0bbff25c1d18c | |
| parent | 37ff5d388f8c004ca248adb635f1cc84d347eda0 (diff) | |
| download | rust-dc82626262605665bbcea8f24925442e48dc897c.tar.gz rust-dc82626262605665bbcea8f24925442e48dc897c.zip | |
wip nth_back on chunks
Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
| -rw-r--r-- | src/libcore/slice/mod.rs | 16 | ||||
| -rw-r--r-- | src/libcore/tests/slice.rs | 13 |
2 files changed, 29 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index d06d107d32a..54c5285bc49 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -4178,6 +4178,22 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { Some(snd) } } + + #[inline] + fn nth_back(&mut self, n: usize) { + let (end, overflow) = self.v.len().overflowing_sub(n); + if end < self.v.len() || overflow { + self.v = &[]; + None + } else { + let start = match end.checked_sub(self.chunk_size) { + Some(sum) => cmp::min(self.v.len(), sum), + None => self.v.len(), + }; + let nth = &self.v[start..end]; + self.v = &self.v[end..]; + } + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index acf6b03791f..0233b96d3a7 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -135,6 +135,19 @@ fn test_chunks_nth() { } #[test] +fn test_chunks_nth_back() { + let v: &[i32] = &[0, 1, 2, 3, 4, 5]; + let mut c = v.chunks(2); + assert_eq!(c.nth_back(1).unwrap(), &[2, 3]); + assert_eq!(c.next().unwrap(), &[4, 5]); + + let v2: &[i32] = &[0, 1, 2, 3, 4]; + let mut c2 = v2.chunks(3); + assert_eq!(c2.nth_back(1).unwrap(), &[0, 1]); + assert_eq!(c2.next(), None); +} + +#[test] fn test_chunks_last() { let v: &[i32] = &[0, 1, 2, 3, 4, 5]; let c = v.chunks(2); |
