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 {
6    /// Item to be used mutably by each threads used in parallel computation.
7    type Item: Send;
8
9    /// Creates an instance of the variable to be used by the `thread_idx`-th thread.
10    fn create(&mut 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 + Send>(T);
18
19impl<T: Clone + Send> UsingClone<T> {
20    pub(crate) fn new(value: T) -> Self {
21        Self(value)
22    }
23}
24
25impl<T: Clone + Send> Using for UsingClone<T> {
26    type Item = T;
27
28    fn create(&mut self, _: usize) -> T {
29        self.0.clone()
30    }
31
32    fn into_inner(self) -> Self::Item {
33        self.0
34    }
35}
36
37/// Using variant that creates instances of each thread using a closure.
38pub struct UsingFun<F, T>
39where
40    T: Send,
41    F: FnMut(usize) -> T,
42{
43    fun: F,
44}
45
46impl<F, T> UsingFun<F, T>
47where
48    T: Send,
49    F: FnMut(usize) -> T,
50{
51    pub(crate) fn new(fun: F) -> Self {
52        Self { fun }
53    }
54}
55
56impl<F, T> Using for UsingFun<F, T>
57where
58    T: Send,
59    F: FnMut(usize) -> T,
60{
61    type Item = T;
62
63    fn create(&mut self, thread_idx: usize) -> Self::Item {
64        (self.fun)(thread_idx)
65    }
66
67    fn into_inner(mut self) -> Self::Item {
68        (self.fun)(0)
69    }
70}