Skip to main content

sql_fun_core/
coll.rs

1//! Basic generic collections for `sql-fun`
2//!
3
4///
5/// Fixed length immutable vector (Boxed slice)
6///
7#[derive(Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, Debug)]
8#[repr(transparent)]
9#[serde(transparent)]
10pub struct IVec<T>(Box<[T]>);
11
12impl<T> Default for IVec<T> {
13    fn default() -> Self {
14        Self(Box::default())
15    }
16}
17
18impl<T> From<Vec<T>> for IVec<T> {
19    fn from(value: Vec<T>) -> Self {
20        Self(value.into_boxed_slice())
21    }
22}
23
24impl<T> FromIterator<T> for IVec<T> {
25    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
26        IVec(iter.into_iter().collect::<Vec<_>>().into_boxed_slice())
27    }
28}
29
30impl<T> std::ops::Deref for IVec<T> {
31    type Target = [T];
32
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl<'a, T> IntoIterator for &'a IVec<T> {
39    type Item = &'a T;
40    type IntoIter = std::slice::Iter<'a, T>;
41    fn into_iter(self) -> Self::IntoIter {
42        self.iter()
43    }
44}
45
46impl<'a, T> IntoIterator for &'a mut IVec<T> {
47    type Item = &'a mut T;
48    type IntoIter = std::slice::IterMut<'a, T>;
49
50    fn into_iter(self) -> Self::IntoIter {
51        self.iter_mut()
52    }
53}
54
55impl<T> IntoIterator for IVec<T> {
56    type Item = T;
57    type IntoIter = std::vec::IntoIter<T>;
58
59    fn into_iter(self) -> Self::IntoIter {
60        self.0.into_iter()
61    }
62}
63
64impl<T> IVec<T> {
65    /// get reference of internal slice
66    #[must_use]
67    pub fn as_slice(&self) -> &[T] {
68        &self.0
69    }
70
71    /// Returns the number of elements in the slice.
72    #[must_use]
73    pub fn len(&self) -> usize {
74        self.0.len()
75    }
76
77    /// Returns true if the slice has a length of 0.
78    #[must_use]
79    pub fn is_empty(&self) -> bool {
80        self.0.is_empty()
81    }
82
83    /// convert into Vec
84    #[must_use]
85    pub fn info_vec(self) -> Vec<T> {
86        Vec::from(self.0)
87    }
88
89    /// Returns an iterator over the slice.
90    ///
91    /// The iterator yields all items from start to end.
92    pub fn iter(&self) -> std::slice::Iter<'_, T> {
93        self.0.iter()
94    }
95
96    /// get mutateble iterator
97    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
98        self.0.iter_mut()
99    }
100}