Rollup merge of #60492 - acrrd:issues/54054_chain, r=SimonSapin

Add custom nth_back for Chain

Implementation of nth_back for Chain.
Part of #54054
This commit is contained in:
Mazdak Farrokhzad 2019-08-16 18:22:20 +02:00 committed by GitHub
commit e632dafba2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 0 deletions

View File

@ -207,6 +207,29 @@ fn next_back(&mut self) -> Option<A::Item> {
}
}
#[inline]
fn nth_back(&mut self, mut n: usize) -> Option<A::Item> {
match self.state {
ChainState::Both | ChainState::Back => {
for x in self.b.by_ref().rev() {
if n == 0 {
return Some(x)
}
n -= 1;
}
if let ChainState::Both = self.state {
self.state = ChainState::Front;
}
}
ChainState::Front => {}
}
if let ChainState::Front = self.state {
self.a.nth_back(n)
} else {
None
}
}
fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
{

View File

@ -103,6 +103,22 @@ fn test_iterator_chain_nth() {
assert_eq!(it.next(), None);
}
#[test]
fn test_iterator_chain_nth_back() {
let xs = [0, 1, 2, 3, 4, 5];
let ys = [30, 40, 50, 60];
let zs = [];
let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
for (i, x) in expected.iter().rev().enumerate() {
assert_eq!(Some(x), xs.iter().chain(&ys).nth_back(i));
}
assert_eq!(zs.iter().chain(&xs).nth_back(0), Some(&5));
let mut it = xs.iter().chain(&zs);
assert_eq!(it.nth_back(5), Some(&0));
assert_eq!(it.next(), None);
}
#[test]
fn test_iterator_chain_last() {
let xs = [0, 1, 2, 3, 4, 5];