Skip to main content

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