Skip to content

Commit

Permalink
feat(FilterMapOk): implement DoubleEndedIterator
Browse files Browse the repository at this point in the history
Refs: #947
  • Loading branch information
Xenira authored and Philippe-Cholet committed May 27, 2024
1 parent 23bf81a commit ad5cc96
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 @@ -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

0 comments on commit ad5cc96

Please sign in to comment.