glossa_shared/
small_list.rs

1use derive_more::{Deref, DerefMut};
2pub use smallvec::SmallVec;
3use tap::Pipe;
4
5use crate::MiniStr;
6
7/// Compact string list optimized for small datasets
8///
9/// Implements stack-allocated storage using `SmallVec`, avoiding heap
10/// allocation when containing up to `N` elements. Ideal for small string
11/// collections created and destroyed frequently.
12///
13/// # Generic Parameter
14///
15/// - `N`: Inline storage capacity determining maximum elements stored on stack
16///
17/// # Example
18///
19/// ```
20/// use glossa_shared::{MiniStr, small_list::SmallList};
21///
22/// // Create from string literals (stack-allocated)
23/// let list: SmallList<4> = ["a", "b", "c"].into_iter().collect();
24/// assert_eq!(list.len(), 3);
25///
26/// // Create from dynamic strings (auto heap allocation when exceeding N)
27/// let strings = vec!["hello".to_string(); 5];
28/// let list: SmallList<3> = strings.into_iter().collect();
29/// assert_eq!(list.len(), 5);
30/// ```
31#[derive(Default, Debug, Clone, Deref, DerefMut)]
32pub struct SmallList<const N: usize>(pub SmallVec<MiniStr, N>);
33
34impl<const N: usize, S> FromIterator<S> for SmallList<N>
35where
36  S: Into<MiniStr>,
37{
38  /// Creates a `SmallList` from an iterator, performing automatic type
39  /// conversion
40  ///
41  /// # Parameter
42  ///
43  /// - `iter`: Any type implementing `IntoIterator` with elements convertible
44  ///   to `MiniStr`
45  ///
46  /// # Conversion Flow
47  /// 1. Iterate through elements
48  /// 2. Convert each element to `MiniStr` via `Into::into`
49  /// 3. Collect into `SmallVec` with stack optimization
50  /// 4. Wrap in `SmallList` container
51  ///
52  /// # Example
53  ///
54  /// ```
55  /// use glossa_shared::{MiniStr, small_list::SmallList};
56  ///
57  /// let list: SmallList<1> = [
58  ///     "Hello",
59  /// ].into_iter().collect();
60  /// ```
61  fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Self {
62    iter
63      .into_iter()
64      .map(Into::into)
65      .collect::<SmallVec<_, N>>()
66      .pipe(SmallList)
67  }
68}