From 4837fb45ff41ad8ff4c6dfc9bd3f8056959f3d4e Mon Sep 17 00:00:00 2001 From: Adrian Friedli Date: Sat, 16 Feb 2019 22:34:28 +0100 Subject: [PATCH 1/2] implement nth_back for Box --- src/liballoc/boxed.rs | 3 +++ src/liballoc/lib.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 51549f92d4dbf..1e3ccf90eb87f 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -662,6 +662,9 @@ impl DoubleEndedIterator for Box { fn next_back(&mut self) -> Option { (**self).next_back() } + fn nth_back(&mut self, n: usize) -> Option { + (**self).nth_back(n) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for Box { diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 95b9dacf8565a..da1afc2ff8aa3 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -115,6 +115,7 @@ #![feature(maybe_uninit)] #![feature(alloc_layout_extra)] #![feature(try_trait)] +#![feature(iter_nth_back)] // Allow testing this library From 739ba0417ae6477ffc9c5e8298b5075725d52420 Mon Sep 17 00:00:00 2001 From: Adrian Friedli Date: Sun, 24 Feb 2019 00:22:41 +0100 Subject: [PATCH 2/2] implement nth_back for Windows --- src/libcore/slice/mod.rs | 13 +++++++++++++ src/libcore/tests/slice.rs | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index acca9748372ca..b048a12e402a5 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -3835,6 +3835,19 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> { ret } } + + #[inline] + fn nth_back(&mut self, n: usize) -> Option { + 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 04d646ea01d03..1e92b6f787870 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -578,6 +578,19 @@ fn test_windows_nth() { assert_eq!(c2.next(), None); } +#[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];