1 #![cfg(feature = "alloc")]
2 
3 use super::*;
4 
5 use alloc::vec::{self, Vec};
6 use core::convert::TryFrom;
7 use tinyvec_macros::impl_mirrored;
8 
9 #[cfg(feature = "serde")]
10 use core::marker::PhantomData;
11 #[cfg(feature = "serde")]
12 use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
13 #[cfg(feature = "serde")]
14 use serde::ser::{Serialize, SerializeSeq, Serializer};
15 
16 /// Helper to make a `TinyVec`.
17 ///
18 /// You specify the backing array type, and optionally give all the elements you
19 /// want to initially place into the array.
20 ///
21 /// ```rust
22 /// use tinyvec::*;
23 ///
24 /// // The backing array type can be specified in the macro call
25 /// let empty_tv = tiny_vec!([u8; 16]);
26 /// let some_ints = tiny_vec!([i32; 4] => 1, 2, 3);
27 /// let many_ints = tiny_vec!([i32; 4] => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
28 ///
29 /// // Or left to inference
30 /// let empty_tv: TinyVec<[u8; 16]> = tiny_vec!();
31 /// let some_ints: TinyVec<[i32; 4]> = tiny_vec!(1, 2, 3);
32 /// let many_ints: TinyVec<[i32; 4]> = tiny_vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
33 /// ```
34 #[macro_export]
35 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
36 macro_rules! tiny_vec {
37   ($array_type:ty => $($elem:expr),* $(,)?) => {
38     {
39       // https://github.com/rust-lang/lang-team/issues/28
40       const INVOKED_ELEM_COUNT: usize = 0 $( + { let _ = stringify!($elem); 1 })*;
41       // If we have more `$elem` than the `CAPACITY` we will simply go directly
42       // to constructing on the heap.
43       match $crate::TinyVec::constructor_for_capacity(INVOKED_ELEM_COUNT) {
44         $crate::TinyVecConstructor::Inline(f) => {
45           f($crate::array_vec!($array_type => $($elem),*))
46         }
47         $crate::TinyVecConstructor::Heap(f) => {
48           f(vec!($($elem),*))
49         }
50       }
51     }
52   };
53   ($array_type:ty) => {
54     $crate::TinyVec::<$array_type>::default()
55   };
56   ($($elem:expr),*) => {
57     $crate::tiny_vec!(_ => $($elem),*)
58   };
59   ($elem:expr; $n:expr) => {
60     $crate::TinyVec::from([$elem; $n])
61   };
62   () => {
63     $crate::tiny_vec!(_)
64   };
65 }
66 
67 #[doc(hidden)] // Internal implementation details of `tiny_vec!`
68 pub enum TinyVecConstructor<A: Array> {
69   Inline(fn(ArrayVec<A>) -> TinyVec<A>),
70   Heap(fn(Vec<A::Item>) -> TinyVec<A>),
71 }
72 
73 /// A vector that starts inline, but can automatically move to the heap.
74 ///
75 /// * Requires the `alloc` feature
76 ///
77 /// A `TinyVec` is either an Inline([`ArrayVec`](crate::ArrayVec::<A>)) or
78 /// Heap([`Vec`](https://doc.rust-lang.org/alloc/vec/struct.Vec.html)). The
79 /// interface for the type as a whole is a bunch of methods that just match on
80 /// the enum variant and then call the same method on the inner vec.
81 ///
82 /// ## Construction
83 ///
84 /// Because it's an enum, you can construct a `TinyVec` simply by making an
85 /// `ArrayVec` or `Vec` and then putting it into the enum.
86 ///
87 /// There is also a macro
88 ///
89 /// ```rust
90 /// # use tinyvec::*;
91 /// let empty_tv = tiny_vec!([u8; 16]);
92 /// let some_ints = tiny_vec!([i32; 4] => 1, 2, 3);
93 /// ```
94 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
95 pub enum TinyVec<A: Array> {
96   #[allow(missing_docs)]
97   Inline(ArrayVec<A>),
98   #[allow(missing_docs)]
99   Heap(Vec<A::Item>),
100 }
101 
102 impl<A> Clone for TinyVec<A>
103 where
104   A: Array + Clone,
105   A::Item: Clone,
106 {
107   #[inline]
clone(&self) -> Self108   fn clone(&self) -> Self {
109     match self {
110       Self::Heap(v) => Self::Heap(v.clone()),
111       Self::Inline(v) => Self::Inline(v.clone()),
112     }
113   }
114 
115   #[inline]
clone_from(&mut self, o: &Self)116   fn clone_from(&mut self, o: &Self) {
117     if o.len() > self.len() {
118       self.reserve(o.len() - self.len());
119     } else {
120       self.truncate(o.len());
121     }
122     let (start, end) = o.split_at(self.len());
123     for (dst, src) in self.iter_mut().zip(start) {
124       dst.clone_from(src);
125     }
126     self.extend_from_slice(end);
127   }
128 }
129 
130 impl<A: Array> Default for TinyVec<A> {
131   #[inline]
132   #[must_use]
default() -> Self133   fn default() -> Self {
134     TinyVec::Inline(ArrayVec::default())
135   }
136 }
137 
138 impl<A: Array> Deref for TinyVec<A> {
139   type Target = [A::Item];
140 
141   impl_mirrored! {
142     type Mirror = TinyVec;
143     #[inline(always)]
144     #[must_use]
145     fn deref(self: &Self) -> &Self::Target;
146   }
147 }
148 
149 impl<A: Array> DerefMut for TinyVec<A> {
150   impl_mirrored! {
151     type Mirror = TinyVec;
152     #[inline(always)]
153     #[must_use]
154     fn deref_mut(self: &mut Self) -> &mut Self::Target;
155   }
156 }
157 
158 impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for TinyVec<A> {
159   type Output = <I as SliceIndex<[A::Item]>>::Output;
160   #[inline(always)]
161   #[must_use]
index(&self, index: I) -> &Self::Output162   fn index(&self, index: I) -> &Self::Output {
163     &self.deref()[index]
164   }
165 }
166 
167 impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for TinyVec<A> {
168   #[inline(always)]
169   #[must_use]
index_mut(&mut self, index: I) -> &mut Self::Output170   fn index_mut(&mut self, index: I) -> &mut Self::Output {
171     &mut self.deref_mut()[index]
172   }
173 }
174 
175 #[cfg(feature = "serde")]
176 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
177 impl<A: Array> Serialize for TinyVec<A>
178 where
179   A::Item: Serialize,
180 {
181   #[must_use]
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,182   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
183   where
184     S: Serializer,
185   {
186     let mut seq = serializer.serialize_seq(Some(self.len()))?;
187     for element in self.iter() {
188       seq.serialize_element(element)?;
189     }
190     seq.end()
191   }
192 }
193 
194 #[cfg(feature = "serde")]
195 #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
196 impl<'de, A: Array> Deserialize<'de> for TinyVec<A>
197 where
198   A::Item: Deserialize<'de>,
199 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,200   fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
201   where
202     D: Deserializer<'de>,
203   {
204     deserializer.deserialize_seq(TinyVecVisitor(PhantomData))
205   }
206 }
207 
208 #[cfg(feature = "arbitrary")]
209 #[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))]
210 impl<'a, A> arbitrary::Arbitrary<'a> for TinyVec<A>
211 where
212   A: Array,
213   A::Item: arbitrary::Arbitrary<'a>,
214 {
arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self>215   fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
216     let v = Vec::arbitrary(u)?;
217     let mut tv = TinyVec::Heap(v);
218     tv.shrink_to_fit();
219     Ok(tv)
220   }
221 }
222 
223 impl<A: Array> TinyVec<A> {
224   /// Returns whether elements are on heap
225   #[inline(always)]
226   #[must_use]
is_heap(&self) -> bool227   pub fn is_heap(&self) -> bool {
228     match self {
229       TinyVec::Heap(_) => true,
230       TinyVec::Inline(_) => false,
231     }
232   }
233   /// Returns whether elements are on stack
234   #[inline(always)]
235   #[must_use]
is_inline(&self) -> bool236   pub fn is_inline(&self) -> bool {
237     !self.is_heap()
238   }
239 
240   /// Shrinks the capacity of the vector as much as possible.\
241   /// It is inlined if length is less than `A::CAPACITY`.
242   /// ```rust
243   /// use tinyvec::*;
244   /// let mut tv = tiny_vec!([i32; 2] => 1, 2, 3);
245   /// assert!(tv.is_heap());
246   /// let _ = tv.pop();
247   /// assert!(tv.is_heap());
248   /// tv.shrink_to_fit();
249   /// assert!(tv.is_inline());
250   /// ```
shrink_to_fit(&mut self)251   pub fn shrink_to_fit(&mut self) {
252     let vec = match self {
253       TinyVec::Inline(_) => return,
254       TinyVec::Heap(h) => h,
255     };
256 
257     if vec.len() > A::CAPACITY {
258       return vec.shrink_to_fit();
259     }
260 
261     let moved_vec = core::mem::replace(vec, Vec::new());
262 
263     let mut av = ArrayVec::default();
264     let mut rest = av.fill(moved_vec);
265     debug_assert!(rest.next().is_none());
266     *self = TinyVec::Inline(av);
267   }
268 
269   /// Moves the content of the TinyVec to the heap, if it's inline.
270   /// ```rust
271   /// use tinyvec::*;
272   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
273   /// assert!(tv.is_inline());
274   /// tv.move_to_the_heap();
275   /// assert!(tv.is_heap());
276   /// ```
277   #[allow(clippy::missing_inline_in_public_items)]
move_to_the_heap(&mut self)278   pub fn move_to_the_heap(&mut self) {
279     let arr = match self {
280       TinyVec::Heap(_) => return,
281       TinyVec::Inline(a) => a,
282     };
283 
284     let v = arr.drain_to_vec();
285     *self = TinyVec::Heap(v);
286   }
287 
288   /// If TinyVec is inline, moves the content of it to the heap.
289   /// Also reserves additional space.
290   /// ```rust
291   /// use tinyvec::*;
292   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
293   /// assert!(tv.is_inline());
294   /// tv.move_to_the_heap_and_reserve(32);
295   /// assert!(tv.is_heap());
296   /// assert!(tv.capacity() >= 35);
297   /// ```
move_to_the_heap_and_reserve(&mut self, n: usize)298   pub fn move_to_the_heap_and_reserve(&mut self, n: usize) {
299     let arr = match self {
300       TinyVec::Heap(h) => return h.reserve(n),
301       TinyVec::Inline(a) => a,
302     };
303 
304     let v = arr.drain_to_vec_and_reserve(n);
305     *self = TinyVec::Heap(v);
306   }
307 
308   /// Reserves additional space.
309   /// Moves to the heap if array can't hold `n` more items
310   /// ```rust
311   /// use tinyvec::*;
312   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3, 4);
313   /// assert!(tv.is_inline());
314   /// tv.reserve(1);
315   /// assert!(tv.is_heap());
316   /// assert!(tv.capacity() >= 5);
317   /// ```
reserve(&mut self, n: usize)318   pub fn reserve(&mut self, n: usize) {
319     let arr = match self {
320       TinyVec::Heap(h) => return h.reserve(n),
321       TinyVec::Inline(a) => a,
322     };
323 
324     if n > arr.capacity() - arr.len() {
325       let v = arr.drain_to_vec_and_reserve(n);
326       *self = TinyVec::Heap(v);
327     }
328 
329     /* In this place array has enough place, so no work is needed more */
330     return;
331   }
332 
333   /// Reserves additional space.
334   /// Moves to the heap if array can't hold `n` more items
335   ///
336   /// From [Vec::reserve_exact](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve_exact)
337   /// ```text
338   /// Note that the allocator may give the collection more space than it requests.
339   /// Therefore, capacity can not be relied upon to be precisely minimal.
340   /// Prefer `reserve` if future insertions are expected.
341   /// ```
342   /// ```rust
343   /// use tinyvec::*;
344   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3, 4);
345   /// assert!(tv.is_inline());
346   /// tv.reserve_exact(1);
347   /// assert!(tv.is_heap());
348   /// assert!(tv.capacity() >= 5);
349   /// ```
reserve_exact(&mut self, n: usize)350   pub fn reserve_exact(&mut self, n: usize) {
351     let arr = match self {
352       TinyVec::Heap(h) => return h.reserve_exact(n),
353       TinyVec::Inline(a) => a,
354     };
355 
356     if n > arr.capacity() - arr.len() {
357       let v = arr.drain_to_vec_and_reserve(n);
358       *self = TinyVec::Heap(v);
359     }
360 
361     /* In this place array has enough place, so no work is needed more */
362     return;
363   }
364 
365   /// Makes a new TinyVec with _at least_ the given capacity.
366   ///
367   /// If the requested capacity is less than or equal to the array capacity you
368   /// get an inline vec. If it's greater than you get a heap vec.
369   /// ```
370   /// # use tinyvec::*;
371   /// let t = TinyVec::<[u8; 10]>::with_capacity(5);
372   /// assert!(t.is_inline());
373   /// assert!(t.capacity() >= 5);
374   ///
375   /// let t = TinyVec::<[u8; 10]>::with_capacity(20);
376   /// assert!(t.is_heap());
377   /// assert!(t.capacity() >= 20);
378   /// ```
379   #[inline]
380   #[must_use]
with_capacity(cap: usize) -> Self381   pub fn with_capacity(cap: usize) -> Self {
382     if cap <= A::CAPACITY {
383       TinyVec::Inline(ArrayVec::default())
384     } else {
385       TinyVec::Heap(Vec::with_capacity(cap))
386     }
387   }
388 }
389 
390 impl<A: Array> TinyVec<A> {
391   /// Move all values from `other` into this vec.
392   #[cfg(feature = "rustc_1_40")]
393   #[inline]
append(&mut self, other: &mut Self)394   pub fn append(&mut self, other: &mut Self) {
395     self.reserve(other.len());
396 
397     /* Doing append should be faster, because it is effectively a memcpy */
398     match (self, other) {
399       (TinyVec::Heap(sh), TinyVec::Heap(oh)) => sh.append(oh),
400       (TinyVec::Inline(a), TinyVec::Heap(h)) => a.extend(h.drain(..)),
401       (ref mut this, TinyVec::Inline(arr)) => this.extend(arr.drain(..)),
402     }
403   }
404 
405   /// Move all values from `other` into this vec.
406   #[cfg(not(feature = "rustc_1_40"))]
407   #[inline]
append(&mut self, other: &mut Self)408   pub fn append(&mut self, other: &mut Self) {
409     match other {
410       TinyVec::Inline(a) => self.extend(a.drain(..)),
411       TinyVec::Heap(h) => self.extend(h.drain(..)),
412     }
413   }
414 
415   impl_mirrored! {
416     type Mirror = TinyVec;
417 
418     /// Remove an element, swapping the end of the vec into its place.
419     ///
420     /// ## Panics
421     /// * If the index is out of bounds.
422     ///
423     /// ## Example
424     /// ```rust
425     /// use tinyvec::*;
426     /// let mut tv = tiny_vec!([&str; 4] => "foo", "bar", "quack", "zap");
427     ///
428     /// assert_eq!(tv.swap_remove(1), "bar");
429     /// assert_eq!(tv.as_slice(), &["foo", "zap", "quack"][..]);
430     ///
431     /// assert_eq!(tv.swap_remove(0), "foo");
432     /// assert_eq!(tv.as_slice(), &["quack", "zap"][..]);
433     /// ```
434     #[inline]
435     pub fn swap_remove(self: &mut Self, index: usize) -> A::Item;
436 
437     /// Remove and return the last element of the vec, if there is one.
438     ///
439     /// ## Failure
440     /// * If the vec is empty you get `None`.
441     #[inline]
442     pub fn pop(self: &mut Self) -> Option<A::Item>;
443 
444     /// Removes the item at `index`, shifting all others down by one index.
445     ///
446     /// Returns the removed element.
447     ///
448     /// ## Panics
449     ///
450     /// If the index is out of bounds.
451     ///
452     /// ## Example
453     ///
454     /// ```rust
455     /// use tinyvec::*;
456     /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
457     /// assert_eq!(tv.remove(1), 2);
458     /// assert_eq!(tv.as_slice(), &[1, 3][..]);
459     /// ```
460     #[inline]
461     pub fn remove(self: &mut Self, index: usize) -> A::Item;
462 
463     /// The length of the vec (in elements).
464     #[inline(always)]
465     #[must_use]
466     pub fn len(self: &Self) -> usize;
467 
468     /// The capacity of the `TinyVec`.
469     ///
470     /// When not heap allocated this is fixed based on the array type.
471     /// Otherwise its the result of the underlying Vec::capacity.
472     #[inline(always)]
473     #[must_use]
474     pub fn capacity(self: &Self) -> usize;
475 
476     /// Reduces the vec's length to the given value.
477     ///
478     /// If the vec is already shorter than the input, nothing happens.
479     #[inline]
480     pub fn truncate(self: &mut Self, new_len: usize);
481 
482     /// A mutable pointer to the backing array.
483     ///
484     /// ## Safety
485     ///
486     /// This pointer has provenance over the _entire_ backing array/buffer.
487     #[inline(always)]
488     #[must_use]
489     pub fn as_mut_ptr(self: &mut Self) -> *mut A::Item;
490 
491     /// A const pointer to the backing array.
492     ///
493     /// ## Safety
494     ///
495     /// This pointer has provenance over the _entire_ backing array/buffer.
496     #[inline(always)]
497     #[must_use]
498     pub fn as_ptr(self: &Self) -> *const A::Item;
499   }
500 
501   /// Walk the vec and keep only the elements that pass the predicate given.
502   ///
503   /// ## Example
504   ///
505   /// ```rust
506   /// use tinyvec::*;
507   ///
508   /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3, 4);
509   /// tv.retain(|&x| x % 2 == 0);
510   /// assert_eq!(tv.as_slice(), &[2, 4][..]);
511   /// ```
512   #[inline]
retain<F: FnMut(&A::Item) -> bool>(self: &mut Self, acceptable: F)513   pub fn retain<F: FnMut(&A::Item) -> bool>(self: &mut Self, acceptable: F) {
514     match self {
515       TinyVec::Inline(i) => i.retain(acceptable),
516       TinyVec::Heap(h) => h.retain(acceptable),
517     }
518   }
519 
520   /// Helper for getting the mut slice.
521   #[inline(always)]
522   #[must_use]
as_mut_slice(self: &mut Self) -> &mut [A::Item]523   pub fn as_mut_slice(self: &mut Self) -> &mut [A::Item] {
524     self.deref_mut()
525   }
526 
527   /// Helper for getting the shared slice.
528   #[inline(always)]
529   #[must_use]
as_slice(self: &Self) -> &[A::Item]530   pub fn as_slice(self: &Self) -> &[A::Item] {
531     self.deref()
532   }
533 
534   /// Removes all elements from the vec.
535   #[inline(always)]
clear(&mut self)536   pub fn clear(&mut self) {
537     self.truncate(0)
538   }
539 
540   /// De-duplicates the vec.
541   #[cfg(feature = "nightly_slice_partition_dedup")]
542   #[inline(always)]
dedup(&mut self) where A::Item: PartialEq,543   pub fn dedup(&mut self)
544   where
545     A::Item: PartialEq,
546   {
547     self.dedup_by(|a, b| a == b)
548   }
549 
550   /// De-duplicates the vec according to the predicate given.
551   #[cfg(feature = "nightly_slice_partition_dedup")]
552   #[inline(always)]
dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut A::Item, &mut A::Item) -> bool,553   pub fn dedup_by<F>(&mut self, same_bucket: F)
554   where
555     F: FnMut(&mut A::Item, &mut A::Item) -> bool,
556   {
557     let len = {
558       let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
559       dedup.len()
560     };
561     self.truncate(len);
562   }
563 
564   /// De-duplicates the vec according to the key selector given.
565   #[cfg(feature = "nightly_slice_partition_dedup")]
566   #[inline(always)]
dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut A::Item) -> K, K: PartialEq,567   pub fn dedup_by_key<F, K>(&mut self, mut key: F)
568   where
569     F: FnMut(&mut A::Item) -> K,
570     K: PartialEq,
571   {
572     self.dedup_by(|a, b| key(a) == key(b))
573   }
574 
575   /// Creates a draining iterator that removes the specified range in the vector
576   /// and yields the removed items.
577   ///
578   /// **Note: This method has significant performance issues compared to
579   /// matching on the TinyVec and then calling drain on the Inline or Heap value
580   /// inside. The draining iterator has to branch on every single access. It is
581   /// provided for simplicity and compatability only.**
582   ///
583   /// ## Panics
584   /// * If the start is greater than the end
585   /// * If the end is past the edge of the vec.
586   ///
587   /// ## Example
588   /// ```rust
589   /// use tinyvec::*;
590   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
591   /// let tv2: TinyVec<[i32; 4]> = tv.drain(1..).collect();
592   /// assert_eq!(tv.as_slice(), &[1][..]);
593   /// assert_eq!(tv2.as_slice(), &[2, 3][..]);
594   ///
595   /// tv.drain(..);
596   /// assert_eq!(tv.as_slice(), &[]);
597   /// ```
598   #[inline]
drain<R: RangeBounds<usize>>( &mut self, range: R, ) -> TinyVecDrain<'_, A>599   pub fn drain<R: RangeBounds<usize>>(
600     &mut self, range: R,
601   ) -> TinyVecDrain<'_, A> {
602     match self {
603       TinyVec::Inline(i) => TinyVecDrain::Inline(i.drain(range)),
604       TinyVec::Heap(h) => TinyVecDrain::Heap(h.drain(range)),
605     }
606   }
607 
608   /// Clone each element of the slice into this vec.
609   /// ```rust
610   /// use tinyvec::*;
611   /// let mut tv = tiny_vec!([i32; 4] => 1, 2);
612   /// tv.extend_from_slice(&[3, 4]);
613   /// assert_eq!(tv.as_slice(), [1, 2, 3, 4]);
614   /// ```
615   #[inline]
extend_from_slice(&mut self, sli: &[A::Item]) where A::Item: Clone,616   pub fn extend_from_slice(&mut self, sli: &[A::Item])
617   where
618     A::Item: Clone,
619   {
620     self.reserve(sli.len());
621     match self {
622       TinyVec::Inline(a) => a.extend_from_slice(sli),
623       TinyVec::Heap(h) => h.extend_from_slice(sli),
624     }
625   }
626 
627   /// Wraps up an array and uses the given length as the initial length.
628   ///
629   /// Note that the `From` impl for arrays assumes the full length is used.
630   ///
631   /// ## Panics
632   ///
633   /// The length must be less than or equal to the capacity of the array.
634   #[inline]
635   #[must_use]
636   #[allow(clippy::match_wild_err_arm)]
from_array_len(data: A, len: usize) -> Self637   pub fn from_array_len(data: A, len: usize) -> Self {
638     match Self::try_from_array_len(data, len) {
639       Ok(out) => out,
640       Err(_) => {
641         panic!("TinyVec: length {} exceeds capacity {}!", len, A::CAPACITY)
642       }
643     }
644   }
645 
646   /// This is an internal implementation detail of the `tiny_vec!` macro, and
647   /// using it other than from that macro is not supported by this crate's
648   /// SemVer guarantee.
649   #[inline(always)]
650   #[doc(hidden)]
constructor_for_capacity(cap: usize) -> TinyVecConstructor<A>651   pub fn constructor_for_capacity(cap: usize) -> TinyVecConstructor<A> {
652     if cap <= A::CAPACITY {
653       TinyVecConstructor::Inline(TinyVec::Inline)
654     } else {
655       TinyVecConstructor::Heap(TinyVec::Heap)
656     }
657   }
658 
659   /// Inserts an item at the position given, moving all following elements +1
660   /// index.
661   ///
662   /// ## Panics
663   /// * If `index` > `len`
664   ///
665   /// ## Example
666   /// ```rust
667   /// use tinyvec::*;
668   /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3);
669   /// tv.insert(1, 4);
670   /// assert_eq!(tv.as_slice(), &[1, 4, 2, 3]);
671   /// tv.insert(4, 5);
672   /// assert_eq!(tv.as_slice(), &[1, 4, 2, 3, 5]);
673   /// ```
674   #[inline]
insert(&mut self, index: usize, item: A::Item)675   pub fn insert(&mut self, index: usize, item: A::Item) {
676     assert!(
677       index <= self.len(),
678       "insertion index (is {}) should be <= len (is {})",
679       index,
680       self.len()
681     );
682 
683     let arr = match self {
684       TinyVec::Heap(v) => return v.insert(index, item),
685       TinyVec::Inline(a) => a,
686     };
687 
688     if let Some(x) = arr.try_insert(index, item) {
689       let mut v = Vec::with_capacity(arr.len() * 2);
690       let mut it =
691         arr.iter_mut().map(|r| core::mem::replace(r, Default::default()));
692       v.extend(it.by_ref().take(index));
693       v.push(x);
694       v.extend(it);
695       *self = TinyVec::Heap(v);
696     }
697   }
698 
699   /// If the vec is empty.
700   #[inline(always)]
701   #[must_use]
is_empty(&self) -> bool702   pub fn is_empty(&self) -> bool {
703     self.len() == 0
704   }
705 
706   /// Makes a new, empty vec.
707   #[inline(always)]
708   #[must_use]
new() -> Self709   pub fn new() -> Self {
710     Self::default()
711   }
712 
713   /// Place an element onto the end of the vec.
714   /// ## Panics
715   /// * If the length of the vec would overflow the capacity.
716   /// ```rust
717   /// use tinyvec::*;
718   /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3);
719   /// tv.push(4);
720   /// assert_eq!(tv.as_slice(), &[1, 2, 3, 4]);
721   /// ```
722   #[inline]
push(&mut self, val: A::Item)723   pub fn push(&mut self, val: A::Item) {
724     // The code path for moving the inline contents to the heap produces a lot
725     // of instructions, but we have a strong guarantee that this is a cold
726     // path. LLVM doesn't know this, inlines it, and this tends to cause a
727     // cascade of other bad inlining decisions because the body of push looks
728     // huge even though nearly every call executes the same few instructions.
729     //
730     // Moving the logic out of line with #[cold] causes the hot code to  be
731     // inlined together, and we take the extra cost of a function call only
732     // in rare cases.
733     #[cold]
734     fn drain_to_heap_and_push<A: Array>(
735       arr: &mut ArrayVec<A>, val: A::Item,
736     ) -> TinyVec<A> {
737       /* Make the Vec twice the size to amortize the cost of draining */
738       let mut v = arr.drain_to_vec_and_reserve(arr.len());
739       v.push(val);
740       TinyVec::Heap(v)
741     }
742 
743     match self {
744       TinyVec::Heap(v) => v.push(val),
745       TinyVec::Inline(arr) => {
746         if let Some(x) = arr.try_push(val) {
747           *self = drain_to_heap_and_push(arr, x);
748         }
749       }
750     }
751   }
752 
753   /// Resize the vec to the new length.
754   ///
755   /// If it needs to be longer, it's filled with clones of the provided value.
756   /// If it needs to be shorter, it's truncated.
757   ///
758   /// ## Example
759   ///
760   /// ```rust
761   /// use tinyvec::*;
762   ///
763   /// let mut tv = tiny_vec!([&str; 10] => "hello");
764   /// tv.resize(3, "world");
765   /// assert_eq!(tv.as_slice(), &["hello", "world", "world"][..]);
766   ///
767   /// let mut tv = tiny_vec!([i32; 10] => 1, 2, 3, 4);
768   /// tv.resize(2, 0);
769   /// assert_eq!(tv.as_slice(), &[1, 2][..]);
770   /// ```
771   #[inline]
resize(&mut self, new_len: usize, new_val: A::Item) where A::Item: Clone,772   pub fn resize(&mut self, new_len: usize, new_val: A::Item)
773   where
774     A::Item: Clone,
775   {
776     self.resize_with(new_len, || new_val.clone());
777   }
778 
779   /// Resize the vec to the new length.
780   ///
781   /// If it needs to be longer, it's filled with repeated calls to the provided
782   /// function. If it needs to be shorter, it's truncated.
783   ///
784   /// ## Example
785   ///
786   /// ```rust
787   /// use tinyvec::*;
788   ///
789   /// let mut tv = tiny_vec!([i32; 3] => 1, 2, 3);
790   /// tv.resize_with(5, Default::default);
791   /// assert_eq!(tv.as_slice(), &[1, 2, 3, 0, 0][..]);
792   ///
793   /// let mut tv = tiny_vec!([i32; 2]);
794   /// let mut p = 1;
795   /// tv.resize_with(4, || {
796   ///   p *= 2;
797   ///   p
798   /// });
799   /// assert_eq!(tv.as_slice(), &[2, 4, 8, 16][..]);
800   /// ```
801   #[inline]
resize_with<F: FnMut() -> A::Item>(&mut self, new_len: usize, f: F)802   pub fn resize_with<F: FnMut() -> A::Item>(&mut self, new_len: usize, f: F) {
803     match new_len.checked_sub(self.len()) {
804       None => return self.truncate(new_len),
805       Some(n) => self.reserve(n),
806     }
807 
808     match self {
809       TinyVec::Inline(a) => a.resize_with(new_len, f),
810       TinyVec::Heap(v) => v.resize_with(new_len, f),
811     }
812   }
813 
814   /// Splits the collection at the point given.
815   ///
816   /// * `[0, at)` stays in this vec
817   /// * `[at, len)` ends up in the new vec.
818   ///
819   /// ## Panics
820   /// * if at > len
821   ///
822   /// ## Example
823   ///
824   /// ```rust
825   /// use tinyvec::*;
826   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
827   /// let tv2 = tv.split_off(1);
828   /// assert_eq!(tv.as_slice(), &[1][..]);
829   /// assert_eq!(tv2.as_slice(), &[2, 3][..]);
830   /// ```
831   #[inline]
split_off(&mut self, at: usize) -> Self832   pub fn split_off(&mut self, at: usize) -> Self {
833     match self {
834       TinyVec::Inline(a) => TinyVec::Inline(a.split_off(at)),
835       TinyVec::Heap(v) => TinyVec::Heap(v.split_off(at)),
836     }
837   }
838 
839   /// Creates a splicing iterator that removes the specified range in the
840   /// vector, yields the removed items, and replaces them with elements from
841   /// the provided iterator.
842   ///
843   /// `splice` fuses the provided iterator, so elements after the first `None`
844   /// are ignored.
845   ///
846   /// ## Panics
847   /// * If the start is greater than the end.
848   /// * If the end is past the edge of the vec.
849   /// * If the provided iterator panics.
850   ///
851   /// ## Example
852   /// ```rust
853   /// use tinyvec::*;
854   /// let mut tv = tiny_vec!([i32; 4] => 1, 2, 3);
855   /// let tv2: TinyVec<[i32; 4]> = tv.splice(1.., 4..=6).collect();
856   /// assert_eq!(tv.as_slice(), &[1, 4, 5, 6][..]);
857   /// assert_eq!(tv2.as_slice(), &[2, 3][..]);
858   ///
859   /// tv.splice(.., None);
860   /// assert_eq!(tv.as_slice(), &[]);
861   /// ```
862   #[inline]
splice<R, I>( &mut self, range: R, replacement: I, ) -> TinyVecSplice<'_, A, core::iter::Fuse<I::IntoIter>> where R: RangeBounds<usize>, I: IntoIterator<Item = A::Item>,863   pub fn splice<R, I>(
864     &mut self, range: R, replacement: I,
865   ) -> TinyVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
866   where
867     R: RangeBounds<usize>,
868     I: IntoIterator<Item = A::Item>,
869   {
870     use core::ops::Bound;
871     let start = match range.start_bound() {
872       Bound::Included(x) => *x,
873       Bound::Excluded(x) => x.saturating_add(1),
874       Bound::Unbounded => 0,
875     };
876     let end = match range.end_bound() {
877       Bound::Included(x) => x.saturating_add(1),
878       Bound::Excluded(x) => *x,
879       Bound::Unbounded => self.len(),
880     };
881     assert!(
882       start <= end,
883       "TinyVec::splice> Illegal range, {} to {}",
884       start,
885       end
886     );
887     assert!(
888       end <= self.len(),
889       "TinyVec::splice> Range ends at {} but length is only {}!",
890       end,
891       self.len()
892     );
893 
894     TinyVecSplice {
895       removal_start: start,
896       removal_end: end,
897       parent: self,
898       replacement: replacement.into_iter().fuse(),
899     }
900   }
901 
902   /// Wraps an array, using the given length as the starting length.
903   ///
904   /// If you want to use the whole length of the array, you can just use the
905   /// `From` impl.
906   ///
907   /// ## Failure
908   ///
909   /// If the given length is greater than the capacity of the array this will
910   /// error, and you'll get the array back in the `Err`.
911   #[inline]
try_from_array_len(data: A, len: usize) -> Result<Self, A>912   pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
913     let arr = ArrayVec::try_from_array_len(data, len)?;
914     Ok(TinyVec::Inline(arr))
915   }
916 }
917 
918 /// Draining iterator for `TinyVecDrain`
919 ///
920 /// See [`TinyVecDrain::drain`](TinyVecDrain::<A>::drain)
921 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
922 pub enum TinyVecDrain<'p, A: Array> {
923   #[allow(missing_docs)]
924   Inline(ArrayVecDrain<'p, A::Item>),
925   #[allow(missing_docs)]
926   Heap(vec::Drain<'p, A::Item>),
927 }
928 
929 impl<'p, A: Array> Iterator for TinyVecDrain<'p, A> {
930   type Item = A::Item;
931 
932   impl_mirrored! {
933     type Mirror = TinyVecDrain;
934 
935     #[inline]
936     fn next(self: &mut Self) -> Option<Self::Item>;
937     #[inline]
938     fn nth(self: &mut Self, n: usize) -> Option<Self::Item>;
939     #[inline]
940     fn size_hint(self: &Self) -> (usize, Option<usize>);
941     #[inline]
942     fn last(self: Self) -> Option<Self::Item>;
943     #[inline]
944     fn count(self: Self) -> usize;
945   }
946 
947   #[inline]
for_each<F: FnMut(Self::Item)>(self, f: F)948   fn for_each<F: FnMut(Self::Item)>(self, f: F) {
949     match self {
950       TinyVecDrain::Inline(i) => i.for_each(f),
951       TinyVecDrain::Heap(h) => h.for_each(f),
952     }
953   }
954 }
955 
956 impl<'p, A: Array> DoubleEndedIterator for TinyVecDrain<'p, A> {
957   impl_mirrored! {
958     type Mirror = TinyVecDrain;
959 
960     #[inline]
961     fn next_back(self: &mut Self) -> Option<Self::Item>;
962 
963     #[cfg(feature = "rustc_1_40")]
964     #[inline]
965     fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>;
966   }
967 }
968 
969 /// Splicing iterator for `TinyVec`
970 /// See [`TinyVec::splice`](TinyVec::<A>::splice)
971 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
972 pub struct TinyVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
973   parent: &'p mut TinyVec<A>,
974   removal_start: usize,
975   removal_end: usize,
976   replacement: I,
977 }
978 
979 impl<'p, A, I> Iterator for TinyVecSplice<'p, A, I>
980 where
981   A: Array,
982   I: Iterator<Item = A::Item>,
983 {
984   type Item = A::Item;
985 
986   #[inline]
next(&mut self) -> Option<A::Item>987   fn next(&mut self) -> Option<A::Item> {
988     if self.removal_start < self.removal_end {
989       match self.replacement.next() {
990         Some(replacement) => {
991           let removed = core::mem::replace(
992             &mut self.parent[self.removal_start],
993             replacement,
994           );
995           self.removal_start += 1;
996           Some(removed)
997         }
998         None => {
999           let removed = self.parent.remove(self.removal_start);
1000           self.removal_end -= 1;
1001           Some(removed)
1002         }
1003       }
1004     } else {
1005       None
1006     }
1007   }
1008 
1009   #[inline]
size_hint(&self) -> (usize, Option<usize>)1010   fn size_hint(&self) -> (usize, Option<usize>) {
1011     let len = self.len();
1012     (len, Some(len))
1013   }
1014 }
1015 
1016 impl<'p, A, I> ExactSizeIterator for TinyVecSplice<'p, A, I>
1017 where
1018   A: Array,
1019   I: Iterator<Item = A::Item>,
1020 {
1021   #[inline]
len(&self) -> usize1022   fn len(&self) -> usize {
1023     self.removal_end - self.removal_start
1024   }
1025 }
1026 
1027 impl<'p, A, I> FusedIterator for TinyVecSplice<'p, A, I>
1028 where
1029   A: Array,
1030   I: Iterator<Item = A::Item>,
1031 {
1032 }
1033 
1034 impl<'p, A, I> DoubleEndedIterator for TinyVecSplice<'p, A, I>
1035 where
1036   A: Array,
1037   I: Iterator<Item = A::Item> + DoubleEndedIterator,
1038 {
1039   #[inline]
next_back(&mut self) -> Option<A::Item>1040   fn next_back(&mut self) -> Option<A::Item> {
1041     if self.removal_start < self.removal_end {
1042       match self.replacement.next_back() {
1043         Some(replacement) => {
1044           let removed = core::mem::replace(
1045             &mut self.parent[self.removal_end - 1],
1046             replacement,
1047           );
1048           self.removal_end -= 1;
1049           Some(removed)
1050         }
1051         None => {
1052           let removed = self.parent.remove(self.removal_end - 1);
1053           self.removal_end -= 1;
1054           Some(removed)
1055         }
1056       }
1057     } else {
1058       None
1059     }
1060   }
1061 }
1062 
1063 impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1064   for TinyVecSplice<'p, A, I>
1065 {
drop(&mut self)1066   fn drop(&mut self) {
1067     for _ in self.by_ref() {}
1068 
1069     let (lower_bound, _) = self.replacement.size_hint();
1070     self.parent.reserve(lower_bound);
1071 
1072     for replacement in self.replacement.by_ref() {
1073       self.parent.insert(self.removal_end, replacement);
1074       self.removal_end += 1;
1075     }
1076   }
1077 }
1078 
1079 impl<A: Array> AsMut<[A::Item]> for TinyVec<A> {
1080   #[inline(always)]
1081   #[must_use]
as_mut(&mut self) -> &mut [A::Item]1082   fn as_mut(&mut self) -> &mut [A::Item] {
1083     &mut *self
1084   }
1085 }
1086 
1087 impl<A: Array> AsRef<[A::Item]> for TinyVec<A> {
1088   #[inline(always)]
1089   #[must_use]
as_ref(&self) -> &[A::Item]1090   fn as_ref(&self) -> &[A::Item] {
1091     &*self
1092   }
1093 }
1094 
1095 impl<A: Array> Borrow<[A::Item]> for TinyVec<A> {
1096   #[inline(always)]
1097   #[must_use]
borrow(&self) -> &[A::Item]1098   fn borrow(&self) -> &[A::Item] {
1099     &*self
1100   }
1101 }
1102 
1103 impl<A: Array> BorrowMut<[A::Item]> for TinyVec<A> {
1104   #[inline(always)]
1105   #[must_use]
borrow_mut(&mut self) -> &mut [A::Item]1106   fn borrow_mut(&mut self) -> &mut [A::Item] {
1107     &mut *self
1108   }
1109 }
1110 
1111 impl<A: Array> Extend<A::Item> for TinyVec<A> {
1112   #[inline]
extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T)1113   fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1114     let iter = iter.into_iter();
1115     let (lower_bound, _) = iter.size_hint();
1116     self.reserve(lower_bound);
1117 
1118     let a = match self {
1119       TinyVec::Heap(h) => return h.extend(iter),
1120       TinyVec::Inline(a) => a,
1121     };
1122 
1123     let mut iter = a.fill(iter);
1124     let maybe = iter.next();
1125 
1126     let surely = match maybe {
1127       Some(x) => x,
1128       None => return,
1129     };
1130 
1131     let mut v = a.drain_to_vec_and_reserve(a.len());
1132     v.push(surely);
1133     v.extend(iter);
1134     *self = TinyVec::Heap(v);
1135   }
1136 }
1137 
1138 impl<A: Array> From<ArrayVec<A>> for TinyVec<A> {
1139   #[inline(always)]
1140   #[must_use]
from(arr: ArrayVec<A>) -> Self1141   fn from(arr: ArrayVec<A>) -> Self {
1142     TinyVec::Inline(arr)
1143   }
1144 }
1145 
1146 impl<A: Array> From<A> for TinyVec<A> {
from(array: A) -> Self1147   fn from(array: A) -> Self {
1148     TinyVec::Inline(ArrayVec::from(array))
1149   }
1150 }
1151 
1152 impl<T, A> From<&'_ [T]> for TinyVec<A>
1153 where
1154   T: Clone + Default,
1155   A: Array<Item = T>,
1156 {
1157   #[inline]
1158   #[must_use]
from(slice: &[T]) -> Self1159   fn from(slice: &[T]) -> Self {
1160     if let Ok(arr) = ArrayVec::try_from(slice) {
1161       TinyVec::Inline(arr)
1162     } else {
1163       TinyVec::Heap(slice.into())
1164     }
1165   }
1166 }
1167 
1168 impl<T, A> From<&'_ mut [T]> for TinyVec<A>
1169 where
1170   T: Clone + Default,
1171   A: Array<Item = T>,
1172 {
1173   #[inline]
1174   #[must_use]
from(slice: &mut [T]) -> Self1175   fn from(slice: &mut [T]) -> Self {
1176     Self::from(&*slice)
1177   }
1178 }
1179 
1180 impl<A: Array> FromIterator<A::Item> for TinyVec<A> {
1181   #[inline]
1182   #[must_use]
from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self1183   fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1184     let mut av = Self::default();
1185     av.extend(iter);
1186     av
1187   }
1188 }
1189 
1190 /// Iterator for consuming an `TinyVec` and returning owned elements.
1191 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1192 pub enum TinyVecIterator<A: Array> {
1193   #[allow(missing_docs)]
1194   Inline(ArrayVecIterator<A>),
1195   #[allow(missing_docs)]
1196   Heap(alloc::vec::IntoIter<A::Item>),
1197 }
1198 
1199 impl<A: Array> TinyVecIterator<A> {
1200   impl_mirrored! {
1201     type Mirror = TinyVecIterator;
1202     /// Returns the remaining items of this iterator as a slice.
1203     #[inline]
1204     #[must_use]
1205     pub fn as_slice(self: &Self) -> &[A::Item];
1206   }
1207 }
1208 
1209 impl<A: Array> FusedIterator for TinyVecIterator<A> {}
1210 
1211 impl<A: Array> Iterator for TinyVecIterator<A> {
1212   type Item = A::Item;
1213 
1214   impl_mirrored! {
1215     type Mirror = TinyVecIterator;
1216 
1217     #[inline]
1218     fn next(self: &mut Self) -> Option<Self::Item>;
1219 
1220     #[inline(always)]
1221     #[must_use]
1222     fn size_hint(self: &Self) -> (usize, Option<usize>);
1223 
1224     #[inline(always)]
1225     fn count(self: Self) -> usize;
1226 
1227     #[inline]
1228     fn last(self: Self) -> Option<Self::Item>;
1229 
1230     #[inline]
1231     fn nth(self: &mut Self, n: usize) -> Option<A::Item>;
1232   }
1233 }
1234 
1235 impl<A: Array> DoubleEndedIterator for TinyVecIterator<A> {
1236   impl_mirrored! {
1237     type Mirror = TinyVecIterator;
1238 
1239     #[inline]
1240     fn next_back(self: &mut Self) -> Option<Self::Item>;
1241 
1242     #[cfg(feature = "rustc_1_40")]
1243     #[inline]
1244     fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>;
1245   }
1246 }
1247 
1248 impl<A: Array> Debug for TinyVecIterator<A>
1249 where
1250   A::Item: Debug,
1251 {
1252   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result1253   fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1254     f.debug_tuple("TinyVecIterator").field(&self.as_slice()).finish()
1255   }
1256 }
1257 
1258 impl<A: Array> IntoIterator for TinyVec<A> {
1259   type Item = A::Item;
1260   type IntoIter = TinyVecIterator<A>;
1261   #[inline(always)]
1262   #[must_use]
into_iter(self) -> Self::IntoIter1263   fn into_iter(self) -> Self::IntoIter {
1264     match self {
1265       TinyVec::Inline(a) => TinyVecIterator::Inline(a.into_iter()),
1266       TinyVec::Heap(v) => TinyVecIterator::Heap(v.into_iter()),
1267     }
1268   }
1269 }
1270 
1271 impl<'a, A: Array> IntoIterator for &'a mut TinyVec<A> {
1272   type Item = &'a mut A::Item;
1273   type IntoIter = core::slice::IterMut<'a, A::Item>;
1274   #[inline(always)]
1275   #[must_use]
into_iter(self) -> Self::IntoIter1276   fn into_iter(self) -> Self::IntoIter {
1277     self.iter_mut()
1278   }
1279 }
1280 
1281 impl<'a, A: Array> IntoIterator for &'a TinyVec<A> {
1282   type Item = &'a A::Item;
1283   type IntoIter = core::slice::Iter<'a, A::Item>;
1284   #[inline(always)]
1285   #[must_use]
into_iter(self) -> Self::IntoIter1286   fn into_iter(self) -> Self::IntoIter {
1287     self.iter()
1288   }
1289 }
1290 
1291 impl<A: Array> PartialEq for TinyVec<A>
1292 where
1293   A::Item: PartialEq,
1294 {
1295   #[inline]
1296   #[must_use]
eq(&self, other: &Self) -> bool1297   fn eq(&self, other: &Self) -> bool {
1298     self.as_slice().eq(other.as_slice())
1299   }
1300 }
1301 impl<A: Array> Eq for TinyVec<A> where A::Item: Eq {}
1302 
1303 impl<A: Array> PartialOrd for TinyVec<A>
1304 where
1305   A::Item: PartialOrd,
1306 {
1307   #[inline]
1308   #[must_use]
partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering>1309   fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1310     self.as_slice().partial_cmp(other.as_slice())
1311   }
1312 }
1313 impl<A: Array> Ord for TinyVec<A>
1314 where
1315   A::Item: Ord,
1316 {
1317   #[inline]
1318   #[must_use]
cmp(&self, other: &Self) -> core::cmp::Ordering1319   fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1320     self.as_slice().cmp(other.as_slice())
1321   }
1322 }
1323 
1324 impl<A: Array> PartialEq<&A> for TinyVec<A>
1325 where
1326   A::Item: PartialEq,
1327 {
1328   #[inline]
1329   #[must_use]
eq(&self, other: &&A) -> bool1330   fn eq(&self, other: &&A) -> bool {
1331     self.as_slice().eq(other.as_slice())
1332   }
1333 }
1334 
1335 impl<A: Array> PartialEq<&[A::Item]> for TinyVec<A>
1336 where
1337   A::Item: PartialEq,
1338 {
1339   #[inline]
1340   #[must_use]
eq(&self, other: &&[A::Item]) -> bool1341   fn eq(&self, other: &&[A::Item]) -> bool {
1342     self.as_slice().eq(*other)
1343   }
1344 }
1345 
1346 impl<A: Array> Hash for TinyVec<A>
1347 where
1348   A::Item: Hash,
1349 {
1350   #[inline]
hash<H: Hasher>(&self, state: &mut H)1351   fn hash<H: Hasher>(&self, state: &mut H) {
1352     self.as_slice().hash(state)
1353   }
1354 }
1355 
1356 // // // // // // // //
1357 // Formatting impls
1358 // // // // // // // //
1359 
1360 impl<A: Array> Binary for TinyVec<A>
1361 where
1362   A::Item: Binary,
1363 {
1364   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1365   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1366     write!(f, "[")?;
1367     if f.alternate() {
1368       write!(f, "\n    ")?;
1369     }
1370     for (i, elem) in self.iter().enumerate() {
1371       if i > 0 {
1372         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1373       }
1374       Binary::fmt(elem, f)?;
1375     }
1376     if f.alternate() {
1377       write!(f, ",\n")?;
1378     }
1379     write!(f, "]")
1380   }
1381 }
1382 
1383 impl<A: Array> Debug for TinyVec<A>
1384 where
1385   A::Item: Debug,
1386 {
1387   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1388   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1389     write!(f, "[")?;
1390     if f.alternate() {
1391       write!(f, "\n    ")?;
1392     }
1393     for (i, elem) in self.iter().enumerate() {
1394       if i > 0 {
1395         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1396       }
1397       Debug::fmt(elem, f)?;
1398     }
1399     if f.alternate() {
1400       write!(f, ",\n")?;
1401     }
1402     write!(f, "]")
1403   }
1404 }
1405 
1406 impl<A: Array> Display for TinyVec<A>
1407 where
1408   A::Item: Display,
1409 {
1410   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1411   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1412     write!(f, "[")?;
1413     if f.alternate() {
1414       write!(f, "\n    ")?;
1415     }
1416     for (i, elem) in self.iter().enumerate() {
1417       if i > 0 {
1418         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1419       }
1420       Display::fmt(elem, f)?;
1421     }
1422     if f.alternate() {
1423       write!(f, ",\n")?;
1424     }
1425     write!(f, "]")
1426   }
1427 }
1428 
1429 impl<A: Array> LowerExp for TinyVec<A>
1430 where
1431   A::Item: LowerExp,
1432 {
1433   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1434   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1435     write!(f, "[")?;
1436     if f.alternate() {
1437       write!(f, "\n    ")?;
1438     }
1439     for (i, elem) in self.iter().enumerate() {
1440       if i > 0 {
1441         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1442       }
1443       LowerExp::fmt(elem, f)?;
1444     }
1445     if f.alternate() {
1446       write!(f, ",\n")?;
1447     }
1448     write!(f, "]")
1449   }
1450 }
1451 
1452 impl<A: Array> LowerHex for TinyVec<A>
1453 where
1454   A::Item: LowerHex,
1455 {
1456   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1457   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1458     write!(f, "[")?;
1459     if f.alternate() {
1460       write!(f, "\n    ")?;
1461     }
1462     for (i, elem) in self.iter().enumerate() {
1463       if i > 0 {
1464         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1465       }
1466       LowerHex::fmt(elem, f)?;
1467     }
1468     if f.alternate() {
1469       write!(f, ",\n")?;
1470     }
1471     write!(f, "]")
1472   }
1473 }
1474 
1475 impl<A: Array> Octal for TinyVec<A>
1476 where
1477   A::Item: Octal,
1478 {
1479   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1480   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1481     write!(f, "[")?;
1482     if f.alternate() {
1483       write!(f, "\n    ")?;
1484     }
1485     for (i, elem) in self.iter().enumerate() {
1486       if i > 0 {
1487         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1488       }
1489       Octal::fmt(elem, f)?;
1490     }
1491     if f.alternate() {
1492       write!(f, ",\n")?;
1493     }
1494     write!(f, "]")
1495   }
1496 }
1497 
1498 impl<A: Array> Pointer for TinyVec<A>
1499 where
1500   A::Item: Pointer,
1501 {
1502   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1503   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1504     write!(f, "[")?;
1505     if f.alternate() {
1506       write!(f, "\n    ")?;
1507     }
1508     for (i, elem) in self.iter().enumerate() {
1509       if i > 0 {
1510         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1511       }
1512       Pointer::fmt(elem, f)?;
1513     }
1514     if f.alternate() {
1515       write!(f, ",\n")?;
1516     }
1517     write!(f, "]")
1518   }
1519 }
1520 
1521 impl<A: Array> UpperExp for TinyVec<A>
1522 where
1523   A::Item: UpperExp,
1524 {
1525   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1526   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1527     write!(f, "[")?;
1528     if f.alternate() {
1529       write!(f, "\n    ")?;
1530     }
1531     for (i, elem) in self.iter().enumerate() {
1532       if i > 0 {
1533         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1534       }
1535       UpperExp::fmt(elem, f)?;
1536     }
1537     if f.alternate() {
1538       write!(f, ",\n")?;
1539     }
1540     write!(f, "]")
1541   }
1542 }
1543 
1544 impl<A: Array> UpperHex for TinyVec<A>
1545 where
1546   A::Item: UpperHex,
1547 {
1548   #[allow(clippy::missing_inline_in_public_items)]
fmt(&self, f: &mut Formatter) -> core::fmt::Result1549   fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1550     write!(f, "[")?;
1551     if f.alternate() {
1552       write!(f, "\n    ")?;
1553     }
1554     for (i, elem) in self.iter().enumerate() {
1555       if i > 0 {
1556         write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1557       }
1558       UpperHex::fmt(elem, f)?;
1559     }
1560     if f.alternate() {
1561       write!(f, ",\n")?;
1562     }
1563     write!(f, "]")
1564   }
1565 }
1566 
1567 #[cfg(feature = "serde")]
1568 #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1569 struct TinyVecVisitor<A: Array>(PhantomData<A>);
1570 
1571 #[cfg(feature = "serde")]
1572 impl<'de, A: Array> Visitor<'de> for TinyVecVisitor<A>
1573 where
1574   A::Item: Deserialize<'de>,
1575 {
1576   type Value = TinyVec<A>;
1577 
expecting( &self, formatter: &mut core::fmt::Formatter, ) -> core::fmt::Result1578   fn expecting(
1579     &self, formatter: &mut core::fmt::Formatter,
1580   ) -> core::fmt::Result {
1581     formatter.write_str("a sequence")
1582   }
1583 
visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> where S: SeqAccess<'de>,1584   fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
1585   where
1586     S: SeqAccess<'de>,
1587   {
1588     let mut new_tinyvec = match seq.size_hint() {
1589       Some(expected_size) => TinyVec::with_capacity(expected_size),
1590       None => Default::default(),
1591     };
1592 
1593     while let Some(value) = seq.next_element()? {
1594       new_tinyvec.push(value);
1595     }
1596 
1597     Ok(new_tinyvec)
1598   }
1599 }
1600