Rollup merge of #60023 - koalatux:nth-back, r=scottmcm

implement specialized nth_back() for Bytes, Fuse and Enumerate

Hi,

After my first PR has been successfully merged, here is my second pull request :-)

Also this PR contains some specializations for the problem discussed in #54054.
This commit is contained in:
Mazdak Farrokhzad 2019-04-19 06:03:12 +02:00 committed by GitHub
commit 291e44b381
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 0 deletions

View File

@ -981,6 +981,16 @@ impl<I> DoubleEndedIterator for Enumerate<I> where
})
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
self.iter.nth_back(n).map(|a| {
let len = self.iter.len();
// Can safely add, `ExactSizeIterator` promises that the number of
// elements fits into a `usize`.
(self.count + len, a)
})
}
#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
@ -1790,6 +1800,17 @@ impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
}
}
#[inline]
default fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
if self.done {
None
} else {
let nth = self.iter.nth_back(n);
self.done = nth.is_none();
nth
}
}
#[inline]
default fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
@ -1878,6 +1899,11 @@ impl<I> DoubleEndedIterator for Fuse<I>
self.iter.next_back()
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
self.iter.nth_back(n)
}
#[inline]
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>

View File

@ -795,6 +795,11 @@ impl DoubleEndedIterator for Bytes<'_> {
self.0.next_back()
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
self.0.nth_back(n)
}
#[inline]
fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where
P: FnMut(&Self::Item) -> bool

View File

@ -389,6 +389,24 @@ fn test_iterator_enumerate_nth() {
assert_eq!(i, 3);
}
#[test]
fn test_iterator_enumerate_nth_back() {
let xs = [0, 1, 2, 3, 4, 5];
let mut it = xs.iter().enumerate();
while let Some((i, &x)) = it.nth_back(0) {
assert_eq!(i, x);
}
let mut it = xs.iter().enumerate();
while let Some((i, &x)) = it.nth_back(1) {
assert_eq!(i, x);
}
let (i, &x) = xs.iter().enumerate().nth_back(3).unwrap();
assert_eq!(i, x);
assert_eq!(i, 2);
}
#[test]
fn test_iterator_enumerate_count() {
let xs = [0, 1, 2, 3, 4, 5];