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#[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
37impl<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 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 #[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 pub fn new_arr(arr: [T; CAP], len: usize) -> Self {
100 Self { arr, len }
101 }
102
103 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 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 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 let ret;
173 unsafe {
174 let ptr = self.arr.as_mut_ptr().add(index);
176 ret = std::ptr::read(ptr);
179
180 std::ptr::copy(ptr.add(1), ptr, len - index - 1);
182 }
183 self.len -= 1;
184 ret
185 }
186
187 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 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 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 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 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 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 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#[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}