orx_parallel/parallelizable_collection_mut.rs
1use crate::{
2 ParIter, ParallelizableCollection, Params, computational_variants::Par, runner::DefaultRunner,
3};
4use orx_concurrent_iter::ConcurrentCollectionMut;
5
6/// A type implementing [`ParallelizableCollectionMut`] is a collection owning the elements such that
7///
8/// * if the elements are of type `T`,
9/// * non-consuming [`par`] method can be called **multiple times** to create parallel
10/// iterators; i.e., [`ParIter`], yielding references to the elements `&T`; and
11/// * non-consuming [`par_mut`] method can be called **multiple times** to create parallel
12/// iterators yielding mutable references to the elements `&mut T`; and
13/// * consuming [`into_par`] method can be called once to create a parallel iterator yielding
14/// owned elements `T`.
15///
16/// This trait can be considered as the *concurrent counterpart* of the [`CollectionMut`] trait.
17///
18/// Note that every [`ConcurrentCollectionMut`] type automatically implements [`ParallelizableCollectionMut`].
19///
20/// [`CollectionMut`]: orx_iterable::CollectionMut
21/// [`ConcurrentCollectionMut`]: orx_concurrent_iter::ConcurrentCollectionMut
22/// [`par`]: crate::ParallelizableCollection::par
23/// [`par_mut`]: crate::ParallelizableCollectionMut::par_mut
24/// [`into_par`]: crate::IntoParIter::into_par
25/// [`ParIter`]: crate::ParIter
26///
27/// # Examples
28///
29/// ```
30/// use orx_parallel::*;
31///
32/// // Vec<T>: ParallelizableCollectionMut<Item = T>
33/// let mut vec = vec![1, 2, 3, 4];
34///
35/// // non-consuming iteration over references
36/// assert_eq!(vec.par().sum(), 10);
37/// assert_eq!(vec.par().min(), Some(&1));
38/// assert_eq!(vec.par().max(), Some(&4));
39///
40/// // non-consuming mutable iteration
41/// vec.par_mut().filter(|x| **x >= 3).for_each(|x| *x += 10);
42/// assert_eq!(&vec, &[1, 2, 13, 14]);
43///
44/// // consuming iteration over owned values
45/// assert_eq!(vec.into_par().max(), Some(14));
46/// ```
47pub trait ParallelizableCollectionMut: ConcurrentCollectionMut + ParallelizableCollection {
48 /// Creates a parallel iterator over mutable references of the collection's elements.
49 ///
50 /// # Examples
51 ///
52 /// ```
53 /// use orx_parallel::*;
54 ///
55 /// // Vec<T>: ParallelizableCollectionMut<Item = T>
56 /// let mut vec = vec![1, 2, 3, 4];
57 ///
58 /// vec.par_mut().filter(|x| **x >= 3).for_each(|x| *x += 10);
59 ///
60 /// assert_eq!(&vec, &[1, 2, 13, 14]);
61 /// ```
62 fn par_mut(&mut self) -> impl ParIter<DefaultRunner, Item = &mut Self::Item> {
63 Par::new(Default::default(), Params::default(), self.con_iter_mut())
64 }
65}
66
67impl<X> ParallelizableCollectionMut for X where X: ConcurrentCollectionMut + ParallelizableCollection
68{}