arrayvec_const/
arrayvec.rs

1
2use std::cmp;
3use std::iter;
4use std::mem;
5use std::ops::{Bound, Deref, DerefMut, RangeBounds};
6use std::ptr;
7use std::slice;
8
9// extra traits
10use std::borrow::{Borrow, BorrowMut};
11use std::hash::{Hash, Hasher};
12use std::fmt;
13
14#[cfg(feature="std")]
15use std::io;
16
17use std::mem::ManuallyDrop;
18use std::mem::MaybeUninit;
19
20use const_panic::concat_panic;
21#[cfg(feature="serde")]
22use serde::{Serialize, Deserialize, Serializer, Deserializer};
23
24use crate::LenUint;
25use crate::errors::CapacityError;
26use crate::utils::MakeMaybeUninit;
27
28/// A vector with a fixed capacity.
29///
30/// The `ArrayVec` is a vector backed by a fixed size array. It keeps track of
31/// the number of initialized elements. The `ArrayVec<T, CAP>` is parameterized
32/// by `T` for the element type and `CAP` for the maximum capacity.
33///
34/// `CAP` is of type `usize` but is range limited to `u32::MAX` (or `u16::MAX` on 16-bit targets);
35/// attempting to create larger arrayvecs with larger capacity will panic.
36///
37/// The vector is a contiguous value (storing the elements inline) that you can store directly on
38/// the stack if needed.
39///
40/// It offers a simple API but also dereferences to a slice, so that the full slice API is
41/// available. The ArrayVec can be converted into a by value iterator.
42#[repr(C)]
43pub struct ArrayVec<T, const CAP: usize> {
44    len: LenUint,
45    // the `len` first elements of the array are initialized
46    xs: [MaybeUninit<T>; CAP],
47}
48
49impl<T, const CAP: usize> Drop for ArrayVec<T, CAP> {
50    fn drop(&mut self) {
51        self.clear();
52
53        // MaybeUninit inhibits array's drop
54    }
55}
56
57
58macro_rules! panic_oob {
59    ($method_name:expr, $index:expr, $len:expr) => {
60        concat_panic!("ArrayVec::", $method_name, ": index ", $index, " is out of bounds in vector of length ", $len)
61    }
62}
63
64impl<T, const CAP: usize> ArrayVec<T, CAP> {
65    /// Capacity
66    const CAPACITY: usize = CAP;
67
68    /// Create a new empty `ArrayVec`.
69    ///
70    /// The maximum capacity is given by the generic parameter `CAP`.
71    ///
72    /// ```
73    /// use arrayvec::ArrayVec;
74    ///
75    /// let mut array = ArrayVec::<_, 16>::new();
76    /// array.push(1);
77    /// array.push(2);
78    /// assert_eq!(&array[..], &[1, 2]);
79    /// assert_eq!(array.capacity(), 16);
80    /// ```
81    #[inline]
82    #[track_caller]
83    pub const fn new() -> ArrayVec<T, CAP> {
84        assert_capacity_limit!(CAP);
85        unsafe {
86            ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 }
87        }
88    }
89
90    /// Create a new empty `ArrayVec` (const fn).
91    ///
92    /// The maximum capacity is given by the generic parameter `CAP`.
93    ///
94    /// ```
95    /// use arrayvec::ArrayVec;
96    ///
97    /// static ARRAY: ArrayVec<u8, 1024> = ArrayVec::new_const();
98    /// ```
99    pub const fn new_const() -> ArrayVec<T, CAP> {
100        assert_capacity_limit_const!(CAP);
101        ArrayVec { xs: MakeMaybeUninit::ARRAY, len: 0 }
102    }
103
104    /// Return the number of elements in the `ArrayVec`.
105    ///
106    /// ```
107    /// use arrayvec::ArrayVec;
108    ///
109    /// let mut array = ArrayVec::from([1, 2, 3]);
110    /// array.pop();
111    /// assert_eq!(array.len(), 2);
112    /// ```
113    #[inline(always)]
114    pub const fn len(&self) -> usize { self.len as usize }
115
116    /// Returns whether the `ArrayVec` is empty.
117    ///
118    /// ```
119    /// use arrayvec::ArrayVec;
120    ///
121    /// let mut array = ArrayVec::from([1]);
122    /// array.pop();
123    /// assert_eq!(array.is_empty(), true);
124    /// ```
125    #[inline]
126    pub const fn is_empty(&self) -> bool { self.len() == 0 }
127
128    /// Return the capacity of the `ArrayVec`.
129    ///
130    /// ```
131    /// use arrayvec::ArrayVec;
132    ///
133    /// let array = ArrayVec::from([1, 2, 3]);
134    /// assert_eq!(array.capacity(), 3);
135    /// ```
136    #[inline(always)]
137    pub const fn capacity(&self) -> usize { CAP }
138
139    /// Return true if the `ArrayVec` is completely filled to its capacity, false otherwise.
140    ///
141    /// ```
142    /// use arrayvec::ArrayVec;
143    ///
144    /// let mut array = ArrayVec::<_, 1>::new();
145    /// assert!(!array.is_full());
146    /// array.push(1);
147    /// assert!(array.is_full());
148    /// ```
149    pub const fn is_full(&self) -> bool { self.len() == self.capacity() }
150
151    /// Returns the capacity left in the `ArrayVec`.
152    ///
153    /// ```
154    /// use arrayvec::ArrayVec;
155    ///
156    /// let mut array = ArrayVec::from([1, 2, 3]);
157    /// array.pop();
158    /// assert_eq!(array.remaining_capacity(), 1);
159    /// ```
160    pub const fn remaining_capacity(&self) -> usize {
161        self.capacity() - self.len()
162    }
163
164    /// Push `element` to the end of the vector.
165    ///
166    /// ***Panics*** if the vector is already full.
167    ///
168    /// ```
169    /// use arrayvec::ArrayVec;
170    ///
171    /// let mut array = ArrayVec::<_, 2>::new();
172    ///
173    /// array.push(1);
174    /// array.push(2);
175    ///
176    /// assert_eq!(&array[..], &[1, 2]);
177    /// ```
178    #[track_caller]
179    pub fn push(&mut self, element: T) {
180        self.try_push(element).unwrap()
181    }
182
183    /// Push `element` to the end of the vector.
184    ///
185    /// Return `Ok` if the push succeeds, or return an error if the vector
186    /// is already full.
187    ///
188    /// ```
189    /// use arrayvec::ArrayVec;
190    ///
191    /// let mut array = ArrayVec::<_, 2>::new();
192    ///
193    /// let push1 = array.try_push(1);
194    /// let push2 = array.try_push(2);
195    ///
196    /// assert!(push1.is_ok());
197    /// assert!(push2.is_ok());
198    ///
199    /// assert_eq!(&array[..], &[1, 2]);
200    ///
201    /// let overflow = array.try_push(3);
202    ///
203    /// assert!(overflow.is_err());
204    /// ```
205    pub const fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>> {
206        if self.len() < Self::CAPACITY {
207            unsafe {
208                self.push_unchecked(element);
209            }
210            Ok(())
211        } else {
212            Err(CapacityError::new(element))
213        }
214    }
215
216    /// Push `element` to the end of the vector without checking the capacity.
217    ///
218    /// It is up to the caller to ensure the capacity of the vector is
219    /// sufficiently large.
220    ///
221    /// This method uses *debug assertions* to check that the arrayvec is not full.
222    ///
223    /// ```
224    /// use arrayvec::ArrayVec;
225    ///
226    /// let mut array = ArrayVec::<_, 2>::new();
227    ///
228    /// if array.len() + 2 <= array.capacity() {
229    ///     unsafe {
230    ///         array.push_unchecked(1);
231    ///         array.push_unchecked(2);
232    ///     }
233    /// }
234    ///
235    /// assert_eq!(&array[..], &[1, 2]);
236    /// ```
237    pub const unsafe fn push_unchecked(&mut self, element: T) {
238        let len = self.len();
239        debug_assert!(len < Self::CAPACITY);
240        ptr::write(self.as_mut_ptr().add(len), element);
241        self.set_len(len + 1);
242    }
243
244    /// Shortens the vector, keeping the first `len` elements and dropping
245    /// the rest.
246    ///
247    /// If `len` is greater than the vector’s current length this has no
248    /// effect.
249    ///
250    /// ```
251    /// use arrayvec::ArrayVec;
252    ///
253    /// let mut array = ArrayVec::from([1, 2, 3, 4, 5]);
254    /// array.truncate(3);
255    /// assert_eq!(&array[..], &[1, 2, 3]);
256    /// array.truncate(4);
257    /// assert_eq!(&array[..], &[1, 2, 3]);
258    /// ```
259    pub fn truncate(&mut self, new_len: usize) {
260        unsafe {
261            let len = self.len();
262            if new_len < len {
263                self.set_len(new_len);
264                let tail = slice::from_raw_parts_mut(self.as_mut_ptr().add(new_len), len - new_len);
265                ptr::drop_in_place(tail);
266            }
267        }
268    }
269
270    /// Remove all elements in the vector.
271    pub fn clear(&mut self) {
272        self.truncate(0)
273    }
274
275
276    /// Get pointer to where element at `index` would be
277    const unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T {
278        self.as_mut_ptr().add(index)
279    }
280
281    /// Insert `element` at position `index`.
282    ///
283    /// Shift up all elements after `index`.
284    ///
285    /// It is an error if the index is greater than the length or if the
286    /// arrayvec is full.
287    ///
288    /// ***Panics*** if the array is full or the `index` is out of bounds. See
289    /// `try_insert` for fallible version.
290    ///
291    /// ```
292    /// use arrayvec::ArrayVec;
293    ///
294    /// let mut array = ArrayVec::<_, 2>::new();
295    ///
296    /// array.insert(0, "x");
297    /// array.insert(0, "y");
298    /// assert_eq!(&array[..], &["y", "x"]);
299    ///
300    /// ```
301    #[track_caller]
302    pub fn insert(&mut self, index: usize, element: T) {
303        self.try_insert(index, element).unwrap()
304    }
305
306    /// Insert `element` at position `index`.
307    ///
308    /// Shift up all elements after `index`; the `index` must be less than
309    /// or equal to the length.
310    ///
311    /// Returns an error if vector is already at full capacity.
312    ///
313    /// ***Panics*** `index` is out of bounds.
314    ///
315    /// ```
316    /// use arrayvec::ArrayVec;
317    ///
318    /// let mut array = ArrayVec::<_, 2>::new();
319    ///
320    /// assert!(array.try_insert(0, "x").is_ok());
321    /// assert!(array.try_insert(0, "y").is_ok());
322    /// assert!(array.try_insert(0, "z").is_err());
323    /// assert_eq!(&array[..], &["y", "x"]);
324    ///
325    /// ```
326    pub const fn try_insert(&mut self, index: usize, element: T) -> Result<(), CapacityError<T>> {
327        if index > self.len() {
328            panic_oob!("try_insert", index, self.len())
329        }
330        if self.len() == self.capacity() {
331            return Err(CapacityError::new(element));
332        }
333        let len = self.len();
334
335        // follows is just like Vec<T>
336        unsafe { // infallible
337            // The spot to put the new value
338            {
339                let p: *mut _ = self.get_unchecked_ptr(index);
340                // Shift everything over to make space. (Duplicating the
341                // `index`th element into two consecutive places.)
342                ptr::copy(p, p.offset(1), len - index);
343                // Write it in, overwriting the first copy of the `index`th
344                // element.
345                ptr::write(p, element);
346            }
347            self.set_len(len + 1);
348        }
349        Ok(())
350    }
351
352    /// Remove the last element in the vector and return it.
353    ///
354    /// Return `Some(` *element* `)` if the vector is non-empty, else `None`.
355    ///
356    /// ```
357    /// use arrayvec::ArrayVec;
358    ///
359    /// let mut array = ArrayVec::<_, 2>::new();
360    ///
361    /// array.push(1);
362    ///
363    /// assert_eq!(array.pop(), Some(1));
364    /// assert_eq!(array.pop(), None);
365    /// ```
366    pub const fn pop(&mut self) -> Option<T> {
367        if self.len() == 0 {
368            return None;
369        }
370        unsafe {
371            let new_len = self.len() - 1;
372            self.set_len(new_len);
373            Some(ptr::read(self.as_ptr().add(new_len)))
374        }
375    }
376
377    /// Remove the element at `index` and swap the last element into its place.
378    ///
379    /// This operation is O(1).
380    ///
381    /// Return the *element* if the index is in bounds, else panic.
382    ///
383    /// ***Panics*** if the `index` is out of bounds.
384    ///
385    /// ```
386    /// use arrayvec::ArrayVec;
387    ///
388    /// let mut array = ArrayVec::from([1, 2, 3]);
389    ///
390    /// assert_eq!(array.swap_remove(0), 1);
391    /// assert_eq!(&array[..], &[3, 2]);
392    ///
393    /// assert_eq!(array.swap_remove(1), 2);
394    /// assert_eq!(&array[..], &[3]);
395    /// ```
396    pub const fn swap_remove(&mut self, index: usize) -> T {
397        union Transmute<T> {
398            mo: ManuallyDrop<Option<T>>,
399            mom: ManuallyDrop<Option<ManuallyDrop<T>>>,
400        }
401        // Wouldn't need this with const_precise_live_drops :(
402        let v = ManuallyDrop::new(self.swap_pop(index));
403        let v = ManuallyDrop::into_inner(unsafe { Transmute{mo: v}.mom });
404
405        match v {
406            Some(v) => {
407                return ManuallyDrop::into_inner(v)
408            },
409            None => {
410                panic_oob!("swap_remove", index, self.len())
411            }
412        }
413    }
414
415    /// Remove the element at `index` and swap the last element into its place.
416    ///
417    /// This is a checked version of `.swap_remove`.  
418    /// This operation is O(1).
419    ///
420    /// Return `Some(` *element* `)` if the index is in bounds, else `None`.
421    ///
422    /// ```
423    /// use arrayvec::ArrayVec;
424    ///
425    /// let mut array = ArrayVec::from([1, 2, 3]);
426    ///
427    /// assert_eq!(array.swap_pop(0), Some(1));
428    /// assert_eq!(&array[..], &[3, 2]);
429    ///
430    /// assert_eq!(array.swap_pop(10), None);
431    /// ```
432    pub const fn swap_pop(&mut self, index: usize) -> Option<T> {
433        let len = self.len();
434        if index >= len {
435            return None;
436        }
437        self.as_mut_slice().swap(index, len - 1);
438        self.pop()
439    }
440
441    /// Remove the element at `index` and shift down the following elements.
442    ///
443    /// The `index` must be strictly less than the length of the vector.
444    ///
445    /// ***Panics*** if the `index` is out of bounds.
446    ///
447    /// ```
448    /// use arrayvec::ArrayVec;
449    ///
450    /// let mut array = ArrayVec::from([1, 2, 3]);
451    ///
452    /// let removed_elt = array.remove(0);
453    /// assert_eq!(removed_elt, 1);
454    /// assert_eq!(&array[..], &[2, 3]);
455    /// ```
456    pub const fn remove(&mut self, index: usize) -> T {
457        union Transmute<T> {
458            mo: ManuallyDrop<Option<T>>,
459            mom: ManuallyDrop<Option<ManuallyDrop<T>>>,
460        }
461        // Wouldn't need this with const_precise_live_drops :(
462        let v = ManuallyDrop::new(self.pop_at(index));
463        let v = ManuallyDrop::into_inner(unsafe { Transmute{mo: v}.mom });
464        
465        match v {
466            Some(v) => {
467                return ManuallyDrop::into_inner(v)
468            },
469            None => {
470                panic_oob!("remove", index, self.len())
471            }
472        }
473    }
474
475    /// Remove the element at `index` and shift down the following elements.
476    ///
477    /// This is a checked version of `.remove(index)`. Returns `None` if there
478    /// is no element at `index`. Otherwise, return the element inside `Some`.
479    ///
480    /// ```
481    /// use arrayvec::ArrayVec;
482    ///
483    /// let mut array = ArrayVec::from([1, 2, 3]);
484    ///
485    /// assert!(array.pop_at(0).is_some());
486    /// assert_eq!(&array[..], &[2, 3]);
487    ///
488    /// assert!(array.pop_at(2).is_none());
489    /// assert!(array.pop_at(10).is_none());
490    /// ```
491    pub const fn pop_at(&mut self, index: usize) -> Option<T> {
492        let len = self.len();
493        if index >= len {
494            return None
495        }
496        
497        unsafe { // infallible
498            // The spot to put take the value
499            let element = {
500                let p: *mut _ = self.get_unchecked_ptr(index);
501                // Read it out, the first copy of the `index`th
502                // element.
503                let element = ptr::read(p);
504                // Shift everything over to compact space. (overwriting the
505                // `index`th element)
506                ptr::copy(p.offset(1), p, len - index - 1);
507                element
508            };
509            self.set_len(len - 1);
510            Some(element)
511        }
512    }
513
514    /// Retains only the elements specified by the predicate.
515    ///
516    /// In other words, remove all elements `e` such that `f(&mut e)` returns false.
517    /// This method operates in place and preserves the order of the retained
518    /// elements.
519    ///
520    /// ```
521    /// use arrayvec::ArrayVec;
522    ///
523    /// let mut array = ArrayVec::from([1, 2, 3, 4]);
524    /// array.retain(|x| *x & 1 != 0 );
525    /// assert_eq!(&array[..], &[1, 3]);
526    /// ```
527    pub fn retain<F>(&mut self, mut f: F)
528        where F: FnMut(&mut T) -> bool
529    {
530        // Check the implementation of
531        // https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain
532        // for safety arguments (especially regarding panics in f and when
533        // dropping elements). Implementation closely mirrored here.
534
535        let original_len = self.len();
536        unsafe { self.set_len(0) };
537
538        struct BackshiftOnDrop<'a, T, const CAP: usize> {
539            v: &'a mut ArrayVec<T, CAP>,
540            processed_len: usize,
541            deleted_cnt: usize,
542            original_len: usize,
543        }
544
545        impl<T, const CAP: usize> Drop for BackshiftOnDrop<'_, T, CAP> {
546            fn drop(&mut self) {
547                if self.deleted_cnt > 0 {
548                    unsafe {
549                        ptr::copy(
550                            self.v.as_ptr().add(self.processed_len),
551                            self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
552                            self.original_len - self.processed_len
553                        );
554                    }
555                }
556                unsafe {
557                    self.v.set_len(self.original_len - self.deleted_cnt);
558                }
559            }
560        }
561
562        let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
563
564        #[inline(always)]
565        fn process_one<F: FnMut(&mut T) -> bool, T, const CAP: usize, const DELETED: bool>(
566            f: &mut F,
567            g: &mut BackshiftOnDrop<'_, T, CAP>
568        ) -> bool {
569            let cur = unsafe { g.v.as_mut_ptr().add(g.processed_len) };
570            if !f(unsafe { &mut *cur }) {
571                g.processed_len += 1;
572                g.deleted_cnt += 1;
573                unsafe { ptr::drop_in_place(cur) };
574                return false;
575            }
576            if DELETED {
577                unsafe {
578                    let hole_slot = cur.sub(g.deleted_cnt);
579                    ptr::copy_nonoverlapping(cur, hole_slot, 1);
580                }
581            }
582            g.processed_len += 1;
583            true
584        }
585
586        // Stage 1: Nothing was deleted.
587        while g.processed_len != original_len {
588            if !process_one::<F, T, CAP, false>(&mut f, &mut g) {
589                break;
590            }
591        }
592
593        // Stage 2: Some elements were deleted.
594        while g.processed_len != original_len {
595            process_one::<F, T, CAP, true>(&mut f, &mut g);
596        }
597
598        drop(g);
599    }
600
601    /// Returns the remaining spare capacity of the vector as a slice of
602    /// `MaybeUninit<T>`.
603    ///
604    /// The returned slice can be used to fill the vector with data (e.g. by
605    /// reading from a file) before marking the data as initialized using the
606    /// [`set_len`] method.
607    ///
608    /// [`set_len`]: ArrayVec::set_len
609    ///
610    /// # Examples
611    ///
612    /// ```
613    /// use arrayvec::ArrayVec;
614    ///
615    /// // Allocate vector big enough for 10 elements.
616    /// let mut v: ArrayVec<i32, 10> = ArrayVec::new();
617    ///
618    /// // Fill in the first 3 elements.
619    /// let uninit = v.spare_capacity_mut();
620    /// uninit[0].write(0);
621    /// uninit[1].write(1);
622    /// uninit[2].write(2);
623    ///
624    /// // Mark the first 3 elements of the vector as being initialized.
625    /// unsafe {
626    ///     v.set_len(3);
627    /// }
628    ///
629    /// assert_eq!(&v[..], &[0, 1, 2]);
630    /// ```
631    pub const fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
632        let len = self.len();
633        self.xs.split_at_mut(len).1
634    }
635
636    /// Set the vector’s length without dropping or moving out elements
637    ///
638    /// This method is `unsafe` because it changes the notion of the
639    /// number of “valid” elements in the vector. Use with care.
640    ///
641    /// This method uses *debug assertions* to check that `length` is
642    /// not greater than the capacity.
643    pub const unsafe fn set_len(&mut self, length: usize) {
644        // type invariant that capacity always fits in LenUint
645        debug_assert!(length <= self.capacity());
646        self.len = length as LenUint;
647    }
648
649    /// Copy all elements from the slice and append to the `ArrayVec`.
650    ///
651    /// ```
652    /// use arrayvec::ArrayVec;
653    ///
654    /// let mut vec: ArrayVec<usize, 10> = ArrayVec::new();
655    /// vec.push(1);
656    /// vec.try_extend_from_slice(&[2, 3]).unwrap();
657    /// assert_eq!(&vec[..], &[1, 2, 3]);
658    /// ```
659    ///
660    /// # Errors
661    ///
662    /// This method will return an error if the capacity left (see
663    /// [`remaining_capacity`]) is smaller then the length of the provided
664    /// slice.
665    ///
666    /// [`remaining_capacity`]: #method.remaining_capacity
667    pub const fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
668        where T: Copy,
669    {
670        if self.remaining_capacity() < other.len() {
671            return Err(CapacityError::new(()));
672        }
673
674        let self_len = self.len();
675        let other_len = other.len();
676
677        unsafe {
678            let dst = self.get_unchecked_ptr(self_len);
679            ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
680            self.set_len(self_len + other_len);
681        }
682        Ok(())
683    }
684
685    /// Create a draining iterator that removes the specified range in the vector
686    /// and yields the removed items from start to end. The element range is
687    /// removed even if the iterator is not consumed until the end.
688    ///
689    /// Note: It is unspecified how many elements are removed from the vector,
690    /// if the `Drain` value is leaked.
691    ///
692    /// **Panics** if the starting point is greater than the end point or if
693    /// the end point is greater than the length of the vector.
694    ///
695    /// ```
696    /// use arrayvec::ArrayVec;
697    ///
698    /// let mut v1 = ArrayVec::from([1, 2, 3]);
699    /// let v2: ArrayVec<_, 3> = v1.drain(0..2).collect();
700    /// assert_eq!(&v1[..], &[3]);
701    /// assert_eq!(&v2[..], &[1, 2]);
702    /// ```
703    pub fn drain<R>(&mut self, range: R) -> Drain<T, CAP>
704        where R: RangeBounds<usize>
705    {
706        // Memory safety
707        //
708        // When the Drain is first created, it shortens the length of
709        // the source vector to make sure no uninitialized or moved-from elements
710        // are accessible at all if the Drain's destructor never gets to run.
711        //
712        // Drain will ptr::read out the values to remove.
713        // When finished, remaining tail of the vec is copied back to cover
714        // the hole, and the vector length is restored to the new length.
715        //
716        let len = self.len();
717        let start = match range.start_bound() {
718            Bound::Unbounded => 0,
719            Bound::Included(&i) => i,
720            Bound::Excluded(&i) => i.saturating_add(1),
721        };
722        let end = match range.end_bound() {
723            Bound::Excluded(&j) => j,
724            Bound::Included(&j) => j.saturating_add(1),
725            Bound::Unbounded => len,
726        };
727        self.drain_range(start, end)
728    }
729
730    fn drain_range(&mut self, start: usize, end: usize) -> Drain<T, CAP>
731    {
732        let len = self.len();
733
734        // bounds check happens here (before length is changed!)
735        let range_slice: *const _ = &self[start..end];
736
737        // Calling `set_len` creates a fresh and thus unique mutable references, making all
738        // older aliases we created invalid. So we cannot call that function.
739        self.len = start as LenUint;
740
741        unsafe {
742            Drain {
743                tail_start: end,
744                tail_len: len - end,
745                iter: (*range_slice).iter(),
746                vec: self as *mut _,
747            }
748        }
749    }
750
751    /// Return the inner fixed size array, if it is full to its capacity.
752    ///
753    /// Return an `Ok` value with the array if length equals capacity,
754    /// return an `Err` with self otherwise.
755    pub const fn into_inner(self) -> Result<[T; CAP], Self> {
756        if self.len() < self.capacity() {
757            Err(self)
758        } else {
759            unsafe { Ok(self.into_inner_unchecked()) }
760        }
761    }
762
763    /// Return the inner fixed size array.
764    ///
765    /// Safety:
766    /// This operation is safe if and only if length equals capacity.
767    pub const unsafe fn into_inner_unchecked(self) -> [T; CAP] {
768        debug_assert!(self.len() == self.capacity());
769        let ptr = self.as_ptr();
770        mem::forget(self);
771        ptr::read(ptr as *const [T; CAP])
772    }
773
774    /// Returns the ArrayVec, replacing the original with a new empty ArrayVec.
775    ///
776    /// ```
777    /// use arrayvec::ArrayVec;
778    ///
779    /// let mut v = ArrayVec::from([0, 1, 2, 3]);
780    /// assert_eq!([0, 1, 2, 3], v.take().into_inner().unwrap());
781    /// assert!(v.is_empty());
782    /// ```
783    pub const fn take(&mut self) -> Self  {
784        mem::replace(self, Self::new_const())
785    }
786
787    /// Return a slice containing all elements of the vector.
788    pub const fn as_slice(&self) -> &[T] {
789        let len = self.len();
790        unsafe {
791            slice::from_raw_parts(self.as_ptr(), len)
792        }
793    }
794
795    /// Return a mutable slice containing all elements of the vector.
796    pub const fn as_mut_slice(&mut self) -> &mut [T] {
797        let len = self.len();
798        unsafe {
799            std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
800        }
801    }
802
803    /// Return a raw pointer to the vector's buffer.
804    pub const fn as_ptr(&self) -> *const T {
805        self.xs.as_ptr() as _
806    }
807
808    /// Return a raw mutable pointer to the vector's buffer.
809    pub const fn as_mut_ptr(&mut self) -> *mut T {
810        self.xs.as_mut_ptr() as _
811    }
812
813}
814
815impl<T, const CAP: usize> Deref for ArrayVec<T, CAP> {
816    type Target = [T];
817    #[inline]
818    fn deref(&self) -> &Self::Target {
819        self.as_slice()
820    }
821}
822
823impl<T, const CAP: usize> DerefMut for ArrayVec<T, CAP> {
824    #[inline]
825    fn deref_mut(&mut self) -> &mut Self::Target {
826        self.as_mut_slice()
827    }
828}
829
830
831/// Create an `ArrayVec` from an array.
832///
833/// ```
834/// use arrayvec::ArrayVec;
835///
836/// let mut array = ArrayVec::from([1, 2, 3]);
837/// assert_eq!(array.len(), 3);
838/// assert_eq!(array.capacity(), 3);
839/// ```
840impl<T, const CAP: usize> From<[T; CAP]> for ArrayVec<T, CAP> {
841    #[track_caller]
842    fn from(array: [T; CAP]) -> Self {
843        let array = ManuallyDrop::new(array);
844        let mut vec = <ArrayVec<T, CAP>>::new();
845        unsafe {
846            (&*array as *const [T; CAP] as *const [MaybeUninit<T>; CAP])
847                .copy_to_nonoverlapping(&mut vec.xs as *mut [MaybeUninit<T>; CAP], 1);
848            vec.set_len(CAP);
849        }
850        vec
851    }
852}
853
854
855/// Try to create an `ArrayVec` from a slice. This will return an error if the slice was too big to
856/// fit.
857///
858/// ```
859/// use arrayvec::ArrayVec;
860/// use std::convert::TryInto as _;
861///
862/// let array: ArrayVec<_, 4> = (&[1, 2, 3] as &[_]).try_into().unwrap();
863/// assert_eq!(array.len(), 3);
864/// assert_eq!(array.capacity(), 4);
865/// ```
866impl<T, const CAP: usize> std::convert::TryFrom<&[T]> for ArrayVec<T, CAP>
867    where T: Clone,
868{
869    type Error = CapacityError;
870
871    fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
872        if Self::CAPACITY < slice.len() {
873            Err(CapacityError::new(()))
874        } else {
875            let mut array = Self::new();
876            array.extend_from_slice(slice);
877            Ok(array)
878        }
879    }
880}
881
882
883/// Iterate the `ArrayVec` with references to each element.
884///
885/// ```
886/// use arrayvec::ArrayVec;
887///
888/// let array = ArrayVec::from([1, 2, 3]);
889///
890/// for elt in &array {
891///     // ...
892/// }
893/// ```
894impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a ArrayVec<T, CAP> {
895    type Item = &'a T;
896    type IntoIter = slice::Iter<'a, T>;
897    fn into_iter(self) -> Self::IntoIter { self.iter() }
898}
899
900/// Iterate the `ArrayVec` with mutable references to each element.
901///
902/// ```
903/// use arrayvec::ArrayVec;
904///
905/// let mut array = ArrayVec::from([1, 2, 3]);
906///
907/// for elt in &mut array {
908///     // ...
909/// }
910/// ```
911impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a mut ArrayVec<T, CAP> {
912    type Item = &'a mut T;
913    type IntoIter = slice::IterMut<'a, T>;
914    fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
915}
916
917/// Iterate the `ArrayVec` with each element by value.
918///
919/// The vector is consumed by this operation.
920///
921/// ```
922/// use arrayvec::ArrayVec;
923///
924/// for elt in ArrayVec::from([1, 2, 3]) {
925///     // ...
926/// }
927/// ```
928impl<T, const CAP: usize> IntoIterator for ArrayVec<T, CAP> {
929    type Item = T;
930    type IntoIter = IntoIter<T, CAP>;
931    fn into_iter(self) -> IntoIter<T, CAP> {
932        IntoIter { index: 0, v: self, }
933    }
934}
935
936
937#[cfg(feature = "zeroize")]
938/// "Best efforts" zeroing of the `ArrayVec`'s buffer when the `zeroize` feature is enabled.
939///
940/// The length is set to 0, and the buffer is dropped and zeroized.
941/// Cannot ensure that previous moves of the `ArrayVec` did not leave values on the stack.
942///
943/// ```
944/// use arrayvec::ArrayVec;
945/// use zeroize::Zeroize;
946/// let mut array = ArrayVec::from([1, 2, 3]);
947/// array.zeroize();
948/// assert_eq!(array.len(), 0);
949/// let data = unsafe { core::slice::from_raw_parts(array.as_ptr(), array.capacity()) };
950/// assert_eq!(data, [0, 0, 0]);
951/// ```
952impl<Z: zeroize::Zeroize, const CAP: usize> zeroize::Zeroize for ArrayVec<Z, CAP> {
953    fn zeroize(&mut self) {
954        // Zeroize all the contained elements.
955        self.iter_mut().zeroize();
956        // Drop all the elements and set the length to 0.
957        self.clear();
958        // Zeroize the backing array.
959        self.xs.zeroize();
960    }
961}
962
963/// By-value iterator for `ArrayVec`.
964pub struct IntoIter<T, const CAP: usize> {
965    index: usize,
966    v: ArrayVec<T, CAP>,
967}
968impl<T, const CAP: usize> IntoIter<T, CAP> {
969    /// Returns the remaining items of this iterator as a slice.
970    pub const fn as_slice(&self) -> &[T] {
971        self.v.as_slice().split_at(self.index).1
972    }
973
974    /// Returns the remaining items of this iterator as a mutable slice.
975    pub const fn as_mut_slice(&mut self) -> &mut [T] {
976        self.v.as_mut_slice().split_at_mut(self.index).1
977    }
978}
979
980impl<T, const CAP: usize> Iterator for IntoIter<T, CAP> {
981    type Item = T;
982
983    fn next(&mut self) -> Option<Self::Item> {
984        if self.index == self.v.len() {
985            None
986        } else {
987            unsafe {
988                let index = self.index;
989                self.index = index + 1;
990                Some(ptr::read(self.v.get_unchecked_ptr(index)))
991            }
992        }
993    }
994
995    fn size_hint(&self) -> (usize, Option<usize>) {
996        let len = self.v.len() - self.index;
997        (len, Some(len))
998    }
999}
1000
1001impl<T, const CAP: usize> DoubleEndedIterator for IntoIter<T, CAP> {
1002    fn next_back(&mut self) -> Option<Self::Item> {
1003        if self.index == self.v.len() {
1004            None
1005        } else {
1006            unsafe {
1007                let new_len = self.v.len() - 1;
1008                self.v.set_len(new_len);
1009                Some(ptr::read(self.v.get_unchecked_ptr(new_len)))
1010            }
1011        }
1012    }
1013}
1014
1015impl<T, const CAP: usize> ExactSizeIterator for IntoIter<T, CAP> { }
1016
1017impl<T, const CAP: usize> Drop for IntoIter<T, CAP> {
1018    fn drop(&mut self) {
1019        // panic safety: Set length to 0 before dropping elements.
1020        let index = self.index;
1021        let len = self.v.len();
1022        unsafe {
1023            self.v.set_len(0);
1024            let elements = slice::from_raw_parts_mut(
1025                self.v.get_unchecked_ptr(index),
1026                len - index);
1027            ptr::drop_in_place(elements);
1028        }
1029    }
1030}
1031
1032impl<T, const CAP: usize> Clone for IntoIter<T, CAP>
1033where T: Clone,
1034{
1035    fn clone(&self) -> IntoIter<T, CAP> {
1036        let mut v = ArrayVec::new();
1037        v.extend_from_slice(&self.v[self.index..]);
1038        v.into_iter()
1039    }
1040}
1041
1042impl<T, const CAP: usize> fmt::Debug for IntoIter<T, CAP>
1043where
1044    T: fmt::Debug,
1045{
1046    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1047        f.debug_list()
1048            .entries(&self.v[self.index..])
1049            .finish()
1050    }
1051}
1052
1053/// A draining iterator for `ArrayVec`.
1054pub struct Drain<'a, T: 'a, const CAP: usize> {
1055    /// Index of tail to preserve
1056    tail_start: usize,
1057    /// Length of tail
1058    tail_len: usize,
1059    /// Current remaining range to remove
1060    iter: slice::Iter<'a, T>,
1061    vec: *mut ArrayVec<T, CAP>,
1062}
1063
1064unsafe impl<'a, T: Sync, const CAP: usize> Sync for Drain<'a, T, CAP> {}
1065unsafe impl<'a, T: Send, const CAP: usize> Send for Drain<'a, T, CAP> {}
1066
1067impl<'a, T: 'a, const CAP: usize> Iterator for Drain<'a, T, CAP> {
1068    type Item = T;
1069
1070    fn next(&mut self) -> Option<Self::Item> {
1071        self.iter.next().map(|elt|
1072            unsafe {
1073                ptr::read(elt as *const _)
1074            }
1075        )
1076    }
1077
1078    fn size_hint(&self) -> (usize, Option<usize>) {
1079        self.iter.size_hint()
1080    }
1081}
1082
1083impl<'a, T: 'a, const CAP: usize> DoubleEndedIterator for Drain<'a, T, CAP>
1084{
1085    fn next_back(&mut self) -> Option<Self::Item> {
1086        self.iter.next_back().map(|elt|
1087            unsafe {
1088                ptr::read(elt as *const _)
1089            }
1090        )
1091    }
1092}
1093
1094impl<'a, T: 'a, const CAP: usize> ExactSizeIterator for Drain<'a, T, CAP> {}
1095
1096impl<'a, T: 'a, const CAP: usize> Drop for Drain<'a, T, CAP> {
1097    fn drop(&mut self) {
1098        // len is currently 0 so panicking while dropping will not cause a double drop.
1099
1100        // exhaust self first
1101        while let Some(_) = self.next() { }
1102
1103        if self.tail_len > 0 {
1104            unsafe {
1105                let source_vec = &mut *self.vec;
1106                // memmove back untouched tail, update to new length
1107                let start = source_vec.len();
1108                let tail = self.tail_start;
1109                let ptr = source_vec.as_mut_ptr();
1110                ptr::copy(ptr.add(tail), ptr.add(start), self.tail_len);
1111                source_vec.set_len(start + self.tail_len);
1112            }
1113        }
1114    }
1115}
1116
1117struct ScopeExitGuard<T, Data, F>
1118    where F: FnMut(&Data, &mut T)
1119{
1120    value: T,
1121    data: Data,
1122    f: F,
1123}
1124
1125impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
1126    where F: FnMut(&Data, &mut T)
1127{
1128    fn drop(&mut self) {
1129        (self.f)(&self.data, &mut self.value)
1130    }
1131}
1132
1133
1134
1135/// Extend the `ArrayVec` with an iterator.
1136/// 
1137/// ***Panics*** if extending the vector exceeds its capacity.
1138impl<T, const CAP: usize> Extend<T> for ArrayVec<T, CAP> {
1139    /// Extend the `ArrayVec` with an iterator.
1140    /// 
1141    /// ***Panics*** if extending the vector exceeds its capacity.
1142    #[track_caller]
1143    fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
1144        unsafe {
1145            self.extend_from_iter::<_, true>(iter)
1146        }
1147    }
1148}
1149
1150#[inline(never)]
1151#[cold]
1152#[track_caller]
1153const fn extend_panic() {
1154    panic!("ArrayVec: capacity exceeded in extend/from_iter");
1155}
1156
1157impl<T, const CAP: usize> ArrayVec<T, CAP> {
1158    /// Extend the arrayvec from the iterable.
1159    ///
1160    /// ## Safety
1161    ///
1162    /// Unsafe because if CHECK is false, the length of the input is not checked.
1163    /// The caller must ensure the length of the input fits in the capacity.
1164    #[track_caller]
1165    pub(crate) unsafe fn extend_from_iter<I, const CHECK: bool>(&mut self, iterable: I)
1166        where I: IntoIterator<Item = T>
1167    {
1168        let take = self.capacity() - self.len();
1169        let len = self.len();
1170        let mut ptr = raw_ptr_add(self.as_mut_ptr(), len);
1171        let end_ptr = raw_ptr_add(ptr, take);
1172        // Keep the length in a separate variable, write it back on scope
1173        // exit. To help the compiler with alias analysis and stuff.
1174        // We update the length to handle panic in the iteration of the
1175        // user's iterator, without dropping any elements on the floor.
1176        let mut guard = ScopeExitGuard {
1177            value: &mut self.len,
1178            data: len,
1179            f: move |&len, self_len| {
1180                **self_len = len as LenUint;
1181            }
1182        };
1183        let mut iter = iterable.into_iter();
1184        loop {
1185            if let Some(elt) = iter.next() {
1186                if ptr == end_ptr && CHECK { extend_panic(); }
1187                debug_assert_ne!(ptr, end_ptr);
1188                if mem::size_of::<T>() != 0 {
1189                    ptr.write(elt);
1190                }
1191                ptr = raw_ptr_add(ptr, 1);
1192                guard.data += 1;
1193            } else {
1194                return; // success
1195            }
1196        }
1197    }
1198
1199    /// Extend the ArrayVec with clones of elements from the slice;
1200    /// the length of the slice must be <= the remaining capacity in the arrayvec.
1201    pub(crate) fn extend_from_slice(&mut self, slice: &[T])
1202        where T: Clone
1203    {
1204        let take = self.capacity() - self.len();
1205        debug_assert!(slice.len() <= take);
1206        unsafe {
1207            let slice = if take < slice.len() { &slice[..take] } else { slice };
1208            self.extend_from_iter::<_, false>(slice.iter().cloned());
1209        }
1210    }
1211}
1212
1213/// Rawptr add but uses arithmetic distance for ZST
1214const unsafe fn raw_ptr_add<T>(ptr: *mut T, offset: usize) -> *mut T {
1215    if mem::size_of::<T>() == 0 {
1216        // Special case for ZST
1217        ptr.cast::<u8>().wrapping_add(offset).cast::<T>()
1218    } else {
1219        ptr.add(offset)
1220    }
1221}
1222
1223/// Create an `ArrayVec` from an iterator.
1224/// 
1225/// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
1226impl<T, const CAP: usize> iter::FromIterator<T> for ArrayVec<T, CAP> {
1227    /// Create an `ArrayVec` from an iterator.
1228    /// 
1229    /// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
1230    fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
1231        let mut array = ArrayVec::new();
1232        array.extend(iter);
1233        array
1234    }
1235}
1236
1237impl<T, const CAP: usize> Clone for ArrayVec<T, CAP>
1238    where T: Clone
1239{
1240    fn clone(&self) -> Self {
1241        self.iter().cloned().collect()
1242    }
1243
1244    fn clone_from(&mut self, rhs: &Self) {
1245        // recursive case for the common prefix
1246        let prefix = cmp::min(self.len(), rhs.len());
1247        self[..prefix].clone_from_slice(&rhs[..prefix]);
1248
1249        if prefix < self.len() {
1250            // rhs was shorter
1251            self.truncate(prefix);
1252        } else {
1253            let rhs_elems = &rhs[self.len()..];
1254            self.extend_from_slice(rhs_elems);
1255        }
1256    }
1257}
1258
1259impl<T, const CAP: usize> Hash for ArrayVec<T, CAP>
1260    where T: Hash
1261{
1262    fn hash<H: Hasher>(&self, state: &mut H) {
1263        Hash::hash(&**self, state)
1264    }
1265}
1266
1267impl<T, const CAP: usize> PartialEq for ArrayVec<T, CAP>
1268    where T: PartialEq
1269{
1270    fn eq(&self, other: &Self) -> bool {
1271        **self == **other
1272    }
1273}
1274
1275impl<T, const CAP: usize> PartialEq<[T]> for ArrayVec<T, CAP>
1276    where T: PartialEq
1277{
1278    fn eq(&self, other: &[T]) -> bool {
1279        **self == *other
1280    }
1281}
1282
1283impl<T, const CAP: usize> Eq for ArrayVec<T, CAP> where T: Eq { }
1284
1285impl<T, const CAP: usize> Borrow<[T]> for ArrayVec<T, CAP> {
1286    fn borrow(&self) -> &[T] { self }
1287}
1288
1289impl<T, const CAP: usize> BorrowMut<[T]> for ArrayVec<T, CAP> {
1290    fn borrow_mut(&mut self) -> &mut [T] { self }
1291}
1292
1293impl<T, const CAP: usize> AsRef<[T]> for ArrayVec<T, CAP> {
1294    fn as_ref(&self) -> &[T] { self }
1295}
1296
1297impl<T, const CAP: usize> AsMut<[T]> for ArrayVec<T, CAP> {
1298    fn as_mut(&mut self) -> &mut [T] { self }
1299}
1300
1301impl<T, const CAP: usize> fmt::Debug for ArrayVec<T, CAP> where T: fmt::Debug {
1302    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
1303}
1304
1305impl<T, const CAP: usize> Default for ArrayVec<T, CAP> {
1306    /// Return an empty array
1307    fn default() -> ArrayVec<T, CAP> {
1308        ArrayVec::new()
1309    }
1310}
1311
1312impl<T, const CAP: usize> PartialOrd for ArrayVec<T, CAP> where T: PartialOrd {
1313    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1314        (**self).partial_cmp(other)
1315    }
1316
1317    fn lt(&self, other: &Self) -> bool {
1318        (**self).lt(other)
1319    }
1320
1321    fn le(&self, other: &Self) -> bool {
1322        (**self).le(other)
1323    }
1324
1325    fn ge(&self, other: &Self) -> bool {
1326        (**self).ge(other)
1327    }
1328
1329    fn gt(&self, other: &Self) -> bool {
1330        (**self).gt(other)
1331    }
1332}
1333
1334impl<T, const CAP: usize> Ord for ArrayVec<T, CAP> where T: Ord {
1335    fn cmp(&self, other: &Self) -> cmp::Ordering {
1336        (**self).cmp(other)
1337    }
1338}
1339
1340#[cfg(feature="std")]
1341/// `Write` appends written data to the end of the vector.
1342///
1343/// Requires `features="std"`.
1344impl<const CAP: usize> io::Write for ArrayVec<u8, CAP> {
1345    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1346        let len = cmp::min(self.remaining_capacity(), data.len());
1347        let _result = self.try_extend_from_slice(&data[..len]);
1348        debug_assert!(_result.is_ok());
1349        Ok(len)
1350    }
1351    fn flush(&mut self) -> io::Result<()> { Ok(()) }
1352}
1353
1354#[cfg(feature="serde")]
1355/// Requires crate feature `"serde"`
1356impl<T: Serialize, const CAP: usize> Serialize for ArrayVec<T, CAP> {
1357    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1358        where S: Serializer
1359    {
1360        serializer.collect_seq(self)
1361    }
1362}
1363
1364#[cfg(feature="serde")]
1365/// Requires crate feature `"serde"`
1366impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec<T, CAP> {
1367    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1368        where D: Deserializer<'de>
1369    {
1370        use serde::de::{Visitor, SeqAccess, Error};
1371        use std::marker::PhantomData;
1372
1373        struct ArrayVecVisitor<'de, T: Deserialize<'de>, const CAP: usize>(PhantomData<(&'de (), [T; CAP])>);
1374
1375        impl<'de, T: Deserialize<'de>, const CAP: usize> Visitor<'de> for ArrayVecVisitor<'de, T, CAP> {
1376            type Value = ArrayVec<T, CAP>;
1377
1378            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1379                write!(formatter, "an array with no more than {} items", CAP)
1380            }
1381
1382            fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error>
1383                where SA: SeqAccess<'de>,
1384            {
1385                let mut values = ArrayVec::<T, CAP>::new();
1386
1387                while let Some(value) = seq.next_element()? {
1388                    if let Err(_) = values.try_push(value) {
1389                        return Err(SA::Error::invalid_length(CAP + 1, &self));
1390                    }
1391                }
1392
1393                Ok(values)
1394            }
1395        }
1396
1397        deserializer.deserialize_seq(ArrayVecVisitor::<T, CAP>(PhantomData))
1398    }
1399}
1400
1401#[cfg(feature = "borsh")]
1402/// Requires crate feature `"borsh"`
1403impl<T, const CAP: usize> borsh::BorshSerialize for ArrayVec<T, CAP>
1404where
1405    T: borsh::BorshSerialize,
1406{
1407    fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
1408        <[T] as borsh::BorshSerialize>::serialize(self.as_slice(), writer)
1409    }
1410}
1411
1412#[cfg(feature = "borsh")]
1413/// Requires crate feature `"borsh"`
1414impl<T, const CAP: usize> borsh::BorshDeserialize for ArrayVec<T, CAP>
1415where
1416    T: borsh::BorshDeserialize,
1417{
1418    fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
1419        let mut values = Self::new();
1420        let len = <u32 as borsh::BorshDeserialize>::deserialize_reader(reader)?;
1421        for _ in 0..len {
1422            let elem = <T as borsh::BorshDeserialize>::deserialize_reader(reader)?;
1423            if let Err(_) = values.try_push(elem) {
1424                return Err(borsh::io::Error::new(
1425                    borsh::io::ErrorKind::InvalidData,
1426                    format!("Expected an array with no more than {} items", CAP),
1427                ));
1428            }
1429        }
1430
1431        Ok(values)
1432    }
1433}