diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-07-03 09:59:12 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-07-03 09:59:12 -0400 |
| commit | 619df2e0c9b8b8190df4cc4a14a57ee7696b06ed (patch) | |
| tree | 3baa93a3f341fabc1573fbe738afdc661bce5e2a | |
| parent | 7d5d59160a5e1f535ddfebb6cee22839cd253673 (diff) | |
| parent | 45832383af02a377877c2701d90dbe29883532a2 (diff) | |
| download | rust-619df2e0c9b8b8190df4cc4a14a57ee7696b06ed.tar.gz rust-619df2e0c9b8b8190df4cc4a14a57ee7696b06ed.zip | |
Rollup merge of #62064 - wizAmit:feature/chunks_exact_nth_back, r=scottmcm
nth_back for chunks_exact wip nth_back for chunks_exact working nth_back for chunks exact Signed-off-by: wizAmit <amitforfriends_dns@yahoo.com> r? @timvermeulen r? @scottmcm
| -rw-r--r-- | src/libcore/slice/mod.rs | 15 | ||||
| -rw-r--r-- | src/libcore/tests/slice.rs | 19 |
2 files changed, 34 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index c6d44324ef5..fe48e2458cd 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -4453,6 +4453,21 @@ impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> { Some(snd) } } + + #[inline] + fn nth_back(&mut self, n: usize) -> Option<Self::Item> { + let len = self.len(); + if n >= len { + self.v = &[]; + None + } else { + let start = (len - 1 - n) * self.chunk_size; + let end = start + self.chunk_size; + let nth_back = &self.v[start..end]; + self.v = &self.v[..start]; + Some(nth_back) + } + } } #[stable(feature = "chunks_exact", since = "1.31.0")] diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index 03e65d2fe0b..13b02c71842 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -276,6 +276,25 @@ fn test_chunks_exact_nth() { } #[test] +fn test_chunks_exact_nth_back() { + let v: &[i32] = &[0, 1, 2, 3, 4, 5]; + let mut c = v.chunks_exact(2); + assert_eq!(c.nth_back(1).unwrap(), &[2, 3]); + 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_exact(3); + assert_eq!(c2.nth_back(0).unwrap(), &[0, 1, 2]); + assert_eq!(c2.next(), None); + assert_eq!(c2.next_back(), None); + + let v3: &[i32] = &[0, 1, 2, 3, 4]; + let mut c3 = v3.chunks_exact(10); + assert_eq!(c3.nth_back(0), None); +} + +#[test] fn test_chunks_exact_last() { let v: &[i32] = &[0, 1, 2, 3, 4, 5]; let c = v.chunks_exact(2); |
