Skip to main content

tinyvec/
tinyvec.rs

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