orx_iterable/obj_safe/
collection_mut_obj.rs

1use crate::obj_safe::collection_obj::CollectionObj;
2use std::boxed::Box;
3
4/// In addition to  [`boxed_iter`], a `CollectionMutObj` provides the [`boxed_iter_mut`] method which returns a boxed
5/// iterator over mutable references of elements of the collection.
6///
7/// It is the object safe counterpart of [`CollectionMut`] trait which can conveniently be made into a trait object.
8///
9/// Note that for collections, `CollectionMutObj` is implicitly implemented and readily available.
10/// Please refer to [`CollectionMut`] documentation for details of automatic implementations.
11///
12/// In order to use object safe iterables and collections please add `--features std` and use
13/// `use orx_iterable::{*, obj_safe::*}` to import dependencies rather than `use orx_iterable::*`.
14///
15/// [`Iterable`]: crate::Iterable
16/// [`Item`]: crate::obj_safe::CollectionMutObj::Item
17/// [`boxed_iter`]: crate::obj_safe::CollectionObj::boxed_iter
18/// [`boxed_iter_mut`]: crate::obj_safe::CollectionMutObj::boxed_iter_mut
19/// [`CollectionMut`]: crate::CollectionMut
20///
21/// # Examples
22///
23/// ```
24/// use orx_iterable::obj_safe::*;
25/// use arrayvec::ArrayVec;
26/// use smallvec::{smallvec, SmallVec};
27/// use std::collections::{LinkedList, VecDeque};
28///
29/// /// first computes sum, and then adds it to each of the elements
30/// fn increment_by_sum(numbers: &mut dyn CollectionMutObj<Item = i32>) {
31///     let sum: i32 = numbers.boxed_iter().sum();
32///
33///     for x in numbers.boxed_iter_mut() {
34///         *x += sum;
35///     }
36/// }
37///
38/// // example collections that automatically implement CollectionMut
39///
40/// let mut x = [1, 2, 3];
41/// increment_by_sum(&mut x);
42/// assert_eq!(x, [7, 8, 9]);
43///
44/// let mut x = vec![1, 2, 3];
45/// increment_by_sum(&mut x);
46///
47/// let mut x = LinkedList::from_iter([1, 2, 3]);
48/// increment_by_sum(&mut x);
49///
50/// let mut x = VecDeque::from_iter([1, 2, 3]);
51/// increment_by_sum(&mut x);
52///
53/// let mut x: SmallVec<[_; 128]> = smallvec![3, 5, 7];
54/// increment_by_sum(&mut x);
55///
56/// let mut x = ArrayVec::<_, 16>::new();
57/// x.extend([3, 5, 7]);
58/// increment_by_sum(&mut x);
59/// ```
60pub trait CollectionMutObj: CollectionObj {
61    /// Creates a new iterator in a box yielding mutable references to the elements of the collection; i.e.,
62    /// type of elements is `&mut Item`.
63    fn boxed_iter_mut(&mut self) -> Box<dyn Iterator<Item = &mut Self::Item> + '_>;
64}
65
66impl<X> CollectionMutObj for X
67where
68    X: IntoIterator,
69    for<'a> &'a X: IntoIterator<Item = &'a <X as IntoIterator>::Item>,
70    for<'a> &'a mut X: IntoIterator<Item = &'a mut <X as IntoIterator>::Item>,
71{
72    fn boxed_iter_mut(&mut self) -> Box<dyn Iterator<Item = &mut Self::Item> + '_> {
73        Box::new(<&mut X as IntoIterator>::into_iter(self))
74    }
75}