Use filter_map in try_par_for_each_in

This simplifies the expression, especially for the rayon part, and also
lets us drop the `E: Copy` constraint.
This commit is contained in:
Josh Stone 2023-11-03 09:17:16 -07:00
parent a026bd49e1
commit 3984914aff

View File

@ -77,12 +77,12 @@ pub fn par_for_each_in<T: IntoIterator>(t: T, mut for_each: impl FnMut(T::Item))
}) })
} }
pub fn try_par_for_each_in<T: IntoIterator, E: Copy>( pub fn try_par_for_each_in<T: IntoIterator, E>(
t: T, t: T,
mut for_each: impl FnMut(T::Item) -> Result<(), E>, mut for_each: impl FnMut(T::Item) -> Result<(), E>,
) -> Result<(), E> { ) -> Result<(), E> {
parallel_guard(|guard| { parallel_guard(|guard| {
t.into_iter().fold(Ok(()), |ret, i| guard.run(|| for_each(i)).unwrap_or(ret).and(ret)) t.into_iter().filter_map(|i| guard.run(|| for_each(i))).fold(Ok(()), Result::and)
}) })
} }
@ -178,7 +178,7 @@ pub fn par_for_each_in<I, T: IntoIterator<Item = I> + IntoParallelIterator<Item
pub fn try_par_for_each_in< pub fn try_par_for_each_in<
T: IntoIterator + IntoParallelIterator<Item = <T as IntoIterator>::Item>, T: IntoIterator + IntoParallelIterator<Item = <T as IntoIterator>::Item>,
E: Copy + Send, E: Send,
>( >(
t: T, t: T,
for_each: impl Fn(<T as IntoIterator>::Item) -> Result<(), E> + DynSync + DynSend, for_each: impl Fn(<T as IntoIterator>::Item) -> Result<(), E> + DynSync + DynSend,
@ -187,11 +187,10 @@ pub fn try_par_for_each_in<
if mode::is_dyn_thread_safe() { if mode::is_dyn_thread_safe() {
let for_each = FromDyn::from(for_each); let for_each = FromDyn::from(for_each);
t.into_par_iter() t.into_par_iter()
.fold_with(Ok(()), |ret, i| guard.run(|| for_each(i)).unwrap_or(ret).and(ret)) .filter_map(|i| guard.run(|| for_each(i)))
.reduce(|| Ok(()), |a, b| a.and(b)) .reduce(|| Ok(()), Result::and)
} else { } else {
t.into_iter() t.into_iter().filter_map(|i| guard.run(|| for_each(i))).fold(Ok(()), Result::and)
.fold(Ok(()), |ret, i| guard.run(|| for_each(i)).unwrap_or(ret).and(ret))
} }
}) })
} }