diff options
| author | kennytm <kennytm@gmail.com> | 2019-03-24 15:32:52 +0800 |
|---|---|---|
| committer | kennytm <kennytm@gmail.com> | 2019-03-24 19:00:10 +0800 |
| commit | cb2dde63d5cdcee619ad65de79029629ccee7604 (patch) | |
| tree | 8872664023450cea7a751b0f445e63e2b60379d2 /src/libcore | |
| parent | 1d286f7918307f1b2bfa9a157070cc99c0465f30 (diff) | |
| parent | 739ba0417ae6477ffc9c5e8298b5075725d52420 (diff) | |
| download | rust-cb2dde63d5cdcee619ad65de79029629ccee7604.tar.gz rust-cb2dde63d5cdcee619ad65de79029629ccee7604.zip | |
Rollup merge of #59328 - koalatux:iter-nth-back, r=scottmcm
Implement specialized nth_back() for Box and Windows. Hi there, this is my first pull request to rust :-) I started implementing some specializations for DoubleEndedIterator::nth_back() and these are the first two. The problem has been discussed in #54054 and nth_back() is tracked in #56995. I'm stuck with the next implementation so I though I do a PR for the ones I'm confident with to get some feedback.
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/slice/mod.rs | 13 | ||||
| -rw-r--r-- | src/libcore/tests/slice.rs | 13 |
2 files changed, 26 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index b3594f8a385..4eb5bddb5d2 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -3867,6 +3867,19 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> { ret } } + + #[inline] + fn nth_back(&mut self, n: usize) -> Option<Self::Item> { + let (end, overflow) = self.v.len().overflowing_sub(n); + if end < self.size || overflow { + self.v = &[]; + None + } else { + let ret = &self.v[end-self.size..end]; + self.v = &self.v[..end-1]; + Some(ret) + } + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index ac9c17a0f7c..4946fd52a7e 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -579,6 +579,19 @@ fn test_windows_nth() { } #[test] +fn test_windows_nth_back() { + let v: &[i32] = &[0, 1, 2, 3, 4, 5]; + let mut c = v.windows(2); + assert_eq!(c.nth_back(2).unwrap()[0], 2); + assert_eq!(c.next_back().unwrap()[1], 2); + + let v2: &[i32] = &[0, 1, 2, 3, 4]; + let mut c2 = v2.windows(4); + assert_eq!(c2.nth_back(1).unwrap()[1], 1); + assert_eq!(c2.next_back(), None); +} + +#[test] fn test_windows_last() { let v: &[i32] = &[0, 1, 2, 3, 4, 5]; let c = v.windows(2); |
