Skip to main content

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