diff options
| author | @amit.chandra <@amit.chandra> | 2019-05-01 23:34:07 +0530 |
|---|---|---|
| committer | wizAmit <amitforfriends_dns@yahoo.com> | 2019-05-04 19:44:09 +0530 |
| commit | 73ca8bc140d4b0935ecb0199ea65723ec6a6791f (patch) | |
| tree | dba793350a53dbaeb4771678b98dc4c861d5743a /src | |
| parent | 4d9b9e9038102ada95d1898d303038803d752f62 (diff) | |
| download | rust-73ca8bc140d4b0935ecb0199ea65723ec6a6791f.tar.gz rust-73ca8bc140d4b0935ecb0199ea65723ec6a6791f.zip | |
hopefully working nth_back on chunks
Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/libcore/slice/mod.rs | 17 | ||||
| -rw-r--r-- | src/libcore/tests/slice.rs | 9 |
2 files changed, 17 insertions, 9 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 049d38c158c..00dbe7104d1 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -4154,18 +4154,19 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { } #[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 = &[]; + fn nth_back(&mut self, n: usize) -> Option<Self::Item> { + let (end, overflow) = self.v.len().overflowing_sub(n * self.chunk_size); + if overflow { + self.v = &mut []; None } else { let start = match end.checked_sub(self.chunk_size) { - Some(sum) => cmp::min(self.v.len(), sum), - None => self.v.len(), + Some(res) => cmp::min(self.v.len(), res), + None => 0, }; - let nth = &self.v[start..end]; - self.v = &self.v[end..]; + let nth_back = &self.v[start..end]; + self.v = &self.v[..start]; + Some(nth_back) } } } diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index 0233b96d3a7..edea405fad7 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -139,12 +139,19 @@ 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]); + assert_eq!(c.next().unwrap(), &[0, 1]); + assert_eq!(c.next(), None); 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); + assert_eq!(c2.next_back(), None); + + let v3: &[i32] = &[0, 1, 2, 3, 4]; + let mut c3 = v3.chunks(10); + assert_eq!(c3.nth_back(0).unwrap(), &[0, 1, 2, 3, 4]); + assert_eq!(c3.next(), None); } #[test] |
