orx_parallel/computational_variants/
par.rs

1use super::{map::ParMap, xap::ParXap};
2use crate::computational_variants::fallible_result::ParResult;
3use crate::executor::parallel_compute as prc;
4use crate::generic_values::{Vector, WhilstAtom};
5use crate::par_iter_result::IntoResult;
6use crate::runner::{DefaultRunner, ParallelRunner};
7use crate::using::{UPar, UsingClone, UsingFun};
8use crate::{
9    ChunkSize, IterationOrder, NumThreads, ParCollectInto, ParIter, Params, default_fns::map_self,
10};
11use crate::{IntoParIter, ParIterResult, ParIterUsing};
12use orx_concurrent_iter::chain::ChainKnownLenI;
13use orx_concurrent_iter::{ConcurrentIter, ExactSizeConcurrentIter};
14
15/// A parallel iterator.
16pub struct Par<I, R = DefaultRunner>
17where
18    R: ParallelRunner,
19    I: ConcurrentIter,
20{
21    orchestrator: R,
22    params: Params,
23    iter: I,
24}
25
26impl<I, R> Par<I, R>
27where
28    R: ParallelRunner,
29    I: ConcurrentIter,
30{
31    pub(crate) fn new(orchestrator: R, params: Params, iter: I) -> Self {
32        Self {
33            orchestrator,
34            iter,
35            params,
36        }
37    }
38
39    pub(crate) fn destruct(self) -> (R, Params, I) {
40        (self.orchestrator, self.params, self.iter)
41    }
42}
43
44unsafe impl<I, R> Send for Par<I, R>
45where
46    R: ParallelRunner,
47    I: ConcurrentIter,
48{
49}
50
51unsafe impl<I, R> Sync for Par<I, R>
52where
53    R: ParallelRunner,
54    I: ConcurrentIter,
55{
56}
57
58impl<I, R> ParIter<R> for Par<I, R>
59where
60    R: ParallelRunner,
61    I: ConcurrentIter,
62{
63    type Item = I::Item;
64
65    fn con_iter(&self) -> &impl ConcurrentIter {
66        &self.iter
67    }
68
69    fn params(&self) -> Params {
70        self.params
71    }
72
73    // params transformations
74
75    fn num_threads(mut self, num_threads: impl Into<NumThreads>) -> Self {
76        self.params = self.params.with_num_threads(num_threads);
77        self
78    }
79
80    fn chunk_size(mut self, chunk_size: impl Into<ChunkSize>) -> Self {
81        self.params = self.params.with_chunk_size(chunk_size);
82        self
83    }
84
85    fn iteration_order(mut self, collect: IterationOrder) -> Self {
86        self.params = self.params.with_collect_ordering(collect);
87        self
88    }
89
90    fn with_runner<Q: ParallelRunner>(self, orchestrator: Q) -> impl ParIter<Q, Item = Self::Item> {
91        Par::new(orchestrator, self.params, self.iter)
92    }
93
94    // using transformations
95
96    fn using<U, F>(
97        self,
98        using: F,
99    ) -> impl ParIterUsing<UsingFun<F, U>, R, Item = <Self as ParIter<R>>::Item>
100    where
101        U: 'static,
102        F: Fn(usize) -> U + Sync,
103    {
104        let using = UsingFun::new(using);
105        let (orchestrator, params, iter) = self.destruct();
106        UPar::new(using, orchestrator, params, iter)
107    }
108
109    fn using_clone<U>(
110        self,
111        value: U,
112    ) -> impl ParIterUsing<UsingClone<U>, R, Item = <Self as ParIter<R>>::Item>
113    where
114        U: Clone + 'static,
115    {
116        let using = UsingClone::new(value);
117        let (orchestrator, params, iter) = self.destruct();
118        UPar::new(using, orchestrator, params, iter)
119    }
120
121    // computation transformations
122
123    fn map<Out, Map>(self, map: Map) -> impl ParIter<R, Item = Out>
124    where
125        Map: Fn(Self::Item) -> Out + Sync,
126    {
127        let (orchestrator, params, iter) = self.destruct();
128        ParMap::new(orchestrator, params, iter, map)
129    }
130
131    fn filter<Filter>(self, filter: Filter) -> impl ParIter<R, Item = Self::Item>
132    where
133        Filter: Fn(&Self::Item) -> bool + Sync,
134    {
135        let (orchestrator, params, iter) = self.destruct();
136        let x1 = move |i: Self::Item| filter(&i).then_some(i);
137        ParXap::new(orchestrator, params, iter, x1)
138    }
139
140    fn flat_map<IOut, FlatMap>(self, flat_map: FlatMap) -> impl ParIter<R, Item = IOut::Item>
141    where
142        IOut: IntoIterator,
143        FlatMap: Fn(Self::Item) -> IOut + Sync,
144    {
145        let (orchestrator, params, iter) = self.destruct();
146        let x1 = move |i: Self::Item| Vector(flat_map(i));
147        ParXap::new(orchestrator, params, iter, x1)
148    }
149
150    fn filter_map<Out, FilterMap>(self, filter_map: FilterMap) -> impl ParIter<R, Item = Out>
151    where
152        FilterMap: Fn(Self::Item) -> Option<Out> + Sync,
153    {
154        let (orchestrator, params, iter) = self.destruct();
155        ParXap::new(orchestrator, params, iter, filter_map)
156    }
157
158    fn take_while<While>(self, take_while: While) -> impl ParIter<R, Item = Self::Item>
159    where
160        While: Fn(&Self::Item) -> bool + Sync,
161    {
162        let (orchestrator, params, iter) = self.destruct();
163        let x1 = move |value: Self::Item| WhilstAtom::new(value, &take_while);
164        ParXap::new(orchestrator, params, iter, x1)
165    }
166
167    fn into_fallible_result<Out, Err>(self) -> impl ParIterResult<R, Item = Out, Err = Err>
168    where
169        Self::Item: IntoResult<Out, Err>,
170    {
171        ParResult::new(self)
172    }
173
174    // collect
175
176    fn collect_into<C>(self, output: C) -> C
177    where
178        C: ParCollectInto<Self::Item>,
179    {
180        let (orchestrator, params, iter) = self.destruct();
181        output.m_collect_into(orchestrator, params, iter, map_self)
182    }
183
184    // reduce
185
186    fn reduce<Reduce>(self, reduce: Reduce) -> Option<Self::Item>
187    where
188        Self::Item: Send,
189        Reduce: Fn(Self::Item, Self::Item) -> Self::Item + Sync,
190    {
191        let (orchestrator, params, iter) = self.destruct();
192        prc::reduce::m(orchestrator, params, iter, map_self, reduce).1
193    }
194
195    // early exit
196
197    fn first(self) -> Option<Self::Item> {
198        let (orchestrator, params, iter) = self.destruct();
199        match params.iteration_order {
200            IterationOrder::Ordered => prc::next::m(orchestrator, params, iter, map_self).1,
201            IterationOrder::Arbitrary => prc::next_any::m(orchestrator, params, iter, map_self).1,
202        }
203    }
204}
205
206impl<I, R> Par<I, R>
207where
208    R: ParallelRunner,
209    I: ConcurrentIter,
210{
211    /// Creates a chain of this and `other` parallel iterators.
212    ///
213    /// The first iterator is required to have a known length for chaining.
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use orx_parallel::*;
219    ///
220    /// let a = vec!['a', 'b', 'c']; // with exact len
221    /// let b = vec!['d', 'e', 'f'].into_iter().filter(|x| *x != 'x');
222    ///
223    /// let chain = a.into_par().chain(b.iter_into_par());
224    /// assert_eq!(
225    ///     chain.collect::<Vec<_>>(),
226    ///     vec!['a', 'b', 'c', 'd', 'e', 'f'],
227    /// );
228    /// ```
229    pub fn chain<C>(self, other: C) -> Par<ChainKnownLenI<I, C::IntoIter>, R>
230    where
231        I: ExactSizeConcurrentIter,
232        C: IntoParIter<Item = I::Item>,
233    {
234        let (orchestrator, params, iter) = self.destruct();
235        let iter = iter.chain(other.into_con_iter());
236        Par::new(orchestrator, params, iter)
237    }
238}