Skip to content

Commit

Permalink
feat(FilterOk): implement DoubleEndedIterator
Browse files Browse the repository at this point in the history
Refs: #947
  • Loading branch information
Xenira committed May 27, 2024
1 parent ac8fb03 commit d882491
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions benches/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,7 @@ bench_specializations! {
v.iter().copied().map_ok(|x| x + 1)
}
filter_ok {
DoubleEndedIterator
{
let v = black_box((0_u32..1024)
.map(|x| if x % 2 == 1 { Err(x) } else { Ok(x) })
Expand Down
24 changes: 24 additions & 0 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,30 @@ where
}
}

impl<I, F, T, E> DoubleEndedIterator for FilterOk<I, F>
where
I: DoubleEndedIterator<Item = Result<T, E>>,
F: FnMut(&T) -> bool,
{
fn next_back(&mut self) -> Option<Self::Item> {
let f = &mut self.f;
self.iter.rfind(|res| match res {
Ok(t) => f(t),
_ => true,
})
}

fn rfold<Acc, Fold>(self, init: Acc, fold_f: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
let mut f = self.f;
self.iter
.filter(|v| v.as_ref().map(&mut f).unwrap_or(true))
.rfold(init, fold_f)
}
}

impl<I, F, T, E> FusedIterator for FilterOk<I, F>
where
I: FusedIterator<Item = Result<T, E>>,
Expand Down
4 changes: 3 additions & 1 deletion tests/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,9 @@ quickcheck! {
}

fn filter_ok(v: Vec<Result<u8, char>>) -> () {
test_specializations(&v.into_iter().filter_ok(|&i| i < 20));
let it = v.into_iter().filter_ok(|&i| i < 20);
test_specializations(&it);
test_double_ended_specializations(&it);
}

fn filter_map_ok(v: Vec<Result<u8, char>>) -> () {
Expand Down

0 comments on commit d882491

Please sign in to comment.