orx_parallel/use_var/use.rs
1/// Worker-local mutable state used by parallel iterators.
2///
3/// A `Use` value provides one mutable slot per participating worker thread.
4/// Parallel combinators initialize the slot for a thread on first access and
5/// then reuse it for subsequent accesses from the same thread.
6///
7/// [`UseVec`](crate::UseVec) is the owned implementation of this trait in this crate.
8///
9/// # Examples
10///
11/// ```
12/// use orx_parallel::{Use, UseVec};
13///
14/// fn bump_first_thread<U: Use<Item = usize>>(use_var: &mut U) -> usize {
15/// *unsafe { use_var.init_get(0) } += 1;
16/// *use_var.get(0)
17/// }
18///
19/// let mut use_vec = UseVec::new(|_| 0usize);
20/// assert_eq!(bump_first_thread(&mut use_vec), 1);
21/// assert_eq!(use_vec.into_vec(), vec![1]);
22/// ```
23pub trait Use: Sync {
24 /// Type of the worker-local mutable value stored for each thread.
25 type Item: Send;
26
27 /// Returns the mutable worker-local value for `thread_idx`, creating it if needed.
28 ///
29 /// # SAFETY
30 ///
31 /// Must be called only once per thread.
32 #[allow(clippy::mut_from_ref)]
33 unsafe fn init_get(&self, thread_idx: usize) -> &mut Self::Item;
34
35 /// Returns the already-initialized mutable worker-local value for `thread_idx`.
36 ///
37 /// # Panics
38 ///
39 /// Panics if the corresponding slot has not been initialized by a previous
40 /// call to [`init_get`](Self::init_get).
41 fn get(&mut self, thread_idx: usize) -> &mut Self::Item;
42
43 /// Returns an upper bound on the number of worker threads that may use this value.
44 ///
45 /// `None` means the implementation does not impose a fixed upper bound.
46 fn max_threads(&self) -> Option<usize>;
47}