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
/// A slice with at least N elements. Can be dereferenced back into a regular slice on demand.
///
/// ```
/// use cl_array_ext::SliceN;
/// let a: &mut [_] = &mut [1, 2, 3, 4, 5];
/// let b: &mut SliceN<_, 3> = a.try_into().unwrap();
///
/// b.head = [3, 2, 1];
/// b.tail.reverse();
///
/// assert_eq!(a, [3, 2, 1, 5, 4]);
/// ```
#[repr(C)]
#[allow(clippy::module_name_repetitions)]
pub struct SliceN<T, const N: usize> {
    /// Head of the slice, where N items are guaranteed to exist
    pub head: [T; N],
    /// Tail of the slice, may be empty
    pub tail: [T],
}

impl<T, const N: usize> SliceN<T, N> {
    /// Increases the bounds of the slice into a new known length.
    /// # Safety
    /// There must be at least M elements in the tail available, otherwise this will result in UB
    pub unsafe fn increase_unchecked<const M: usize>(&self) -> &SliceN<T, { N + M }> {
        let (p, meta) = (self as *const SliceN<T, N>).to_raw_parts();
        &*core::ptr::from_raw_parts(p, meta - M)
    }

    /// Increases the bounds of the slice into a new known length.
    /// # Safety
    /// There must be at least M elements in the tail available, otherwise this will result in UB
    pub unsafe fn increase_unchecked_mut<const M: usize>(&mut self) -> &mut SliceN<T, { N + M }> {
        let (p, meta) = (self as *mut SliceN<T, N>).to_raw_parts();
        &mut *core::ptr::from_raw_parts_mut(p, meta - M)
    }

    /// Increases the bounds of the slice into a new known length.
    /// # Errors
    /// There should be at least M elements in the tail available, otherwise this will return an error
    pub fn increase<const M: usize>(&self) -> Result<&SliceN<T, { N + M }>, NotEnoughEntries> {
        if self.tail.len() < M {
            Err(NotEnoughEntries)
        } else {
            unsafe { Ok(self.increase_unchecked::<M>()) }
        }
    }

    /// Increases the bounds of the slice into a new known length.
    /// # Errors
    /// There should be at least M elements in the tail available, otherwise this will return an error
    pub fn increase_mut<const M: usize>(
        &mut self,
    ) -> Result<&mut SliceN<T, { N + M }>, NotEnoughEntries> {
        if self.tail.len() < M {
            Err(NotEnoughEntries)
        } else {
            unsafe { Ok(self.increase_unchecked_mut::<M>()) }
        }
    }

    /// Decreases the bounds of the slice to a smaller known length.
    pub fn downsize<const M: usize>(&self) -> &SliceN<T, M>
    where
        [T; N - M]: Sized, // M <= N
    {
        unsafe { SliceN::<T, M>::from_unchecked(self) }
    }

    /// Decreases the bounds of the slice to a smaller known length.
    pub fn downsize_mut<const M: usize>(&mut self) -> &mut SliceN<T, M>
    where
        [T; N - M]: Sized, // M <= N
    {
        unsafe { SliceN::<T, M>::from_unchecked_mut(self) }
    }

    /// Convert a slice into one that is guaranteed to have at least N elements
    /// # Safety
    /// The length of the slice must be >= N, otherwise this will result in UB
    pub unsafe fn from_unchecked(slice: &[T]) -> &Self {
        // extract the pointer metadata for the slice
        let (p, meta) = (slice as *const [T]).to_raw_parts();
        // convert the address and meta back into a ref
        &*core::ptr::from_raw_parts(p, meta - N)
    }

    /// Convert a mut slice into one that is guaranteed to have at least N elements
    /// # Safety
    /// The length of the slice must be >= N, otherwise this will result in UB
    pub unsafe fn from_unchecked_mut(slice: &mut [T]) -> &mut Self {
        // extract the pointer metadata for the slice
        let (p, meta) = (slice as *mut [T]).to_raw_parts();
        // convert the address and meta back into a ref
        &mut *core::ptr::from_raw_parts_mut(p, meta - N)
    }
}

/// Error type returned by the [`TryFrom`] implementations for [`SliceN`]
#[derive(Debug)]
pub struct NotEnoughEntries;

impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a SliceN<T, N> {
    type Error = NotEnoughEntries;
    fn try_from(value: &'a [T]) -> Result<Self, Self::Error> {
        if value.len() < N {
            Err(NotEnoughEntries)
        } else {
            unsafe { Ok(SliceN::<T, N>::from_unchecked(value)) }
        }
    }
}

impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut SliceN<T, N> {
    type Error = NotEnoughEntries;
    fn try_from(value: &'a mut [T]) -> Result<Self, Self::Error> {
        if value.len() < N {
            Err(NotEnoughEntries)
        } else {
            unsafe { Ok(SliceN::<T, N>::from_unchecked_mut(value)) }
        }
    }
}

use core::fmt;
impl<T: fmt::Debug, const N: usize> fmt::Debug for SliceN<T, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

use core::ops::{Deref, DerefMut};

impl<T, const N: usize> Deref for SliceN<T, N> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        // extract the pointer metadata for the slice
        let (p, meta) = (self as *const SliceN<T, N>).to_raw_parts();
        // convert the address and meta back into a ref
        unsafe { &*core::ptr::from_raw_parts(p, meta + N) }
    }
}

impl<T, const N: usize> DerefMut for SliceN<T, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // extract the pointer metadata for the slice
        let (p, meta) = (self as *mut SliceN<T, N>).to_raw_parts();
        // convert the address and meta back into a ref
        unsafe { &mut *core::ptr::from_raw_parts_mut(p, meta + N) }
    }
}

#[cfg(test)]
mod tests {
    use crate::SliceN;

    #[test]
    fn slice_n() {
        let a: &[_] = &[1, 2, 3, 4, 5];
        let b: &SliceN<_, 3> = a.try_into().unwrap();

        assert_eq!(b.len(), 5);
        assert_eq!(b.head, [1, 2, 3]);
        assert_eq!(b.tail, [4, 5]);
        assert_eq!(&**b, a);

        let b = b.increase::<2>().unwrap();
        assert_eq!(b.head, [1, 2, 3, 4, 5]);
        assert_eq!(b.tail, []);
        let _ = b.increase::<1>().unwrap_err();
        let _ = <&SliceN<_, 6>>::try_from(a).unwrap_err();
    }

    #[test]
    fn slice_n_mut() {
        let a: &mut [_] = &mut [1, 2, 3, 4, 5];
        let b: &mut SliceN<_, 3> = a.try_into().unwrap();

        b.head = [3, 2, 1];
        b.downsize_mut::<2>().head = [9, 8];

        assert_eq!(a, [9, 8, 1, 4, 5]);
    }
}