Skip to content

Commit e80a375

Browse files
committed
Add custom nth_back for Skip
1 parent 758dc9a commit e80a375

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
@@ -2280,6 +2280,40 @@ fn test_skip_try_folds() {
22802280
assert_eq!(iter.next_back(), Some(24));
22812281
}
22822282

2283+
#[test]
2284+
fn test_skip_nth_back() {
2285+
let xs = [0, 1, 2, 3, 4, 5];
2286+
let mut it = xs.iter().skip(2);
2287+
assert_eq!(it.nth_back(0), Some(&5));
2288+
assert_eq!(it.nth_back(1), Some(&3));
2289+
assert_eq!(it.nth_back(0), Some(&2));
2290+
assert_eq!(it.nth_back(0), None);
2291+
2292+
let ys = [2, 3, 4, 5];
2293+
let mut ity = ys.iter();
2294+
let mut it = xs.iter().skip(2);
2295+
assert_eq!(it.nth_back(1), ity.nth_back(1));
2296+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2297+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2298+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2299+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2300+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2301+
assert_eq!(it.nth_back(0), ity.nth_back(0));
2302+
assert_eq!(it.clone().nth(0), ity.clone().nth(0));
2303+
2304+
let mut it = xs.iter().skip(2);
2305+
assert_eq!(it.nth_back(4), None);
2306+
assert_eq!(it.nth_back(0), None);
2307+
2308+
let mut it = xs.iter();
2309+
it.by_ref().skip(2).nth_back(3);
2310+
assert_eq!(it.next_back(), Some(&1));
2311+
2312+
let mut it = xs.iter();
2313+
it.by_ref().skip(2).nth_back(10);
2314+
assert_eq!(it.next_back(), Some(&1));
2315+
}
2316+
22832317
#[test]
22842318
fn test_take_try_folds() {
22852319
let f = &|acc, x| i32::checked_add(2*acc, x);

0 commit comments

Comments
 (0)