orx_concurrent_iter/
concurrent_collection_mut.rs

1use crate::{ConcurrentCollection, ConcurrentIter, IntoConcurrentIter};
2
3/// A type implementing [`ConcurrentCollectionMut`] is a collection owning the elements such that
4///
5/// * if the elements are of type `T`,
6/// * then, non-consuming [`con_iter_mut`] method can be called **multiple times** to create concurrent
7///   iterators; i.e., [`ConcurrentIter`], yielding references to the elements `&T`; and further,
8/// * non-consuming mutable [`con_iter_mut`] method can be called to create concurrent iterators
9///   yielding mutable references to elements `&mut T`.
10///
11/// This trait can be considered as the *concurrent counterpart* of the [`CollectionMut`] trait.
12///
13/// [`con_iter_mut`]: crate::ConcurrentCollectionMut::con_iter_mut
14/// [`CollectionMut`]: orx_iterable::CollectionMut
15/// [`ConcurrentIter`]: crate::ConcurrentIter
16///
17/// # Examples
18///
19/// ```
20/// use orx_concurrent_iter::*;
21///
22/// let mut data = vec![1, 2];
23///
24/// let con_iter = data.con_iter_mut();
25/// assert_eq!(con_iter.next(), Some(&mut 1));
26/// assert_eq!(con_iter.next(), Some(&mut 2));
27/// assert_eq!(con_iter.next(), None);
28///
29/// let con_iter = data.con_iter_mut();
30/// while let Some(x) = con_iter.next() {
31///     *x *= 100;
32/// }
33/// assert_eq!(data, vec![100, 200]);
34/// ```
35pub trait ConcurrentCollectionMut: ConcurrentCollection {
36    /// Type of the mutable concurrent iterator that this type can create with `con_iter_mut` method.
37    type IterMut<'a>: ConcurrentIter<Item = &'a mut Self::Item>
38    where
39        Self: 'a;
40
41    /// Creates a concurrent iterator to mutable references of the underlying data; i.e., `&mut Self::Item`.
42    ///
43    /// # Examples
44    ///
45    /// ```
46    /// use orx_concurrent_iter::*;
47    ///
48    /// let mut data = vec![1, 2];
49    ///
50    /// let con_iter = data.con_iter_mut();
51    /// assert_eq!(con_iter.next(), Some(&mut 1));
52    /// assert_eq!(con_iter.next(), Some(&mut 2));
53    /// assert_eq!(con_iter.next(), None);
54    ///
55    /// let con_iter = data.con_iter_mut();
56    /// while let Some(x) = con_iter.next() {
57    ///     *x *= 100;
58    /// }
59    /// assert_eq!(data, vec![100, 200]);
60    /// ```
61    fn con_iter_mut(&mut self) -> Self::IterMut<'_>;
62}
63
64impl<X> ConcurrentCollectionMut for X
65where
66    X: IntoConcurrentIter,
67    for<'a> &'a X: IntoConcurrentIter<Item = &'a <X as IntoConcurrentIter>::Item>,
68    for<'a> &'a mut X: IntoConcurrentIter<Item = &'a mut <X as IntoConcurrentIter>::Item>,
69{
70    type IterMut<'a>
71        = <&'a mut X as IntoConcurrentIter>::IntoIter
72    where
73        Self: 'a;
74
75    fn con_iter_mut(&mut self) -> Self::IterMut<'_> {
76        <&mut X as IntoConcurrentIter>::into_con_iter(self)
77    }
78}