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

/// 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();
///
/// // can be indexed by the `Len` type
/// assert_ne!(arr2[3u8], 4);
/// arr[2] = 4;
/// arr2[3] = 4;
/// assert_eq!(arr[2], 4);
///
/// // can still be indexed by `usize`, as a slice
/// assert_eq!(arr2.as_slice()[3usize], 4);
///
/// // can also be freely iterated
/// for x in arr.iter_mut() {
///     *x += 1;
/// }
///
/// assert_eq!(arr[2], 5);
///
/// dbg!(arr);
/// ```
#[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: std::ptr::NonNull::new(raw).unwrap(),
            len,
        }
    }

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

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

    /// 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> {
    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.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: Copy + Into<usize> + TryFrom<usize>> Index<Len> for Array<T, Len> {
    type Output = T;

    fn index(&self, index: Len) -> &Self::Output {
        &self.deref()[index.into()]
    }
}

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

/// `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);
    }
}