noalloc_vec_rs/
vec.rs

1use core::mem::ManuallyDrop;
2use core::mem::MaybeUninit;
3use core::mem::size_of;
4use core::ops::Deref;
5use core::ops::DerefMut;
6use core::ptr;
7use core::slice;
8
9use crate::assert_lte;
10
11/// A fixed-size vector with a maximum length specified at compile time.
12#[derive(Debug)]
13pub struct Vec<T, const MAX_LENGTH: usize> {
14    array: [MaybeUninit<T>; MAX_LENGTH],
15    length: usize,
16}
17
18/// An iterator over the elements of a `Vec`.
19pub struct IntoIter<T, const MAX_LENGTH: usize> {
20    vec: Vec<T, MAX_LENGTH>,
21    next: usize,
22}
23
24impl<T, const MAX_LENGTH: usize> IntoIter<T, MAX_LENGTH> {
25    /// Creates a new `IntoIter` from a `Vec`.
26    ///
27    /// # Arguments
28    ///
29    /// * `vec` - The `Vec` to iterate over.
30    ///
31    /// # Returns
32    ///
33    /// A new `IntoIter` instance.
34    #[must_use]
35    pub const fn new(vec: Vec<T, MAX_LENGTH>) -> Self {
36        Self { vec, next: 0 }
37    }
38}
39
40impl<T, const MAX_LENGTH: usize> Vec<T, MAX_LENGTH> {
41    /// Creates a new, empty `Vec` with a maximum length specified at compile time.
42    ///
43    /// # Returns
44    ///
45    /// A new, empty `Vec` instance.
46    #[must_use]
47    pub const fn new() -> Self {
48        Self {
49            array: [const { MaybeUninit::uninit() }; MAX_LENGTH],
50            length: 0,
51        }
52    }
53
54    /// Attempts to push a value onto the vector.
55    ///
56    /// # Arguments
57    ///
58    /// * `value` - The value to push onto the vector.
59    ///
60    /// # Returns
61    ///
62    /// * `Ok(())` if the value was successfully pushed
63    /// * `Err(())` if the vector is full.
64    #[allow(clippy::result_unit_err)]
65    pub fn push(&mut self, value: T) -> Result<(), ()> {
66        if self.length < MAX_LENGTH {
67            // This is a safe operation because we've checked that the vector is not full
68            unsafe { self.push_unchecked(value) };
69
70            Ok(())
71        } else {
72            Err(())
73        }
74    }
75
76    /// Pushes a value onto the vector without checking if it is full.
77    ///
78    /// # Arguments
79    ///
80    /// * `value` - The value to push onto the vector.
81    ///
82    /// # Safety
83    ///
84    /// Capacity must be checked before calling this function.
85    pub const unsafe fn push_unchecked(&mut self, value: T) {
86        self.array[self.length].write(value);
87        self.length += 1;
88    }
89
90    /// Removes the last element from the vector and returns it.
91    ///
92    /// # Returns
93    ///
94    /// * `Some(T)` if the vector is not empty
95    /// * `None` if the vector is empty.
96    #[must_use]
97    pub fn pop(&mut self) -> Option<T> {
98        if self.length > 0 {
99            // This is a safe operation because we've checked that the vector is not empty
100            unsafe { Some(self.pop_unchecked()) }
101        } else {
102            None
103        }
104    }
105
106    /// Removes the last element from the vector and returns it without checking if it is empty.
107    ///
108    /// # Returns
109    ///
110    /// The last element of the vector.
111    ///
112    /// # Safety
113    ///
114    /// Capacity must be checked before calling this function.
115    #[must_use]
116    pub unsafe fn pop_unchecked(&mut self) -> T {
117        self.length -= 1;
118        unsafe { self.get_unchecked(self.length) }
119    }
120
121    /// Writes a value to the specified index in the vector.
122    ///
123    /// # Arguments
124    ///
125    /// * `index` - The index at which to write the value.
126    /// * `value` - The value to write.
127    ///
128    /// # Returns
129    ///
130    /// * `Ok(())` if the value was successfully written.
131    /// * `Err(())` if the index is out of bounds.
132    #[allow(clippy::result_unit_err)]
133    pub fn write(&mut self, index: usize, value: T) -> Result<(), ()> {
134        if index <= self.length && index < MAX_LENGTH {
135            // This is a safe operation because we've checked that the vector can hold the value
136            unsafe { self.write_unchecked(index, value) };
137
138            Ok(())
139        } else {
140            Err(())
141        }
142    }
143
144    /// Writes a value to the specified index in the vector without checking bounds.
145    ///
146    /// # Arguments
147    ///
148    /// * `index` - The index at which to write the value.
149    /// * `value` - The value to write.
150    ///
151    /// # Safety
152    ///
153    /// Capacity must be checked before calling this function.
154    pub const unsafe fn write_unchecked(&mut self, index: usize, value: T) {
155        // Make sure all the previous bytes are initialized before reading the array
156        self.array[index].write(value);
157        if index >= self.length {
158            self.length = index + 1;
159        }
160    }
161
162    /// Writes a slice of values to the vector starting at the specified index.
163    ///
164    /// # Arguments
165    ///
166    /// * `index` - The starting index at which to write the slice.
167    /// * `value` - The slice of values to write.
168    ///
169    /// # Returns
170    ///
171    /// * `Ok(())` if the slice was successfully written.
172    /// * `Err(())` if the index or slice length is out of bounds.
173    #[allow(clippy::result_unit_err)]
174    pub const fn write_slice(&mut self, index: usize, value: &[T]) -> Result<(), ()>
175    where
176        T: Copy,
177    {
178        if index <= self.length && index + value.len() <= MAX_LENGTH {
179            // This is a safe operation because we've checked that the vector can hold the slice
180            unsafe { self.write_slice_unchecked(index, value) };
181
182            Ok(())
183        } else {
184            Err(())
185        }
186    }
187
188    /// Writes a slice of values to the vector starting at the specified index without checking bounds.
189    ///
190    /// # Arguments
191    ///
192    /// * `start_index` - The starting index at which to write the slice.
193    /// * `value` - The slice of values to write.
194    ///
195    /// # Safety
196    ///
197    /// Capacity must be checked before calling this function.
198    pub const unsafe fn write_slice_unchecked(&mut self, mut start_index: usize, value: &[T])
199    where
200        T: Copy,
201    {
202        // Make sure all the previous bytes are initialized before reading the array
203        let mut index = 0;
204        while index < value.len() {
205            unsafe { self.write_unchecked(start_index, value[index]) };
206
207            index += 1;
208            start_index += 1;
209        }
210    }
211
212    /// Attempts to insert a value at the specified index in the vector.
213    ///
214    /// # Arguments
215    ///
216    /// * `index` - The index at which to insert the value.
217    /// * `value` - The value to insert.
218    ///
219    /// # Returns
220    ///
221    /// * `Ok(())` if the value was successfully inserted.
222    /// * `Err(())` if the index is out of bounds or the vector is full.
223    #[allow(clippy::result_unit_err)]
224    pub fn insert(&mut self, index: usize, value: T) -> Result<(), ()> {
225        // Check if the element can be inserted
226        if index > self.length || self.length + 1 > MAX_LENGTH {
227            Err(())
228        } else {
229            // Shift all the elements after the index to the right
230            unsafe {
231                let start_slice = self.as_mut_ptr().add(index);
232                ptr::copy(start_slice, start_slice.add(1), self.length - index);
233                ptr::write(start_slice, value);
234            }
235
236            self.length += 1;
237
238            Ok(())
239        }
240    }
241
242    /// Removes the element at the specified index from the vector and returns it.
243    ///
244    /// # Arguments
245    ///
246    /// * `index` - The index of the element to remove.
247    ///
248    /// # Returns
249    ///
250    /// * `Some(T)` if the element was successfully removed.
251    /// * `None` if the index is out of bounds.
252    #[must_use]
253    pub fn remove(&mut self, index: usize) -> Option<T> {
254        if index < self.length {
255            // This is a safe operation because we know that the index is within bounds
256            let value = unsafe { self.get_unchecked(index) };
257
258            // Shift all the elements after the index to the left
259            unsafe {
260                let start_slice = self.as_mut_ptr().add(index);
261                ptr::copy(start_slice.add(1), start_slice, self.length - index - 1);
262            }
263
264            self.length -= 1;
265
266            Some(value)
267        } else {
268            None
269        }
270    }
271
272    /// Returns a reference to the element at the specified index.
273    ///
274    /// # Arguments
275    ///
276    /// * `index` - The index of the element to get.
277    ///
278    /// # Returns
279    ///
280    /// * `Some(&T)` if the index is within bounds.
281    /// * `None` if the index is out of bounds.
282    #[must_use]
283    pub fn get(&self, index: usize) -> Option<T> {
284        if index < self.length {
285            // This is a safe operation because we know that the index is within bounds
286            unsafe { Some(self.get_unchecked(index)) }
287        } else {
288            None
289        }
290    }
291
292    /// Returns a reference to the element at the specified index without checking bounds.
293    ///
294    /// # Arguments
295    ///
296    /// * `index` - The index of the element to get.
297    ///
298    /// # Returns
299    ///
300    /// A reference to the element at the specified index.
301    ///
302    /// # Safety
303    ///
304    /// Capacity must be checked before calling this function.
305    #[must_use]
306    pub unsafe fn get_unchecked(&self, index: usize) -> T {
307        unsafe { self.array.get_unchecked(index).as_ptr().read() }
308    }
309
310    /// Returns a mutable reference to the element at the specified index.
311    ///
312    /// # Arguments
313    ///
314    /// * `index` - The index of the element to get.
315    ///
316    /// # Returns
317    ///
318    /// * `Some(&mut T)` if the index is within bounds.
319    /// * `None` if the index is out of bounds.
320    #[must_use]
321    pub fn get_mut(&mut self, index: usize) -> Option<T> {
322        if index < self.length {
323            // This is a safe operation because we know the index is within bounds
324            unsafe { Some(self.get_mut_unchecked(index)) }
325        } else {
326            None
327        }
328    }
329
330    /// Returns a mutable reference to the element at the specified index without checking bounds.
331    ///
332    /// # Arguments
333    ///
334    /// * `index` - The index of the element to get.
335    ///
336    /// # Returns
337    ///
338    /// A mutable reference to the element at the specified index.
339    ///
340    /// # Safety
341    ///
342    /// Capacity must be checked before calling this function.
343    #[must_use]
344    pub unsafe fn get_mut_unchecked(&mut self, index: usize) -> T {
345        unsafe { self.array.get_unchecked_mut(index).as_mut_ptr().read() }
346    }
347
348    /// Truncates the vector to the specified length.
349    ///
350    /// # Arguments
351    ///
352    /// * `new_length` - The new length of the vector.
353    pub fn truncate(&mut self, new_length: usize) {
354        if new_length >= self.length {
355            return;
356        }
357
358        // Update the length
359        let remaining_len = self.length - new_length;
360        self.length = new_length;
361
362        // Drop the old elements that are outside of the new length
363        let start_slice = unsafe { self.as_mut_ptr().add(new_length) };
364        let slice_to_drop = ptr::slice_from_raw_parts_mut(start_slice, remaining_len);
365        unsafe {
366            ptr::drop_in_place(slice_to_drop);
367        }
368    }
369
370    /// Clears the vector, removing all elements.
371    pub fn clear(&mut self) {
372        self.truncate(0);
373    }
374
375    unsafe fn extend<I>(&mut self, iter: I)
376    where
377        I: IntoIterator<Item = T>,
378    {
379        for elem in iter {
380            unsafe { self.push_unchecked(elem) };
381        }
382    }
383
384    /// Returns a slice containing the entire vector.
385    ///
386    /// # Returns
387    ///
388    /// A slice containing the entire vector.
389    #[must_use]
390    pub const fn as_slice(&self) -> &[T] {
391        unsafe { slice::from_raw_parts(self.array.as_ptr().cast::<T>(), self.length) }
392    }
393
394    /// Returns a mutable slice containing the entire vector.
395    ///
396    /// # Returns
397    ///
398    /// A mutable slice containing the entire vector.
399    #[must_use]
400    pub const fn as_mut_slice(&mut self) -> &mut [T] {
401        unsafe { slice::from_raw_parts_mut(self.array.as_mut_ptr().cast::<T>(), self.length) }
402    }
403
404    #[must_use]
405    unsafe fn from_array_unchecked<const LENGTH: usize>(from_array: [T; LENGTH]) -> Self {
406        let mut vec = Self::new();
407
408        // Do not drop the elements of the array, since we're moving them into the vector
409        let array = ManuallyDrop::new(from_array);
410
411        while vec.length < array.len() {
412            vec.array[vec.length] =
413                MaybeUninit::new(unsafe { ptr::read(&raw const array[vec.length]) });
414            vec.length += 1;
415        }
416
417        vec
418    }
419
420    #[must_use]
421    const unsafe fn from_slice_unchecked(from_slice: &[T]) -> Self
422    where
423        T: Copy,
424    {
425        let mut vec = Self::new();
426
427        while vec.length < from_slice.len() {
428            vec.array[vec.length] = MaybeUninit::new(from_slice[vec.length]);
429            vec.length += 1;
430        }
431
432        vec
433    }
434
435    #[must_use]
436    unsafe fn from_uint_unchecked(mut value: u64, max_length: usize) -> Self
437    where
438        T: From<u8>,
439    {
440        let mut vec = Self::new();
441
442        let mut real_length = 0;
443        let mut index = 0;
444        while index < max_length {
445            let byte = (value & 0xff) as u8;
446            if byte != 0 {
447                real_length = index + 1;
448            }
449
450            unsafe { vec.push_unchecked(byte.into()) };
451
452            // Shift the value to the right
453            value >>= 8;
454
455            index += 1;
456        }
457
458        vec.length = real_length;
459        vec
460    }
461
462    #[must_use]
463    fn to_uint(&self) -> u64
464    where
465        T: Into<u8>,
466    {
467        let mut value = 0;
468        let mut index = 0;
469        while index < self.len() {
470            // This is a safe operation because we know that the index is within bounds
471            let byte = unsafe { self.get_unchecked(index).into() };
472
473            value |= u64::from(byte) << (index * 8);
474
475            index += 1;
476        }
477
478        value
479    }
480
481    /// Returns the current length of the vector.
482    ///
483    /// # Returns
484    ///
485    /// The current length of the vector.
486    #[must_use]
487    pub const fn len(&self) -> usize {
488        self.length
489    }
490
491    /// Returns the remaining capacity of the vector.
492    ///
493    /// # Returns
494    ///
495    /// The remaining capacity of the vector.
496    #[must_use]
497    pub const fn remaining_len(&self) -> usize {
498        MAX_LENGTH - self.length
499    }
500
501    /// Checks if the vector is empty.
502    ///
503    /// # Returns
504    ///
505    /// * `true` if the vector is empty
506    /// * `false` if the vector is not empty
507    #[must_use]
508    pub const fn is_empty(&self) -> bool {
509        self.length == 0
510    }
511}
512
513/// Default implementation for `Vec`.
514///
515/// This allows creating a `Vec` using `Vec::default()`.
516impl<T, const MAX_LENGTH: usize> Default for Vec<T, MAX_LENGTH> {
517    /// Creates a new, empty `Vec` with a maximum length specified at compile time.
518    ///
519    /// # Returns
520    ///
521    /// A new, empty `Vec` instance.
522    fn default() -> Self {
523        Self::new()
524    }
525}
526
527/// Drop implementation for `Vec`.
528///
529/// This ensures that all elements in the `Vec` are properly dropped when the `Vec` goes out of scope.
530impl<T, const LENGTH: usize> Drop for Vec<T, LENGTH> {
531    /// Drops all elements in the `Vec`.
532    fn drop(&mut self) {
533        unsafe {
534            ptr::drop_in_place(self.as_mut_slice());
535        }
536    }
537}
538
539/// Implementation of `IntoIterator` for `&Vec`.
540///
541/// This allows iterating over references to the elements of a `Vec`.
542impl<'a, T, const MAX_LENGTH: usize> IntoIterator for &'a Vec<T, MAX_LENGTH> {
543    type Item = &'a T;
544    type IntoIter = slice::Iter<'a, T>;
545
546    /// Returns an iterator over the elements of the `Vec`.
547    fn into_iter(self) -> Self::IntoIter {
548        self.iter()
549    }
550}
551
552/// Implementation of `Iterator` for `IntoIter`.
553///
554/// This allows iterating over the elements of a `Vec` by value.
555impl<T, const MAX_LENGTH: usize> Iterator for IntoIter<T, MAX_LENGTH> {
556    type Item = T;
557
558    /// Returns the next element in the iterator.
559    fn next(&mut self) -> Option<Self::Item> {
560        if self.next < self.vec.len() {
561            // This is a safe operation because we know that the index is within bounds
562            let value = unsafe { self.vec.get_unchecked(self.next) };
563            self.next += 1;
564
565            Some(value)
566        } else {
567            None
568        }
569    }
570}
571
572/// Drop implementation for `IntoIter`.
573///
574/// This ensures that all remaining elements in the `IntoIter` are properly dropped when the `IntoIter` goes out of scope.
575impl<T, const MAX_LENGTH: usize> Drop for IntoIter<T, MAX_LENGTH> {
576    /// Drops all remaining elements in the `IntoIter`.
577    fn drop(&mut self) {
578        unsafe {
579            // Drop all the remaining elements, and set the length to 0
580            ptr::drop_in_place(&raw mut self.vec.as_mut_slice()[self.next..]);
581            self.vec.length = 0;
582        }
583    }
584}
585
586/// Implementation of `IntoIterator` for `Vec`.
587///
588/// This allows converting a `Vec` into an `IntoIter`.
589impl<T, const MAX_LENGTH: usize> IntoIterator for Vec<T, MAX_LENGTH> {
590    type Item = T;
591    type IntoIter = IntoIter<T, MAX_LENGTH>;
592
593    /// Converts the `Vec` into an `IntoIter`.
594    fn into_iter(self) -> Self::IntoIter {
595        IntoIter::new(self)
596    }
597}
598
599/// Implementation of `PartialEq` for `Vec`.
600///
601/// This allows comparing two `Vec`s for equality.
602impl<TA, TB, const MAX_LENGTH_A: usize, const MAX_LENGTH_B: usize> PartialEq<Vec<TB, MAX_LENGTH_B>>
603    for Vec<TA, MAX_LENGTH_A>
604where
605    TA: PartialEq<TB>,
606{
607    /// Compares two `Vec`s for equality.
608    fn eq(&self, other: &Vec<TB, MAX_LENGTH_B>) -> bool {
609        <[TA]>::eq(self, &**other)
610    }
611}
612
613/// Implementation of `Eq` for `Vec`.
614///
615/// This allows comparing two `Vec`s for equality.
616impl<T, const MAX_LENGTH: usize> Eq for Vec<T, MAX_LENGTH> where T: Eq {}
617
618/// Implementation of `TryFrom` for `Vec`.
619///
620/// This allows converting a slice into a `Vec`.
621impl<T: Copy, const MAX_LENGTH: usize> TryFrom<&[T]> for Vec<T, MAX_LENGTH> {
622    type Error = ();
623
624    /// Converts a slice into a `Vec`.
625    fn try_from(values: &[T]) -> Result<Self, Self::Error> {
626        // Runtime check
627        if values.len() > MAX_LENGTH {
628            return Err(());
629        }
630
631        // This is a safe operation because we check at runtime that the length is sufficient
632        Ok(unsafe { Self::from_slice_unchecked(values) })
633    }
634}
635
636/// Implementation of `From` for `Vec`.
637///
638/// This allows converting a `Vec` into another `Vec`.
639impl<T: Copy, const LENGTH: usize, const MAX_LENGTH: usize> From<&Vec<T, LENGTH>>
640    for Vec<T, MAX_LENGTH>
641{
642    /// Converts a `Vec` into another `Vec`.
643    fn from(values: &Vec<T, LENGTH>) -> Self {
644        // Build time assertion
645        assert_lte!(LENGTH, MAX_LENGTH);
646
647        // This is a safe operation because we check at build time that the length is sufficient
648        unsafe { Self::from_slice_unchecked(values) }
649    }
650}
651
652/// Implementation of `From` for `Vec`.
653///
654/// This allows converting an array into a `Vec`.
655impl<T, const LENGTH: usize, const MAX_LENGTH: usize> From<[T; LENGTH]> for Vec<T, MAX_LENGTH> {
656    /// Converts an array into a `Vec`.
657    fn from(values: [T; LENGTH]) -> Self {
658        // Build time assertion
659        assert_lte!(LENGTH, MAX_LENGTH);
660
661        // This is a safe operation because we check at build time that the length is sufficient
662        unsafe { Self::from_array_unchecked(values) }
663    }
664}
665
666/// Implementation of `From` for `Vec`.
667///
668/// This allows converting a reference to an array into a `Vec`.
669impl<T: Copy, const LENGTH: usize, const MAX_LENGTH: usize> From<&[T; LENGTH]>
670    for Vec<T, MAX_LENGTH>
671{
672    /// Converts a reference to an array into a `Vec`.
673    fn from(values: &[T; LENGTH]) -> Self {
674        // Build time assertion
675        assert_lte!(LENGTH, MAX_LENGTH);
676
677        // This is a safe operation because we check at build time that the length is sufficient
678        unsafe { Self::from_slice_unchecked(values) }
679    }
680}
681
682/// Implementation of `From` for `Vec`.
683///
684/// This allows converting a `u8` into a `Vec`.
685impl<const MAX_LENGTH: usize> From<u8> for Vec<u8, MAX_LENGTH> {
686    /// Converts a `u8` into a `Vec`.
687    fn from(value: u8) -> Self {
688        // Build time assertion
689        const VALUE_LENGTH: usize = size_of::<u8>();
690        assert_lte!(VALUE_LENGTH, MAX_LENGTH);
691
692        // This is a safe operation because we check at build time that the length is sufficient
693        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
694    }
695}
696
697/// Implementation of `From` for `Vec`.
698///
699/// This allows converting a `u16` into a `Vec`.
700impl<const MAX_LENGTH: usize> From<u16> for Vec<u8, MAX_LENGTH> {
701    /// Converts a `u16` into a `Vec`.
702    fn from(value: u16) -> Self {
703        // Build time assertion
704        const VALUE_LENGTH: usize = size_of::<u16>();
705        assert_lte!(VALUE_LENGTH, MAX_LENGTH);
706
707        // This is a safe operation because we check at build time that the length is sufficient
708        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
709    }
710}
711
712/// Implementation of `From` for `Vec`.
713///
714/// This allows converting a `u32` into a `Vec`.
715impl<const MAX_LENGTH: usize> From<u32> for Vec<u8, MAX_LENGTH> {
716    /// Converts a `u32` into a `Vec`.
717    fn from(value: u32) -> Self {
718        // Build time assertion
719        const VALUE_LENGTH: usize = size_of::<u32>();
720        assert_lte!(VALUE_LENGTH, MAX_LENGTH);
721
722        // This is a safe operation because we check at build time that the length is sufficient
723        unsafe { Self::from_uint_unchecked(u64::from(value), VALUE_LENGTH) }
724    }
725}
726
727/// Implementation of `From` for `Vec`.
728///
729/// This allows converting a `u64` into a `Vec`.
730impl<const MAX_LENGTH: usize> From<u64> for Vec<u8, MAX_LENGTH> {
731    /// Converts a `u64` into a `Vec`.
732    fn from(value: u64) -> Self {
733        // Build time assertion
734        const VALUE_LENGTH: usize = size_of::<u64>();
735        assert_lte!(VALUE_LENGTH, MAX_LENGTH);
736
737        // This is a safe operation because we check at build time that the length is sufficient
738        unsafe { Self::from_uint_unchecked(value, VALUE_LENGTH) }
739    }
740}
741
742/// Implementation of `Deref` for `Vec`.
743///
744/// This allows dereferencing a `Vec` to get a slice of its elements.
745impl<T, const MAX_LENGTH: usize> Deref for Vec<T, MAX_LENGTH> {
746    type Target = [T];
747
748    /// Dereferences the `Vec` to get a slice of its elements.
749    fn deref(&self) -> &Self::Target {
750        self.as_slice()
751    }
752}
753
754/// Implementation of `DerefMut` for `Vec`.
755///
756/// This allows dereferencing a mutable `Vec` to get a mutable slice of its elements.
757impl<T, const MAX_LENGTH: usize> DerefMut for Vec<T, MAX_LENGTH> {
758    /// Dereferences the mutable `Vec` to get a mutable slice of its elements.
759    fn deref_mut(&mut self) -> &mut [T] {
760        self.as_mut_slice()
761    }
762}
763
764/// Implementation of `From` for `u8`.
765///
766/// This allows converting a `Vec` into a `u8`.
767impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u8
768where
769    T: Into<Self>,
770{
771    #[allow(clippy::cast_possible_truncation)]
772    /// Converts a `Vec` into a `u8`.
773    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
774        value.to_uint() as Self
775    }
776}
777
778/// Implementation of `From` for `u16`.
779///
780/// This allows converting a `Vec` into a `u16`.
781impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u16
782where
783    T: Into<u8>,
784{
785    #[allow(clippy::cast_possible_truncation)]
786    /// Converts a `Vec` into a `u16`.
787    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
788        value.to_uint() as Self
789    }
790}
791
792/// Implementation of `From` for `u32`.
793///
794/// This allows converting a `Vec` into a `u32`.
795impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u32
796where
797    T: Into<u8>,
798{
799    #[allow(clippy::cast_possible_truncation)]
800    /// Converts a `Vec` into a `u32`.
801    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
802        value.to_uint() as Self
803    }
804}
805
806/// Implementation of `From` for `u64`.
807///
808/// This allows converting a `Vec` into a `u64`.
809impl<T, const MAX_LENGTH: usize> From<&Vec<T, MAX_LENGTH>> for u64
810where
811    T: Into<u8>,
812{
813    /// Converts a `Vec` into a `u64`.
814    fn from(value: &Vec<T, MAX_LENGTH>) -> Self {
815        value.to_uint() as Self
816    }
817}
818
819/// Implementation of `Extend` for `Vec`.
820///
821/// This allows extending a `Vec` with references to elements.
822impl<'a, T, const MAX_LENGTH: usize> Extend<&'a T> for Vec<T, MAX_LENGTH>
823where
824    T: 'a + Copy,
825{
826    /// Extends the `Vec` with references to elements.
827    /// Check left capacity before using this method.
828    fn extend<I>(&mut self, iter: I)
829    where
830        I: IntoIterator<Item = &'a T>,
831    {
832        // This is not a safe operation, the caller must ensure there is enough capacity
833        unsafe { self.extend(iter.into_iter().copied()) };
834    }
835}
836
837/// Implementation of `Extend` for `Vec`.
838///
839/// This allows extending a `Vec` with elements.
840impl<T, const MAX_LENGTH: usize> Extend<T> for Vec<T, MAX_LENGTH>
841where
842    T: Copy,
843{
844    /// Extends the `Vec` with elements.
845    /// Check left capacity before using this method.
846    fn extend<I>(&mut self, iter: I)
847    where
848        I: IntoIterator<Item = T>,
849    {
850        // This is not a safe operation, the caller must ensure there is enough capacity
851        unsafe { self.extend(iter) };
852    }
853}
854
855/// Implementation of `Clone` for `Vec`.
856///
857/// This allows cloning a `Vec`.
858impl<T, const MAX_LENGTH: usize> Clone for Vec<T, MAX_LENGTH>
859where
860    T: Clone,
861{
862    /// Clones the `Vec`.
863    fn clone(&self) -> Self {
864        let mut new_vec = Self::new();
865        for elem in self {
866            // This is a safe operation because the destination vector has the same capacity as the source vector
867            unsafe { new_vec.push_unchecked(elem.clone()) };
868        }
869
870        new_vec
871    }
872}
873
874#[cfg(test)]
875mod tests {
876    use crate::vec::Vec;
877
878    #[test]
879    fn test_vec_new() {
880        let vec = Vec::<u8, 1>::new();
881
882        assert_eq!(0, vec.len());
883        assert!(vec.is_empty());
884    }
885
886    #[test]
887    fn test_vec_push() {
888        let mut vec = Vec::<u8, 1>::new();
889
890        assert_eq!(Ok(()), vec.push(1));
891        assert_eq!(1, vec.len());
892        assert!(!vec.is_empty());
893    }
894
895    #[test]
896    fn test_vec_push_out_of_bound() {
897        let mut vec = Vec::<u8, 1>::new();
898
899        assert_eq!(Ok(()), vec.push(1));
900        assert_eq!(Err(()), vec.push(2));
901    }
902
903    #[test]
904    fn test_vec_push_unchecked() {
905        let mut vec = Vec::<u8, 1>::new();
906
907        unsafe { vec.push_unchecked(1) };
908
909        assert_eq!(1, vec.len());
910        assert!(!vec.is_empty());
911    }
912
913    #[test]
914    fn test_vec_pop() {
915        let mut vec = Vec::<u8, 1>::new();
916
917        assert_eq!(Ok(()), vec.push(1));
918        assert_eq!(Some(1), vec.pop());
919        assert_eq!(0, vec.len());
920        assert_eq!(None, vec.pop());
921    }
922
923    #[test]
924    fn test_vec_pop_unchecked() {
925        let mut vec = Vec::<u8, 1>::new();
926        let _ = vec.push(1);
927
928        assert_eq!(1, unsafe { vec.pop_unchecked() });
929        assert_eq!(0, vec.len());
930        assert_eq!(None, vec.pop());
931    }
932
933    #[test]
934    fn test_vec_write() {
935        let mut vec = Vec::<u8, 3>::new();
936
937        assert_eq!(Ok(()), vec.write(0, 1));
938        assert_eq!(1, vec.len());
939        assert_eq!(Some(1), vec.get(0));
940        assert_eq!(None, vec.get(1));
941    }
942
943    #[test]
944    fn test_vec_write_out_of_bound() {
945        let mut vec = Vec::<u8, 3>::new();
946
947        assert_eq!(Err(()), vec.write(3, 1));
948    }
949
950    #[test]
951    fn test_vec_write_unchecked() {
952        let mut vec = Vec::<u8, 3>::new();
953
954        unsafe { vec.write_unchecked(0, 1) };
955
956        assert_eq!(1, vec.len());
957        assert_eq!(Some(1), vec.get(0));
958        assert_eq!(None, vec.get(1));
959    }
960
961    #[test]
962    fn test_vec_write_slice() {
963        let mut vec = Vec::<u8, 3>::new();
964
965        assert_eq!(Ok(()), vec.write_slice(0, &[1, 2, 3]));
966        assert_eq!(3, vec.len());
967        assert_eq!(Some(1), vec.get(0));
968        assert_eq!(Some(2), vec.get(1));
969        assert_eq!(Some(3), vec.get(2));
970        assert_eq!(None, vec.get(3));
971    }
972
973    #[test]
974    fn test_vec_write_slice_out_of_bound() {
975        let mut vec = Vec::<u8, 3>::new();
976
977        assert_eq!(Err(()), vec.write_slice(1, &[1, 2, 3]));
978    }
979
980    #[test]
981    fn test_vec_write_slice_unchecked() {
982        let mut vec = Vec::<u8, 3>::new();
983
984        unsafe { vec.write_slice_unchecked(0, &[1, 2, 3]) };
985
986        assert_eq!(3, vec.len());
987        assert_eq!(Some(1), vec.get(0));
988        assert_eq!(Some(2), vec.get(1));
989        assert_eq!(Some(3), vec.get(2));
990        assert_eq!(None, vec.get(3));
991    }
992
993    #[test]
994    fn test_vec_insert_at_start() {
995        let mut vec = Vec::<u8, 3>::new();
996
997        assert_eq!(Ok(()), vec.insert(0, 1));
998        assert_eq!(1, vec.len());
999        assert_eq!(Some(1), vec.get(0));
1000        assert_eq!(None, vec.get(1));
1001    }
1002
1003    #[test]
1004    fn test_vec_insert_in_middle() {
1005        let mut vec = Vec::<u8, 4>::from([1, 2, 3]);
1006
1007        assert_eq!(Ok(()), vec.insert(1, 4));
1008        assert_eq!(4, vec.len());
1009        assert_eq!(Some(1), vec.get(0));
1010        assert_eq!(Some(4), vec.get(1));
1011        assert_eq!(Some(2), vec.get(2));
1012        assert_eq!(Some(3), vec.get(3));
1013    }
1014
1015    #[test]
1016    fn test_vec_insert_out_of_bound() {
1017        let mut vec = Vec::<u8, 0>::new();
1018
1019        assert_eq!(Err(()), vec.insert(1, 1));
1020    }
1021
1022    #[test]
1023    fn test_vec_remove() {
1024        let mut vec = Vec::<u8, 3>::from([1, 2, 3]);
1025
1026        assert_eq!(Some(2), vec.remove(1));
1027        assert_eq!(2, vec.len());
1028        assert_eq!(Some(1), vec.get(0));
1029        assert_eq!(Some(3), vec.get(1));
1030        assert_eq!(None, vec.get(2));
1031    }
1032
1033    #[test]
1034    fn test_vec_remove_last() {
1035        let mut vec = Vec::<u8, 3>::from([1, 2, 3]);
1036
1037        assert_eq!(Some(3), vec.remove(2));
1038        assert_eq!(2, vec.len());
1039        assert_eq!(Some(1), vec.get(0));
1040        assert_eq!(Some(2), vec.get(1));
1041        assert_eq!(None, vec.get(2));
1042    }
1043
1044    #[test]
1045    fn test_vec_remove_out_of_bound() {
1046        let mut vec = Vec::<u8, 1>::new();
1047
1048        assert_eq!(None, vec.remove(1));
1049    }
1050
1051    #[test]
1052    fn test_vec_get() {
1053        let mut vec = Vec::<u8, 1>::new();
1054        let _ = vec.push(1);
1055
1056        assert_eq!(Some(1), vec.get(0));
1057        assert_eq!(1, vec.len());
1058        assert_eq!(None, vec.get(1));
1059    }
1060
1061    #[test]
1062    fn test_vec_get_out_of_bound() {
1063        let mut vec = Vec::<u8, 1>::new();
1064        let _ = vec.push(1);
1065
1066        assert_eq!(None, vec.get(1));
1067        assert_eq!(1, vec.len());
1068    }
1069
1070    #[test]
1071    fn test_vec_get_unchecked() {
1072        let mut vec = Vec::<u8, 1>::new();
1073        let _ = vec.push(1);
1074
1075        assert_eq!(1, unsafe { vec.get_unchecked(0) });
1076        assert_eq!(1, vec.len());
1077    }
1078
1079    #[test]
1080    fn test_vec_get_mut() {
1081        let mut vec = Vec::<u8, 1>::new();
1082        let _ = vec.push(1);
1083
1084        assert_eq!(Some(1), vec.get_mut(0));
1085        assert_eq!(1, vec.len());
1086        assert_eq!(None, vec.get_mut(1));
1087    }
1088
1089    #[test]
1090    fn test_vec_get_mut_out_of_bound() {
1091        let mut vec = Vec::<u8, 1>::new();
1092        let _ = vec.push(1);
1093
1094        assert_eq!(None, vec.get_mut(1));
1095        assert_eq!(1, vec.len());
1096    }
1097
1098    #[test]
1099    fn test_vec_get_mut_unchecked() {
1100        let mut vec = Vec::<u8, 1>::new();
1101        let _ = vec.push(1);
1102
1103        assert_eq!(1, unsafe { vec.get_mut_unchecked(0) });
1104        assert_eq!(1, vec.len());
1105    }
1106
1107    #[test]
1108    fn test_vec_extend() {
1109        let mut vec = Vec::<u8, 3>::new();
1110        let array: [u8; 3] = [1, 2, 3];
1111
1112        unsafe { vec.extend(array.iter().copied()) };
1113        assert_eq!(3, vec.len());
1114        assert_eq!(Some(1), vec.get(0));
1115        assert_eq!(Some(2), vec.get(1));
1116        assert_eq!(Some(3), vec.get(2));
1117        assert_eq!(None, vec.get(3));
1118    }
1119
1120    #[test]
1121    fn test_as_slice_with_empty_vec() {
1122        let vec = Vec::<u8, 1>::new();
1123
1124        let array = vec.as_slice();
1125
1126        assert_eq!(0, array.len());
1127    }
1128
1129    #[test]
1130    fn test_as_mut_slice_with_empty_vec() {
1131        let mut vec = Vec::<u8, 1>::new();
1132
1133        let array = vec.as_mut_slice();
1134
1135        assert_eq!(0, array.len());
1136    }
1137
1138    #[test]
1139    fn test_vec_truncate() {
1140        let mut vec = Vec::<u8, 1>::new();
1141
1142        assert_eq!(Ok(()), vec.push(1));
1143        assert!(!vec.is_empty());
1144
1145        vec.truncate(0);
1146
1147        assert_eq!(0, vec.len());
1148        assert!(vec.is_empty());
1149    }
1150
1151    #[test]
1152    fn test_vec_truncate_with_new_length_equal_current_length() {
1153        let mut vec = Vec::<u8, 1>::new();
1154
1155        assert_eq!(Ok(()), vec.push(1));
1156        assert!(!vec.is_empty());
1157
1158        vec.truncate(1);
1159
1160        assert_eq!(1, vec.len());
1161        assert!(!vec.is_empty());
1162    }
1163
1164    #[test]
1165    fn test_vec_truncate_with_new_length_superior_to_current_length() {
1166        let mut vec = Vec::<u8, 1>::new();
1167
1168        assert_eq!(Ok(()), vec.push(1));
1169        assert!(!vec.is_empty());
1170
1171        vec.truncate(2);
1172
1173        assert_eq!(1, vec.len());
1174        assert!(!vec.is_empty());
1175    }
1176
1177    #[test]
1178    fn test_vec_clear() {
1179        let mut vec = Vec::<u8, 1>::new();
1180
1181        assert_eq!(Ok(()), vec.push(1));
1182        assert!(!vec.is_empty());
1183
1184        vec.clear();
1185
1186        assert_eq!(0, vec.len());
1187        assert!(vec.is_empty());
1188    }
1189
1190    #[test]
1191    fn test_vec_try_from_array_as_slice() {
1192        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();
1193
1194        assert_eq!(3, vec.len());
1195        assert_eq!(Some(1), vec.get(0));
1196        assert_eq!(Some(2), vec.get(1));
1197        assert_eq!(Some(3), vec.get(2));
1198        assert_eq!(None, vec.get(3));
1199    }
1200
1201    #[test]
1202    fn test_vec_try_from_array_as_slice_shorter_than_vec_size() {
1203        let vec: Vec<u8, 8> = [1, 2, 3].as_slice().try_into().unwrap();
1204
1205        assert_eq!(3, vec.len());
1206        assert_eq!(Some(1), vec.get(0));
1207        assert_eq!(Some(2), vec.get(1));
1208        assert_eq!(Some(3), vec.get(2));
1209        assert_eq!(None, vec.get(3));
1210    }
1211
1212    #[test]
1213    fn test_small_vec_try_from_array_as_slice_should_failed() {
1214        let vec_result: Result<Vec<u8, 1>, _> = [1, 2, 3].as_slice().try_into();
1215
1216        assert!(vec_result.is_err());
1217    }
1218
1219    #[test]
1220    fn test_vec_from_array() {
1221        let vec: Vec<u8, 3> = Vec::from(&[1, 2, 3]);
1222
1223        assert_eq!(3, vec.len());
1224        assert_eq!(Some(1), vec.get(0));
1225        assert_eq!(Some(2), vec.get(1));
1226        assert_eq!(Some(3), vec.get(2));
1227        assert_eq!(None, vec.get(3));
1228    }
1229
1230    #[test]
1231    fn test_vec_from_array_same_size_as_vec() {
1232        let vec: Vec<u8, 3> = [1, 2, 3].into();
1233
1234        assert_eq!(3, vec.len());
1235        assert_eq!(Some(1), vec.get(0));
1236        assert_eq!(Some(2), vec.get(1));
1237        assert_eq!(Some(3), vec.get(2));
1238        assert_eq!(None, vec.get(3));
1239    }
1240
1241    #[test]
1242    fn test_vec_from_u8() {
1243        let vec: Vec<u8, 8> = 0xffu8.into();
1244
1245        assert_eq!(1, vec.len());
1246        assert_eq!(Some(0xff), vec.get(0));
1247        assert_eq!(None, vec.get(1));
1248        assert_eq!(None, vec.get(2));
1249        assert_eq!(None, vec.get(3));
1250        assert_eq!(None, vec.get(4));
1251        assert_eq!(None, vec.get(5));
1252        assert_eq!(None, vec.get(6));
1253        assert_eq!(None, vec.get(7));
1254    }
1255
1256    #[test]
1257    fn test_vec_from_u16() {
1258        let vec: Vec<u8, 8> = 0xff00u16.into();
1259
1260        assert_eq!(2, vec.len());
1261        assert_eq!(Some(0x00), vec.get(0));
1262        assert_eq!(Some(0xff), vec.get(1));
1263        assert_eq!(None, vec.get(2));
1264        assert_eq!(None, vec.get(3));
1265        assert_eq!(None, vec.get(4));
1266        assert_eq!(None, vec.get(5));
1267        assert_eq!(None, vec.get(6));
1268        assert_eq!(None, vec.get(7));
1269    }
1270
1271    #[test]
1272    fn test_vec_from_number_shorter_than_real_u16() {
1273        let vec: Vec<u8, 8> = 0x00ffu16.into();
1274
1275        assert_eq!(1, vec.len());
1276        assert_eq!(Some(0xff), vec.get(0));
1277        assert_eq!(None, vec.get(1));
1278        assert_eq!(None, vec.get(2));
1279        assert_eq!(None, vec.get(3));
1280        assert_eq!(None, vec.get(4));
1281        assert_eq!(None, vec.get(5));
1282        assert_eq!(None, vec.get(6));
1283        assert_eq!(None, vec.get(7));
1284    }
1285
1286    #[test]
1287    fn test_vec_from_u32() {
1288        let vec: Vec<u8, 8> = 0xff00_ff00_u32.into();
1289
1290        assert_eq!(4, vec.len());
1291        assert_eq!(Some(0x00), vec.get(0));
1292        assert_eq!(Some(0xff), vec.get(1));
1293        assert_eq!(Some(0x00), vec.get(2));
1294        assert_eq!(Some(0xff), vec.get(3));
1295        assert_eq!(None, vec.get(4));
1296        assert_eq!(None, vec.get(5));
1297        assert_eq!(None, vec.get(6));
1298        assert_eq!(None, vec.get(7));
1299    }
1300
1301    #[test]
1302    fn test_vec_from_u64() {
1303        let vec: Vec<u8, 8> = 0xff00_ff00_ff00_ff00_u64.into();
1304
1305        assert_eq!(8, vec.len());
1306        assert_eq!(Some(0x00), vec.get(0));
1307        assert_eq!(Some(0xff), vec.get(1));
1308        assert_eq!(Some(0x00), vec.get(2));
1309        assert_eq!(Some(0xff), vec.get(3));
1310        assert_eq!(Some(0x00), vec.get(4));
1311        assert_eq!(Some(0xff), vec.get(5));
1312        assert_eq!(Some(0x00), vec.get(6));
1313        assert_eq!(Some(0xff), vec.get(7));
1314    }
1315
1316    #[test]
1317    fn test_u8_from_vec() {
1318        let vec: Vec<u8, 1> = Vec::from([0x2A]);
1319        let value = u8::from(&vec);
1320
1321        assert_eq!(42, value);
1322    }
1323
1324    #[test]
1325    fn test_u16_from_vec() {
1326        let vec: Vec<u8, 2> = Vec::from([0xD2, 0x04]);
1327        let value = u16::from(&vec);
1328
1329        assert_eq!(1234, value);
1330    }
1331
1332    #[test]
1333    fn test_u32_from_vec() {
1334        let vec: Vec<u8, 4> = Vec::from([0x52, 0xAA, 0x08, 0x00]);
1335        let value = u32::from(&vec);
1336
1337        assert_eq!(567_890, value);
1338    }
1339
1340    #[test]
1341    fn test_u64_from_vec() {
1342        let vec: Vec<u8, 8> = Vec::from([0x08, 0x1A, 0x99, 0xBE, 0x1C, 0x00, 0x00, 0x00]);
1343        let value = u64::from(&vec);
1344
1345        assert_eq!(123_456_789_000, value);
1346    }
1347
1348    #[test]
1349    fn test_deref_with_empty_vec() {
1350        let vec = Vec::<u8, 1>::new();
1351
1352        let array = &*vec;
1353
1354        assert_eq!(0, array.len());
1355    }
1356
1357    #[test]
1358    #[allow(unused_mut)]
1359    fn test_deref_mut_with_empty_vec() {
1360        let mut vec = Vec::<u8, 1>::new();
1361
1362        let array = &*vec;
1363
1364        assert_eq!(0, array.len());
1365    }
1366
1367    #[test]
1368    fn test_into_iter_vec_with_for_loop() {
1369        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();
1370
1371        // Using for loop
1372        vec.into_iter().for_each(|value| {
1373            assert!(matches!(value, 1..=3));
1374        });
1375    }
1376
1377    #[test]
1378    fn test_into_iter_vec_with_iterator() {
1379        let vec: Vec<u8, 3> = [1, 2, 3].as_slice().try_into().unwrap();
1380
1381        // Using iterator
1382        let mut into_iter = vec.into_iter();
1383        assert_eq!(Some(1), into_iter.next());
1384        assert_eq!(Some(2), into_iter.next());
1385        assert_eq!(Some(3), into_iter.next());
1386    }
1387}