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
use std::{
    alloc::{alloc_zeroed, Layout},
    convert::{TryFrom, TryInto},
    fmt,
    fmt::{Debug, Formatter},
    ops::{Deref, DerefMut},
};

/// 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;
/// arr2[3] = 4;
/// assert_eq!(arr[2],4);
/// assert_eq!(arr2[3],4);
/// ```
pub struct Array<T, Len: Copy + Into<usize> + TryFrom<usize>> {
    ptr: std::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(&mut self[..]);
            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: std::ptr::NonNull::new(raw).unwrap(),
            len,
        }
    }

    /// Constructs a new `Array` from a given `Vec`.
    ///
    /// # Example
    ///
    /// ```
    /// use dynamic_array::SmallArray;
    ///
    /// let v = vec![8,9,10usize];
    /// 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)
    }

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

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

impl<T: Clone, Len: Copy + Into<usize> + TryFrom<usize>> Clone for Array<T, Len> {
    fn clone(&self) -> Self {
        unsafe {
            let other = Self::zeroed(self.len);
            other
                .ptr
                .as_ptr()
                .copy_from_nonoverlapping(self.ptr.as_ptr(), self.len.into());
            other
        }
    }
}

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[..], f)
    }
}