use crate::parallel::Reduce;
#[cfg(not(feature = "parallel"))]
mod not_parallel {
pub fn join<O1, O2>(left: impl FnOnce() -> O1, right: impl FnOnce() -> O2) -> (O1, O2) {
(left(), right())
}
pub struct Scope<'env> {
_marker: std::marker::PhantomData<&'env mut &'env ()>,
}
pub struct ThreadBuilder<'a, 'env> {
scope: &'a Scope<'env>,
}
#[allow(unsafe_code)]
unsafe impl Sync for Scope<'_> {}
impl<'a, 'env> ThreadBuilder<'a, 'env> {
pub fn name(self, _new: String) -> Self {
self
}
pub fn spawn<F, T>(&self, f: F) -> std::io::Result<ScopedJoinHandle<'a, T>>
where
F: FnOnce(&Scope<'env>) -> T,
F: Send + 'env,
T: Send + 'env,
{
Ok(self.scope.spawn(f))
}
}
impl<'env> Scope<'env> {
pub fn builder(&self) -> ThreadBuilder<'_, 'env> {
ThreadBuilder { scope: self }
}
pub fn spawn<'scope, F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
where
F: FnOnce(&Scope<'env>) -> T,
F: Send + 'env,
T: Send + 'env,
{
ScopedJoinHandle {
result: f(self),
_marker: Default::default(),
}
}
}
pub fn threads<'env, F, R>(f: F) -> std::thread::Result<R>
where
F: FnOnce(&Scope<'env>) -> R,
{
Ok(f(&Scope {
_marker: Default::default(),
}))
}
pub struct ScopedJoinHandle<'scope, T> {
result: T,
_marker: std::marker::PhantomData<&'scope mut &'scope ()>,
}
impl<T> ScopedJoinHandle<'_, T> {
pub fn join(self) -> std::thread::Result<T> {
Ok(self.result)
}
}
pub fn in_parallel_with_slice<I, S, R, E>(
input: &mut [I],
_thread_limit: Option<usize>,
mut new_thread_state: impl FnMut(usize) -> S + Clone,
mut consume: impl FnMut(&mut I, &mut S) -> Result<(), E> + Clone,
mut periodic: impl FnMut() -> Option<std::time::Duration>,
state_to_rval: impl FnOnce(S) -> R + Clone,
) -> Result<Vec<R>, E> {
let mut state = new_thread_state(0);
for item in input {
consume(item, &mut state)?;
if periodic().is_none() {
break;
}
}
Ok(vec![state_to_rval(state)])
}
}
#[cfg(not(feature = "parallel"))]
pub use not_parallel::{in_parallel_with_slice, join, threads, Scope, ScopedJoinHandle};
pub fn in_parallel<I, S, O, R>(
input: impl Iterator<Item = I>,
_thread_limit: Option<usize>,
new_thread_state: impl Fn(usize) -> S,
consume: impl Fn(I, &mut S) -> O,
mut reducer: R,
) -> Result<<R as Reduce>::Output, <R as Reduce>::Error>
where
R: Reduce<Input = O>,
{
let mut state = new_thread_state(0);
for item in input {
drop(reducer.feed(consume(item, &mut state))?);
}
reducer.finalize()
}