orx_iterable/collection.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
use crate::{
    transformations::{
        ChainedCol, FilteredCol, FlattenedCol, FusedCol, ReversedCol, SkippedCol, SkippedWhileCol,
        SteppedByCol, TakenCol, TakenWhileCol,
    },
    Iterable,
};
/// A collection providing the `iter` method which returns an iterator over shared references
/// of elements of the collection.
///
/// # 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>`
///
/// Then, `X` implements `Collection<Item = T>`.
/// Further, `&X` implements `Iterable<Item = &T>`.
///
/// # Examples
///
/// ```
/// use orx_iterable::*;
/// use arrayvec::ArrayVec;
/// use smallvec::{smallvec, SmallVec};
/// use std::collections::{BinaryHeap, BTreeSet, HashSet, LinkedList, VecDeque};
///
/// struct Stats {
///     count: usize,
///     mean: i64,
///     std_dev: i64,
/// }
///
/// /// we need multiple iterations over numbers to compute the stats
/// fn statistics(numbers: &impl Collection<Item = i64>) -> Stats {
///     let count = numbers.iter().count() as i64;
///     let sum = numbers.iter().sum::<i64>();
///     let mean = sum / count;
///     let sum_sq_errors: i64 = numbers.iter().map(|x| (x - mean) * (x - mean)).sum();
///     let std_dev = f64::sqrt(sum_sq_errors as f64 / (count - 1) as f64) as i64;
///     Stats {
///         count: count as usize,
///         mean,
///         std_dev,
///     }
/// }
///
/// // example collections that automatically implement Collection
///
/// statistics(&[3, 5, 7]);
/// statistics(&vec![3, 5, 7]);
/// statistics(&LinkedList::from_iter([3, 5, 7]));
/// statistics(&VecDeque::from_iter([3, 5, 7]));
/// statistics(&HashSet::<_>::from_iter([3, 5, 7]));
/// statistics(&BTreeSet::<_>::from_iter([3, 5, 7]));
/// statistics(&BinaryHeap::<_>::from_iter([3, 5, 7]));
///
/// let x: SmallVec<[_; 128]> = smallvec![3, 5, 7];
/// statistics(&x);
///
/// let mut x = ArrayVec::<_, 16>::new();
/// x.extend([3, 5, 7]);
/// statistics(&x);
/// ```
pub trait Collection {
    /// Type of elements stored by the collection.
    type Item;
    /// Related type implementing `Iterable` trait that the `as_iterable` method returns.
    /// If the type of the `Collection` is `X`, the corresponding `Iterable` type is almost
    /// always `&X` due to the following relation among the both traits.
    ///
    /// Practically, these definitions correspond to the following relations:
    /// * if a collection `X` implements [`Collection<Item = T>`], then `&X` implements [`Iterable<Item = &T>`];
    /// * on the other hand, a type implementing [`Iterable`] may not be a collection at all, such as [`Range<usize>`],
    ///   and hence, does not necessarily implement [`Collection`].
    ///
    /// [`Range<usize>`]: core::ops::Range
    type Iterable<'i>: Iterable<Item = &'i Self::Item>
    where
        Self: 'i;
    /// Creates a new iterator yielding references to the elements of the collection; i.e.,
    /// type of elements is `&Collection::Item`.
    fn iter(&self) -> <Self::Iterable<'_> as Iterable>::Iter {
        self.as_iterable().iter()
    }
    /// Returns the corresponding `Iterable` type of this collection, which is often nothing but `&Self`.
    fn as_iterable(&self) -> Self::Iterable<'_>;
    // provided
    /// Consumes this collection and `other`; 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 a = vec!['a', 'b'];
    /// let b = ['c', 'd', 'e'];
    ///
    /// let mut it = a.into_chained(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']);
    /// ```
    fn into_chained<I>(self, other: I) -> ChainedCol<Self, I, Self, I>
    where
        Self: Sized,
        I: Collection<Item = Self::Item>,
    {
        ChainedCol {
            it1: self,
            it2: other,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is a filtered version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [0i32, 1, 2];
    ///
    /// let mut it = a.into_filtered(|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]);
    /// ```
    fn into_filtered<P>(self, filter: P) -> FilteredCol<Self, Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        FilteredCol {
            it: self,
            filter,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is a flattened version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
    ///
    /// let mut it = data.into_flattened();
    ///
    /// for x in it.iter_mut() {
    ///     *x *= 2;
    /// }
    ///
    /// assert_eq!(it.iter().count(), 6);
    /// assert_eq!(it.iter().sum::<u32>(), 2 * 21);
    /// ```
    fn into_flattened(self) -> FlattenedCol<Self, Self>
    where
        Self: Sized,
        Self::Item: IntoIterator,
        for<'i> &'i Self::Item: IntoIterator<Item = &'i <Self::Item as IntoIterator>::Item>,
    {
        FlattenedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is a fused version of this collection.
    ///
    /// See [`core::iter::Fuse`] for details on fused iterators.
    fn into_fused(self) -> FusedCol<Self, Self>
    where
        Self: Sized,
    {
        FusedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is a reversed version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
    ///
    /// let a = [1, 2, 3];
    ///
    /// let it = a.into_reversed();
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&3, &2, &1]);
    ///
    /// let it = it.into_reversed();
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&1, &2, &3]);
    /// ```
    fn into_reversed(self) -> ReversedCol<Self, Self>
    where
        Self: Sized,
        for<'b> <Self::Iterable<'b> as Iterable>::Iter: DoubleEndedIterator,
    {
        ReversedCol {
            it: self,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is skipped-by-`n` version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [1, 2, 3, 4, 5];
    ///
    /// let it = a.into_skipped(2);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&3, &4, &5]);
    ///
    /// let it = it.into_skipped(1);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&4, &5]);
    /// ```
    fn into_skipped(self, n: usize) -> SkippedCol<Self, Self>
    where
        Self: Sized,
    {
        SkippedCol {
            it: self,
            n,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is skipped-while version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [-1i32, 0, 1];
    ///
    /// let it = a.into_skipped_while(|x| x.is_negative());
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&0, &1]);
    /// ```
    fn into_skipped_while<P>(self, skip_while: P) -> SkippedWhileCol<Self, Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        SkippedWhileCol {
            it: self,
            skip_while,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is stepped-by-`step` version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [0, 1, 2, 3, 4, 5];
    ///
    /// let it = a.into_stepped_by(2);
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&0, &2, &4]);
    /// ```
    fn into_stepped_by(self, step: usize) -> SteppedByCol<Self, Self>
    where
        Self: Sized,
    {
        SteppedByCol {
            it: self,
            step,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is taken-`n` version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [1, 2, 3, 4, 5];
    ///
    /// let it = a.into_taken(3);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&1, &2, &3]);
    ///
    /// let it = it.into_taken(2);
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&1, &2]);
    /// ```
    fn into_taken(self, n: usize) -> TakenCol<Self, Self>
    where
        Self: Sized,
    {
        TakenCol {
            it: self,
            n,
            phantom: Default::default(),
        }
    }
    /// Consumes this collection and creates an iterable collection which is taken-while version of this collection.
    ///
    /// # Examples
    ///
    /// ```
    /// use orx_iterable::*;
    ///
    /// let a = [-1i32, 0, 1];
    ///
    /// let it = a.into_taken_while(|x| x.is_negative());
    ///
    /// assert_eq!(it.iter().collect::<Vec<_>>(), [&-1]);
    /// ```
    fn into_taken_while<P>(self, take_while: P) -> TakenWhileCol<Self, Self, P>
    where
        Self: Sized,
        P: Fn(&Self::Item) -> bool + Copy,
    {
        TakenWhileCol {
            it: self,
            take_while,
            phantom: Default::default(),
        }
    }
}
impl<X> Collection for X
where
    X: IntoIterator,
    for<'a> &'a X: IntoIterator<Item = &'a <X as IntoIterator>::Item>,
{
    type Item = <X as IntoIterator>::Item;
    type Iterable<'i>
        = &'i X
    where
        Self: 'i;
    fn iter(&self) -> <Self::Iterable<'_> as Iterable>::Iter {
        <&X as IntoIterator>::into_iter(self)
    }
    fn as_iterable(&self) -> Self::Iterable<'_> {
        self
    }
}