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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::{
    alloc::{alloc_zeroed, Layout},
    cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd},
    convert::{TryFrom, TryInto},
    fmt,
    fmt::{Debug, Formatter},
    ops::{Deref, DerefMut, Index, IndexMut},
    ptr::NonNull,
    slice::SliceIndex,
};

/// A dynamically-allocated array of fixed size.
///
/// # Example
///
/// ```
/// use dynamic_array::SmallArray;
///
/// let mut arr = SmallArray::<u32>::zeroed(9);
///
/// assert!(!arr.is_empty());
///
/// // can be freely dereferenced
/// assert_eq!(arr[3], 0);
///
/// arr[7] = 8;
///
/// assert_eq!(arr[7], 8);
///
/// let mut arr2 = arr.clone();
///
/// assert_ne!(arr2[3], 4);
/// arr[2] = 4;
/// arr[4] = 0xdead;
/// arr2[3] = 4;
/// assert_eq!(arr[2], 4);
///
/// // can be sliced
/// assert_eq!(arr[2..5], [4u32, 0, 0xdead]);
///
/// // can also be freely iterated
/// for x in arr.iter_mut() {
///     *x += 1;
/// }
///
/// assert_eq!(arr[2], 5);
///
/// ```
#[cfg_attr(feature = "packed", repr(packed))]
pub struct Array<T, Len: Copy + Into<usize> + TryFrom<usize>> {
    ptr: NonNull<T>,
    len: Len,
}

unsafe impl<T: Sync, Len: Copy + Into<usize> + TryFrom<usize>> Sync for Array<T, Len> {}
unsafe impl<T: Send, Len: Copy + Into<usize> + TryFrom<usize>> Send for Array<T, Len> {}

impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Drop for Array<T, Len> {
    fn drop(&mut self) {
        unsafe {
            std::ptr::drop_in_place(self.deref_mut());
            Vec::from_raw_parts(self.ptr.as_ptr(), 0, self.len.into());
        }
    }
}

impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Array<T, Len> {
    /// Creates a zeroed `Array` with length `len`.
    pub fn zeroed(len: Len) -> Self {
        unsafe {
            let layout = Layout::array::<T>(len.into()).unwrap();
            let ptr = alloc_zeroed(layout).cast::<T>();

            Self::from_raw(ptr, len)
        }
    }

    /// Constructs a new `Array` from a raw pointer.
    ///
    /// After calling this function the pointer is owned by the resulting `Array`.
    pub fn from_raw(raw: *mut T, len: Len) -> Self {
        Self {
            ptr: NonNull::new(raw).unwrap(),
            len,
        }
    }

    /// Extracts a slice containing all the elements of `self`.
    pub fn as_slice(&self) -> &[T] {
        self
    }

    /// Extracts a mutable slice containing all the elements of `self`.
    pub fn as_slice_mut(&mut self) -> &mut [T] {
        self
    }

    /// Constructs a new `Array` from a given `Vec`.
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_array::SmallArray;
    ///
    /// let mut v = vec![8,9,10usize];
    /// v.reserve(1000);
    ///
    /// let arr = SmallArray::from_vec(v);
    ///
    /// assert_eq!(arr.len(), 3);
    /// ```
    pub fn from_vec(mut v: Vec<T>) -> Self
    where
        <Len as TryFrom<usize>>::Error: Debug,
    {
        let len = v.len().try_into().unwrap();
        let ptr = v.as_mut_ptr();
        std::mem::forget(v);

        Self::from_raw(ptr, len)
    }

    /// Constructs a `Vec` from `Self`.
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_array::SmallArray;
    ///
    /// let arr = SmallArray::<usize>::zeroed(5);
    ///
    /// let v: Vec<usize> = arr.into_vec();
    ///
    /// assert_eq!(v.len(), 5);
    /// assert_eq!(v[3], 0);
    /// ```
    pub fn into_vec(self) -> Vec<T> {
        unsafe {
            let size = self.len().try_into().unwrap();
            let v = Vec::from_raw_parts(self.ptr.as_ptr(), size, size);
            std::mem::forget(self);
            v
        }
    }

    /// The length of the array
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_array::SmallArray;
    /// let arr = SmallArray::<()>::zeroed(42);
    ///
    /// assert_eq!(arr.len(), 42);
    /// ```
    pub fn len(&self) -> Len {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len().into() == 0
    }
}

/**********************************************************************/
// Trait implementations

impl<T: Clone, Len: Copy + Into<usize> + TryFrom<usize>> Clone for Array<T, Len>
where
    <Len as TryFrom<usize>>::Error: Debug,
{
    fn clone(&self) -> Self {
        let mut other = Vec::with_capacity(self.len.into());
        for x in self.iter().cloned() {
            other.push(x);
        }

        let boxed = other.into_boxed_slice();
        let vec = Vec::from(boxed);

        Self::from_vec(vec)
    }
}

impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Deref for Array<T, Len> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len.into()) }
    }
}

impl<T, Len: Copy + Into<usize> + TryFrom<usize>> DerefMut for Array<T, Len> {
    fn deref_mut(&mut self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len.into()) }
    }
}

impl<T: Debug, Len: Copy + Into<usize> + TryFrom<usize>> Debug for Array<T, Len> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_slice(), f)
    }
}

impl<T, Len: Copy + Into<usize> + TryFrom<usize>> IntoIterator for Array<T, Len> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_vec().into_iter()
    }
}

impl<'t, T, Len: Copy + Into<usize> + TryFrom<usize>> IntoIterator for &'t Array<T, Len> {
    type Item = &'t T;
    type IntoIter = std::slice::Iter<'t, T>;

    fn into_iter(self) -> std::slice::Iter<'t, T> {
        self.iter()
    }
}

impl<'t, T, Len: Copy + Into<usize> + TryFrom<usize>> IntoIterator for &'t mut Array<T, Len> {
    type Item = &'t mut T;
    type IntoIter = std::slice::IterMut<'t, T>;

    fn into_iter(self) -> std::slice::IterMut<'t, T> {
        self.iter_mut()
    }
}

impl<T, Len> Eq for Array<T, Len>
where
    T: Eq,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
}

impl<T, Len> PartialEq for Array<T, Len>
where
    T: PartialEq<T>,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self[..] == other[..]
    }
    #[inline]
    fn ne(&self, other: &Self) -> bool {
        self[..] != other[..]
    }
}

impl<T, Len, U> PartialEq<[U]> for Array<T, Len>
where
    T: PartialEq<U>,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
    #[inline]
    fn eq(&self, other: &[U]) -> bool {
        self[..] == other[..]
    }
    #[inline]
    fn ne(&self, other: &[U]) -> bool {
        self[..] != other[..]
    }
}

impl<T, Len, U, const N: usize> PartialEq<[U; N]> for Array<T, Len>
where
    T: PartialEq<U>,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
    #[inline]
    fn eq(&self, other: &[U; N]) -> bool {
        self[..] == other[..]
    }
    #[inline]
    fn ne(&self, other: &[U; N]) -> bool {
        self[..] != other[..]
    }
}

impl<T, Len> Ord for Array<T, Len>
where
    T: Ord,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(&**self, &**other)
    }
}

impl<T, Len> PartialOrd for Array<T, Len>
where
    T: Ord,
    Len: Copy + Into<usize> + TryFrom<usize>,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
}

impl<T, Len, I> Index<I> for Array<T, Len>
where
    Len: Copy + Into<usize> + TryFrom<usize>,
    I: SliceIndex<[T]>,
{
    type Output = I::Output;

    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        Index::index(&**self, index)
    }
}

impl<T, Len, I> IndexMut<I> for Array<T, Len>
where
    Len: Copy + Into<usize> + TryFrom<usize>,
    I: SliceIndex<[T]>,
{
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        IndexMut::index_mut(&mut **self, index)
    }
}

/// `Default` does not always make sense for `Array`. This is an opt-in feature in case it is needed.
///
/// The resulting `Array` is rather unusable, as its length is 0.
#[cfg(feature = "default-derive")]
impl<T: Default, Len: Copy + Into<usize> + TryFrom<usize>> Default for Array<T, Len>
where
    <Len as TryFrom<usize>>::Error: Debug,
{
    fn default() -> Self {
        Self {
            ptr: NonNull::dangling(),
            len: 0.try_into().unwrap(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Array;

    #[cfg(feature = "packed")]
    #[test]
    fn packed() {
        assert_eq!(std::mem::size_of::<Array<usize, u8>>(), 9);
    }

    #[cfg(not(feature = "packed"))]
    #[test]
    fn not_packed() {
        assert_eq!(std::mem::size_of::<Array<usize, u8>>(), 16);
    }

    #[cfg(feature = "default-derive")]
    #[test]
    fn default() {
        let arr = Array::<u8, u8>::default();
        assert_eq!(arr.len(), 0);
    }
}