Skip to main content

faer/utils/
mod.rs

1#![allow(missing_docs)]
2/// compile-time bound-checked indexing types
3pub mod bound;
4#[doc(hidden)]
5pub mod thread {
6	use crate::*;
7	/// executes the two operations, possibly in parallel, while splitting the
8	/// amount of parallelism between the two
9	#[inline]
10	pub fn join_raw(
11		op_a: impl Send + FnOnce(Par),
12		op_b: impl Send + FnOnce(Par),
13		parallelism: Par,
14	) {
15		fn implementation<'a>(
16			op_a: &'a mut (dyn Send + FnMut(Par)),
17			op_b: &'a mut (dyn Send + FnMut(Par)),
18			parallelism: Par,
19		) {
20			match parallelism {
21				Par::Seq => {
22					(op_a(parallelism), op_b(parallelism));
23				},
24				#[cfg(feature = "rayon")]
25				Par::Rayon(n_threads) => {
26					let n_threads = n_threads.get();
27					if n_threads == 1 {
28						(op_a(Par::Seq), op_b(Par::Seq));
29					} else {
30						let parallelism = Par::Rayon(
31							core::num::NonZeroUsize::new(
32								n_threads - n_threads / 2,
33							)
34							.unwrap(),
35						);
36						spindle::for_each(2, [op_a, op_b], |op| {
37							op(parallelism)
38						});
39					}
40				},
41			};
42		}
43		let mut op_a = Some(op_a);
44		let mut op_b = Some(op_b);
45		implementation(
46			&mut |parallelism| op_a.take().unwrap()(parallelism),
47			&mut |parallelism| op_b.take().unwrap()(parallelism),
48			parallelism,
49		)
50	}
51	/// unsafe [`Send`] and [`Sync`] pointer type
52	pub struct Ptr<T>(pub *mut T);
53	unsafe impl<T> Send for Ptr<T> {}
54	unsafe impl<T> Sync for Ptr<T> {}
55	impl<T> Copy for Ptr<T> {}
56	impl<T> Clone for Ptr<T> {
57		#[inline]
58		fn clone(&self) -> Self {
59			*self
60		}
61	}
62	/// the amount of threads that should ideally execute an operation with the
63	/// given parallelism
64	#[inline]
65	pub fn parallelism_degree(parallelism: Par) -> usize {
66		match parallelism {
67			Par::Seq => 1,
68			#[cfg(feature = "rayon")]
69			Par::Rayon(n_threads) => n_threads.get(),
70		}
71	}
72	/// returns the start and length of a subsegment of `0..n`, split between
73	/// `chunk_count` consumers, for the consumer at index `idx`
74	///
75	/// for the same `n` and `chunk_count`, different values of `idx` between in
76	/// `0..chunk_count` will represent distinct subsegments
77	#[inline]
78	pub fn par_split_indices(
79		n: usize,
80		idx: usize,
81		chunk_count: usize,
82	) -> (usize, usize) {
83		let chunk_size = n / chunk_count;
84		let rem = n % chunk_count;
85		let idx_to_col_start = move |idx| {
86			if idx < rem {
87				idx * (chunk_size + 1)
88			} else {
89				rem + idx * chunk_size
90			}
91		};
92		let start = idx_to_col_start(idx);
93		let end = idx_to_col_start(idx + 1);
94		(start, end - start)
95	}
96}
97/// approximate comparators for testing purposes
98pub mod approx;
99/// simd helper utilities based on lifetime-bound indices
100pub mod simd;