orx_iterable/collection_mut.rs
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
use crate::{
    transformations::{
        ChainedCol, FilteredCol, FlattenedCol, FusedCol, ReversedCol, SkippedCol, SkippedWhileCol,
        SteppedByCol, TakenCol, TakenWhileCol,
    },
    Collection, Iterable,
};
/// A mutable collection providing the `iter_mut` method which returns an iterator over mutable references
/// of elements of the collection.
///
/// Since it extends `Collection`, `iter` method is also available which returns an iterator over shared references
/// of elements.
///
/// # Auto Implementations
///
/// Consider a collection type `X` storing elements of type `T`. Provided that the following implementations are provided:
///
/// * `X: IntoIterator<Item = T>`
/// * `&X: IntoIterator<Item = &T>`
/// * `&mut X: IntoIterator<Item = &mut T>`
///
/// Then, `X` implements `Collection<Item = T>` and `CollectionMut<Item = T>`.
/// Further, `&X` implements `Iterable<Item = &T>`.
///
/// # Examples
///
/// ```
/// use orx_iterable::*;
/// use arrayvec::ArrayVec;
/// use smallvec::{smallvec, SmallVec};
/// use std::collections::{LinkedList, VecDeque};
///
/// /// first computes sum, and then adds it to each of the elements
/// fn increment_by_sum(numbers: &mut impl CollectionMut<Item = i32>) {
///     let sum: i32 = numbers.iter().sum();
///
///     for x in numbers.iter_mut() {
///         *x += sum;
///     }
/// }
///
/// // example collections that automatically implement CollectionMut
///
/// let mut x = [1, 2, 3];
/// increment_by_sum(&mut x);
/// assert_eq!(x, [7, 8, 9]);
///
/// let mut x = vec![1, 2, 3];
/// increment_by_sum(&mut x);
///
/// let mut x = LinkedList::from_iter([1, 2, 3]);
/// increment_by_sum(&mut x);
///
/// let mut x = VecDeque::from_iter([1, 2, 3]);
/// increment_by_sum(&mut x);
///
/// let mut x: SmallVec<[_; 128]> = smallvec![3, 5, 7];
/// increment_by_sum(&mut x);
///
/// let mut x = ArrayVec::<_, 16>::new();
/// x.extend([3, 5, 7]);
/// increment_by_sum(&mut x);
/// ```
pub trait CollectionMut: Collection {
    /// Type of the iterator yielding mutable references created by the [`iter_mut`] method.
    ///
    /// [`iter_mut`]: crate::CollectionMut::iter_mut
    type IterMut<'i>: Iterator<Item = &'i mut Self::Item>
    where
        Self: 'i;
    /// Creates a new iterator yielding mutable references to the elements of the collection; i.e.,
    /// type of elements is `&mut Collection::Item`.
    fn iter_mut(&mut self) -> Self::IterMut<'_>;
    // provided
    /// Combines mutable references of this collection and `other`; and creates an iterable collection which
    /// is a chain of these two collections.
    ///
    /// Note that this method does not change the memory locations of the elements; i.e.,
    /// the elements still live in two separate collections; however, now chained together.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = vec!['a', 'b'];
    /// let mut b = ['c', 'd', 'e'];
    ///
    /// let mut it = a.chained_mut(&mut b);
    ///
    /// *it.iter_mut().last().unwrap() = 'x';
    ///
    /// assert_eq!(it.iter().count(), 5);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), vec![&'a', &'b', &'c', &'d', &'x']);
    ///
    /// // neither a nor b is consumed
    /// assert_eq!(a, ['a', 'b']);
    /// assert_eq!(b, ['c', 'd', 'x']);
    /// ```
    fn chained_mut<'a, I>(
        &'a mut self,
        other: &'a mut I,
    ) -> ChainedCol<Self, I, &'a mut Self, &'a mut I>
    where
        Self: Sized,
        I: CollectionMut<Item = Self::Item>,
    {
        ChainedCol {
            it1: self,
            it2: other,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is a filtered version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [0i32, 1, 2];
    ///
    /// let mut it = a.filtered_mut(|x| x.is_positive());
    ///
    /// for x in it.iter_mut() {
    ///     *x *= 2;
    /// }
    ///
    /// assert_eq!(it.iter().count(), 2);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&2, &4]);
    ///
    /// // a is not consumed
    /// assert_eq!(a, [0, 2, 4]);
    /// ```
    fn filtered_mut<P>(&mut self, filter: P) -> FilteredCol<Self, &mut Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        FilteredCol {
            it: self,
            filter,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is a flattened version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut data = vec![vec![1, 2, 3, 4], vec![5, 6]];
    ///
    /// let mut it = data.flattened_mut();
    ///
    /// for x in it.iter_mut() {
    ///     *x *= 2;
    /// }
    ///
    /// assert_eq!(it.iter().count(), 6);
    /// assert_eq!(it.iter().sum::<u32>(), 2 * 21);
    ///
    /// // data is not consumed
    /// assert_eq!(data, [vec![2, 4, 6, 8], vec![10, 12]]);
    /// ```
    fn flattened_mut(&mut self) -> FlattenedCol<Self, &mut Self>
    where
        Self: Sized,
        Self::Item: IntoIterator,
        for<'i> &'i Self::Item: IntoIterator<Item = &'i <Self::Item as IntoIterator>::Item>,
        for<'i> &'i mut Self::Item: IntoIterator<Item = &'i mut <Self::Item as IntoIterator>::Item>,
    {
        FlattenedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is a fused version of this collection from its mutable reference.
    ///
    /// See [`core::iter::Fuse`] for details on fused iterators.
    fn fused_mut(&mut self) -> FusedCol<Self, &mut Self>
    where
        Self: Sized,
    {
        FusedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is a reversed version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut data = vec![vec![1, 2, 3, 4], vec![5, 6]];
    ///
    /// let mut a = [1, 2, 3];
    ///
    /// let mut it = a.reversed_mut();
    /// *it.iter_mut().next().unwrap() += 10;
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&13, &2, &1]);
    /// ```
    fn reversed_mut(&mut self) -> ReversedCol<Self, &mut Self>
    where
        Self: Sized,
        for<'b> <Self::Iterable<'b> as Iterable>::Iter: DoubleEndedIterator,
        for<'b> Self::IterMut<'b>: DoubleEndedIterator,
    {
        ReversedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is skipped-by-`n` version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [1, 2, 3, 4, 5];
    ///
    /// let mut it = a.skipped_mut(2);
    ///
    /// for x in it.iter_mut() {
    ///     *x += 10;
    /// }
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&13, &14, &15]);
    ///
    /// assert_eq!(a, [1, 2, 13, 14, 15]);
    /// ```
    fn skipped_mut(&mut self, n: usize) -> SkippedCol<Self, &mut Self>
    where
        Self: Sized,
    {
        SkippedCol {
            it: self,
            n,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is skipped-while version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [-1i32, 0, 1];
    ///
    /// let mut it = a.skipped_while_mut(|x| x.is_negative());
    ///
    /// for x in it.iter_mut() {
    ///     *x += 10;
    /// }
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&10, &11]);
    ///
    /// assert_eq!(a, [-1, 10, 11]);
    /// ```
    fn skipped_while_mut<P>(&mut self, skip_while: P) -> SkippedWhileCol<Self, &mut Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        SkippedWhileCol {
            it: self,
            skip_while,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is stepped-by-`step` version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [0, 1, 2, 3, 4, 5];
    ///
    /// let mut it = a.stepped_by_mut(2);
    ///
    /// for x in it.iter_mut() {
    ///     *x *= 10;
    /// }
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&0, &20, &40]);
    ///
    /// assert_eq!(a, [0, 1, 20, 3, 40, 5]);
    /// ```
    fn stepped_by_mut(&mut self, step: usize) -> SteppedByCol<Self, &mut Self>
    where
        Self: Sized,
    {
        SteppedByCol {
            it: self,
            step,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is taken-`n` version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [1, 2, 3, 4, 5];
    ///
    /// let mut it = a.taken_mut(3);
    ///
    /// for x in it.iter_mut() {
    ///     *x += 10;
    /// }
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&11, &12, &13]);
    ///
    /// assert_eq!(a, [11, 12, 13, 4, 5]);
    /// ```
    fn taken_mut(&mut self, n: usize) -> TakenCol<Self, &mut Self>
    where
        Self: Sized,
    {
        TakenCol {
            it: self,
            n,
            phantom: Default::default(),
        }
    }
    /// Creates an iterable collection view which is taken-while version of this collection from its mutable reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let mut a = [-1i32, 0, 1];
    ///
    /// let mut it = a.taken_while_mut(|x| x.is_negative());
    ///
    /// for x in it.iter_mut() {
    ///     *x *= 10;
    /// }
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&-10]);
    ///
    /// assert_eq!(a, [-10, 0, 1]);
    /// ```
    fn taken_while_mut<P>(&mut self, take_while: P) -> TakenWhileCol<Self, &mut Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        TakenWhileCol {
            it: self,
            take_while,
            phantom: Default::default(),
        }
    }
}
impl<X> CollectionMut for X
where
    X: IntoIterator,
    for<'a> &'a X: IntoIterator<Item = &'a <X as IntoIterator>::Item>,
    for<'a> &'a mut X: IntoIterator<Item = &'a mut <X as IntoIterator>::Item>,
{
    type IterMut<'i>
        = <&'i mut X as IntoIterator>::IntoIter
    where
        Self: 'i;
    fn iter_mut(&mut self) -> Self::IterMut<'_> {
        <&mut X as IntoIterator>::into_iter(self)
    }
}