vector_array/
vec.rs

1use crate::error::ArrTooSmall;
2use std::fmt::{Debug, Formatter};
3use std::ops::{Index, IndexMut};
4use std::slice::IterMut;
5
6#[cfg(test)]
7mod test;
8
9/// A Vec but entirely on the stack.
10///
11/// # Example
12/// ```
13/// use vector_array::vec::VecArray;
14///
15/// let mut vec: VecArray<_, 10> = VecArray::new();
16/// vec.push(9).unwrap();
17/// assert_eq!(vec[0], 9);
18/// ```
19#[derive(Clone)]
20pub struct VecArray<T, const CAP: usize> {
21    arr: [T; CAP],
22    len: usize,
23}
24
25pub struct IntoIter<T, const CAP: usize> {
26    arr: [T; CAP],
27    len: usize,
28    itr: usize,
29}
30
31#[derive(Clone)]
32pub struct Iter<'a, T> {
33    arr: &'a [T],
34    itr: usize,
35}
36
37/// Does the same as ::new
38impl<T, const CAP: usize> Default for VecArray<T, CAP>
39where
40    T: Default,
41{
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl<T, const CAP: usize> VecArray<T, CAP>
48where
49    T: Default,
50{
51    /// Initializes all elements with defaults (does not increment length)
52    ///
53    /// # Example
54    /// ```
55    /// use vector_array::vec::VecArray;
56    ///
57    /// let mut vec: VecArray<_, 10> = VecArray::new();
58    /// vec.push(9).unwrap();
59    /// assert_eq!(vec[0], 9);
60    /// ```
61    ///
62    /// Use ::new_no_default if type doesn't implement default
63    ///
64    pub fn new() -> Self {
65        let mut slf = Self::new_no_default();
66        slf.arr
67            .iter_mut()
68            .for_each(|x| unsafe { std::ptr::write(x as *mut T, Default::default()) });
69        slf
70    }
71}
72
73impl<T, const CAP: usize> VecArray<T, CAP> {
74    /// Creates a new VecArray. Use ::new if type has default especially if type contains pointers/references (think String, Box, etc)
75    ///
76    /// # Example
77    /// ```
78    /// use vector_array::vec::VecArray;
79    ///
80    /// let mut vec: VecArray<_, 10> = VecArray::new_no_default();
81    /// vec.push(9).unwrap();
82    /// assert_eq!(vec[0], 9);
83    /// ```
84    ///
85    /// # Safety
86    /// There may be problems with drops if your type contains references for example.
87    /// 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.
88    ///
89    #[allow(clippy::uninit_assumed_init)]
90    pub fn new_no_default() -> Self {
91        Self {
92            arr: unsafe { std::mem::MaybeUninit::uninit().assume_init() },
93            len: 0,
94        }
95    }
96
97    /// Creates a new VecArray. Use when type doesnt implement default and (drop) safety is a problem.
98    ///
99    pub fn new_arr(arr: [T; CAP], len: usize) -> Self {
100        Self { arr, len }
101    }
102
103    /// Pushes an element.
104    ///
105    /// # Example
106    /// ```
107    /// use vector_array::vec::VecArray;
108    ///
109    /// let mut vec: VecArray<_, 10> = VecArray::new();
110    /// vec.push(9).unwrap();
111    /// assert_eq!(vec[0], 9);
112    /// ```
113    pub fn push(&mut self, value: T) -> Result<(), ArrTooSmall> {
114        if self.len < CAP {
115            unsafe {
116                std::ptr::write(&mut self.arr[self.len] as *mut T, value);
117            }
118            self.len += 1;
119            Ok(())
120        } else {
121            Err(ArrTooSmall)
122        }
123    }
124
125    /// Removes the last element
126    ///
127    /// # Example
128    /// ```
129    /// use vector_array::vec::VecArray;
130    ///
131    /// let mut vec: VecArray<_, 10> = VecArray::new();
132    /// vec.push(9).unwrap();
133    /// assert_eq!(vec.pop(), Some(9));
134    /// ```
135    ///
136    /// # Safety
137    /// Returns memory which will realistically wont be used anymore
138    ///
139    pub fn pop(&mut self) -> Option<T> {
140        if self.len == 0 {
141            None
142        } else {
143            self.len -= 1;
144            Some(unsafe { std::ptr::read(&self.arr[self.len] as *const T) })
145        }
146    }
147
148    /// Removes an element.
149    ///
150    /// # Panics
151    /// If index is greater than or equal to length
152    ///
153    /// # Example
154    /// ```
155    /// use vector_array::vec::VecArray;
156    /// let mut vec: VecArray<_, 10> = VecArray::new();
157    /// vec.push(9).unwrap();
158    /// vec.remove(0);
159    /// assert!(vec.is_empty());
160    /// ```
161    ///
162    /// # Safety
163    /// Copied from Vec source code
164    ///
165    pub fn remove(&mut self, index: usize) -> T {
166        let len = self.len;
167        if index >= len {
168            panic!("Removal index (is {index}) should be < len (is {len})");
169        }
170
171        // infallible
172        let ret;
173        unsafe {
174            // the place we are taking from.
175            let ptr = self.arr.as_mut_ptr().add(index);
176            // copy it out, unsafely having a copy of the value on
177            // the stack and in the vector at the same time.
178            ret = std::ptr::read(ptr);
179
180            // Shift everything down to fill in that spot.
181            std::ptr::copy(ptr.add(1), ptr, len - index - 1);
182        }
183        self.len -= 1;
184        ret
185    }
186
187    //// Inserts an element at position index within the vector, shifting all elements after it to the right.
188    ///
189    /// # Panics
190    /// If index is greater than or equal to length or new length is greater than CAP
191    ///
192    /// # Example
193    /// ```
194    /// use vector_array::{vec_arr, VecArray};
195    ///
196    /// let mut vec: VecArray<_, 10> = vec_arr![1, 2, 3];
197    /// vec.insert(1, 4);
198    /// assert_eq!(vec, vec_arr![1, 4, 2, 3]);
199    /// vec.insert(2, 5);
200    /// assert_eq!(vec, vec_arr![1, 4, 5, 2, 3]);
201    /// ```
202    ///
203    /// # Safety
204    /// Copied from Vec source code
205    ///
206    pub fn insert(&mut self, index: usize, element: T) {
207        if self.len + 1 > CAP {
208            panic!("Array too small")
209        }
210
211        if index >= self.len {
212            panic!("Index out of bounds");
213        }
214
215        unsafe {
216            let ptr = self.arr.as_mut_ptr().add(index);
217            std::ptr::copy(ptr, ptr.add(1), self.len - index);
218            std::ptr::write(ptr, element);
219        }
220        self.len += 1;
221    }
222    /// Swaps two elements in the vec.
223    ///
224    /// # Panics
225    /// Panics if one of the indexes are out of bounds.
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use vector_array::{vec_arr, VecArray};
231    ///
232    /// let mut vec: VecArray<_, 10> = vec_arr![0, 1, 2, 3];
233    /// vec.swap(2, 3);
234    /// assert_eq!(vec, vec_arr![0, 1, 3, 2]);
235    /// ```
236    ///
237    pub fn swap(&mut self, index1: usize, index2: usize) {
238        if index1 >= self.len || index2 >= self.len {
239            panic!("Index out of bounds");
240        }
241        unsafe {
242            let ptr = self.arr.as_mut_ptr();
243            let two = std::ptr::read(ptr.add(index2));
244            std::ptr::copy(ptr.add(index1), ptr.add(index2), 1);
245            std::ptr::write(ptr.add(index1), two);
246        }
247    }
248
249    pub fn get(&self, index: usize) -> Option<&T> {
250        if index >= self.len {
251            None
252        } else {
253            Some(&self.arr[index])
254        }
255    }
256
257    pub fn set(&mut self, index: usize, value: T) -> Result<(), ArrTooSmall> {
258        if index >= self.len {
259            Err(ArrTooSmall)
260        } else {
261            self.arr[index] = value;
262            Ok(())
263        }
264    }
265
266    pub fn truncate(&mut self, len: usize) {
267        if len > self.len {
268            return;
269        }
270        self.len = len;
271    }
272
273    pub fn last(&self) -> Option<&T> {
274        if self.len == 0 {
275            None
276        } else {
277            Some(&self.arr[self.len - 1])
278        }
279    }
280
281    pub fn first(&self) -> Option<&T> {
282        if self.len == 0 {
283            None
284        } else {
285            Some(&self.arr[0])
286        }
287    }
288
289    pub fn iter(&self) -> Iter<T> {
290        Iter {
291            arr: &self.arr[..self.len],
292            itr: 0,
293        }
294    }
295
296    pub fn iter_mut(&mut self) -> IterMut<T> {
297        self.arr[..self.len].iter_mut()
298    }
299
300    #[inline]
301    pub fn as_mut_ptr(&mut self) -> *mut T {
302        self.arr.as_mut_ptr()
303    }
304
305    #[inline]
306    pub fn as_ptr(&self) -> *const T {
307        self.arr.as_ptr()
308    }
309
310    #[inline]
311    /// Returns the entire array
312    ///
313    /// # Safety
314    /// Can point to uninitialized memory, causes a segfault if memory is not properly initialized
315    ///
316    pub unsafe fn get_arr(self) -> [T; CAP] {
317        self.arr
318    }
319
320    #[inline]
321    pub fn len(&self) -> usize {
322        self.len
323    }
324
325    #[inline]
326    pub fn is_empty(&self) -> bool {
327        self.len == 0
328    }
329
330    #[inline]
331    pub fn as_slice(&self) -> &[T] {
332        &self.arr[..self.len]
333    }
334
335    #[inline]
336    pub fn as_mut_slice(&mut self) -> &mut [T] {
337        &mut self.arr[..self.len]
338    }
339
340    #[inline]
341    pub fn clear(&mut self) {
342        self.len = 0;
343    }
344
345    #[inline]
346    pub fn capacity(&self) -> usize {
347        CAP
348    }
349}
350
351impl<T, const CAP: usize> From<VecArray<T, CAP>> for Vec<T> {
352    fn from(val: VecArray<T, CAP>) -> Self {
353        let mut vec = Vec::from(val.arr);
354        vec.truncate(val.len);
355        vec
356    }
357}
358
359impl<T, const CAP: usize> Index<usize> for VecArray<T, CAP> {
360    type Output = T;
361
362    /// # Panics
363    /// If index is greater than or equal to length
364    ///
365    /// Use .get instead
366    fn index(&self, index: usize) -> &Self::Output {
367        if index >= self.len {
368            panic!("Index too big");
369        } else {
370            &self.arr[index]
371        }
372    }
373}
374
375impl<T, const CAP: usize> IndexMut<usize> for VecArray<T, CAP> {
376    /// # Panics
377    /// If index is greater than or equal to length
378    ///
379    /// Use .set instead
380    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
381        if index >= self.len {
382            panic!("Index too big");
383        } else {
384            &mut self.arr[index]
385        }
386    }
387}
388
389impl<T, const CAP: usize> From<Vec<T>> for VecArray<T, CAP>
390where
391    T: Default,
392{
393    /// # Panics
394    /// If inputs length is greater than CAP
395    ///
396    fn from(value: Vec<T>) -> Self {
397        if value.len() > CAP {
398            panic!("Vector too long");
399        } else {
400            let mut slf = Self::new();
401            for x in value {
402                slf.push(x).unwrap();
403            }
404            slf
405        }
406    }
407}
408
409impl<T, const CAP: usize> IntoIterator for VecArray<T, CAP> {
410    type Item = T;
411    type IntoIter = IntoIter<Self::Item, CAP>;
412
413    fn into_iter(self) -> Self::IntoIter {
414        Self::IntoIter {
415            arr: self.arr,
416            len: self.len,
417            itr: 0,
418        }
419    }
420}
421
422impl<T, const CAP: usize> Iterator for IntoIter<T, CAP> {
423    type Item = T;
424
425    /// # Safety
426    /// Is not unsafe because value wont be visited again
427    ///
428    fn next(&mut self) -> Option<Self::Item> {
429        if self.itr >= self.len {
430            None
431        } else {
432            let ret = Some(unsafe { std::ptr::read(&self.arr[self.itr] as *const T) });
433            self.itr += 1;
434            ret
435        }
436    }
437}
438
439impl<'a, T> Iterator for Iter<'a, T> {
440    type Item = &'a T;
441
442    fn next(&mut self) -> Option<Self::Item> {
443        if self.itr >= self.arr.len() {
444            None
445        } else {
446            let ret = Some(&self.arr[self.itr]);
447            self.itr += 1;
448            ret
449        }
450    }
451}
452
453impl<T, const CAP: usize> Debug for VecArray<T, CAP>
454where
455    T: Debug,
456{
457    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
458        let vec = (0..self.len).map(|i| &self.arr[i]).collect::<Vec<_>>();
459        if f.alternate() {
460            write!(f, "{vec:#?}")
461        } else {
462            write!(f, "{vec:?}")
463        }
464    }
465}
466
467impl<T, const CAP: usize> PartialEq for VecArray<T, CAP>
468where
469    T: PartialEq,
470{
471    fn eq(&self, other: &Self) -> bool {
472        if self.len != other.len {
473            false
474        } else {
475            self.arr[..self.len] == other.arr[..other.len]
476        }
477    }
478}
479
480/// Creates a VecArray just like the vec! macro
481#[macro_export()]
482macro_rules! vec_arr {
483    () => { VecArray::new() };
484    ($($x:expr),+ $(,)?) => {
485        {
486            let mut temp_vec = VecArray::new();
487            $(
488                temp_vec.push($x).expect(&format!("VecArray to small, (used in macro vec_arr! at line {})", line!()));
489            )*
490            temp_vec
491        }
492    };
493	($x:expr; $n:literal) => {
494		{
495            let mut temp_vec = VecArray::new();
496			for i in 0..$n => {
497                temp_vec.push($x.clone()).expect(&format!("VecArray to small, (used in macro vec_arr! at line {})", line!()));
498			}
499			temp_vec
500		}
501	}
502}