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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#![doc=include_str!("../README.md")]
use std::slice;

/// A reference to a region of memory which is known to contain `N` or more elements
/// of type `T`.
///
/// Much like `[T]` itself, it is not possible to construct an owned `MinSlice`.
/// `MinSlice` is merely a way of reinterpreting an existing slice
/// (`&[T]` or `&mut [T]`), and it is exactly the same size as a slice:
/// one pointer and one `usize`.
/// 
/// # Example
/// 
/// ```
/// # use nslice::MinSlice;
/// let slice: &[u8] = b"Hello, world";
/// let minslice = MinSlice::<u8, 12>::from_slice(slice).unwrap();
/// let value: u8 = minslice.head[6];
/// assert_eq!(value, b' ')
/// ```
pub struct MinSlice<T, const N: usize> {
    /// The bounded region of memory. Exactly `N` `T`s.
    pub head: [T; N],
    /// Zero or more remaining `T`s after the `N` in the bounded region.
    pub tail: [T],
}

/// A reference to a region of memory which contains exactly `N` elements of type `T`.
///
/// `ExactSlice` is merely a way of reinterpreting an existing slice
/// (`&[T]` or `&mut [T]`), but because there is no need to store a length
/// for retrieval at runtime, its representation consists of just one pointer.

pub struct ExactSlice<T, const N: usize> {
    /// The bounded region of memory. Exactly `N` `T`s.
    head: [T; N]
}

impl<T, const N: usize> MinSlice<T, N> {
    /// Produce a `&MinSlice` from a slice of `T`s.
    /// Returns `None` if there are not enough elements in `slice`.
    pub fn from_slice(slice: &[T]) -> Option<&MinSlice<T, N>> {
        if slice.len() >= N {
            Some(unsafe { Self::from_slice_unchecked(slice) })
        } else {
            None
        }
    }
    
    /// Produce a `&mut MinSlice` from a mutable slice of `T`s.
    /// Returns `None` if there are not enough elements in `slice`.
    pub fn from_mut(slice: &mut [T]) -> Option<&mut MinSlice<T, N>> {
        if slice.len() >= N {
            Some(unsafe { Self::from_mut_unchecked(slice) })
        } else {
            None
        }
    }
}

impl<T, const N: usize> MinSlice<T, N> {
    /// Returns a slice over the memory referred to by the `MinSlice`.
    /// Its length is guaranteed to be no less than `N`.
    pub fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.head.as_ptr(), N + self.tail.len()) }
    }

    /// Returns a mutable slice over the memory referred to by the `MinSlice`.
    /// Its length is guaranteed to be no less than `N`.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { slice::from_raw_parts_mut(self.head.as_mut_ptr(), N + self.tail.len()) }
    }

    /// Resize the `MinSlice`, returning a new `Some(&MinSlice<T, M>)`
    /// if there are at least `M` `T`s in `self`. 
    pub fn resize<const M: usize>(&self) -> Option<&MinSlice<T, M>> {
        MinSlice::<T, M>::from_slice(self.as_slice())
    }

    /// Resize the `MinSlice`, returning a new `Some(&mut MinSlice<T, M>)`
    /// if there are at least `M` `T`s in `self`. 
    pub fn resize_mut<const M: usize>(&mut self) -> Option<&mut MinSlice<T, M>> {
        MinSlice::<T, M>::from_mut(self.as_mut_slice())
    }

    /// Get a reference to a value from the `MinSlice` by index.
    /// 
    /// Return `Some(&T)` for the `T` at index `i` if `i < (N + self.tail.len)`,
    /// or `None` otherwise.
    pub fn get(&self, i: usize) -> Option<&T> {
        if i < N {
            Some(&self.head[i])
        } else {
            self.tail.get(i)
        }
    }

    /// Get a mutable reference to a value from the `MinSlice` by index.
    /// 
    /// Return `Some(&mut T)` for the `T` at index `i` if `i < (N + self.tail.len)`,
    /// or `None` otherwise.
    pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
        if i < N {
            Some(&mut self.head[i])
        } else {
            self.tail.get_mut(i)
        }
    } 

    /// Produce a `&MinSlice` from a slice of `T`s without checking its length.
    ///
    /// # Safety
    ///
    /// The caller is responsible for upholding the length invariant
    /// `slice.len() >= N`, in addition to all normal slice invariants.
    pub unsafe fn from_slice_unchecked(slice: &[T]) -> &MinSlice<T, N> {
        let resized = slice::from_raw_parts(slice.as_ptr(), slice.len() - N);
        &*(resized as *const [T] as *const MinSlice<T, N>)
    }

    /// Produce a `&mut MinSlice` from a slice of `T`s without checking its length.
    ///
    /// # Safety
    ///
    /// The caller is responsible for upholding the length invariant
    /// `slice.len() >= N`, in addition to all normal slice invariants.
    pub unsafe fn from_mut_unchecked(slice: &mut [T]) -> &mut MinSlice<T, N> {
        let resized = slice::from_raw_parts_mut(slice.as_mut_ptr(), slice.len() - N);
        &mut *(resized as *mut [T] as *mut MinSlice<T, N>)
    }
}

impl<T, const N: usize> ExactSlice<T, N> {
    /// Produce a `&ExactSlice` from an array of `N` `T`s.
    pub fn from_array(array: &[T; N]) -> &ExactSlice<T, N> {
        unsafe { Self::from_slice_unchecked(&array[..]) }
    }

    /// Produce a `&mut ExactSlice` from an array of `N` `T`s.
    pub fn from_mut_array(array: &mut [T; N]) -> &mut ExactSlice<T, N> {
        unsafe { Self::from_mut_unchecked(&mut array[..]) }
    }

    /// Produce an `&ExactSlice` from a slice of `T`s.
    /// Returns `None` if there are not the correct number of elements in `slice`.
    pub fn from_slice(slice: &[T]) -> Option<&ExactSlice<T, N>> {
        if slice.len() == N {
            Some(unsafe { Self::from_slice_unchecked(slice) })
        } else {
            None
        }
    }

    /// Produce an `&mut ExactSlice` from a mutable slice of `T`s.
    /// Returns `None` if there are not the correct number of elements in `slice`.
    pub fn from_mut(slice: &mut [T]) -> Option<&mut ExactSlice<T, N>> {
        if slice.len() == N {
            Some(unsafe { Self::from_mut_unchecked(slice) })
        } else {
            None
        }
    }

    /// Returns a slice over the memory referred to by the `ExactSlice`.
    /// Its length is guaranteed to be exactly `N`.
    pub fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.head.as_ptr(), N) }
    }

    /// Returns a mutable slice over the memory referred to by the `ExactSlice`.
    /// Its length is guaranteed to be exactly `N`.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { slice::from_raw_parts_mut(self.head.as_mut_ptr(), N) }
    }

    /// Produce a `&MinSlice` from this `&ExactSlice`. Its `tail` will be empty.
    pub fn as_min_slice(&self) -> &MinSlice<T, N> {
        unsafe { MinSlice::from_slice_unchecked(&self.head[..]) }
    }

    /// Produce a `&mut MinSlice` from this `&min ExactSlice`. Its `tail` will be empty.
    pub fn as_mut_min_slice(&mut self) -> &mut MinSlice<T, N> {
        unsafe { MinSlice::from_mut_unchecked(&mut self.head[..]) }
    }

    /// Produce an `&ExactSlice` from a slice of `T`s without checking its length.
    ///
    /// # Safety
    ///
    /// The caller is responsible for upholding the length invariant
    /// `slice.len() == N`, in addition to all normal slice invariants.
    pub unsafe fn from_slice_unchecked(slice: &[T]) -> &ExactSlice<T, N> {
        &*(slice.as_ptr() as *const ExactSlice<T, N>)
    }

    /// Produce an `&mut ExactSlice` from a slice of `T`s without checking its length.
    ///
    /// # Safety
    ///
    /// The caller is responsible for upholding the length invariant
    /// `slice.len() == N`, in addition to all normal slice invariants.
    pub unsafe fn from_mut_unchecked(slice: &mut [T]) -> &mut ExactSlice<T, N> {
        &mut *(slice.as_mut_ptr() as *mut ExactSlice<T, N>)
    }
}

impl<'a, T, const N: usize> Into<&'a MinSlice<T, N>> for &'a ExactSlice<T, N> {
    fn into(self) -> &'a MinSlice<T, N> {
        self.as_min_slice()
    }
}

impl<'a, T, const N: usize> Into<&'a mut MinSlice<T, N>> for &'a mut ExactSlice<T, N> {
    fn into(self) -> &'a mut MinSlice<T, N> {
        self.as_mut_min_slice()
    }
}

impl<'a, T, const N: usize> Into<&'a ExactSlice<T, N>> for &'a MinSlice<T, N> {
    fn into(self) -> &'a ExactSlice<T, N> {
        unsafe { ExactSlice::from_slice_unchecked(&self.head[..]) }
    }
}

impl<'a, T, const N: usize> Into<&'a mut ExactSlice<T, N>> for &'a mut MinSlice<T, N> {
    fn into(self) -> &'a mut ExactSlice<T, N> {
        unsafe { ExactSlice::from_mut_unchecked(&mut self.head[..]) }
    }
}

#[test]
fn basic_min_success() {
    let slice = &[1, 2, 3, 4, 5, 6];
    let minslice: &MinSlice<_, 3> = MinSlice::from_slice(slice).unwrap();
    assert_eq!(minslice.tail.len(), 3);
    assert_eq!(minslice.head[0], 1);
    assert_eq!(minslice.tail[2], 6);
}

#[test]
fn basic_min_failure() {
    let slice = &[1, 2, 3, 4, 5, 6];
    let minslice: Option<&MinSlice<_, 7>> = MinSlice::from_slice(slice);
    assert!(minslice.is_none());
}

#[test]
fn basic_exact_success() {
    let slice = &[1, 2, 3, 4, 5, 6];
    let exactslice: &ExactSlice<_, 6> = ExactSlice::from_slice(slice).unwrap();
    assert_eq!(exactslice.head[0], 1);
}


#[test]
fn basic_exact_failure() {
    let slice = &[1, 2, 3, 4, 5, 6];
    let exactslice: Option<&ExactSlice<_, 3>> = ExactSlice::from_slice(slice);
    assert!(exactslice.is_none());
}

#[test]
fn array_exact_success() {
    let array = [1, 2, 3, 4, 5, 6];
    let exactslice: &ExactSlice<_, 6> = ExactSlice::from_array(&array);
    assert_eq!(exactslice.head[0], 1);
    assert_eq!(exactslice.head[5], 6);
}