Skip to main content

binius_utils/rayon/
mod.rs

1// Copyright 2024-2025 Irreducible Inc.
2//
3// The code is initially based on `maybe-rayon` crate, https://github.com/shssoichiro/maybe-rayon
4// Original: Copyright (c) 2021 Joshua Holmer
5// Licensed under MIT License
6
7//! This crate provides a subset of the `rayon` API to allow conditional
8//! compilation without `rayon`.
9//! This is useful for profiling single-threaded code, as it simplifies call stacks significantly.
10//! The initial code was taken from the `maybe-rayon` crate, but many changes were made to
11//! support the usage of `ParallelIterator` and `IndexedParallelIterator` methods, which have
12//! different signatures from `std::iter::Iterator`. Some of these changes may be potentially
13//! backward-incompatible, and given the absence of tests in the original crate, it is very unlikely
14//! that it is possible to commit the changes back to the original crate.
15
16cfg_if::cfg_if! {
17	if #[cfg(any(not(feature = "rayon"), all(target_arch="wasm32", not(target_feature = "atomics"))))] {
18		pub mod iter;
19		pub mod slice;
20
21		pub mod prelude {
22			pub use super::{iter::*, slice::*};
23		}
24
25		#[derive(Default)]
26		pub struct ThreadPoolBuilder();
27		impl ThreadPoolBuilder {
28			#[inline(always)]
29			pub const fn new() -> Self {
30				Self()
31			}
32
33			#[inline(always)]
34			pub const fn build(self) -> Result<ThreadPool, ::core::convert::Infallible> {
35				Ok(ThreadPool())
36			}
37
38			#[inline(always)]
39			pub const fn num_threads(self, _num_threads: usize) -> Self {
40				Self()
41			}
42
43			#[inline(always)]
44			pub const fn use_current_thread(self) -> Self {
45				Self()
46			}
47
48			#[inline(always)]
49			pub const fn build_global(self) -> Result<(), ThreadPoolBuildError> {
50				Ok(())
51			}
52		}
53
54		#[derive(Debug)]
55		pub struct ThreadPool();
56		impl ThreadPool {
57			#[inline(always)]
58			pub fn install<OP, R>(&self, op: OP) -> R
59			where
60				OP: FnOnce() -> R + Send,
61				R: Send,
62			{
63				op()
64			}
65		}
66
67		#[derive(Debug, Default)]
68		pub struct ThreadPoolBuildError;
69		impl std::fmt::Display for ThreadPoolBuildError {
70			fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71				write!(f, "ThreadPoolBuildError")
72			}
73		}
74		impl std::error::Error for ThreadPoolBuildError {}
75
76		#[inline(always)]
77		pub const fn current_num_threads() -> usize {
78			1
79		}
80
81		#[inline(always)]
82		pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
83		where
84			A: FnOnce() -> RA + Send,
85			B: FnOnce() -> RB + Send,
86			RA: Send,
87			RB: Send,
88		{
89			(oper_a(), oper_b())
90		}
91	} else {
92		pub use rayon::*;
93	}
94}
95
96pub mod config;
97pub mod task_size;