pencil_box/array/flatten.rs
1/// Flattens a nested collection structure into a single `Vec<T>`, supporting various common patterns
2/// such as slices of slices, slices of vectors, vectors of boxes, etc.
3///
4/// # Type Parameters
5///
6/// - `T`: The inner element type. Must implement `Clone`.
7/// - `Outer`: The outer collection type. Must implement `AsRef<[Inner]>`.
8/// - `Inner`: The inner collection type. Must implement `AsRef<[T]>`.
9///
10/// # Arguments
11///
12/// - `nested`: A nested collection where each inner element can be referenced as a slice of `T`.
13///
14/// # Returns
15///
16/// A flattened `Vec<T>` containing all elements from the nested collection in order.
17///
18/// # Behavior
19///
20/// - Iterates through each inner collection inside `nested` and clones each item into a new vector.
21/// - Preserves order of elements across all nested containers.
22/// - Generic over many common nested forms such as:
23/// - `&[&[T]]`
24/// - `&[&Vec<T>]`
25/// - `&[Box<[T]>]`
26/// - `&[Vec<T>]`
27/// - `&Vec<Vec<T>>`
28/// - `Vec<&[T]>`
29/// - `Vec<&Vec<T>>`
30/// - `Vec<Vec<T>>`
31/// - `Vec<Box<[T]>>`
32/// - `&[T; N]` where `T = Vec<_>`
33///
34/// # Performance
35///
36/// - ๐ Time complexity is **O(n)** where `n` is the total number of elements across all inner collections.
37/// - `.cloned()` operates **per-element**, not as a full slice clone โ each `T` is cloned individually using `T::clone()`.
38/// - There is **no quadratic behavior**, because no full slice or repeated reallocation occurs during iteration.
39/// - The final vector is allocated with capacity and built efficiently via `.collect()`.
40///
41/// # Examples
42///
43/// ### ๐ Basic numeric types
44/// ```rust
45/// use pencil_box::array::flatten::flatten;
46///
47/// let a: &[&[i32]] = &[&[1, 2], &[3]];
48/// assert_eq!(flatten(a), vec![1, 2, 3]);
49/// ```
50///
51/// ### ๐งต Strings
52/// ```rust
53/// let strs: Vec<Vec<String>> = vec![
54/// vec!["foo".to_string(), "bar".to_string()],
55/// vec!["baz".to_string()],
56/// ];
57/// assert_eq!(flatten(&strs), vec!["foo", "bar", "baz"]);
58/// ```
59///
60/// ### ๐ Booleans
61/// ```rust
62/// let flags: &[Vec<bool>] = &[vec![true], vec![false, true]];
63/// assert_eq!(flatten(flags), vec![true, false, true]);
64/// ```
65///
66/// ### ๐งฑ Structs
67/// ```rust
68/// #[derive(Debug, Clone, PartialEq)]
69/// struct Point {
70/// x: i32,
71/// y: i32,
72/// }
73///
74/// let nested: &[Vec<Point>] = &[
75/// vec![Point { x: 1, y: 2 }],
76/// vec![Point { x: 3, y: 4 }],
77/// ];
78///
79/// assert_eq!(
80/// flatten(nested),
81/// vec![Point { x: 1, y: 2 }, Point { x: 3, y: 4 }]
82/// );
83/// ```
84///
85/// ### ๐งฉ Enums
86/// ```rust
87/// #[derive(Debug, Clone, PartialEq)]
88/// enum State {
89/// Idle,
90/// Running(u32),
91/// }
92///
93/// let states: Vec<Vec<State>> = vec![
94/// vec![State::Idle],
95/// vec![State::Running(42)],
96/// ];
97///
98/// assert_eq!(flatten(&states), vec![State::Idle, State::Running(42)]);
99/// ```
100///
101/// # Panic Safety
102///
103/// โ
This function is panic-free for valid inputs.
104///
105/// # Notes
106///
107/// To avoid unnecessary cloning, consider using references to `T` instead of `T` directly when possible.
108///
109/// # See Also
110///
111/// - [`flat_map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map)
112/// - [`concat`](https://doc.rust-lang.org/std/slice/fn.concat.html) for `Vec<Vec<T>>` only
113
114pub fn flatten<T: Clone, Outer, Inner>(nested: Outer) -> Vec<T>
115where
116 Outer: AsRef<[Inner]>,
117 Inner: AsRef<[T]>,
118{
119 nested
120 .as_ref()
121 .iter()
122 .flat_map(|inner| inner.as_ref().iter().cloned())
123 .collect()
124
125}