use alloc::vec::Vec;
use crate::error::Result;
pub(crate) type Threads = Option<usize>;
#[cfg(feature = "parallel")]
#[inline]
const fn is_serial(threads: Threads) -> bool {
matches!(threads, Some(0 | 1))
}
pub(crate) fn scope<R: Send>(threads: Threads, body: impl FnOnce(Threads) -> R + Send) -> R {
#[cfg(feature = "parallel")]
match threads {
Some(n) if n > 1 => {
return match rayon::ThreadPoolBuilder::new().num_threads(n).build() {
Ok(pool) => pool.install(|| body(None)),
Err(_) => body(Some(1)),
};
}
_ => {}
}
body(threads)
}
pub(crate) fn try_map<T, U, F>(items: &[T], threads: Threads, f: F) -> Result<Vec<U>>
where
T: Sync,
U: Send,
F: Fn(&T) -> Result<U> + Send + Sync,
{
#[cfg(feature = "parallel")]
if !is_serial(threads) {
use rayon::prelude::*;
return items.par_iter().map(&f).collect();
}
let _ = threads;
items.iter().map(f).collect()
}
#[cfg_attr(not(feature = "parallel"), allow(unused_variables))]
pub(crate) fn for_each_band<F>(
out: &mut [u8],
row_bytes: usize,
rows_per_band: usize,
threads: Threads,
f: F,
) where
F: Fn(usize, &mut [u8]) + Send + Sync,
{
#[cfg(feature = "parallel")]
if !is_serial(threads) && rows_per_band > 0 && row_bytes > 0 {
use rayon::prelude::*;
let band = rows_per_band * row_bytes;
out.par_chunks_mut(band)
.enumerate()
.for_each(|(i, dst)| f(i * rows_per_band, dst));
return;
}
f(0, out);
}