1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use crate::no_std::pipelines::tap::Tap;
use rayon::{iter::Either, prelude::*};
use std::{
iter::Product,
ops::{Add, DerefMut},
prelude::v1::*,
};
pub trait ParSort<T> {
fn psort(self) -> Self;
}
impl<T, P> ParSort<T> for P
where
T: Ord + Send,
P: DerefMut,
P::Target: ParallelSliceMut<T>,
{
/// Sorts `Vec` in parallel.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// // Array:
/// assert_eq!([6, 3, 8, 1].psort(), [1, 3, 6, 8]);
///
/// // Vec:
/// let v = vec![7, 4, 9, 2].psort();
/// assert_eq!(v, vec![2, 4, 7, 9]);
///
/// // DST:
/// fn foo(arr: &mut [u8]) -> &mut [u8] {
/// arr.psort()
/// }
/// assert_eq!(foo(&mut [8, 5, 10, 3]), [3, 5, 8, 10]);
/// ```
fn psort(self) -> Self {
self.tap_mut(|v| v.par_sort())
}
}
pub trait ParMutExt<T, R> {
fn on_each(self, f: impl Fn(&mut T) -> R + Sync + Send) -> Self;
fn map(&mut self, f: impl Fn(&mut T) -> R + Sync + Send) -> Vec<R>
where
R: Send;
fn filter_map(&mut self, f: impl Fn(&mut T) -> Option<R> + Sync + Send) -> Vec<R>
where
R: Send;
fn bind(&mut self, f: impl Fn(&mut T) -> R + Sync + Send) -> Vec<R>
where
R: IntoParallelIterator,
Vec<R>: FromParallelIterator<<R as IntoParallelIterator>::Item>;
}
impl<T, R, P> ParMutExt<T, R> for P
where
P: DerefMut,
P::Target: for<'a> IntoParallelRefMutIterator<'a, Item = &'a mut T>,
{
/// Performs the given `f` on each element in parallel, and returns the itself afterwards.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, no_std::functions::fun::s, standard::{functions::ext::*, parallelisms::par_vec_ext::*}};
///
/// assert_eqs!{
/// vec!["hello", "rust"].on_each(|s| *s.echo()), vec!["hello", "rust"]; // * => inner return by auto copy
/// vec![s("Jan"), s("Febr")].on_each(|s| *s += "uary"), vec!["January", "February"];
/// }
/// ```
fn on_each(self, f: impl Fn(&mut T) -> R + Sync + Send) -> Self {
self.tap_mut(|v| {
v.par_iter_mut().for_each(|e| {
f(e);
})
})
}
/// Returns a `Vec` containing the results of applying the given `f` function
/// to each element in the original.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, standard::parallelisms::par_vec_ext::*};
///
/// let mut v1 = vec![1, 2, 3];
/// let v2 = v1.map(|i| { *i += 1; *i + 1 });
///
/// assert_eqs! {
/// v1, [2, 3, 4];
/// v2, [3, 4, 5];
/// }
/// ```
fn map(&mut self, f: impl Fn(&mut T) -> R + Sync + Send) -> Vec<R>
where
R: Send,
{
self.par_iter_mut().map(f).collect()
}
/// A combined map and filter. Filtering is handled via `Option` instead of `Boolean`
/// such that the output type `R` can be different than the input type `T`.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, no_std::{pipelines::tap::Tap, functions::fun::s}, standard::parallelisms::par_vec_ext::*};
///
/// let mut v1 = vec![s("Jan"), s("1"), s("Febr"), s("2")];
/// let v2 = v1.filter_map(|s| s.parse::<u8>().ok().tap_mut(|_| *s += "uary"));
///
/// assert_eqs! {
/// v2, vec![1, 2];
/// v1, vec!["January", "1uary", "February", "2uary"];
/// }
/// ```
fn filter_map(&mut self, f: impl Fn(&mut T) -> Option<R> + Sync + Send) -> Vec<R>
where
R: Send,
{
self.par_iter_mut().filter_map(f).collect()
}
/// Returns a `Vec` containing the unwrapped results of applying
/// the given `f` function to each element in the original.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, standard::parallelisms::par_vec_ext::*};
///
/// let mut v1 = vec![[1, 2], [3, 4], [5, 6], [7, 8]];
/// let v2 = v1.map(|i| { i[0] += 1; i[1] -= 1; i[0] + i[1] });
///
/// assert_eqs! {
/// v1, [[2, 1], [4, 3], [6, 5], [8, 7]];
/// v2, [3, 7, 11, 15];
/// }
/// ```
fn bind(&mut self, f: impl Fn(&mut T) -> R + Sync + Send) -> Vec<R>
where
R: IntoParallelIterator,
Vec<R>: FromParallelIterator<<R as IntoParallelIterator>::Item>,
{
self.par_iter_mut().flat_map(f).collect()
}
}
/// This trait is to implement some extension functions for `Vec` type,
/// which need one generic type, and do not need reference.
pub trait ParExt<T> {
fn for_each<R>(self, f: impl Fn(T) -> R + Sync + Send);
fn filter(self, f: impl Fn(&T) -> bool + Sync + Send) -> Vec<T>
where
T: Send;
fn fold(self, init: T, f: impl Fn(T, T) -> T + Sync + Send) -> T
where
T: Sync + Copy;
fn reduce(self, f: impl Fn(T, T) -> T + Sync + Send) -> T
where
T: Sync + Copy + Default;
fn sum(self) -> T
where
T: Sync + Copy + Default + Add<Output = T>;
fn product(self) -> T
where
T: Send + Product;
fn partition(self, f: impl Fn(&T) -> bool + Sync + Send) -> (Vec<T>, Vec<T>)
where
T: Send;
fn partition3(
self,
predicate1: impl Fn(&T) -> bool + Sync + Send,
predicate2: impl Fn(&T) -> bool + Sync + Send,
) -> (Vec<T>, Vec<T>, Vec<T>)
where
T: Send;
}
impl<T, P> ParExt<T> for P
where
P: IntoParallelIterator<Item = T> + for<'a> IntoParallelRefIterator<'a>,
{
/// Executes `f` on each item produced by the iterator for `Vec` in parallel.
///
/// # Examples
///
/// ```
/// use ext::{no_std::functions::fun::s, standard::{functions::ext::*, parallelisms::par_vec_ext::*}};
///
/// vec![s("abc"), s("xyz")].for_each(|s| s.echo());
/// ```
fn for_each<R>(self, f: impl Fn(T) -> R + Sync + Send) {
self.into_par_iter().for_each(|e| {
f(e);
});
}
/// Returns a `Vec` containing only elements matching the given `f` predicate in parallel.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].filter(|i| i % 2 == 0), vec![2, 4]);
/// ```
fn filter(self, f: impl Fn(&T) -> bool + Sync + Send) -> Vec<T>
where
T: Send,
{
self.into_par_iter().filter(f).collect()
}
/// Accumulates value starting with initial value,
/// and applying operation `f` from left to right in parallel.
///
/// Returns the specified initial value if the `Vec` is empty.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].fold(0, |acc, i| acc + i), 10);
/// ```
fn fold(self, init: T, f: impl Fn(T, T) -> T + Sync + Send) -> T
where
T: Sync + Copy,
{
self.into_par_iter().reduce(|| init, f)
}
/// Accumulates value starting with default value,
/// and applying operation `f` from left to right in parallel.
///
/// Returns the default value if the `Vec` is empty.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].reduce(|acc, i| acc + i), 10);
/// ```
fn reduce(self, f: impl Fn(T, T) -> T + Sync + Send) -> T
where
T: Sync + Copy + Default,
{
self.fold(T::default(), f)
}
/// Returns the sum of all elements
/// which implement the `Add` trait in parallel for `Vec` type.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].sum(), 10);
/// ```
fn sum(self) -> T
where
T: Sync + Copy + Default + Add<Output = T>,
{
self.reduce(|a, b| a + b)
}
/// Returns the product of all elements
/// which implement the `Product` trait in parallel for `Vec` type.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].product(), 24);
/// ```
fn product(self) -> T
where
T: Send + Product,
{
self.into_par_iter().product()
}
/// Splits the original `Vec` into a couple of `Vec` according to the condition,
/// where first `Vec` contains elements for which predicate yielded true,
/// while second `Vec` contains elements for which predicate yielded false.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3, 4].partition(|i| i % 2 != 0), (vec![1, 3], vec![2, 4]));
/// ```
fn partition(self, f: impl Fn(&T) -> bool + Sync + Send) -> (Vec<T>, Vec<T>)
where
T: Send,
{
self.into_par_iter().partition(f)
}
/// Splits the original `Vec` into a triple of `Vec` according to the condition,
/// where first `Vec` contains elements for first predicate yielded true,
/// where second `Vec` contains elements for second predicate yielded true,
/// while third `Vec` contains elements for which two predicates yielded false.
///
/// # Examples
///
/// ```
/// use ext::standard::parallelisms::par_vec_ext::*;
///
/// assert_eq!(vec![1, 2, 3].partition3(|i| i < &2, |i| i == &2), (vec![1], vec![2], vec![3]));
/// ```
fn partition3(
self,
predicate1: impl Fn(&T) -> bool + Sync + Send,
predicate2: impl Fn(&T) -> bool + Sync + Send,
) -> (Vec<T>, Vec<T>, Vec<T>)
where
T: Send,
{
let ((first, second), third) = self.into_par_iter().partition_map(|e| {
if predicate1(&e) {
Either::Left(Either::Left(e))
} else if predicate2(&e) {
Either::Left(Either::Right(e))
} else {
Either::Right(e)
}
});
(first, second, third)
}
}