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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#![feature(const_generics, specialization, maybe_uninit_extra, maybe_uninit_slice)]

use std::convert::TryInto;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ops::{Deref, DerefMut};

#[cfg(test)]
mod test;

mod extend;

/// An array backed fixed capcity vector
pub struct ArrayVec<T, const N: usize> {
    arr: [MaybeUninit<T>; N],
    len: usize,
}

/// Creates a new empty array
impl<T, const N: usize> Default for ArrayVec<T, { N }> {
    fn default() -> Self {
        ArrayVec {
            arr: unsafe {
                // this is safe because the array is an array of `MaybeUninit<T>`
                MaybeUninit::uninit().assume_init()
            },
            len: 0,
        }
    }
}

impl<T, const N: usize> ArrayVec<T, { N }> {
    /// The pointer to the start of the array, only valid to read for `self.len()` elements
    ///
    /// This pointer is not valid to write to, use `as_mut_ptr` instead
    pub fn as_ptr(&self) -> *const T {
        MaybeUninit::first_ptr(&self.arr)
    }

    /// The pointer to the start of the array, only valid to read for `self.len()` elements, and to write for N elements
    pub fn as_mut_ptr(&mut self) -> *mut T {
        MaybeUninit::first_ptr_mut(&mut self.arr)
    }

    /// As a shared reference to a slice
    pub fn as_slice(&self) -> &[T] {
        self
    }

    /// As a unique reference to a slice
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        self
    }

    /// Puts an element onto the end of the `ArrayVec`
    pub fn push(&mut self, value: T) -> Result<(), T> {
        let res: Result<(), [T; 1]> = self.push_array([value]);

        res.map_err(|[val]| val)
    }

    /// Insert a single element into the `ArrayVec` at the given index
    pub fn insert(&mut self, value: T, index: usize) -> Result<(), T> {
        let res: Result<(), [T; 1]> = self.insert_array([value], index);

        res.map_err(|[val]| val)
    }

    /// Removes the last element from the `ArrayVec`
    pub fn pop(&mut self) -> Option<T> {
        let [val]: [T; 1] = self.pop_array()?;

        Some(val)
    }

    /// Put all of the elements of the array into the end of the `ArrayVec`
    pub fn push_array<const M: usize>(&mut self, array: [T; M]) -> Result<(), [T; M]> {
        if self.len + M <= N {
            unsafe {
                (self.as_mut_ptr().add(self.len) as *mut [T; M]).write(array);
            }
            self.len += M;
            Ok(())
        } else {
            Err(array)
        }
    }

    /// Insert all of the elements of the array into the `ArrayVec` at the given index
    pub fn insert_array<const M: usize>(
        &mut self,
        arr: [T; M],
        index: usize,
    ) -> Result<(), [T; M]> {
        if index <= self.len && self.len + M <= N {
            unsafe {
                let ptr = self.as_mut_ptr().add(index);

                std::ptr::copy(ptr, ptr.add(M), M);

                (ptr as *mut [T; M]).write(arr);
            }

            self.len += M;

            Ok(())
        } else {
            Err(arr)
        }
    }

    /// Pop the last M elements of the array at once
    pub fn pop_array<const M: usize>(&mut self) -> Option<[T; M]> {
        if N <= M {
            return None;
        }

        self.len = self.len.checked_sub(M)?;

        unsafe {
            let ptr = self.as_ptr().add(self.len) as *const [T; M];
            Some(ptr.read())
        }
    }

    /// The length of the `ArrayVec`
    pub fn len(&self) -> usize {
        self.len
    }

    /// Removes all elements from the `ArrayVec`
    pub fn clear(&mut self) {
        unsafe {
            std::ptr::drop_in_place(self.as_mut_slice());
        }
        self.len = 0;
    }

    /// This function logically takes ownership of the items inside of the slice
    unsafe fn copy_from_slice_unchecked(&mut self, slice: &[T]) {
        debug_assert!(self.len + slice.len() <= N);

        std::ptr::copy_nonoverlapping(slice.as_ptr(), self.as_mut_ptr().add(self.len), slice.len());

        self.len += slice.len();
    }

    /// Convert to an array, panics if the ArrayVec is not full
    pub fn into_array(self) -> [T; N] {
        assert_eq!(
            self.len, N,
            "Tried to convert an ArrayVec into an array when it wasn't fully initialized"
        );

        unsafe {
            self.into_array_unchecked()
        }
    }

    /// Convert to an array, not checked in release mode and will panic in debug mode
    pub unsafe fn into_array_unchecked(mut self) -> [T; N] {
        debug_assert_eq!(
            self.len, N,
            "Tried to convert an ArrayVec into an array when it wasn't fully initialized"
        );

        self.len = 0;
        
        let mut arr = MaybeUninit::<[T; N]>::uninit();

        std::ptr::copy_nonoverlapping(
            self.as_ptr(),
            arr.as_mut_ptr() as *mut T,
            N
        );

        arr.assume_init()
    }
}

impl<T: Clone, const N: usize> Clone for ArrayVec<T, { N }> {
    fn clone(&self) -> Self {
        let mut arr = ArrayVec::<T, { N }>::default();

        arr.extend_from_slice(self);

        arr
    }
}

impl<T, const N: usize> Deref for ArrayVec<T, { N }> {
    type Target = [T];

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

impl<T, const N: usize> DerefMut for ArrayVec<T, { N }> {
    fn deref_mut(&mut self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
    }
}

impl<T, const N: usize> Drop for ArrayVec<T, { N }> {
    fn drop(&mut self) {
        self.clear()
    }
}

impl<T, const N: usize> From<[T; N]> for ArrayVec<T, { N }> {
    fn from(arr: [T; N]) -> Self {
        let arr = std::mem::ManuallyDrop::new(arr);

        Self {
            arr: unsafe {
                std::ptr::read(&arr as &[T; N] as *const [T; N] as *const [MaybeUninit<T>; N])
            },
            len: N,
        }
    }
}

impl<T, const N: usize> TryInto<[T; N]> for ArrayVec<T, { N }> {
    type Error = Self;

    fn try_into(self) -> Result<[T; N], Self> {
        if self.len == N {
            unsafe { Ok(self.into_array_unchecked()) }
        } else {
            Err(self)
        }
    }
}

impl<T, const N: usize> IntoIterator for ArrayVec<T, { N }> {
    type Item = T;
    type IntoIter = IntoIter<T, { N }>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            arr: ManuallyDrop::new(self),
            idx: 0,
        }
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a mut ArrayVec<T, { N }> {
    type Item = &'a mut T;
    type IntoIter = std::slice::IterMut<'a, T>;

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

impl<'a, T, const N: usize> IntoIterator for &'a ArrayVec<T, { N }> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

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

/// An iterator over the elements of a `ArrayVec`
pub struct IntoIter<T, const N: usize> {
    arr: ManuallyDrop<ArrayVec<T, { N }>>,
    idx: usize,
}

impl<T: Clone, const N: usize> Clone for IntoIter<T, { N }> {
    fn clone(&self) -> Self {
        let mut arr = ArrayVec::<T, { N }>::default();

        arr.extend_from_slice(&self.arr[self.idx..]);

        IntoIter {
            arr: ManuallyDrop::new(arr),
            idx: 0,
        }
    }
}

impl<T, const N: usize> Iterator for IntoIter<T, { N }> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if N == 0 || self.arr.len == self.idx {
            None
        } else {
            let output = unsafe { self.arr.as_ptr().add(self.idx).read() };

            self.idx += 1;

            Some(output)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = self.arr.len - self.idx;

        (size, Some(size))
    }

    fn nth(&mut self, n: usize) -> Option<T> {
        match self.idx.checked_add(n) {
            Some(idx) if idx < self.arr.len => {
                unsafe {
                    std::ptr::drop_in_place(&mut self.arr[self.idx..idx]);
                }
                self.idx = idx;
                self.next()
            }
            _ => {
                unsafe {
                    std::ptr::drop_in_place(&mut self.arr[self.idx..]);
                }
                self.idx = self.arr.len;
                None
            }
        }
    }
}

impl<T, const N: usize> ExactSizeIterator for IntoIter<T, { N }> {}
impl<T, const N: usize> std::iter::FusedIterator for IntoIter<T, { N }> {}

impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, { N }> {
    fn next_back(&mut self) -> Option<T> {
        if self.idx == self.arr.len {
            None
        } else {
            self.arr.pop()
        }
    }

    fn nth_back(&mut self, n: usize) -> Option<T> {
        match self.arr.len.checked_sub(n) {
            Some(len) if self.idx < len => {
                unsafe {
                    std::ptr::drop_in_place(&mut self.arr[len..]);
                }
                self.arr.len = len;
                self.next_back()
            }
            _ => {
                unsafe {
                    std::ptr::drop_in_place(&mut self.arr[self.idx..]);
                }
                self.idx = self.arr.len;
                None
            }
        }
    }
}

impl<T, const N: usize> Extend<T> for ArrayVec<T, { N }> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let _ = iter.into_iter().take(N).try_fold((), |_, x| self.push(x));
    }
}

impl<T, const N: usize> std::iter::FromIterator<T> for ArrayVec<T, { N }> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut arr = ArrayVec::<T, { N }>::default();

        arr.extend(iter);

        arr
    }
}

impl<T, const N: usize> Drop for IntoIter<T, { N }> {
    fn drop(&mut self) {
        unsafe {
            std::ptr::drop_in_place(std::slice::from_raw_parts_mut(
                self.arr.as_mut_ptr().add(self.idx),
                self.arr.len - self.idx,
            ))
        }
    }
}

impl<T: Eq, const N: usize> Eq for ArrayVec<T, { N }> {}
impl<T: PartialEq, const N: usize, const M: usize> PartialEq<ArrayVec<T, { M }>>
    for ArrayVec<T, { N }>
{
    fn eq(&self, other: &ArrayVec<T, { M }>) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T: PartialOrd, const N: usize, const M: usize> PartialOrd<ArrayVec<T, { M }>>
    for ArrayVec<T, { N }>
{
    fn partial_cmp(&self, other: &ArrayVec<T, { M }>) -> Option<std::cmp::Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
}

impl<T: Ord, const N: usize> Ord for ArrayVec<T, { N }> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

use std::hash::{Hash, Hasher};

impl<T: Hash, const N: usize> Hash for ArrayVec<T, { N }> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state)
    }
}