Skip to content

Commit 3e08f1b

Browse files
authored
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
2 parents 3c805ce + e80a375 commit 3e08f1b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/libcore/iter/adapters/mod.rs

+14
Original file line numberDiff line numberDiff line change
@@ -1509,6 +1509,20 @@ impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSize
15091509
}
15101510
}
15111511

1512+
#[inline]
1513+
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1514+
let len = self.len();
1515+
if n < len {
1516+
self.iter.nth_back(n)
1517+
} else {
1518+
if len > 0 {
1519+
// consume the original iterator
1520+
self.iter.nth_back(len-1);
1521+
}
1522+
None
1523+
}
1524+
}
1525+
15121526
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
15131527
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
15141528
{

src/libcore/tests/iter.rs

+34
Original file line numberDiff line numberDiff line change
@@ -2333,6 +2333,40 @@ fn test_skip_try_folds() {
23332333
assert_eq!(iter.next_back(), Some(24));
23342334
}
23352335

2336+
#[test]
2337+
fn test_skip_nth_back() {
2338+
let xs = [0, 1, 2, 3, 4, 5];
2339+
let mut it = xs.iter().skip(2);
2340+
assert_eq!(it.nth_back(0), Some(&5));
2341+
assert_eq!(it.nth_back(1), Some(&3));
2342+
assert_eq!(it.nth_back(0), Some(&2));
2343+
assert_eq!(it.nth_back(0), None);
2344+
2345+
let ys = [2, 3, 4, 5];
2346+
let mut ity = ys.iter();
2347+
let mut it = xs.iter().skip(2);
2348+
assert_eq!(it.nth_back(1), ity.nth_back(1));
2349+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2350+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2351+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2352+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2353+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2354+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2355+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2356+
2357+
let mut it = xs.iter().skip(2);
2358+
assert_eq!(it.nth_back(4), None);
2359+
assert_eq!(it.nth_back(0), None);
2360+
2361+
let mut it = xs.iter();
2362+
it.by_ref().skip(2).nth_back(3);
2363+
assert_eq!(it.next_back(), Some(&1));
2364+
2365+
let mut it = xs.iter();
2366+
it.by_ref().skip(2).nth_back(10);
2367+
assert_eq!(it.next_back(), Some(&1));
2368+
}
2369+
23362370
#[test]
23372371
fn test_take_try_folds() {
23382372
let f = &|acc, x| i32::checked_add(2*acc, x);

0 commit comments

Comments
 (0)