Rollup merge of #60454 - acrrd:issues/54054_skip, r=scottmcm

Add custom nth_back to Skip

Implementation of nth_back for Skip.
Part of #54054
This commit is contained in:
Mazdak Farrokhzad 2019-06-20 08:35:58 +02:00 committed by GitHub
commit 3e08f1b57e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -1509,6 +1509,20 @@ impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSize
}
}
#[inline]
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
let len = self.len();
if n < len {
self.iter.nth_back(n)
} else {
if len > 0 {
// consume the original iterator
self.iter.nth_back(len-1);
}
None
}
}
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>
{

View File

@ -2333,6 +2333,40 @@ fn test_skip_try_folds() {
assert_eq!(iter.next_back(), Some(24));
}
#[test]
fn test_skip_nth_back() {
let xs = [0, 1, 2, 3, 4, 5];
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(0), Some(&5));
assert_eq!(it.nth_back(1), Some(&3));
assert_eq!(it.nth_back(0), Some(&2));
assert_eq!(it.nth_back(0), None);
let ys = [2, 3, 4, 5];
let mut ity = ys.iter();
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(1), ity.nth_back(1));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
assert_eq!(it.nth_back(0), ity.nth_back(0));
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
let mut it = xs.iter().skip(2);
assert_eq!(it.nth_back(4), None);
assert_eq!(it.nth_back(0), None);
let mut it = xs.iter();
it.by_ref().skip(2).nth_back(3);
assert_eq!(it.next_back(), Some(&1));
let mut it = xs.iter();
it.by_ref().skip(2).nth_back(10);
assert_eq!(it.next_back(), Some(&1));
}
#[test]
fn test_take_try_folds() {
let f = &|acc, x| i32::checked_add(2*acc, x);