Skip to content

Commit

Permalink
Rollup merge of rust-lang#60454 - acrrd:issues/54054_skip, r=scottmcm
Browse files Browse the repository at this point in the history
Add custom nth_back to Skip

Implementation of nth_back for Skip.
Part of rust-lang#54054
  • Loading branch information
Centril authored Jun 20, 2019
2 parents 3c805ce + e80a375 commit 3e08f1b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/libcore/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>
{
Expand Down
34 changes: 34 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 3e08f1b

Please sign in to comment.