Add custom nth_back for Chain
This commit is contained in:
parent
d15fc17381
commit
7b6ad60672
2 changed files with 39 additions and 0 deletions
|
@ -207,6 +207,29 @@ impl<A, B> DoubleEndedIterator for Chain<A, B> where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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
|
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>
|
Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||||
{
|
{
|
||||||
|
|
|
@ -103,6 +103,22 @@ fn test_iterator_chain_nth() {
|
||||||
assert_eq!(it.next(), None);
|
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]
|
#[test]
|
||||||
fn test_iterator_chain_last() {
|
fn test_iterator_chain_last() {
|
||||||
let xs = [0, 1, 2, 3, 4, 5];
|
let xs = [0, 1, 2, 3, 4, 5];
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue