orx_parallel/using/
using_variants.rs

1/// A type that can [`create`] a value per thread, which will then be send to the thread,
2/// and used mutable by the defined computation.
3///
4/// [`create`]: crate::using::Using::create
5pub trait Using: Sync {
6    /// Item to be used mutably by each threads used in parallel computation.
7    type Item: 'static;
8
9    /// Creates an instance of the variable to be used by the `thread_idx`-th thread.
10    fn create(&self, thread_idx: usize) -> Self::Item;
11
12    /// Consumes self and creates exactly one instance of the variable.
13    fn into_inner(self) -> Self::Item;
14}
15
16/// Using variant that creates instances of each thread by cloning an initial value.
17pub struct UsingClone<T: Clone + 'static>(T);
18
19impl<T: Clone + 'static> UsingClone<T> {
20    pub(crate) fn new(value: T) -> Self {
21        Self(value)
22    }
23}
24
25impl<T: Clone + 'static> Using for UsingClone<T> {
26    type Item = T;
27
28    fn create(&self, _: usize) -> T {
29        self.0.clone()
30    }
31
32    fn into_inner(self) -> Self::Item {
33        self.0
34    }
35}
36
37unsafe impl<T: Clone + 'static> Sync for UsingClone<T> {}
38
39/// Using variant that creates instances of each thread using a closure.
40pub struct UsingFun<F, T>
41where
42    T: 'static,
43    F: Fn(usize) -> T + Sync,
44{
45    fun: F,
46}
47
48impl<F, T> UsingFun<F, T>
49where
50    T: 'static,
51    F: Fn(usize) -> T + Sync,
52{
53    pub(crate) fn new(fun: F) -> Self {
54        Self { fun }
55    }
56}
57
58impl<F, T> Using for UsingFun<F, T>
59where
60    T: 'static,
61    F: Fn(usize) -> T + Sync,
62{
63    type Item = T;
64
65    fn create(&self, thread_idx: usize) -> Self::Item {
66        (self.fun)(thread_idx)
67    }
68
69    fn into_inner(self) -> Self::Item {
70        (self.fun)(0)
71    }
72}