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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use crate::error::ArrTooSmall;
use std::fmt::{Debug, Formatter};
use std::ops::{Index, IndexMut};
use std::slice::IterMut;

#[cfg(test)]
mod test;

/// A Vec but entirely on the stack.
///
/// # Example
/// ```
/// use vector_array::vec::VecArray;
///
/// let mut vec: VecArray<_, 10> = VecArray::new();
/// vec.push(9).unwrap();
/// assert_eq!(vec[0], 9);
/// ```
#[derive(Clone)]
pub struct VecArray<T, const CAP: usize> {
    arr: [T; CAP],
    len: usize,
}

pub struct IntoIter<T, const CAP: usize> {
    arr: [T; CAP],
    len: usize,
    itr: usize,
}

#[derive(Clone)]
pub struct Iter<'a, T> {
    arr: &'a [T],
    itr: usize,
}

/// Does the same as ::new
impl<T, const CAP: usize> Default for VecArray<T, CAP>
where
    T: Default,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T, const CAP: usize> VecArray<T, CAP>
where
    T: Default,
{
    /// Initializes all elements with defaults (does not increment length)
    ///
    /// # Example
    /// ```
    /// use vector_array::vec::VecArray;
    ///
    /// let mut vec: VecArray<_, 10> = VecArray::new();
    /// vec.push(9).unwrap();
    /// assert_eq!(vec[0], 9);
    /// ```
    ///
    /// Use ::new_no_default if type doesn't implement default
    ///
    pub fn new() -> Self {
        let mut slf = Self::new_no_default();
        slf.arr
            .iter_mut()
            .for_each(|x| unsafe { std::ptr::write(x as *mut T, Default::default()) });
        slf
    }
}

impl<T, const CAP: usize> VecArray<T, CAP> {
    /// Creates a new VecArray. Use ::new if type has default especially if type contains pointers/references (think String, Box, etc)
    ///
    /// # Example
    /// ```
    /// use vector_array::vec::VecArray;
    ///
    /// let mut vec: VecArray<_, 10> = VecArray::new_no_default();
    /// vec.push(9).unwrap();
    /// assert_eq!(vec[0], 9);
    /// ```
    ///
    /// # Safety
    /// There may be problems with drops if your type contains references for example.
    /// There also may be problems if you try to index in to parts of the array which are no yet initialized but this is nearly impossible.
    ///
    #[allow(clippy::uninit_assumed_init)]
    pub fn new_no_default() -> Self {
        Self {
            arr: unsafe { std::mem::MaybeUninit::uninit().assume_init() },
            len: 0,
        }
    }

    /// Creates a new VecArray. Use when type doesnt implement default and (drop) safety is a problem.
    ///
    pub fn new_arr(arr: [T; CAP], len: usize) -> Self {
        Self { arr, len }
    }

    /// Pushes an element.
    ///
    /// # Example
    /// ```
    /// use vector_array::vec::VecArray;
    ///
    /// let mut vec: VecArray<_, 10> = VecArray::new();
    /// vec.push(9).unwrap();
    /// assert_eq!(vec[0], 9);
    /// ```
    pub fn push(&mut self, value: T) -> Result<(), ArrTooSmall> {
        if self.len < CAP {
            unsafe {
                std::ptr::write(&mut self.arr[self.len] as *mut T, value);
            }
            self.len += 1;
            Ok(())
        } else {
            Err(ArrTooSmall)
        }
    }

    /// Removes the last element
    ///
    /// # Example
    /// ```
    /// use vector_array::vec::VecArray;
    ///
    /// let mut vec: VecArray<_, 10> = VecArray::new();
    /// vec.push(9).unwrap();
    /// assert_eq!(vec.pop(), Some(9));
    /// ```
    ///
    /// # Safety
    /// Returns memory which will realistically wont be used anymore
    ///
    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            None
        } else {
            self.len -= 1;
            Some(unsafe { std::ptr::read(&self.arr[self.len] as *const T) })
        }
    }

    /// Removes an element.
    ///
    /// # Panics
    /// If index is greater than or equal to length
    ///
    /// # Example
    /// ```
    /// use vector_array::vec::VecArray;
    /// let mut vec: VecArray<_, 10> = VecArray::new();
    /// vec.push(9).unwrap();
    /// vec.remove(0);
    /// assert!(vec.is_empty());
    /// ```
    ///
    /// # Safety
    /// Copied from Vec source code
    ///
    pub fn remove(&mut self, index: usize) -> T {
        let len = self.len;
        if index >= len {
            panic!("Removal index (is {index}) should be < len (is {len})");
        }

        // infallible
        let ret;
        unsafe {
            // the place we are taking from.
            let ptr = self.arr.as_mut_ptr().add(index);
            // copy it out, unsafely having a copy of the value on
            // the stack and in the vector at the same time.
            ret = std::ptr::read(ptr);

            // Shift everything down to fill in that spot.
            std::ptr::copy(ptr.add(1), ptr, len - index - 1);
        }
        self.len -= 1;
        ret
    }

    //// Inserts an element at position index within the vector, shifting all elements after it to the right.
    ///
    /// # Panics
    /// If index is greater than or equal to length or new length is greater than CAP
    /// # Example
    /// ```
    /// use vector_array::{vec_arr, VecArray};
    ///
    /// let mut vec: VecArray<_, 10> = vec_arr![1, 2, 3];
    /// vec.insert(1, 4);
    /// assert_eq!(vec, vec_arr![1, 4, 2, 3]);
    /// vec.insert(2, 5);
    /// assert_eq!(vec, vec_arr![1, 4, 5, 2, 3]);
    /// ```
    ///
    /// # Safety
    /// Copied from Vec source code
    ///
    pub fn insert(&mut self, index: usize, element: T) {
        if self.len + 1 > CAP {
            panic!("Array too small")
        }

        if index >= self.len {
            panic!("Index out of bounds");
        }
        unsafe {
            let ptr = self.arr.as_mut_ptr().add(index);
            std::ptr::copy(ptr, ptr.add(1), self.len - index);
            std::ptr::write(ptr, element);
        }
        self.len += 1;
    }
    /// Swaps two elements in the slice.
    ///
    /// # Panics
    /// Panics if one of the indexes are out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use vector_array::{vec_arr, VecArray};
    ///
    /// let mut vec: VecArray<_, 10> = vec_arr![0, 1, 2, 3];
    /// vec.swap(2, 3);
    /// assert_eq!(vec, vec_arr![0, 1, 3, 2]);
    /// ```
    ///
    pub fn swap(&mut self, index1: usize, index2: usize) {
        dbg!(self.len);
        if index1 >= self.len || index2 >= self.len {
            panic!("Index out of bounds");
        }
        unsafe {
            let ptr = self.arr.as_mut_ptr();
            let two = std::ptr::read(ptr.add(index2));
            std::ptr::copy(ptr.add(index1), ptr.add(index2), 1);
            std::ptr::write(ptr.add(index1), two);
        }
    }

    pub fn get(&self, index: usize) -> Option<&T> {
        if index >= self.len {
            None
        } else {
            Some(&self.arr[index])
        }
    }

    pub fn set(&mut self, index: usize, value: T) -> Result<(), ArrTooSmall> {
        if index >= self.len {
            Err(ArrTooSmall)
        } else {
            self.arr[index] = value;
            Ok(())
        }
    }

    pub fn truncate(&mut self, len: usize) {
        if len > self.len {
            return;
        }
        self.len = len;
    }

    pub fn last(&self) -> Option<&T> {
        if self.len == 0 {
            None
        } else {
            Some(&self.arr[self.len - 1])
        }
    }

    pub fn first(&self) -> Option<&T> {
        if self.len == 0 {
            None
        } else {
            Some(&self.arr[0])
        }
    }

    pub fn iter(&self) -> Iter<T> {
        Iter {
            arr: &self.arr[..self.len],
            itr: 0,
        }
    }

    pub fn iter_mut(&mut self) -> IterMut<T> {
        self.arr[..self.len].iter_mut()
    }

    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.arr.as_mut_ptr()
    }

    #[inline]
    pub fn as_ptr(&self) -> *const T {
        self.arr.as_ptr()
    }

    #[inline]
    /// Returns the entire array
    ///
    /// # Safety
    /// Can point to uninitialized memory, causes a segfault if memory is not properly initialized
    ///
    pub unsafe fn get_arr(self) -> [T; CAP] {
        self.arr
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

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

    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.arr[..self.len]
    }

    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.arr[..self.len]
    }

    #[inline]
    pub fn clear(&mut self) {
        self.len = 0;
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        CAP
    }
}

impl<T, const CAP: usize> From<VecArray<T, CAP>> for Vec<T> {
    fn from(val: VecArray<T, CAP>) -> Self {
        let mut vec = Vec::from(val.arr);
        vec.truncate(val.len);
        vec
    }
}

impl<T, const CAP: usize> Index<usize> for VecArray<T, CAP> {
    type Output = T;

    /// # Panics
    /// If index is greater than or equal to length
    ///
    /// Use .get instead
    fn index(&self, index: usize) -> &Self::Output {
        if index >= self.len {
            panic!("Index too big");
        } else {
            &self.arr[index]
        }
    }
}

impl<T, const CAP: usize> IndexMut<usize> for VecArray<T, CAP> {
    /// # Panics
    /// If index is greater than or equal to length
    ///
    /// Use .set instead
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        if index >= self.len {
            panic!("Index too big");
        } else {
            &mut self.arr[index]
        }
    }
}

impl<T, const CAP: usize> From<Vec<T>> for VecArray<T, CAP>
where
    T: Default,
{
    /// # Panics
    /// If inputs length is greater than CAP
    ///
    fn from(value: Vec<T>) -> Self {
        if value.len() > CAP {
            panic!("Vector too long");
        } else {
            let mut slf = Self::new();
            for x in value {
                slf.push(x).unwrap();
            }
            slf
        }
    }
}

impl<T, const CAP: usize> IntoIterator for VecArray<T, CAP> {
    type Item = T;
    type IntoIter = IntoIter<Self::Item, CAP>;

    fn into_iter(self) -> Self::IntoIter {
        Self::IntoIter {
            arr: self.arr,
            len: self.len,
            itr: 0,
        }
    }
}

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

    /// # Safety
    /// Is not unsafe because value wont be visited again
    ///
    fn next(&mut self) -> Option<Self::Item> {
        if self.itr >= self.len {
            None
        } else {
            let ret = Some(unsafe { std::ptr::read(&self.arr[self.itr] as *const T) });
            self.itr += 1;
            ret
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.itr >= self.arr.len() {
            None
        } else {
            let ret = Some(&self.arr[self.itr]);
            self.itr += 1;
            ret
        }
    }
}

impl<T, const CAP: usize> Debug for VecArray<T, CAP>
where
    T: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let vec = (0..self.len).map(|i| &self.arr[i]).collect::<Vec<_>>();
        if f.alternate() {
            write!(f, "{vec:#?}")
        } else {
            write!(f, "{vec:?}")
        }
    }
}

impl<T, const CAP: usize> PartialEq for VecArray<T, CAP>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        if self.len != other.len {
            false
        } else {
            self.arr[..self.len] == other.arr[..other.len]
        }
    }
}

/// Creates a VecArray just like the vec! macro
#[macro_export()]
macro_rules! vec_arr {
    () => { VecArray::new() };
    ($($x:expr),+ $(,)?) => {
        {
            let mut temp_vec = VecArray::new();
            $(
                temp_vec.push($x).expect(&format!("VecArray to small, (used in macro vec_arr! at line {})", line!()));
            )*
            temp_vec
        }
    };
	($x:expr; $n:literal) => {
		{
            let mut temp_vec = VecArray::new();
			for i in 0..$n => {
                temp_vec.push($x.clone()).expect(&format!("VecArray to small, (used in macro vec_arr! at line {})", line!()));
			}
			temp_vec
		}
	}
}