Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(FilterMapOk): implement DoubleEndedIterator #950

Merged
merged 2 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benches/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,7 @@ bench_specializations! {
v.iter().copied().filter_ok(|x| x % 3 == 0)
}
filter_map_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 @@ -1041,6 +1041,30 @@ where
}
}

impl<I, F, T, U, E> DoubleEndedIterator for FilterMapOk<I, F>
where
I: DoubleEndedIterator<Item = Result<T, E>>,
F: FnMut(T) -> Option<U>,
{
fn next_back(&mut self) -> Option<Self::Item> {
let f = &mut self.f;
self.iter.by_ref().rev().find_map(|res| match res {
Ok(t) => f(t).map(Ok),
Err(e) => Some(Err(e)),
})
}

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_map(|v| transpose_result(v.map(&mut f)))
.rfold(init, fold_f)
}
}

impl<I, F, T, U, E> FusedIterator for FilterMapOk<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 @@ -453,7 +453,9 @@ quickcheck! {
}

fn filter_map_ok(v: Vec<Result<u8, char>>) -> () {
test_specializations(&v.into_iter().filter_map_ok(|i| if i < 20 { Some(i * 2) } else { None }));
let it = v.into_iter().filter_map_ok(|i| if i < 20 { Some(i * 2) } else { None });
test_specializations(&it);
test_double_ended_specializations(&it);
}

// `SmallIter2<u8>` because `Vec<u8>` is too slow and we get bad coverage from a singleton like Option<u8>
Expand Down