Skip to main content

tinyvec/
arrayvec.rs

1use super::*;
2use core::convert::{TryFrom, TryInto};
3
4#[cfg(feature = "serde")]
5use core::marker::PhantomData;
6#[cfg(feature = "serde")]
7use serde_core::de::{
8  Deserialize, Deserializer, Error as DeserializeError, SeqAccess, Visitor,
9};
10#[cfg(feature = "serde")]
11use serde_core::ser::{Serialize, SerializeSeq, Serializer};
12
13/// Helper to make an `ArrayVec`.
14///
15/// You specify the backing array type, and optionally give all the elements you
16/// want to initially place into the array.
17///
18/// ```rust
19/// use tinyvec::*;
20///
21/// // The backing array type can be specified in the macro call
22/// let empty_av = array_vec!([u8; 16]);
23/// let some_ints = array_vec!([i32; 4] => 1, 2, 3);
24///
25/// // Or left to inference
26/// let empty_av: ArrayVec<[u8; 10]> = array_vec!();
27/// let some_ints: ArrayVec<[u8; 10]> = array_vec!(5, 6, 7, 8);
28/// ```
29#[macro_export]
30macro_rules! array_vec {
31  ($array_type:ty => $($elem:expr),* $(,)?) => {
32    {
33      let mut av: $crate::ArrayVec<$array_type> = Default::default();
34      $( av.push($elem); )*
35      av
36    }
37  };
38  ($array_type:ty) => {
39    $crate::ArrayVec::<$array_type>::default()
40  };
41  ($($elem:expr),*) => {
42    $crate::array_vec!(_ => $($elem),*)
43  };
44  ($elem:expr; $n:expr) => {
45    $crate::ArrayVec::from([$elem; $n])
46  };
47  () => {
48    $crate::array_vec!(_)
49  };
50}
51
52/// An array-backed, vector-like data structure.
53///
54/// * `ArrayVec` has a fixed capacity, equal to the minimum of the array size
55///   and `u16::MAX`. Note that not all capacities are necessarily supported by
56///   default. See comments in [`Array`].
57/// * `ArrayVec` has a variable length, as you add and remove elements. Attempts
58///   to fill the vec beyond its capacity will cause a panic.
59/// * All of the vec's array slots are always initialized in terms of Rust's
60///   memory model. When you remove an element from a location, the old value at
61///   that location is replaced with the type's default value.
62///
63/// The overall API of this type is intended to, as much as possible, emulate
64/// the API of the [`Vec`](https://doc.rust-lang.org/alloc/vec/struct.Vec.html)
65/// type.
66///
67/// ## Construction
68///
69/// You can use the `array_vec!` macro similarly to how you might use the `vec!`
70/// macro. Specify the array type, then optionally give all the initial values
71/// you want to have.
72/// ```rust
73/// # use tinyvec::*;
74/// let some_ints = array_vec!([i32; 4] => 1, 2, 3);
75/// assert_eq!(some_ints.len(), 3);
76/// ```
77///
78/// The [`default`](ArrayVec::new) for an `ArrayVec` is to have a default
79/// array with length 0. The [`new`](ArrayVec::new) method is the same as
80/// calling `default`
81/// ```rust
82/// # use tinyvec::*;
83/// let some_ints = ArrayVec::<[i32; 7]>::default();
84/// assert_eq!(some_ints.len(), 0);
85///
86/// let more_ints = ArrayVec::<[i32; 7]>::new();
87/// assert_eq!(some_ints, more_ints);
88/// ```
89///
90/// If you have an array and want the _whole thing_ to count as being "in" the
91/// new `ArrayVec` you can use one of the `from` implementations. If you want
92/// _part of_ the array then you can use
93/// [`from_array_len`](ArrayVec::from_array_len):
94/// ```rust
95/// # use tinyvec::*;
96/// let some_ints = ArrayVec::from([5, 6, 7, 8]);
97/// assert_eq!(some_ints.len(), 4);
98///
99/// let more_ints = ArrayVec::from_array_len([5, 6, 7, 8], 2);
100/// assert_eq!(more_ints.len(), 2);
101///
102/// let no_ints: ArrayVec<[u8; 5]> = ArrayVec::from_array_empty([1, 2, 3, 4, 5]);
103/// assert_eq!(no_ints.len(), 0);
104/// ```
105#[repr(C)]
106pub struct ArrayVec<A> {
107  len: u16,
108  pub(crate) data: A,
109}
110
111impl<A> Clone for ArrayVec<A>
112where
113  A: Array + Clone,
114  A::Item: Clone,
115{
116  #[inline]
117  fn clone(&self) -> Self {
118    Self { data: self.data.clone(), len: self.len }
119  }
120
121  #[inline]
122  fn clone_from(&mut self, o: &Self) {
123    let iter = self
124      .data
125      .as_slice_mut()
126      .iter_mut()
127      .zip(o.data.as_slice())
128      .take(self.len.max(o.len) as usize);
129    for (dst, src) in iter {
130      dst.clone_from(src)
131    }
132    if let Some(to_drop) =
133      self.data.as_slice_mut().get_mut((o.len as usize)..(self.len as usize))
134    {
135      to_drop.iter_mut().for_each(|x| drop(core::mem::take(x)));
136    }
137    self.len = o.len;
138  }
139}
140
141impl<A> Copy for ArrayVec<A>
142where
143  A: Array + Copy,
144  A::Item: Copy,
145{
146}
147
148impl<A: Array> Default for ArrayVec<A> {
149  #[inline]
150  fn default() -> Self {
151    Self { len: 0, data: A::default() }
152  }
153}
154
155impl<A: Array> Deref for ArrayVec<A> {
156  type Target = [A::Item];
157  #[inline(always)]
158  fn deref(&self) -> &Self::Target {
159    &self.data.as_slice()[..self.len as usize]
160  }
161}
162
163impl<A: Array> DerefMut for ArrayVec<A> {
164  #[inline(always)]
165  fn deref_mut(&mut self) -> &mut Self::Target {
166    &mut self.data.as_slice_mut()[..self.len as usize]
167  }
168}
169
170impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for ArrayVec<A> {
171  type Output = <I as SliceIndex<[A::Item]>>::Output;
172  #[inline(always)]
173  fn index(&self, index: I) -> &Self::Output {
174    &self.deref()[index]
175  }
176}
177
178impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for ArrayVec<A> {
179  #[inline(always)]
180  fn index_mut(&mut self, index: I) -> &mut Self::Output {
181    &mut self.deref_mut()[index]
182  }
183}
184
185#[cfg(feature = "serde")]
186#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
187impl<A: Array> Serialize for ArrayVec<A>
188where
189  A::Item: Serialize,
190{
191  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
192  where
193    S: Serializer,
194  {
195    let mut seq = serializer.serialize_seq(Some(self.len()))?;
196    for element in self.iter() {
197      seq.serialize_element(element)?;
198    }
199    seq.end()
200  }
201}
202
203#[cfg(feature = "serde")]
204#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
205impl<'de, A: Array> Deserialize<'de> for ArrayVec<A>
206where
207  A::Item: Deserialize<'de>,
208{
209  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210  where
211    D: Deserializer<'de>,
212  {
213    deserializer.deserialize_seq(ArrayVecVisitor(PhantomData))
214  }
215}
216
217#[cfg(feature = "borsh")]
218#[cfg_attr(docs_rs, doc(cfg(feature = "borsh")))]
219impl<A: Array> borsh::BorshSerialize for ArrayVec<A>
220where
221  <A as Array>::Item: borsh::BorshSerialize,
222{
223  fn serialize<W: borsh::io::Write>(
224    &self, writer: &mut W,
225  ) -> borsh::io::Result<()> {
226    <usize as borsh::BorshSerialize>::serialize(&self.len(), writer)?;
227    for elem in self.iter() {
228      <<A as Array>::Item as borsh::BorshSerialize>::serialize(elem, writer)?;
229    }
230    Ok(())
231  }
232}
233
234#[cfg(feature = "borsh")]
235#[cfg_attr(docs_rs, doc(cfg(feature = "borsh")))]
236impl<A: Array> borsh::BorshDeserialize for ArrayVec<A>
237where
238  <A as Array>::Item: borsh::BorshDeserialize,
239{
240  fn deserialize_reader<R: borsh::io::Read>(
241    reader: &mut R,
242  ) -> borsh::io::Result<Self> {
243    let len = <usize as borsh::BorshDeserialize>::deserialize_reader(reader)?;
244    let mut new_arrayvec = Self::default();
245
246    for idx in 0..len {
247      let value =
248        <<A as Array>::Item as borsh::BorshDeserialize>::deserialize_reader(
249          reader,
250        )?;
251      if idx >= new_arrayvec.capacity() {
252        return Err(borsh::io::Error::new(
253          borsh::io::ErrorKind::InvalidData,
254          "invalid ArrayVec length",
255        ));
256      }
257      new_arrayvec.push(value)
258    }
259
260    Ok(new_arrayvec)
261  }
262}
263
264#[cfg(feature = "arbitrary")]
265#[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))]
266impl<'a, A> arbitrary::Arbitrary<'a> for ArrayVec<A>
267where
268  A: Array,
269  A::Item: arbitrary::Arbitrary<'a>,
270{
271  fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
272    let max_len = A::CAPACITY.min(u16::MAX as usize) as u16;
273    let len = u.int_in_range::<u16>(0..=max_len)?;
274    let mut self_: Self = Default::default();
275    for _ in 0..len {
276      self_.push(u.arbitrary()?);
277    }
278    Ok(self_)
279  }
280
281  fn size_hint(depth: usize) -> (usize, Option<usize>) {
282    arbitrary::size_hint::recursion_guard(depth, |depth| {
283      let max_len = A::CAPACITY.min(u16::MAX as usize);
284      let inner = A::Item::size_hint(depth).1;
285      (0, inner.map(|inner| 2 + max_len * inner))
286    })
287  }
288}
289
290impl<A: Array> ArrayVec<A> {
291  /// Move all values from `other` into this vec.
292  ///
293  /// ## Panics
294  /// * If the vec overflows its capacity
295  ///
296  /// ## Example
297  /// ```rust
298  /// # use tinyvec::*;
299  /// let mut av = array_vec!([i32; 10] => 1, 2, 3);
300  /// let mut av2 = array_vec!([i32; 10] => 4, 5, 6);
301  /// av.append(&mut av2);
302  /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]);
303  /// assert_eq!(av2, &[][..]);
304  /// ```
305  #[inline]
306  pub fn append(&mut self, other: &mut Self) {
307    assert!(
308      self.try_append(other).is_none(),
309      "ArrayVec::append> total length {} exceeds capacity {}!",
310      self.len() + other.len(),
311      A::CAPACITY
312    );
313  }
314
315  /// Move all values from `other` into this vec.
316  /// If appending would overflow the capacity, Some(other) is returned.
317  /// ## Example
318  /// ```rust
319  /// # use tinyvec::*;
320  /// let mut av = array_vec!([i32; 7] => 1, 2, 3);
321  /// let mut av2 = array_vec!([i32; 7] => 4, 5, 6);
322  /// av.append(&mut av2);
323  /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]);
324  /// assert_eq!(av2, &[][..]);
325  ///
326  /// let mut av3 = array_vec!([i32; 7] => 7, 8, 9);
327  /// assert!(av.try_append(&mut av3).is_some());
328  /// assert_eq!(av, &[1, 2, 3, 4, 5, 6][..]);
329  /// assert_eq!(av3, &[7, 8, 9][..]);
330  /// ```
331  #[inline]
332  pub fn try_append<'other>(
333    &mut self, other: &'other mut Self,
334  ) -> Option<&'other mut Self> {
335    let new_len = self.len() + other.len();
336    if new_len > A::CAPACITY {
337      return Some(other);
338    }
339
340    let iter = other.iter_mut().map(core::mem::take);
341    for item in iter {
342      self.push(item);
343    }
344
345    other.set_len(0);
346
347    return None;
348  }
349
350  /// A `*mut` pointer to the backing array.
351  ///
352  /// ## Safety
353  ///
354  /// This pointer has provenance over the _entire_ backing array.
355  #[inline(always)]
356  #[must_use]
357  pub fn as_mut_ptr(&mut self) -> *mut A::Item {
358    self.data.as_slice_mut().as_mut_ptr()
359  }
360
361  /// Performs a `deref_mut`, into unique slice form.
362  #[inline(always)]
363  #[must_use]
364  pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
365    self.deref_mut()
366  }
367
368  /// A `*const` pointer to the backing array.
369  ///
370  /// ## Safety
371  ///
372  /// This pointer has provenance over the _entire_ backing array.
373  #[inline(always)]
374  #[must_use]
375  pub fn as_ptr(&self) -> *const A::Item {
376    self.data.as_slice().as_ptr()
377  }
378
379  /// Performs a `deref`, into shared slice form.
380  #[inline(always)]
381  #[must_use]
382  pub fn as_slice(&self) -> &[A::Item] {
383    self.deref()
384  }
385
386  /// The capacity of the `ArrayVec`.
387  ///
388  /// This is fixed based on the array type, but can't yet be made a `const fn`
389  /// on Stable Rust.
390  #[inline(always)]
391  #[must_use]
392  pub fn capacity(&self) -> usize {
393    // Note: This shouldn't use A::CAPACITY, because unsafe code can't rely on
394    // any Array invariants. This ensures that at the very least, the returned
395    // value is a valid length for a subslice of the backing array.
396    self.data.as_slice().len().min(u16::MAX as usize)
397  }
398
399  /// Truncates the `ArrayVec` down to length 0.
400  #[inline(always)]
401  pub fn clear(&mut self) {
402    self.truncate(0)
403  }
404
405  /// Creates a draining iterator that removes the specified range in the vector
406  /// and yields the removed items.
407  ///
408  /// ## Panics
409  /// * If the start is greater than the end
410  /// * If the end is past the edge of the vec.
411  ///
412  /// ## Example
413  /// ```rust
414  /// # use tinyvec::*;
415  /// let mut av = array_vec!([i32; 4] => 1, 2, 3);
416  /// let av2: ArrayVec<[i32; 4]> = av.drain(1..).collect();
417  /// assert_eq!(av.as_slice(), &[1][..]);
418  /// assert_eq!(av2.as_slice(), &[2, 3][..]);
419  ///
420  /// av.drain(..);
421  /// assert_eq!(av.as_slice(), &[]);
422  /// ```
423  #[inline]
424  pub fn drain<R>(&mut self, range: R) -> ArrayVecDrain<'_, A::Item>
425  where
426    R: RangeBounds<usize>,
427  {
428    ArrayVecDrain::new(self, range)
429  }
430
431  /// Returns the inner array of the `ArrayVec`.
432  ///
433  /// This returns the full array, even if the `ArrayVec` length is currently
434  /// less than that.
435  ///
436  /// ## Example
437  ///
438  /// ```rust
439  /// # use tinyvec::{array_vec, ArrayVec};
440  /// let mut favorite_numbers = array_vec!([i32; 5] => 87, 48, 33, 9, 26);
441  /// assert_eq!(favorite_numbers.clone().into_inner(), [87, 48, 33, 9, 26]);
442  ///
443  /// favorite_numbers.pop();
444  /// assert_eq!(favorite_numbers.into_inner(), [87, 48, 33, 9, 0]);
445  /// ```
446  ///
447  /// A use for this function is to build an array from an iterator by first
448  /// collecting it into an `ArrayVec`.
449  ///
450  /// ```rust
451  /// # use tinyvec::ArrayVec;
452  /// let arr_vec: ArrayVec<[i32; 10]> = (1..=3).cycle().take(10).collect();
453  /// let inner = arr_vec.into_inner();
454  /// assert_eq!(inner, [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]);
455  /// ```
456  #[inline]
457  pub fn into_inner(self) -> A {
458    self.data
459  }
460
461  /// Clone each element of the slice into this `ArrayVec`.
462  ///
463  /// ## Panics
464  /// * If the `ArrayVec` would overflow, this will panic.
465  #[inline]
466  pub fn extend_from_slice(&mut self, sli: &[A::Item])
467  where
468    A::Item: Clone,
469  {
470    if sli.is_empty() {
471      return;
472    }
473
474    let new_len = self.len as usize + sli.len();
475    assert!(
476      new_len <= A::CAPACITY,
477      "ArrayVec::extend_from_slice> total length {} exceeds capacity {}!",
478      new_len,
479      A::CAPACITY
480    );
481
482    let target = &mut self.data.as_slice_mut()[self.len as usize..new_len];
483    target.clone_from_slice(sli);
484    self.set_len(new_len);
485  }
486
487  /// Fill the vector until its capacity has been reached.
488  ///
489  /// Successively fills unused space in the spare slice of the vector with
490  /// elements from the iterator. It then returns the remaining iterator
491  /// without exhausting it. This also allows appending the head of an
492  /// infinite iterator.
493  ///
494  /// This is an alternative to `Extend::extend` method for cases where the
495  /// length of the iterator can not be checked. Since this vector can not
496  /// reallocate to increase its capacity, it is unclear what to do with
497  /// remaining elements in the iterator and the iterator itself. The
498  /// interface also provides no way to communicate this to the caller.
499  ///
500  /// ## Panics
501  /// * If the `next` method of the provided iterator panics.
502  ///
503  /// ## Example
504  ///
505  /// ```rust
506  /// # use tinyvec::*;
507  /// let mut av = array_vec!([i32; 4]);
508  /// let mut to_inf = av.fill(0..);
509  /// assert_eq!(&av[..], [0, 1, 2, 3]);
510  /// assert_eq!(to_inf.next(), Some(4));
511  /// ```
512  #[inline]
513  pub fn fill<I: IntoIterator<Item = A::Item>>(
514    &mut self, iter: I,
515  ) -> I::IntoIter {
516    // If this is written as a call to push for each element in iter, the
517    // compiler emits code that updates the length for every element. The
518    // additional complexity from that length update is worth nearly 2x in
519    // the runtime of this function.
520    let mut iter = iter.into_iter();
521    let mut pushed = 0;
522    let to_take = self.capacity() - self.len();
523    let target = &mut self.data.as_slice_mut()[self.len as usize..];
524    for element in iter.by_ref().take(to_take) {
525      target[pushed] = element;
526      pushed += 1;
527    }
528    self.len += pushed as u16;
529    iter
530  }
531
532  /// Wraps up an array and uses the given length as the initial length.
533  ///
534  /// If you want to simply use the full array, use `from` instead.
535  ///
536  /// ## Panics
537  ///
538  /// * The length specified must be less than or equal to the capacity of the
539  ///   array.
540  #[inline]
541  #[must_use]
542  #[allow(clippy::match_wild_err_arm)]
543  pub fn from_array_len(data: A, len: usize) -> Self {
544    match Self::try_from_array_len(data, len) {
545      Ok(out) => out,
546      Err(_) => panic!(
547        "ArrayVec::from_array_len> length {} exceeds capacity {}!",
548        len,
549        A::CAPACITY
550      ),
551    }
552  }
553
554  /// Inserts an item at the position given, moving all following elements +1
555  /// index.
556  ///
557  /// ## Panics
558  /// * If `index` > `len`
559  /// * If the capacity is exhausted
560  ///
561  /// ## Example
562  /// ```rust
563  /// use tinyvec::*;
564  /// let mut av = array_vec!([i32; 10] => 1, 2, 3);
565  /// av.insert(1, 4);
566  /// assert_eq!(av.as_slice(), &[1, 4, 2, 3]);
567  /// av.insert(4, 5);
568  /// assert_eq!(av.as_slice(), &[1, 4, 2, 3, 5]);
569  /// ```
570  #[inline]
571  pub fn insert(&mut self, index: usize, item: A::Item) {
572    let x = self.try_insert(index, item);
573    assert!(x.is_none(), "ArrayVec::insert> capacity overflow!");
574  }
575
576  /// Tries to insert an item at the position given, moving all following
577  /// elements +1 index.
578  /// Returns back the element if the capacity is exhausted,
579  /// otherwise returns None.
580  ///
581  /// ## Panics
582  /// * If `index` > `len`
583  ///
584  /// ## Example
585  /// ```rust
586  /// use tinyvec::*;
587  /// let mut av = array_vec!([&'static str; 4] => "one", "two", "three");
588  /// av.insert(1, "four");
589  /// assert_eq!(av.as_slice(), &["one", "four", "two", "three"]);
590  /// assert_eq!(av.try_insert(4, "five"), Some("five"));
591  /// ```
592  #[inline]
593  pub fn try_insert(
594    &mut self, index: usize, mut item: A::Item,
595  ) -> Option<A::Item> {
596    assert!(
597      index <= self.len as usize,
598      "ArrayVec::try_insert> index {} is out of bounds {}",
599      index,
600      self.len
601    );
602
603    // A previous implementation used self.try_push and slice::rotate_right
604    // rotate_right and rotate_left generate a huge amount of code and fail to
605    // inline; calling them here incurs the cost of all the cases they
606    // handle even though we're rotating a usually-small array by a constant
607    // 1 offset. This swap-based implementation benchmarks much better for
608    // small array lengths in particular.
609
610    if (self.len as usize) < A::CAPACITY {
611      self.len += 1;
612    } else {
613      return Some(item);
614    }
615
616    let target = &mut self.as_mut_slice()[index..];
617    #[allow(clippy::needless_range_loop)]
618    for i in 0..target.len() {
619      core::mem::swap(&mut item, &mut target[i]);
620    }
621    return None;
622  }
623
624  /// Checks if the length is 0.
625  #[inline(always)]
626  #[must_use]
627  pub fn is_empty(&self) -> bool {
628    self.len == 0
629  }
630
631  /// Checks if the length is equal to capacity.
632  #[inline(always)]
633  #[must_use]
634  pub fn is_full(&self) -> bool {
635    self.len() == self.capacity()
636  }
637
638  /// The length of the `ArrayVec` (in elements).
639  #[inline(always)]
640  #[must_use]
641  pub fn len(&self) -> usize {
642    self.len as usize
643  }
644
645  /// Makes a new, empty `ArrayVec`.
646  #[inline(always)]
647  #[must_use]
648  pub fn new() -> Self {
649    Self::default()
650  }
651
652  /// Remove and return the last element of the vec, if there is one.
653  ///
654  /// ## Failure
655  /// * If the vec is empty you get `None`.
656  ///
657  /// ## Example
658  /// ```rust
659  /// # use tinyvec::*;
660  /// let mut av = array_vec!([i32; 10] => 1, 2);
661  /// assert_eq!(av.pop(), Some(2));
662  /// assert_eq!(av.pop(), Some(1));
663  /// assert_eq!(av.pop(), None);
664  /// ```
665  #[inline]
666  pub fn pop(&mut self) -> Option<A::Item> {
667    if self.len > 0 {
668      self.len -= 1;
669      let out =
670        core::mem::take(&mut self.data.as_slice_mut()[self.len as usize]);
671      Some(out)
672    } else {
673      None
674    }
675  }
676
677  /// Place an element onto the end of the vec.
678  ///
679  /// ## Panics
680  /// * If the length of the vec would overflow the capacity.
681  ///
682  /// ## Example
683  /// ```rust
684  /// # use tinyvec::*;
685  /// let mut av = array_vec!([i32; 2]);
686  /// assert_eq!(&av[..], []);
687  /// av.push(1);
688  /// assert_eq!(&av[..], [1]);
689  /// av.push(2);
690  /// assert_eq!(&av[..], [1, 2]);
691  /// // av.push(3); this would overflow the ArrayVec and panic!
692  /// ```
693  #[inline(always)]
694  pub fn push(&mut self, val: A::Item) {
695    let x = self.try_push(val);
696    assert!(x.is_none(), "ArrayVec::push> capacity overflow!");
697  }
698
699  /// Tries to place an element onto the end of the vec.\
700  /// Returns back the element if the capacity is exhausted,
701  /// otherwise returns None.
702  /// ```rust
703  /// # use tinyvec::*;
704  /// let mut av = array_vec!([i32; 2]);
705  /// assert_eq!(av.as_slice(), []);
706  /// assert_eq!(av.try_push(1), None);
707  /// assert_eq!(&av[..], [1]);
708  /// assert_eq!(av.try_push(2), None);
709  /// assert_eq!(&av[..], [1, 2]);
710  /// assert_eq!(av.try_push(3), Some(3));
711  /// ```
712  #[inline(always)]
713  pub fn try_push(&mut self, val: A::Item) -> Option<A::Item> {
714    debug_assert!(self.len as usize <= A::CAPACITY);
715
716    let itemref = match self.data.as_slice_mut().get_mut(self.len as usize) {
717      None => return Some(val),
718      Some(x) => x,
719    };
720
721    *itemref = val;
722    self.len += 1;
723    return None;
724  }
725
726  /// Removes the item at `index`, shifting all others down by one index.
727  ///
728  /// Returns the removed element.
729  ///
730  /// ## Panics
731  ///
732  /// * If the index is out of bounds.
733  ///
734  /// ## Example
735  ///
736  /// ```rust
737  /// # use tinyvec::*;
738  /// let mut av = array_vec!([i32; 4] => 1, 2, 3);
739  /// assert_eq!(av.remove(1), 2);
740  /// assert_eq!(&av[..], [1, 3]);
741  /// ```
742  #[inline]
743  pub fn remove(&mut self, index: usize) -> A::Item {
744    let targets: &mut [A::Item] = &mut self.deref_mut()[index..];
745    let item = core::mem::take(&mut targets[0]);
746
747    // A previous implementation used rotate_left
748    // rotate_right and rotate_left generate a huge amount of code and fail to
749    // inline; calling them here incurs the cost of all the cases they
750    // handle even though we're rotating a usually-small array by a constant
751    // 1 offset. This swap-based implementation benchmarks much better for
752    // small array lengths in particular.
753
754    for i in 0..targets.len() - 1 {
755      targets.swap(i, i + 1);
756    }
757    self.len -= 1;
758    item
759  }
760
761  /// As [`resize_with`](ArrayVec::resize_with)
762  /// and it clones the value as the closure.
763  ///
764  /// ## Example
765  ///
766  /// ```rust
767  /// # use tinyvec::*;
768  ///
769  /// let mut av = array_vec!([&str; 10] => "hello");
770  /// av.resize(3, "world");
771  /// assert_eq!(&av[..], ["hello", "world", "world"]);
772  ///
773  /// let mut av = array_vec!([i32; 10] => 1, 2, 3, 4);
774  /// av.resize(2, 0);
775  /// assert_eq!(&av[..], [1, 2]);
776  /// ```
777  #[inline]
778  pub fn resize(&mut self, new_len: usize, new_val: A::Item)
779  where
780    A::Item: Clone,
781  {
782    self.resize_with(new_len, || new_val.clone())
783  }
784
785  /// Resize the vec to the new length.
786  ///
787  /// If it needs to be longer, it's filled with repeated calls to the provided
788  /// function. If it needs to be shorter, it's truncated.
789  ///
790  /// ## Example
791  ///
792  /// ```rust
793  /// # use tinyvec::*;
794  ///
795  /// let mut av = array_vec!([i32; 10] => 1, 2, 3);
796  /// av.resize_with(5, Default::default);
797  /// assert_eq!(&av[..], [1, 2, 3, 0, 0]);
798  ///
799  /// let mut av = array_vec!([i32; 10]);
800  /// let mut p = 1;
801  /// av.resize_with(4, || {
802  ///   p *= 2;
803  ///   p
804  /// });
805  /// assert_eq!(&av[..], [2, 4, 8, 16]);
806  /// ```
807  #[inline]
808  pub fn resize_with<F: FnMut() -> A::Item>(
809    &mut self, new_len: usize, mut f: F,
810  ) {
811    match new_len.checked_sub(self.len as usize) {
812      None => self.truncate(new_len),
813      Some(new_elements) => {
814        for _ in 0..new_elements {
815          self.push(f());
816        }
817      }
818    }
819  }
820
821  /// Walk the vec and keep only the elements that pass the predicate given.
822  ///
823  /// ## Example
824  ///
825  /// ```rust
826  /// # use tinyvec::*;
827  ///
828  /// let mut av = array_vec!([i32; 10] => 1, 1, 2, 3, 3, 4);
829  /// av.retain(|&x| x % 2 == 0);
830  /// assert_eq!(&av[..], [2, 4]);
831  /// ```
832  #[inline]
833  pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut acceptable: F) {
834    // Drop guard to contain exactly the remaining elements when the test
835    // panics.
836    struct JoinOnDrop<'vec, Item> {
837      items: &'vec mut [Item],
838      done_end: usize,
839      // Start of tail relative to `done_end`.
840      tail_start: usize,
841    }
842
843    impl<Item> Drop for JoinOnDrop<'_, Item> {
844      fn drop(&mut self) {
845        self.items[self.done_end..].rotate_left(self.tail_start);
846      }
847    }
848
849    let mut rest = JoinOnDrop {
850      items: &mut self.data.as_slice_mut()[..self.len as usize],
851      done_end: 0,
852      tail_start: 0,
853    };
854
855    let len = self.len as usize;
856    for idx in 0..len {
857      // Loop start invariant: idx = rest.done_end + rest.tail_start
858      if !acceptable(&rest.items[idx]) {
859        let _ = core::mem::take(&mut rest.items[idx]);
860        self.len -= 1;
861        rest.tail_start += 1;
862      } else {
863        rest.items.swap(rest.done_end, idx);
864        rest.done_end += 1;
865      }
866    }
867  }
868
869  /// Retains only the elements specified by the predicate, passing a mutable
870  /// reference to it.
871  ///
872  /// In other words, remove all elements e such that f(&mut e) returns false.
873  /// This method operates in place, visiting each element exactly once in the
874  /// original order, and preserves the order of the retained elements.
875  ///
876  ///
877  /// ## Example
878  ///
879  /// ```rust
880  /// # use tinyvec::*;
881  ///
882  /// let mut av = array_vec!([i32; 10] => 1, 1, 2, 3, 3, 4);
883  /// av.retain_mut(|x| if *x % 2 == 0 { *x *= 2; true } else { false });
884  /// assert_eq!(&av[..], [4, 8]);
885  /// ```
886  #[inline]
887  pub fn retain_mut<F>(&mut self, mut acceptable: F)
888  where
889    F: FnMut(&mut A::Item) -> bool,
890  {
891    // Drop guard to contain exactly the remaining elements when the test
892    // panics.
893    struct JoinOnDrop<'vec, Item> {
894      items: &'vec mut [Item],
895      done_end: usize,
896      // Start of tail relative to `done_end`.
897      tail_start: usize,
898    }
899
900    impl<Item> Drop for JoinOnDrop<'_, Item> {
901      fn drop(&mut self) {
902        self.items[self.done_end..].rotate_left(self.tail_start);
903      }
904    }
905
906    let mut rest = JoinOnDrop {
907      items: &mut self.data.as_slice_mut()[..self.len as usize],
908      done_end: 0,
909      tail_start: 0,
910    };
911
912    let len = self.len as usize;
913    for idx in 0..len {
914      // Loop start invariant: idx = rest.done_end + rest.tail_start
915      if !acceptable(&mut rest.items[idx]) {
916        let _ = core::mem::take(&mut rest.items[idx]);
917        self.len -= 1;
918        rest.tail_start += 1;
919      } else {
920        rest.items.swap(rest.done_end, idx);
921        rest.done_end += 1;
922      }
923    }
924  }
925
926  /// Forces the length of the vector to `new_len`.
927  ///
928  /// ## Panics
929  /// * If `new_len` is greater than the vec's capacity.
930  ///
931  /// ## Safety
932  /// * This is a fully safe operation! The inactive memory already counts as
933  ///   "initialized" by Rust's rules.
934  /// * Other than "the memory is initialized" there are no other guarantees
935  ///   regarding what you find in the inactive portion of the vec.
936  #[inline(always)]
937  pub fn set_len(&mut self, new_len: usize) {
938    if new_len > A::CAPACITY {
939      // Note(Lokathor): Technically we don't have to panic here, and we could
940      // just let some other call later on trigger a panic on accident when the
941      // length is wrong. However, it's a lot easier to catch bugs when things
942      // are more "fail-fast".
943      panic!(
944        "ArrayVec::set_len> new length {} exceeds capacity {}",
945        new_len,
946        A::CAPACITY
947      )
948    }
949
950    let new_len: u16 = new_len
951      .try_into()
952      .expect("ArrayVec::set_len> new length is not in range 0..=u16::MAX");
953    self.len = new_len;
954  }
955
956  /// Splits the collection at the point given.
957  ///
958  /// * `[0, at)` stays in this vec
959  /// * `[at, len)` ends up in the new vec.
960  ///
961  /// ## Panics
962  /// * if at > len
963  ///
964  /// ## Example
965  ///
966  /// ```rust
967  /// # use tinyvec::*;
968  /// let mut av = array_vec!([i32; 4] => 1, 2, 3);
969  /// let av2 = av.split_off(1);
970  /// assert_eq!(&av[..], [1]);
971  /// assert_eq!(&av2[..], [2, 3]);
972  /// ```
973  #[inline]
974  pub fn split_off(&mut self, at: usize) -> Self {
975    // FIXME: should this just use drain into the output?
976    if at > self.len() {
977      panic!(
978        "ArrayVec::split_off> at value {} exceeds length of {}",
979        at, self.len
980      );
981    }
982    let mut new = Self::default();
983    let moves = &mut self.as_mut_slice()[at..];
984    let split_len = moves.len();
985    let targets = &mut new.data.as_slice_mut()[..split_len];
986    moves.swap_with_slice(targets);
987
988    /* moves.len() <= u16::MAX, so these are surely in u16 range */
989    new.len = split_len as u16;
990    self.len = at as u16;
991    new
992  }
993
994  /// Creates a splicing iterator that removes the specified range in the
995  /// vector, yields the removed items, and replaces them with elements from
996  /// the provided iterator.
997  ///
998  /// `splice` fuses the provided iterator, so elements after the first `None`
999  /// are ignored.
1000  ///
1001  /// ## Panics
1002  /// * If the start is greater than the end.
1003  /// * If the end is past the edge of the vec.
1004  /// * If the provided iterator panics.
1005  /// * If the new length would overflow the capacity of the array. Because
1006  ///   `ArrayVecSplice` adds elements to this vec in its destructor when
1007  ///   necessary, this panic would occur when it is dropped.
1008  ///
1009  /// ## Example
1010  /// ```rust
1011  /// use tinyvec::*;
1012  /// let mut av = array_vec!([i32; 4] => 1, 2, 3);
1013  /// let av2: ArrayVec<[i32; 4]> = av.splice(1.., 4..=6).collect();
1014  /// assert_eq!(av.as_slice(), &[1, 4, 5, 6][..]);
1015  /// assert_eq!(av2.as_slice(), &[2, 3][..]);
1016  ///
1017  /// av.splice(.., None);
1018  /// assert_eq!(av.as_slice(), &[]);
1019  /// ```
1020  #[inline]
1021  pub fn splice<R, I>(
1022    &mut self, range: R, replacement: I,
1023  ) -> ArrayVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
1024  where
1025    R: RangeBounds<usize>,
1026    I: IntoIterator<Item = A::Item>,
1027  {
1028    use core::ops::Bound;
1029    let start = match range.start_bound() {
1030      Bound::Included(x) => *x,
1031      Bound::Excluded(x) => x.saturating_add(1),
1032      Bound::Unbounded => 0,
1033    };
1034    let end = match range.end_bound() {
1035      Bound::Included(x) => x.saturating_add(1),
1036      Bound::Excluded(x) => *x,
1037      Bound::Unbounded => self.len(),
1038    };
1039    assert!(
1040      start <= end,
1041      "ArrayVec::splice> Illegal range, {} to {}",
1042      start,
1043      end
1044    );
1045    assert!(
1046      end <= self.len(),
1047      "ArrayVec::splice> Range ends at {} but length is only {}!",
1048      end,
1049      self.len()
1050    );
1051
1052    ArrayVecSplice {
1053      removal_start: start,
1054      removal_end: end,
1055      parent: self,
1056      replacement: replacement.into_iter().fuse(),
1057    }
1058  }
1059
1060  /// Remove an element, swapping the end of the vec into its place.
1061  ///
1062  /// ## Panics
1063  /// * If the index is out of bounds.
1064  ///
1065  /// ## Example
1066  /// ```rust
1067  /// # use tinyvec::*;
1068  /// let mut av = array_vec!([&str; 4] => "foo", "bar", "quack", "zap");
1069  ///
1070  /// assert_eq!(av.swap_remove(1), "bar");
1071  /// assert_eq!(&av[..], ["foo", "zap", "quack"]);
1072  ///
1073  /// assert_eq!(av.swap_remove(0), "foo");
1074  /// assert_eq!(&av[..], ["quack", "zap"]);
1075  /// ```
1076  #[inline]
1077  pub fn swap_remove(&mut self, index: usize) -> A::Item {
1078    assert!(
1079      index < self.len(),
1080      "ArrayVec::swap_remove> index {} is out of bounds {}",
1081      index,
1082      self.len
1083    );
1084    if index == self.len() - 1 {
1085      self.pop().unwrap()
1086    } else {
1087      let i = self.pop().unwrap();
1088      replace(&mut self[index], i)
1089    }
1090  }
1091
1092  /// Reduces the vec's length to the given value.
1093  ///
1094  /// If the vec is already shorter than the input, nothing happens.
1095  #[inline]
1096  pub fn truncate(&mut self, new_len: usize) {
1097    if new_len >= self.len as usize {
1098      return;
1099    }
1100
1101    if needs_drop::<A::Item>() {
1102      let len = self.len as usize;
1103      self.data.as_slice_mut()[new_len..len]
1104        .iter_mut()
1105        .map(core::mem::take)
1106        .for_each(drop);
1107    }
1108
1109    /* new_len is less than self.len */
1110    self.len = new_len as u16;
1111  }
1112
1113  /// Wraps an array, using the given length as the starting length.
1114  ///
1115  /// If you want to use the whole length of the array, you can just use the
1116  /// `From` impl.
1117  ///
1118  /// ## Failure
1119  ///
1120  /// If the given length is greater than the capacity of the array this will
1121  /// error, and you'll get the array back in the `Err`.
1122  #[inline]
1123  #[cfg(not(feature = "latest_stable_rust"))]
1124  pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1125    /* Note(Soveu): Should we allow A::CAPACITY > u16::MAX for now? */
1126    if len <= A::CAPACITY {
1127      Ok(Self { data, len: len as u16 })
1128    } else {
1129      Err(data)
1130    }
1131  }
1132
1133  /// Wraps an array, using the given length as the starting length.
1134  ///
1135  /// If you want to use the whole length of the array, you can just use the
1136  /// `From` impl.
1137  ///
1138  /// ## Failure
1139  ///
1140  /// If the given length is greater than the capacity of the array this will
1141  /// error, and you'll get the array back in the `Err`.
1142  #[inline]
1143  #[cfg(feature = "latest_stable_rust")]
1144  pub const fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1145    /* Note(Soveu): Should we allow A::CAPACITY > u16::MAX for now? */
1146    if len <= A::CAPACITY {
1147      Ok(Self { data, len: len as u16 })
1148    } else {
1149      Err(data)
1150    }
1151  }
1152}
1153
1154impl<A> ArrayVec<A> {
1155  /// Wraps up an array as a new empty `ArrayVec`.
1156  ///
1157  /// If you want to simply use the full array, use `from` instead.
1158  ///
1159  /// ## Examples
1160  ///
1161  /// This method in particular allows to create values for statics:
1162  ///
1163  /// ```rust
1164  /// # use tinyvec::ArrayVec;
1165  /// static DATA: ArrayVec<[u8; 5]> = ArrayVec::from_array_empty([0; 5]);
1166  /// assert_eq!(DATA.len(), 0);
1167  /// ```
1168  ///
1169  /// But of course it is just an normal empty `ArrayVec`:
1170  ///
1171  /// ```rust
1172  /// # use tinyvec::ArrayVec;
1173  /// let mut data = ArrayVec::from_array_empty([1, 2, 3, 4]);
1174  /// assert_eq!(&data[..], &[]);
1175  /// data.push(42);
1176  /// assert_eq!(&data[..], &[42]);
1177  /// ```
1178  #[inline]
1179  #[must_use]
1180  pub const fn from_array_empty(data: A) -> Self {
1181    Self { data, len: 0 }
1182  }
1183}
1184
1185#[cfg(feature = "grab_spare_slice")]
1186impl<A: Array> ArrayVec<A> {
1187  /// Obtain the shared slice of the array _after_ the active memory.
1188  ///
1189  /// ## Example
1190  /// ```rust
1191  /// # use tinyvec::*;
1192  /// let mut av = array_vec!([i32; 4]);
1193  /// assert_eq!(av.grab_spare_slice().len(), 4);
1194  /// av.push(10);
1195  /// av.push(11);
1196  /// av.push(12);
1197  /// av.push(13);
1198  /// assert_eq!(av.grab_spare_slice().len(), 0);
1199  /// ```
1200  #[inline(always)]
1201  pub fn grab_spare_slice(&self) -> &[A::Item] {
1202    &self.data.as_slice()[self.len as usize..]
1203  }
1204
1205  /// Obtain the mutable slice of the array _after_ the active memory.
1206  ///
1207  /// ## Example
1208  /// ```rust
1209  /// # use tinyvec::*;
1210  /// let mut av = array_vec!([i32; 4]);
1211  /// assert_eq!(av.grab_spare_slice_mut().len(), 4);
1212  /// av.push(10);
1213  /// av.push(11);
1214  /// assert_eq!(av.grab_spare_slice_mut().len(), 2);
1215  /// ```
1216  #[inline(always)]
1217  pub fn grab_spare_slice_mut(&mut self) -> &mut [A::Item] {
1218    &mut self.data.as_slice_mut()[self.len as usize..]
1219  }
1220}
1221
1222#[cfg(feature = "nightly_slice_partition_dedup")]
1223impl<A: Array> ArrayVec<A> {
1224  /// De-duplicates the vec contents.
1225  #[inline(always)]
1226  pub fn dedup(&mut self)
1227  where
1228    A::Item: PartialEq,
1229  {
1230    self.dedup_by(|a, b| a == b)
1231  }
1232
1233  /// De-duplicates the vec according to the predicate given.
1234  #[inline(always)]
1235  pub fn dedup_by<F>(&mut self, same_bucket: F)
1236  where
1237    F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1238  {
1239    let len = {
1240      let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1241      dedup.len()
1242    };
1243    self.truncate(len);
1244  }
1245
1246  /// De-duplicates the vec according to the key selector given.
1247  #[inline(always)]
1248  pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1249  where
1250    F: FnMut(&mut A::Item) -> K,
1251    K: PartialEq,
1252  {
1253    self.dedup_by(|a, b| key(a) == key(b))
1254  }
1255}
1256
1257impl<A> ArrayVec<A> {
1258  /// Returns the reference to the inner array of the `ArrayVec`.
1259  ///
1260  /// This returns the full array, even if the `ArrayVec` length is currently
1261  /// less than that.
1262  #[inline(always)]
1263  #[must_use]
1264  pub const fn as_inner(&self) -> &A {
1265    &self.data
1266  }
1267
1268  /// Returns a mutable reference to the inner array of the `ArrayVec`.
1269  ///
1270  /// This returns the full array, even if the `ArrayVec` length is currently
1271  /// less than that.
1272  #[inline(always)]
1273  #[must_use]
1274  #[cfg(feature = "latest_stable_rust")]
1275  pub const fn as_mut_inner(&mut self) -> &mut A {
1276    &mut self.data
1277  }
1278}
1279
1280/// Splicing iterator for `ArrayVec`
1281/// See [`ArrayVec::splice`](ArrayVec::<A>::splice)
1282pub struct ArrayVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
1283  parent: &'p mut ArrayVec<A>,
1284  removal_start: usize,
1285  removal_end: usize,
1286  replacement: I,
1287}
1288
1289impl<'p, A: Array, I: Iterator<Item = A::Item>> Iterator
1290  for ArrayVecSplice<'p, A, I>
1291{
1292  type Item = A::Item;
1293
1294  #[inline]
1295  fn next(&mut self) -> Option<A::Item> {
1296    if self.removal_start < self.removal_end {
1297      match self.replacement.next() {
1298        Some(replacement) => {
1299          let removed = core::mem::replace(
1300            &mut self.parent[self.removal_start],
1301            replacement,
1302          );
1303          self.removal_start += 1;
1304          Some(removed)
1305        }
1306        None => {
1307          let removed = self.parent.remove(self.removal_start);
1308          self.removal_end -= 1;
1309          Some(removed)
1310        }
1311      }
1312    } else {
1313      None
1314    }
1315  }
1316
1317  #[inline]
1318  fn size_hint(&self) -> (usize, Option<usize>) {
1319    let len = self.len();
1320    (len, Some(len))
1321  }
1322}
1323
1324impl<'p, A, I> ExactSizeIterator for ArrayVecSplice<'p, A, I>
1325where
1326  A: Array,
1327  I: Iterator<Item = A::Item>,
1328{
1329  #[inline]
1330  fn len(&self) -> usize {
1331    self.removal_end - self.removal_start
1332  }
1333}
1334
1335impl<'p, A, I> FusedIterator for ArrayVecSplice<'p, A, I>
1336where
1337  A: Array,
1338  I: Iterator<Item = A::Item>,
1339{
1340}
1341
1342impl<'p, A, I> DoubleEndedIterator for ArrayVecSplice<'p, A, I>
1343where
1344  A: Array,
1345  I: Iterator<Item = A::Item> + DoubleEndedIterator,
1346{
1347  #[inline]
1348  fn next_back(&mut self) -> Option<A::Item> {
1349    if self.removal_start < self.removal_end {
1350      match self.replacement.next_back() {
1351        Some(replacement) => {
1352          let removed = core::mem::replace(
1353            &mut self.parent[self.removal_end - 1],
1354            replacement,
1355          );
1356          self.removal_end -= 1;
1357          Some(removed)
1358        }
1359        None => {
1360          let removed = self.parent.remove(self.removal_end - 1);
1361          self.removal_end -= 1;
1362          Some(removed)
1363        }
1364      }
1365    } else {
1366      None
1367    }
1368  }
1369}
1370
1371impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1372  for ArrayVecSplice<'p, A, I>
1373{
1374  #[inline]
1375  fn drop(&mut self) {
1376    for _ in self.by_ref() {}
1377
1378    // FIXME: reserve lower bound of size_hint
1379
1380    for replacement in self.replacement.by_ref() {
1381      self.parent.insert(self.removal_end, replacement);
1382      self.removal_end += 1;
1383    }
1384  }
1385}
1386
1387impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> {
1388  #[inline(always)]
1389  fn as_mut(&mut self) -> &mut [A::Item] {
1390    &mut *self
1391  }
1392}
1393
1394impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> {
1395  #[inline(always)]
1396  fn as_ref(&self) -> &[A::Item] {
1397    &*self
1398  }
1399}
1400
1401impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
1402  #[inline(always)]
1403  fn borrow(&self) -> &[A::Item] {
1404    &*self
1405  }
1406}
1407
1408impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> {
1409  #[inline(always)]
1410  fn borrow_mut(&mut self) -> &mut [A::Item] {
1411    &mut *self
1412  }
1413}
1414
1415impl<A: Array> Extend<A::Item> for ArrayVec<A> {
1416  #[inline]
1417  fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1418    for t in iter {
1419      self.push(t)
1420    }
1421  }
1422}
1423
1424impl<A: Array> From<A> for ArrayVec<A> {
1425  #[inline(always)]
1426  /// The output has a length equal to the full array.
1427  ///
1428  /// If you want to select a length, use
1429  /// [`from_array_len`](ArrayVec::from_array_len)
1430  fn from(data: A) -> Self {
1431    let len: u16 = data
1432      .as_slice()
1433      .len()
1434      .try_into()
1435      .expect("ArrayVec::from> length must be in range 0..=u16::MAX");
1436    Self { len, data }
1437  }
1438}
1439
1440/// The error type returned when a conversion from a slice to an [`ArrayVec`]
1441/// fails.
1442#[derive(Debug, Copy, Clone)]
1443#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1444pub struct TryFromSliceError(());
1445
1446impl core::fmt::Display for TryFromSliceError {
1447  #[inline]
1448  fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1449    f.write_str("could not convert slice to ArrayVec")
1450  }
1451}
1452
1453#[cfg(feature = "std")]
1454impl std::error::Error for TryFromSliceError {}
1455
1456impl<T, A> TryFrom<&'_ [T]> for ArrayVec<A>
1457where
1458  T: Clone + Default,
1459  A: Array<Item = T>,
1460{
1461  type Error = TryFromSliceError;
1462
1463  #[inline]
1464  /// The output has a length equal to that of the slice, with the same capacity
1465  /// as `A`.
1466  fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
1467    if slice.len() > A::CAPACITY {
1468      Err(TryFromSliceError(()))
1469    } else {
1470      let mut arr = ArrayVec::new();
1471      // We do not use ArrayVec::extend_from_slice, because it looks like LLVM
1472      // fails to deduplicate all the length-checking logic between the
1473      // above if and the contents of that method, thus producing much
1474      // slower code. Unlike many of the other optimizations in this
1475      // crate, this one is worth keeping an eye on. I see no reason, for
1476      // any element type, that these should produce different code. But
1477      // they do. (rustc 1.51.0)
1478      arr.set_len(slice.len());
1479      arr.as_mut_slice().clone_from_slice(slice);
1480      Ok(arr)
1481    }
1482  }
1483}
1484
1485impl<A: Array> FromIterator<A::Item> for ArrayVec<A> {
1486  #[inline]
1487  fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1488    let mut av = Self::default();
1489    for i in iter {
1490      av.push(i)
1491    }
1492    av
1493  }
1494}
1495
1496/// Iterator for consuming an `ArrayVec` and returning owned elements.
1497pub struct ArrayVecIterator<A: Array> {
1498  base: u16,
1499  tail: u16,
1500  data: A,
1501}
1502
1503impl<A: Array> ArrayVecIterator<A> {
1504  /// Returns the remaining items of this iterator as a slice.
1505  #[inline]
1506  #[must_use]
1507  pub fn as_slice(&self) -> &[A::Item] {
1508    &self.data.as_slice()[self.base as usize..self.tail as usize]
1509  }
1510}
1511impl<A: Array> FusedIterator for ArrayVecIterator<A> {}
1512impl<A: Array> Iterator for ArrayVecIterator<A> {
1513  type Item = A::Item;
1514  #[inline]
1515  fn next(&mut self) -> Option<Self::Item> {
1516    let slice =
1517      &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1518    let itemref = slice.first_mut()?;
1519    self.base += 1;
1520    return Some(core::mem::take(itemref));
1521  }
1522  #[inline(always)]
1523  fn size_hint(&self) -> (usize, Option<usize>) {
1524    let s = self.tail - self.base;
1525    let s = s as usize;
1526    (s, Some(s))
1527  }
1528  #[inline(always)]
1529  fn count(self) -> usize {
1530    self.size_hint().0
1531  }
1532  #[inline]
1533  fn last(mut self) -> Option<Self::Item> {
1534    self.next_back()
1535  }
1536  #[inline]
1537  fn nth(&mut self, n: usize) -> Option<A::Item> {
1538    let slice = &mut self.data.as_slice_mut();
1539    let slice = &mut slice[self.base as usize..self.tail as usize];
1540
1541    if let Some(x) = slice.get_mut(n) {
1542      /* n is in range [0 .. self.tail - self.base) so in u16 range */
1543      self.base += n as u16 + 1;
1544      return Some(core::mem::take(x));
1545    }
1546
1547    self.base = self.tail;
1548    return None;
1549  }
1550}
1551
1552impl<A: Array> DoubleEndedIterator for ArrayVecIterator<A> {
1553  #[inline]
1554  fn next_back(&mut self) -> Option<Self::Item> {
1555    let slice =
1556      &mut self.data.as_slice_mut()[self.base as usize..self.tail as usize];
1557    let item = slice.last_mut()?;
1558    self.tail -= 1;
1559    return Some(core::mem::take(item));
1560  }
1561
1562  #[inline]
1563  fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1564    let base = self.base as usize;
1565    let tail = self.tail as usize;
1566    let slice = &mut self.data.as_slice_mut()[base..tail];
1567    let n = n.saturating_add(1);
1568
1569    if let Some(n) = slice.len().checked_sub(n) {
1570      let item = &mut slice[n];
1571      /* n is in [0..self.tail - self.base] range, so in u16 range */
1572      self.tail = self.base + n as u16;
1573      return Some(core::mem::take(item));
1574    }
1575
1576    self.tail = self.base;
1577    return None;
1578  }
1579}
1580
1581impl<A: Array> ExactSizeIterator for ArrayVecIterator<A> {
1582  #[inline]
1583  fn len(&self) -> usize {
1584    self.size_hint().0
1585  }
1586}
1587
1588impl<A: Array> Debug for ArrayVecIterator<A>
1589where
1590  A::Item: Debug,
1591{
1592  #[allow(clippy::missing_inline_in_public_items)]
1593  fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1594    f.debug_tuple("ArrayVecIterator").field(&self.as_slice()).finish()
1595  }
1596}
1597
1598#[cfg(feature = "defmt")]
1599#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1600impl<A: Array> defmt::Format for ArrayVecIterator<A>
1601where
1602  A::Item: defmt::Format,
1603{
1604  fn format(&self, fmt: defmt::Formatter<'_>) {
1605    defmt::write!(fmt, "ArrayVecIterator({:?})", self.as_slice())
1606  }
1607}
1608
1609impl<A: Array> IntoIterator for ArrayVec<A> {
1610  type Item = A::Item;
1611  type IntoIter = ArrayVecIterator<A>;
1612  #[inline(always)]
1613  fn into_iter(self) -> Self::IntoIter {
1614    ArrayVecIterator { base: 0, tail: self.len, data: self.data }
1615  }
1616}
1617
1618impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
1619  type Item = &'a mut A::Item;
1620  type IntoIter = core::slice::IterMut<'a, A::Item>;
1621  #[inline(always)]
1622  fn into_iter(self) -> Self::IntoIter {
1623    self.iter_mut()
1624  }
1625}
1626
1627impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
1628  type Item = &'a A::Item;
1629  type IntoIter = core::slice::Iter<'a, A::Item>;
1630  #[inline(always)]
1631  fn into_iter(self) -> Self::IntoIter {
1632    self.iter()
1633  }
1634}
1635
1636impl<A: Array> PartialEq for ArrayVec<A>
1637where
1638  A::Item: PartialEq,
1639{
1640  #[inline]
1641  fn eq(&self, other: &Self) -> bool {
1642    self.as_slice().eq(other.as_slice())
1643  }
1644}
1645impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq {}
1646
1647impl<A: Array> PartialOrd for ArrayVec<A>
1648where
1649  A::Item: PartialOrd,
1650{
1651  #[inline]
1652  fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1653    self.as_slice().partial_cmp(other.as_slice())
1654  }
1655}
1656impl<A: Array> Ord for ArrayVec<A>
1657where
1658  A::Item: Ord,
1659{
1660  #[inline]
1661  fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1662    self.as_slice().cmp(other.as_slice())
1663  }
1664}
1665
1666impl<A: Array> PartialEq<&A> for ArrayVec<A>
1667where
1668  A::Item: PartialEq,
1669{
1670  #[inline]
1671  fn eq(&self, other: &&A) -> bool {
1672    self.as_slice().eq(other.as_slice())
1673  }
1674}
1675
1676impl<A: Array> PartialEq<&[A::Item]> for ArrayVec<A>
1677where
1678  A::Item: PartialEq,
1679{
1680  #[inline]
1681  fn eq(&self, other: &&[A::Item]) -> bool {
1682    self.as_slice().eq(*other)
1683  }
1684}
1685
1686impl<A: Array> Hash for ArrayVec<A>
1687where
1688  A::Item: Hash,
1689{
1690  #[inline]
1691  fn hash<H: Hasher>(&self, state: &mut H) {
1692    self.as_slice().hash(state)
1693  }
1694}
1695
1696#[cfg(feature = "experimental_write_impl")]
1697impl<A: Array<Item = u8>> core::fmt::Write for ArrayVec<A> {
1698  fn write_str(&mut self, s: &str) -> core::fmt::Result {
1699    let my_len = self.len();
1700    let str_len = s.as_bytes().len();
1701    if my_len + str_len <= A::CAPACITY {
1702      let remainder = &mut self.data.as_slice_mut()[my_len..];
1703      let target = &mut remainder[..str_len];
1704      target.copy_from_slice(s.as_bytes());
1705      Ok(())
1706    } else {
1707      Err(core::fmt::Error)
1708    }
1709  }
1710}
1711
1712// // // // // // // //
1713// Formatting impls
1714// // // // // // // //
1715
1716impl<A: Array> Binary for ArrayVec<A>
1717where
1718  A::Item: Binary,
1719{
1720  #[allow(clippy::missing_inline_in_public_items)]
1721  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1722    write!(f, "[")?;
1723    if f.alternate() {
1724      write!(f, "\n    ")?;
1725    }
1726    for (i, elem) in self.iter().enumerate() {
1727      if i > 0 {
1728        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1729      }
1730      Binary::fmt(elem, f)?;
1731    }
1732    if f.alternate() {
1733      write!(f, ",\n")?;
1734    }
1735    write!(f, "]")
1736  }
1737}
1738
1739impl<A: Array> Debug for ArrayVec<A>
1740where
1741  A::Item: Debug,
1742{
1743  #[allow(clippy::missing_inline_in_public_items)]
1744  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1745    <[A::Item] as Debug>::fmt(self.as_slice(), f)
1746  }
1747}
1748
1749#[cfg(feature = "defmt")]
1750#[cfg_attr(docs_rs, doc(cfg(feature = "defmt")))]
1751impl<A: Array> defmt::Format for ArrayVec<A>
1752where
1753  A::Item: defmt::Format,
1754{
1755  fn format(&self, fmt: defmt::Formatter<'_>) {
1756    defmt::Format::format(self.as_slice(), fmt)
1757  }
1758}
1759
1760impl<A: Array> Display for ArrayVec<A>
1761where
1762  A::Item: Display,
1763{
1764  #[allow(clippy::missing_inline_in_public_items)]
1765  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1766    write!(f, "[")?;
1767    if f.alternate() {
1768      write!(f, "\n    ")?;
1769    }
1770    for (i, elem) in self.iter().enumerate() {
1771      if i > 0 {
1772        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1773      }
1774      Display::fmt(elem, f)?;
1775    }
1776    if f.alternate() {
1777      write!(f, ",\n")?;
1778    }
1779    write!(f, "]")
1780  }
1781}
1782
1783impl<A: Array> LowerExp for ArrayVec<A>
1784where
1785  A::Item: LowerExp,
1786{
1787  #[allow(clippy::missing_inline_in_public_items)]
1788  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1789    write!(f, "[")?;
1790    if f.alternate() {
1791      write!(f, "\n    ")?;
1792    }
1793    for (i, elem) in self.iter().enumerate() {
1794      if i > 0 {
1795        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1796      }
1797      LowerExp::fmt(elem, f)?;
1798    }
1799    if f.alternate() {
1800      write!(f, ",\n")?;
1801    }
1802    write!(f, "]")
1803  }
1804}
1805
1806impl<A: Array> LowerHex for ArrayVec<A>
1807where
1808  A::Item: LowerHex,
1809{
1810  #[allow(clippy::missing_inline_in_public_items)]
1811  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1812    write!(f, "[")?;
1813    if f.alternate() {
1814      write!(f, "\n    ")?;
1815    }
1816    for (i, elem) in self.iter().enumerate() {
1817      if i > 0 {
1818        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1819      }
1820      LowerHex::fmt(elem, f)?;
1821    }
1822    if f.alternate() {
1823      write!(f, ",\n")?;
1824    }
1825    write!(f, "]")
1826  }
1827}
1828
1829impl<A: Array> Octal for ArrayVec<A>
1830where
1831  A::Item: Octal,
1832{
1833  #[allow(clippy::missing_inline_in_public_items)]
1834  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1835    write!(f, "[")?;
1836    if f.alternate() {
1837      write!(f, "\n    ")?;
1838    }
1839    for (i, elem) in self.iter().enumerate() {
1840      if i > 0 {
1841        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1842      }
1843      Octal::fmt(elem, f)?;
1844    }
1845    if f.alternate() {
1846      write!(f, ",\n")?;
1847    }
1848    write!(f, "]")
1849  }
1850}
1851
1852impl<A: Array> Pointer for ArrayVec<A>
1853where
1854  A::Item: Pointer,
1855{
1856  #[allow(clippy::missing_inline_in_public_items)]
1857  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1858    write!(f, "[")?;
1859    if f.alternate() {
1860      write!(f, "\n    ")?;
1861    }
1862    for (i, elem) in self.iter().enumerate() {
1863      if i > 0 {
1864        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1865      }
1866      Pointer::fmt(elem, f)?;
1867    }
1868    if f.alternate() {
1869      write!(f, ",\n")?;
1870    }
1871    write!(f, "]")
1872  }
1873}
1874
1875impl<A: Array> UpperExp for ArrayVec<A>
1876where
1877  A::Item: UpperExp,
1878{
1879  #[allow(clippy::missing_inline_in_public_items)]
1880  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1881    write!(f, "[")?;
1882    if f.alternate() {
1883      write!(f, "\n    ")?;
1884    }
1885    for (i, elem) in self.iter().enumerate() {
1886      if i > 0 {
1887        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1888      }
1889      UpperExp::fmt(elem, f)?;
1890    }
1891    if f.alternate() {
1892      write!(f, ",\n")?;
1893    }
1894    write!(f, "]")
1895  }
1896}
1897
1898impl<A: Array> UpperHex for ArrayVec<A>
1899where
1900  A::Item: UpperHex,
1901{
1902  #[allow(clippy::missing_inline_in_public_items)]
1903  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1904    write!(f, "[")?;
1905    if f.alternate() {
1906      write!(f, "\n    ")?;
1907    }
1908    for (i, elem) in self.iter().enumerate() {
1909      if i > 0 {
1910        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1911      }
1912      UpperHex::fmt(elem, f)?;
1913    }
1914    if f.alternate() {
1915      write!(f, ",\n")?;
1916    }
1917    write!(f, "]")
1918  }
1919}
1920
1921#[cfg(feature = "alloc")]
1922use alloc::vec::Vec;
1923
1924#[cfg(all(feature = "alloc", feature = "rustc_1_57"))]
1925use alloc::collections::TryReserveError;
1926
1927#[cfg(feature = "alloc")]
1928impl<A: Array> ArrayVec<A> {
1929  /// Drains all elements to a Vec, but reserves additional space
1930  /// ```
1931  /// # use tinyvec::*;
1932  /// let mut av = array_vec!([i32; 7] => 1, 2, 3);
1933  /// let v = av.drain_to_vec_and_reserve(10);
1934  /// assert_eq!(v, &[1, 2, 3]);
1935  /// assert_eq!(v.capacity(), 13);
1936  /// ```
1937  #[inline]
1938  pub fn drain_to_vec_and_reserve(&mut self, n: usize) -> Vec<A::Item> {
1939    let cap = n + self.len();
1940    let mut v = Vec::with_capacity(cap);
1941    let iter = self.iter_mut().map(core::mem::take);
1942    v.extend(iter);
1943    self.set_len(0);
1944    return v;
1945  }
1946
1947  /// Tries to drain all elements to a Vec, but reserves additional space.
1948  ///
1949  /// # Errors
1950  ///
1951  /// If the allocator reports a failure, then an error is returned.
1952  ///
1953  /// ```
1954  /// # use tinyvec::*;
1955  /// let mut av = array_vec!([i32; 7] => 1, 2, 3);
1956  /// let v = av.try_drain_to_vec_and_reserve(10);
1957  /// assert!(matches!(v, Ok(_)));
1958  /// let v = v.unwrap();
1959  /// assert_eq!(v, &[1, 2, 3]);
1960  /// assert_eq!(v.capacity(), 13);
1961  /// ```
1962  #[inline]
1963  #[cfg(feature = "rustc_1_57")]
1964  pub fn try_drain_to_vec_and_reserve(
1965    &mut self, n: usize,
1966  ) -> Result<Vec<A::Item>, TryReserveError> {
1967    let cap = n + self.len();
1968    let mut v = Vec::new();
1969    v.try_reserve(cap)?;
1970    let iter = self.iter_mut().map(core::mem::take);
1971    v.extend(iter);
1972    self.set_len(0);
1973    return Ok(v);
1974  }
1975
1976  /// Drains all elements to a Vec
1977  /// ```
1978  /// # use tinyvec::*;
1979  /// let mut av = array_vec!([i32; 7] => 1, 2, 3);
1980  /// let v = av.drain_to_vec();
1981  /// assert_eq!(v, &[1, 2, 3]);
1982  /// assert_eq!(v.capacity(), 3);
1983  /// ```
1984  #[inline]
1985  pub fn drain_to_vec(&mut self) -> Vec<A::Item> {
1986    self.drain_to_vec_and_reserve(0)
1987  }
1988
1989  /// Tries to drain all elements to a Vec.
1990  ///
1991  /// # Errors
1992  ///
1993  /// If the allocator reports a failure, then an error is returned.
1994  ///
1995  /// ```
1996  /// # use tinyvec::*;
1997  /// let mut av = array_vec!([i32; 7] => 1, 2, 3);
1998  /// let v = av.try_drain_to_vec();
1999  /// assert!(matches!(v, Ok(_)));
2000  /// let v = v.unwrap();
2001  /// assert_eq!(v, &[1, 2, 3]);
2002  /// // Vec may reserve more than necessary in order to prevent more future allocations.
2003  /// assert!(v.capacity() >= 3);
2004  /// ```
2005  #[inline]
2006  #[cfg(feature = "rustc_1_57")]
2007  pub fn try_drain_to_vec(&mut self) -> Result<Vec<A::Item>, TryReserveError> {
2008    self.try_drain_to_vec_and_reserve(0)
2009  }
2010}
2011
2012#[cfg(feature = "serde")]
2013struct ArrayVecVisitor<A: Array>(PhantomData<A>);
2014
2015#[cfg(feature = "serde")]
2016impl<'de, A: Array> Visitor<'de> for ArrayVecVisitor<A>
2017where
2018  A::Item: Deserialize<'de>,
2019{
2020  type Value = ArrayVec<A>;
2021
2022  fn expecting(
2023    &self, formatter: &mut core::fmt::Formatter,
2024  ) -> core::fmt::Result {
2025    formatter.write_str("a sequence")
2026  }
2027
2028  fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
2029  where
2030    S: SeqAccess<'de>,
2031  {
2032    let mut new_arrayvec: ArrayVec<A> = Default::default();
2033
2034    let mut idx = 0usize;
2035    while let Some(value) = seq.next_element()? {
2036      if new_arrayvec.len() >= new_arrayvec.capacity() {
2037        return Err(DeserializeError::invalid_length(idx, &self));
2038      }
2039      new_arrayvec.push(value);
2040      idx = idx + 1;
2041    }
2042
2043    Ok(new_arrayvec)
2044  }
2045}
2046
2047#[cfg(test)]
2048mod test {
2049  use super::*;
2050
2051  #[test]
2052  fn retain_mut_empty_vec() {
2053    let mut av: ArrayVec<[i32; 4]> = ArrayVec::new();
2054    av.retain_mut(|&mut x| x % 2 == 0);
2055    assert_eq!(av.len(), 0);
2056  }
2057
2058  #[test]
2059  fn retain_mut_all_elements() {
2060    let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 2, 4, 6, 8);
2061    av.retain_mut(|&mut x| x % 2 == 0);
2062    assert_eq!(av.len(), 4);
2063    assert_eq!(av.as_slice(), &[2, 4, 6, 8]);
2064  }
2065
2066  #[test]
2067  fn retain_mut_some_elements() {
2068    let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 2, 3, 4);
2069    av.retain_mut(|&mut x| x % 2 == 0);
2070    assert_eq!(av.len(), 2);
2071    assert_eq!(av.as_slice(), &[2, 4]);
2072  }
2073
2074  #[test]
2075  fn retain_mut_no_elements() {
2076    let mut av: ArrayVec<[i32; 4]> = array_vec!([i32; 4] => 1, 3, 5, 7);
2077    av.retain_mut(|&mut x| x % 2 == 0);
2078    assert_eq!(av.len(), 0);
2079  }
2080
2081  #[test]
2082  fn retain_mut_zero_capacity() {
2083    let mut av: ArrayVec<[i32; 0]> = ArrayVec::new();
2084    av.retain_mut(|&mut x| x % 2 == 0);
2085    assert_eq!(av.len(), 0);
2086  }
2087
2088  #[cfg(feature = "alloc")]
2089  #[test]
2090  fn array_like_debug() {
2091    #[derive(Debug, Default, Copy, Clone)]
2092    struct S {
2093      x: u8,
2094      y: u8,
2095    }
2096
2097    use core::fmt::Write;
2098
2099    let mut ar: [S; 2] = [S { x: 1, y: 2 }, S { x: 3, y: 4 }];
2100    let mut buf_ar = alloc::string::String::new();
2101    write!(&mut buf_ar, "{ar:#?}");
2102
2103    let av: ArrayVec<[S; 2]> = ArrayVec::from(ar);
2104    let mut buf_av = alloc::string::String::new();
2105    write!(&mut buf_av, "{av:#?}");
2106
2107    assert_eq!(buf_av, buf_ar)
2108  }
2109}