p3-maybe-rayon 0.6.2

Feature-gated wrapper around rayon
Documentation
//! Thin compatibility layer that re-exports either `rayon` or a sequential
//! fallback under a unified prelude, gated by the `parallel` feature.

#![no_std]

#[cfg(not(feature = "parallel"))]
mod serial;

pub mod prelude {
    #[cfg(not(feature = "parallel"))]
    pub use core::iter::{
        ExactSizeIterator as IndexedParallelIterator, Iterator as ParallelIterator,
    };
    use core::marker::{Send, Sync};

    #[cfg(feature = "parallel")]
    pub use rayon::prelude::*;
    #[cfg(feature = "parallel")]
    pub use rayon::{current_num_threads, join};

    #[cfg(not(feature = "parallel"))]
    pub use super::serial::*;

    pub trait SharedExt: ParallelIterator {
        /// Folds each split of the iterator with `fold_op` (seeded by `identity`), then
        /// combines the per-split accumulators with `reduce_op`.
        ///
        /// `identity()` must be neutral for `reduce_op`, and `fold_op`/`reduce_op` must be
        /// mutually associative so that regrouping splits doesn't change the result — under
        /// the `parallel` feature the split count (and thus how many times `reduce_op` runs)
        /// depends on the thread pool. **The serial fallback never calls `reduce_op`** (there
        /// is only one split), so an inconsistent `reduce_op` yields results that diverge
        /// between `cargo test` and `cargo test --features parallel`.
        fn par_fold_reduce<Acc, Id, F, R>(self, identity: Id, fold_op: F, reduce_op: R) -> Acc
        where
            Acc: Send,
            Id: Fn() -> Acc + Sync + Send,
            F: Fn(Acc, Self::Item) -> Acc + Sync + Send,
            R: Fn(Acc, Acc) -> Acc + Sync + Send;
    }

    impl<I: ParallelIterator> SharedExt for I {
        #[inline]
        fn par_fold_reduce<Acc, Id, F, R>(self, identity: Id, fold_op: F, reduce_op: R) -> Acc
        where
            Acc: Send,
            Id: Fn() -> Acc + Sync + Send,
            F: Fn(Acc, Self::Item) -> Acc + Sync + Send,
            R: Fn(Acc, Acc) -> Acc + Sync + Send,
        {
            #[cfg(feature = "parallel")]
            {
                self.fold(&identity, fold_op).reduce(&identity, reduce_op)
            }

            #[cfg(not(feature = "parallel"))]
            {
                let _ = reduce_op;
                self.fold(identity(), fold_op)
            }
        }
    }
}

pub mod iter {
    #[cfg(not(feature = "parallel"))]
    pub use core::iter::{repeat, repeat_n};

    #[cfg(feature = "parallel")]
    pub use rayon::iter::{repeat, repeat_n};
}