orx_iterable/transformations/
flattened.rs

1use crate::{Collection, CollectionMut, Iterable};
2use core::marker::PhantomData;
3use orx_self_or::SoM;
4
5/// Wraps an `Iterable` and creates a new `Iterable` which flattens the elements of
6/// the original iterable filtered by a predicate.
7pub struct Flattened<I>
8where
9    I: Iterable,
10    I::Item: IntoIterator,
11{
12    pub(crate) it: I,
13}
14
15impl<I> Iterable for Flattened<I>
16where
17    I: Iterable,
18    I::Item: IntoIterator,
19{
20    type Item = <I::Item as IntoIterator>::Item;
21
22    type Iter = core::iter::Flatten<I::Iter>;
23
24    fn iter(&self) -> Self::Iter {
25        self.it.iter().flatten()
26    }
27}
28
29// col
30
31/// Wraps an `Collection` and creates a new `Collection` which flattens the elements of
32/// the original iterable filtered by a predicate.
33pub struct FlattenedCol<I, E>
34where
35    I: Collection,
36    I::Item: IntoIterator,
37    for<'i> &'i I::Item: IntoIterator<Item = &'i <I::Item as IntoIterator>::Item>,
38    E: SoM<I>,
39{
40    pub(crate) it: E,
41    pub(crate) phantom: PhantomData<I>,
42}
43
44impl<'a, I, E> Iterable for &'a FlattenedCol<I, E>
45where
46    I: Collection,
47    I::Item: IntoIterator,
48    for<'i> &'i I::Item: IntoIterator<Item = &'i <I::Item as IntoIterator>::Item>,
49    E: SoM<I>,
50{
51    type Item = &'a <I::Item as IntoIterator>::Item;
52
53    type Iter = core::iter::Flatten<<I::Iterable<'a> as Iterable>::Iter>;
54
55    fn iter(&self) -> Self::Iter {
56        self.it.get_ref().iter().flatten()
57    }
58}
59
60impl<I, E> Collection for FlattenedCol<I, E>
61where
62    I: Collection,
63    I::Item: IntoIterator,
64    for<'i> &'i I::Item: IntoIterator<Item = &'i <I::Item as IntoIterator>::Item>,
65    E: SoM<I>,
66{
67    type Item = <I::Item as IntoIterator>::Item;
68
69    type Iterable<'i>
70        = &'i Self
71    where
72        Self: 'i;
73
74    fn as_iterable(&self) -> Self::Iterable<'_> {
75        self
76    }
77}
78
79impl<I, E> CollectionMut for FlattenedCol<I, E>
80where
81    I: CollectionMut,
82    I::Item: IntoIterator,
83    for<'i> &'i I::Item: IntoIterator<Item = &'i <I::Item as IntoIterator>::Item>,
84    for<'i> &'i mut I::Item: IntoIterator<Item = &'i mut <I::Item as IntoIterator>::Item>,
85    E: SoM<I>,
86{
87    type IterMut<'i>
88        = core::iter::Flatten<I::IterMut<'i>>
89    where
90        Self: 'i;
91
92    fn iter_mut(&mut self) -> Self::IterMut<'_> {
93        self.it.get_mut().iter_mut().flatten()
94    }
95}