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