1#![cfg(feature = "alloc")]
2
3use super::*;
4
5use alloc::vec::{self, Vec};
6use core::convert::TryFrom;
7use tinyvec_macros::impl_mirrored;
8
9#[cfg(feature = "rustc_1_57")]
10use alloc::collections::TryReserveError;
11
12#[cfg(feature = "serde")]
13use core::marker::PhantomData;
14#[cfg(feature = "serde")]
15use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
16#[cfg(feature = "serde")]
17use serde::ser::{Serialize, SerializeSeq, Serializer};
18
19#[macro_export]
38#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
39macro_rules! tiny_vec {
40 ($array_type:ty => $($elem:expr),* $(,)?) => {
41 {
42 const INVOKED_ELEM_COUNT: usize = 0 $( + { let _ = stringify!($elem); 1 })*;
44 match $crate::TinyVec::constructor_for_capacity(INVOKED_ELEM_COUNT) {
47 $crate::TinyVecConstructor::Inline(f) => {
48 f($crate::array_vec!($array_type => $($elem),*))
49 }
50 $crate::TinyVecConstructor::Heap(f) => {
51 f(vec!($($elem),*))
52 }
53 }
54 }
55 };
56 ($array_type:ty) => {
57 $crate::TinyVec::<$array_type>::default()
58 };
59 ($($elem:expr),*) => {
60 $crate::tiny_vec!(_ => $($elem),*)
61 };
62 ($elem:expr; $n:expr) => {
63 $crate::TinyVec::from([$elem; $n])
64 };
65 () => {
66 $crate::tiny_vec!(_)
67 };
68}
69
70#[doc(hidden)] pub enum TinyVecConstructor<A: Array> {
72 Inline(fn(ArrayVec<A>) -> TinyVec<A>),
73 Heap(fn(Vec<A::Item>) -> TinyVec<A>),
74}
75
76#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
98pub enum TinyVec<A: Array> {
99 #[allow(missing_docs)]
100 Inline(ArrayVec<A>),
101 #[allow(missing_docs)]
102 Heap(Vec<A::Item>),
103}
104
105impl<A> Clone for TinyVec<A>
106where
107 A: Array + Clone,
108 A::Item: Clone,
109{
110 #[inline]
111 fn clone(&self) -> Self {
112 match self {
113 TinyVec::Heap(v) => TinyVec::Heap(v.clone()),
114 TinyVec::Inline(v) => TinyVec::Inline(v.clone()),
115 }
116 }
117
118 #[inline]
119 fn clone_from(&mut self, o: &Self) {
120 if o.len() > self.len() {
121 self.reserve(o.len() - self.len());
122 } else {
123 self.truncate(o.len());
124 }
125 let (start, end) = o.split_at(self.len());
126 for (dst, src) in self.iter_mut().zip(start) {
127 dst.clone_from(src);
128 }
129 self.extend_from_slice(end);
130 }
131}
132
133impl<A: Array> Default for TinyVec<A> {
134 #[inline]
135 #[must_use]
136 fn default() -> Self {
137 TinyVec::Inline(ArrayVec::default())
138 }
139}
140
141impl<A: Array> Deref for TinyVec<A> {
142 type Target = [A::Item];
143
144 impl_mirrored! {
145 type Mirror = TinyVec;
146 #[inline(always)]
147 #[must_use]
148 fn deref(self: &Self) -> &Self::Target;
149 }
150}
151
152impl<A: Array> DerefMut for TinyVec<A> {
153 impl_mirrored! {
154 type Mirror = TinyVec;
155 #[inline(always)]
156 #[must_use]
157 fn deref_mut(self: &mut Self) -> &mut Self::Target;
158 }
159}
160
161impl<A: Array, I: SliceIndex<[A::Item]>> Index<I> for TinyVec<A> {
162 type Output = <I as SliceIndex<[A::Item]>>::Output;
163 #[inline(always)]
164 #[must_use]
165 fn index(&self, index: I) -> &Self::Output {
166 &self.deref()[index]
167 }
168}
169
170impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for TinyVec<A> {
171 #[inline(always)]
172 #[must_use]
173 fn index_mut(&mut self, index: I) -> &mut Self::Output {
174 &mut self.deref_mut()[index]
175 }
176}
177
178#[cfg(feature = "std")]
179#[cfg_attr(docs_rs, doc(cfg(feature = "std")))]
180impl<A: Array<Item = u8>> std::io::Write for TinyVec<A> {
181 #[inline(always)]
182 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
183 self.extend_from_slice(buf);
184 Ok(buf.len())
185 }
186
187 #[inline(always)]
188 fn flush(&mut self) -> std::io::Result<()> {
189 Ok(())
190 }
191}
192
193#[cfg(feature = "serde")]
194#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
195impl<A: Array> Serialize for TinyVec<A>
196where
197 A::Item: Serialize,
198{
199 #[must_use]
200 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
201 where
202 S: Serializer,
203 {
204 let mut seq = serializer.serialize_seq(Some(self.len()))?;
205 for element in self.iter() {
206 seq.serialize_element(element)?;
207 }
208 seq.end()
209 }
210}
211
212#[cfg(feature = "serde")]
213#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
214impl<'de, A: Array> Deserialize<'de> for TinyVec<A>
215where
216 A::Item: Deserialize<'de>,
217{
218 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
219 where
220 D: Deserializer<'de>,
221 {
222 deserializer.deserialize_seq(TinyVecVisitor(PhantomData))
223 }
224}
225
226#[cfg(feature = "arbitrary")]
227#[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))]
228impl<'a, A> arbitrary::Arbitrary<'a> for TinyVec<A>
229where
230 A: Array,
231 A::Item: arbitrary::Arbitrary<'a>,
232{
233 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
234 let v = Vec::arbitrary(u)?;
235 let mut tv = TinyVec::Heap(v);
236 tv.shrink_to_fit();
237 Ok(tv)
238 }
239}
240
241impl<A: Array> TinyVec<A> {
242 #[inline(always)]
244 #[must_use]
245 pub fn is_heap(&self) -> bool {
246 match self {
247 TinyVec::Heap(_) => true,
248 TinyVec::Inline(_) => false,
249 }
250 }
251 #[inline(always)]
253 #[must_use]
254 pub fn is_inline(&self) -> bool {
255 !self.is_heap()
256 }
257
258 pub fn shrink_to_fit(&mut self) {
270 let vec = match self {
271 TinyVec::Inline(_) => return,
272 TinyVec::Heap(h) => h,
273 };
274
275 if vec.len() > A::CAPACITY {
276 return vec.shrink_to_fit();
277 }
278
279 let moved_vec = core::mem::replace(vec, Vec::new());
280
281 let mut av = ArrayVec::default();
282 let mut rest = av.fill(moved_vec);
283 debug_assert!(rest.next().is_none());
284 *self = TinyVec::Inline(av);
285 }
286
287 #[allow(clippy::missing_inline_in_public_items)]
296 pub fn move_to_the_heap(&mut self) {
297 let arr = match self {
298 TinyVec::Heap(_) => return,
299 TinyVec::Inline(a) => a,
300 };
301
302 let v = arr.drain_to_vec();
303 *self = TinyVec::Heap(v);
304 }
305
306 #[cfg(feature = "rustc_1_57")]
321 pub fn try_move_to_the_heap(&mut self) -> Result<(), TryReserveError> {
322 let arr = match self {
323 TinyVec::Heap(_) => return Ok(()),
324 TinyVec::Inline(a) => a,
325 };
326
327 let v = arr.try_drain_to_vec()?;
328 *self = TinyVec::Heap(v);
329 return Ok(());
330 }
331
332 pub fn move_to_the_heap_and_reserve(&mut self, n: usize) {
343 let arr = match self {
344 TinyVec::Heap(h) => return h.reserve(n),
345 TinyVec::Inline(a) => a,
346 };
347
348 let v = arr.drain_to_vec_and_reserve(n);
349 *self = TinyVec::Heap(v);
350 }
351
352 #[cfg(feature = "rustc_1_57")]
368 pub fn try_move_to_the_heap_and_reserve(
369 &mut self, n: usize,
370 ) -> Result<(), TryReserveError> {
371 let arr = match self {
372 TinyVec::Heap(h) => return h.try_reserve(n),
373 TinyVec::Inline(a) => a,
374 };
375
376 let v = arr.try_drain_to_vec_and_reserve(n)?;
377 *self = TinyVec::Heap(v);
378 return Ok(());
379 }
380
381 pub fn reserve(&mut self, n: usize) {
392 let arr = match self {
393 TinyVec::Heap(h) => return h.reserve(n),
394 TinyVec::Inline(a) => a,
395 };
396
397 if n > arr.capacity() - arr.len() {
398 let v = arr.drain_to_vec_and_reserve(n);
399 *self = TinyVec::Heap(v);
400 }
401
402 return;
404 }
405
406 #[cfg(feature = "rustc_1_57")]
422 pub fn try_reserve(&mut self, n: usize) -> Result<(), TryReserveError> {
423 let arr = match self {
424 TinyVec::Heap(h) => return h.try_reserve(n),
425 TinyVec::Inline(a) => a,
426 };
427
428 if n > arr.capacity() - arr.len() {
429 let v = arr.try_drain_to_vec_and_reserve(n)?;
430 *self = TinyVec::Heap(v);
431 }
432
433 return Ok(());
435 }
436
437 pub fn reserve_exact(&mut self, n: usize) {
455 let arr = match self {
456 TinyVec::Heap(h) => return h.reserve_exact(n),
457 TinyVec::Inline(a) => a,
458 };
459
460 if n > arr.capacity() - arr.len() {
461 let v = arr.drain_to_vec_and_reserve(n);
462 *self = TinyVec::Heap(v);
463 }
464
465 return;
467 }
468
469 #[cfg(feature = "rustc_1_57")]
491 pub fn try_reserve_exact(&mut self, n: usize) -> Result<(), TryReserveError> {
492 let arr = match self {
493 TinyVec::Heap(h) => return h.try_reserve_exact(n),
494 TinyVec::Inline(a) => a,
495 };
496
497 if n > arr.capacity() - arr.len() {
498 let v = arr.try_drain_to_vec_and_reserve(n)?;
499 *self = TinyVec::Heap(v);
500 }
501
502 return Ok(());
504 }
505
506 #[inline]
521 #[must_use]
522 pub fn with_capacity(cap: usize) -> Self {
523 if cap <= A::CAPACITY {
524 TinyVec::Inline(ArrayVec::default())
525 } else {
526 TinyVec::Heap(Vec::with_capacity(cap))
527 }
528 }
529}
530
531impl<A: Array> TinyVec<A> {
532 #[inline]
534 pub fn append(&mut self, other: &mut Self) {
535 self.reserve(other.len());
536
537 match (self, other) {
539 (TinyVec::Heap(sh), TinyVec::Heap(oh)) => sh.append(oh),
540 (TinyVec::Inline(a), TinyVec::Heap(h)) => a.extend(h.drain(..)),
541 (ref mut this, TinyVec::Inline(arr)) => this.extend(arr.drain(..)),
542 }
543 }
544
545 impl_mirrored! {
546 type Mirror = TinyVec;
547
548 #[inline]
565 pub fn swap_remove(self: &mut Self, index: usize) -> A::Item;
566
567 #[inline]
572 pub fn pop(self: &mut Self) -> Option<A::Item>;
573
574 #[inline]
591 pub fn remove(self: &mut Self, index: usize) -> A::Item;
592
593 #[inline(always)]
595 #[must_use]
596 pub fn len(self: &Self) -> usize;
597
598 #[inline(always)]
603 #[must_use]
604 pub fn capacity(self: &Self) -> usize;
605
606 #[inline]
610 pub fn truncate(self: &mut Self, new_len: usize);
611
612 #[inline(always)]
618 #[must_use]
619 pub fn as_mut_ptr(self: &mut Self) -> *mut A::Item;
620
621 #[inline(always)]
627 #[must_use]
628 pub fn as_ptr(self: &Self) -> *const A::Item;
629 }
630
631 #[inline]
643 pub fn retain<F: FnMut(&A::Item) -> bool>(self: &mut Self, acceptable: F) {
644 match self {
645 TinyVec::Inline(i) => i.retain(acceptable),
646 TinyVec::Heap(h) => h.retain(acceptable),
647 }
648 }
649
650 #[inline]
663 #[cfg(feature = "rustc_1_61")]
664 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, acceptable: F) {
665 match self {
666 TinyVec::Inline(i) => i.retain_mut(acceptable),
667 TinyVec::Heap(h) => h.retain_mut(acceptable),
668 }
669 }
670
671 #[inline(always)]
673 #[must_use]
674 pub fn as_mut_slice(self: &mut Self) -> &mut [A::Item] {
675 self.deref_mut()
676 }
677
678 #[inline(always)]
680 #[must_use]
681 pub fn as_slice(self: &Self) -> &[A::Item] {
682 self.deref()
683 }
684
685 #[inline(always)]
687 pub fn clear(&mut self) {
688 self.truncate(0)
689 }
690
691 #[cfg(feature = "nightly_slice_partition_dedup")]
693 #[inline(always)]
694 pub fn dedup(&mut self)
695 where
696 A::Item: PartialEq,
697 {
698 self.dedup_by(|a, b| a == b)
699 }
700
701 #[cfg(feature = "nightly_slice_partition_dedup")]
703 #[inline(always)]
704 pub fn dedup_by<F>(&mut self, same_bucket: F)
705 where
706 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
707 {
708 let len = {
709 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
710 dedup.len()
711 };
712 self.truncate(len);
713 }
714
715 #[cfg(feature = "nightly_slice_partition_dedup")]
717 #[inline(always)]
718 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
719 where
720 F: FnMut(&mut A::Item) -> K,
721 K: PartialEq,
722 {
723 self.dedup_by(|a, b| key(a) == key(b))
724 }
725
726 #[inline]
750 pub fn drain<R: RangeBounds<usize>>(
751 &mut self, range: R,
752 ) -> TinyVecDrain<'_, A> {
753 match self {
754 TinyVec::Inline(i) => TinyVecDrain::Inline(i.drain(range)),
755 TinyVec::Heap(h) => TinyVecDrain::Heap(h.drain(range)),
756 }
757 }
758
759 #[inline]
767 pub fn extend_from_slice(&mut self, sli: &[A::Item])
768 where
769 A::Item: Clone,
770 {
771 self.reserve(sli.len());
772 match self {
773 TinyVec::Inline(a) => a.extend_from_slice(sli),
774 TinyVec::Heap(h) => h.extend_from_slice(sli),
775 }
776 }
777
778 #[inline]
786 #[must_use]
787 #[allow(clippy::match_wild_err_arm)]
788 pub fn from_array_len(data: A, len: usize) -> Self {
789 match Self::try_from_array_len(data, len) {
790 Ok(out) => out,
791 Err(_) => {
792 panic!("TinyVec: length {} exceeds capacity {}!", len, A::CAPACITY)
793 }
794 }
795 }
796
797 #[inline(always)]
801 #[doc(hidden)]
802 pub fn constructor_for_capacity(cap: usize) -> TinyVecConstructor<A> {
803 if cap <= A::CAPACITY {
804 TinyVecConstructor::Inline(TinyVec::Inline)
805 } else {
806 TinyVecConstructor::Heap(TinyVec::Heap)
807 }
808 }
809
810 #[inline]
826 pub fn insert(&mut self, index: usize, item: A::Item) {
827 assert!(
828 index <= self.len(),
829 "insertion index (is {}) should be <= len (is {})",
830 index,
831 self.len()
832 );
833
834 let arr = match self {
835 TinyVec::Heap(v) => return v.insert(index, item),
836 TinyVec::Inline(a) => a,
837 };
838
839 if let Some(x) = arr.try_insert(index, item) {
840 let mut v = Vec::with_capacity(arr.len() * 2);
841 let mut it =
842 arr.iter_mut().map(|r| core::mem::replace(r, Default::default()));
843 v.extend(it.by_ref().take(index));
844 v.push(x);
845 v.extend(it);
846 *self = TinyVec::Heap(v);
847 }
848 }
849
850 #[inline(always)]
852 #[must_use]
853 pub fn is_empty(&self) -> bool {
854 self.len() == 0
855 }
856
857 #[inline(always)]
859 #[must_use]
860 pub fn new() -> Self {
861 Self::default()
862 }
863
864 #[inline]
866 pub fn push(&mut self, val: A::Item) {
867 #[cold]
877 fn drain_to_heap_and_push<A: Array>(
878 arr: &mut ArrayVec<A>, val: A::Item,
879 ) -> TinyVec<A> {
880 let mut v = arr.drain_to_vec_and_reserve(arr.len());
882 v.push(val);
883 TinyVec::Heap(v)
884 }
885
886 match self {
887 TinyVec::Heap(v) => v.push(val),
888 TinyVec::Inline(arr) => {
889 if let Some(x) = arr.try_push(val) {
890 *self = drain_to_heap_and_push(arr, x);
891 }
892 }
893 }
894 }
895
896 #[inline]
915 pub fn resize(&mut self, new_len: usize, new_val: A::Item)
916 where
917 A::Item: Clone,
918 {
919 self.resize_with(new_len, || new_val.clone());
920 }
921
922 #[inline]
945 pub fn resize_with<F: FnMut() -> A::Item>(&mut self, new_len: usize, f: F) {
946 match new_len.checked_sub(self.len()) {
947 None => return self.truncate(new_len),
948 Some(n) => self.reserve(n),
949 }
950
951 match self {
952 TinyVec::Inline(a) => a.resize_with(new_len, f),
953 TinyVec::Heap(v) => v.resize_with(new_len, f),
954 }
955 }
956
957 #[inline]
975 pub fn split_off(&mut self, at: usize) -> Self {
976 match self {
977 TinyVec::Inline(a) => TinyVec::Inline(a.split_off(at)),
978 TinyVec::Heap(v) => TinyVec::Heap(v.split_off(at)),
979 }
980 }
981
982 #[inline]
1006 pub fn splice<R, I>(
1007 &mut self, range: R, replacement: I,
1008 ) -> TinyVecSplice<'_, A, core::iter::Fuse<I::IntoIter>>
1009 where
1010 R: RangeBounds<usize>,
1011 I: IntoIterator<Item = A::Item>,
1012 {
1013 use core::ops::Bound;
1014 let start = match range.start_bound() {
1015 Bound::Included(x) => *x,
1016 Bound::Excluded(x) => x.saturating_add(1),
1017 Bound::Unbounded => 0,
1018 };
1019 let end = match range.end_bound() {
1020 Bound::Included(x) => x.saturating_add(1),
1021 Bound::Excluded(x) => *x,
1022 Bound::Unbounded => self.len(),
1023 };
1024 assert!(
1025 start <= end,
1026 "TinyVec::splice> Illegal range, {} to {}",
1027 start,
1028 end
1029 );
1030 assert!(
1031 end <= self.len(),
1032 "TinyVec::splice> Range ends at {} but length is only {}!",
1033 end,
1034 self.len()
1035 );
1036
1037 TinyVecSplice {
1038 removal_start: start,
1039 removal_end: end,
1040 parent: self,
1041 replacement: replacement.into_iter().fuse(),
1042 }
1043 }
1044
1045 #[inline]
1055 pub fn try_from_array_len(data: A, len: usize) -> Result<Self, A> {
1056 let arr = ArrayVec::try_from_array_len(data, len)?;
1057 Ok(TinyVec::Inline(arr))
1058 }
1059}
1060
1061#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1065pub enum TinyVecDrain<'p, A: Array> {
1066 #[allow(missing_docs)]
1067 Inline(ArrayVecDrain<'p, A::Item>),
1068 #[allow(missing_docs)]
1069 Heap(vec::Drain<'p, A::Item>),
1070}
1071
1072impl<'p, A: Array> Iterator for TinyVecDrain<'p, A> {
1073 type Item = A::Item;
1074
1075 impl_mirrored! {
1076 type Mirror = TinyVecDrain;
1077
1078 #[inline]
1079 fn next(self: &mut Self) -> Option<Self::Item>;
1080 #[inline]
1081 fn nth(self: &mut Self, n: usize) -> Option<Self::Item>;
1082 #[inline]
1083 fn size_hint(self: &Self) -> (usize, Option<usize>);
1084 #[inline]
1085 fn last(self: Self) -> Option<Self::Item>;
1086 #[inline]
1087 fn count(self: Self) -> usize;
1088 }
1089
1090 #[inline]
1091 fn for_each<F: FnMut(Self::Item)>(self, f: F) {
1092 match self {
1093 TinyVecDrain::Inline(i) => i.for_each(f),
1094 TinyVecDrain::Heap(h) => h.for_each(f),
1095 }
1096 }
1097}
1098
1099impl<'p, A: Array> DoubleEndedIterator for TinyVecDrain<'p, A> {
1100 impl_mirrored! {
1101 type Mirror = TinyVecDrain;
1102
1103 #[inline]
1104 fn next_back(self: &mut Self) -> Option<Self::Item>;
1105
1106 #[inline]
1107 fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>;
1108 }
1109}
1110
1111#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1114pub struct TinyVecSplice<'p, A: Array, I: Iterator<Item = A::Item>> {
1115 parent: &'p mut TinyVec<A>,
1116 removal_start: usize,
1117 removal_end: usize,
1118 replacement: I,
1119}
1120
1121impl<'p, A, I> Iterator for TinyVecSplice<'p, A, I>
1122where
1123 A: Array,
1124 I: Iterator<Item = A::Item>,
1125{
1126 type Item = A::Item;
1127
1128 #[inline]
1129 fn next(&mut self) -> Option<A::Item> {
1130 if self.removal_start < self.removal_end {
1131 match self.replacement.next() {
1132 Some(replacement) => {
1133 let removed = core::mem::replace(
1134 &mut self.parent[self.removal_start],
1135 replacement,
1136 );
1137 self.removal_start += 1;
1138 Some(removed)
1139 }
1140 None => {
1141 let removed = self.parent.remove(self.removal_start);
1142 self.removal_end -= 1;
1143 Some(removed)
1144 }
1145 }
1146 } else {
1147 None
1148 }
1149 }
1150
1151 #[inline]
1152 fn size_hint(&self) -> (usize, Option<usize>) {
1153 let len = self.len();
1154 (len, Some(len))
1155 }
1156}
1157
1158impl<'p, A, I> ExactSizeIterator for TinyVecSplice<'p, A, I>
1159where
1160 A: Array,
1161 I: Iterator<Item = A::Item>,
1162{
1163 #[inline]
1164 fn len(&self) -> usize {
1165 self.removal_end - self.removal_start
1166 }
1167}
1168
1169impl<'p, A, I> FusedIterator for TinyVecSplice<'p, A, I>
1170where
1171 A: Array,
1172 I: Iterator<Item = A::Item>,
1173{
1174}
1175
1176impl<'p, A, I> DoubleEndedIterator for TinyVecSplice<'p, A, I>
1177where
1178 A: Array,
1179 I: Iterator<Item = A::Item> + DoubleEndedIterator,
1180{
1181 #[inline]
1182 fn next_back(&mut self) -> Option<A::Item> {
1183 if self.removal_start < self.removal_end {
1184 match self.replacement.next_back() {
1185 Some(replacement) => {
1186 let removed = core::mem::replace(
1187 &mut self.parent[self.removal_end - 1],
1188 replacement,
1189 );
1190 self.removal_end -= 1;
1191 Some(removed)
1192 }
1193 None => {
1194 let removed = self.parent.remove(self.removal_end - 1);
1195 self.removal_end -= 1;
1196 Some(removed)
1197 }
1198 }
1199 } else {
1200 None
1201 }
1202 }
1203}
1204
1205impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1206 for TinyVecSplice<'p, A, I>
1207{
1208 fn drop(&mut self) {
1209 for _ in self.by_ref() {}
1210
1211 let (lower_bound, _) = self.replacement.size_hint();
1212 self.parent.reserve(lower_bound);
1213
1214 for replacement in self.replacement.by_ref() {
1215 self.parent.insert(self.removal_end, replacement);
1216 self.removal_end += 1;
1217 }
1218 }
1219}
1220
1221impl<A: Array> AsMut<[A::Item]> for TinyVec<A> {
1222 #[inline(always)]
1223 #[must_use]
1224 fn as_mut(&mut self) -> &mut [A::Item] {
1225 &mut *self
1226 }
1227}
1228
1229impl<A: Array> AsRef<[A::Item]> for TinyVec<A> {
1230 #[inline(always)]
1231 #[must_use]
1232 fn as_ref(&self) -> &[A::Item] {
1233 &*self
1234 }
1235}
1236
1237impl<A: Array> Borrow<[A::Item]> for TinyVec<A> {
1238 #[inline(always)]
1239 #[must_use]
1240 fn borrow(&self) -> &[A::Item] {
1241 &*self
1242 }
1243}
1244
1245impl<A: Array> BorrowMut<[A::Item]> for TinyVec<A> {
1246 #[inline(always)]
1247 #[must_use]
1248 fn borrow_mut(&mut self) -> &mut [A::Item] {
1249 &mut *self
1250 }
1251}
1252
1253impl<A: Array> Extend<A::Item> for TinyVec<A> {
1254 #[inline]
1255 fn extend<T: IntoIterator<Item = A::Item>>(&mut self, iter: T) {
1256 let iter = iter.into_iter();
1257 let (lower_bound, _) = iter.size_hint();
1258 self.reserve(lower_bound);
1259
1260 let a = match self {
1261 TinyVec::Heap(h) => return h.extend(iter),
1262 TinyVec::Inline(a) => a,
1263 };
1264
1265 let mut iter = a.fill(iter);
1266 let maybe = iter.next();
1267
1268 let surely = match maybe {
1269 Some(x) => x,
1270 None => return,
1271 };
1272
1273 let mut v = a.drain_to_vec_and_reserve(a.len());
1274 v.push(surely);
1275 v.extend(iter);
1276 *self = TinyVec::Heap(v);
1277 }
1278}
1279
1280impl<A: Array> From<ArrayVec<A>> for TinyVec<A> {
1281 #[inline(always)]
1282 #[must_use]
1283 fn from(arr: ArrayVec<A>) -> Self {
1284 TinyVec::Inline(arr)
1285 }
1286}
1287
1288impl<A: Array> From<A> for TinyVec<A> {
1289 fn from(array: A) -> Self {
1290 TinyVec::Inline(ArrayVec::from(array))
1291 }
1292}
1293
1294impl<T, A> From<&'_ [T]> for TinyVec<A>
1295where
1296 T: Clone + Default,
1297 A: Array<Item = T>,
1298{
1299 #[inline]
1300 #[must_use]
1301 fn from(slice: &[T]) -> Self {
1302 if let Ok(arr) = ArrayVec::try_from(slice) {
1303 TinyVec::Inline(arr)
1304 } else {
1305 TinyVec::Heap(slice.into())
1306 }
1307 }
1308}
1309
1310impl<T, A> From<&'_ mut [T]> for TinyVec<A>
1311where
1312 T: Clone + Default,
1313 A: Array<Item = T>,
1314{
1315 #[inline]
1316 #[must_use]
1317 fn from(slice: &mut [T]) -> Self {
1318 Self::from(&*slice)
1319 }
1320}
1321
1322impl<A: Array> FromIterator<A::Item> for TinyVec<A> {
1323 #[inline]
1324 #[must_use]
1325 fn from_iter<T: IntoIterator<Item = A::Item>>(iter: T) -> Self {
1326 let mut av = Self::default();
1327 av.extend(iter);
1328 av
1329 }
1330}
1331
1332#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1334pub enum TinyVecIterator<A: Array> {
1335 #[allow(missing_docs)]
1336 Inline(ArrayVecIterator<A>),
1337 #[allow(missing_docs)]
1338 Heap(alloc::vec::IntoIter<A::Item>),
1339}
1340
1341impl<A: Array> TinyVecIterator<A> {
1342 impl_mirrored! {
1343 type Mirror = TinyVecIterator;
1344 #[inline]
1346 #[must_use]
1347 pub fn as_slice(self: &Self) -> &[A::Item];
1348 }
1349}
1350
1351impl<A: Array> FusedIterator for TinyVecIterator<A> {}
1352
1353impl<A: Array> Iterator for TinyVecIterator<A> {
1354 type Item = A::Item;
1355
1356 impl_mirrored! {
1357 type Mirror = TinyVecIterator;
1358
1359 #[inline]
1360 fn next(self: &mut Self) -> Option<Self::Item>;
1361
1362 #[inline(always)]
1363 #[must_use]
1364 fn size_hint(self: &Self) -> (usize, Option<usize>);
1365
1366 #[inline(always)]
1367 fn count(self: Self) -> usize;
1368
1369 #[inline]
1370 fn last(self: Self) -> Option<Self::Item>;
1371
1372 #[inline]
1373 fn nth(self: &mut Self, n: usize) -> Option<A::Item>;
1374 }
1375}
1376
1377impl<A: Array> DoubleEndedIterator for TinyVecIterator<A> {
1378 impl_mirrored! {
1379 type Mirror = TinyVecIterator;
1380
1381 #[inline]
1382 fn next_back(self: &mut Self) -> Option<Self::Item>;
1383
1384 #[inline]
1385 fn nth_back(self: &mut Self, n: usize) -> Option<Self::Item>;
1386 }
1387}
1388
1389impl<A: Array> ExactSizeIterator for TinyVecIterator<A> {
1390 impl_mirrored! {
1391 type Mirror = TinyVecIterator;
1392 #[inline]
1393 fn len(self: &Self) -> usize;
1394 }
1395}
1396
1397impl<A: Array> Debug for TinyVecIterator<A>
1398where
1399 A::Item: Debug,
1400{
1401 #[allow(clippy::missing_inline_in_public_items)]
1402 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1403 f.debug_tuple("TinyVecIterator").field(&self.as_slice()).finish()
1404 }
1405}
1406
1407impl<A: Array> IntoIterator for TinyVec<A> {
1408 type Item = A::Item;
1409 type IntoIter = TinyVecIterator<A>;
1410 #[inline(always)]
1411 #[must_use]
1412 fn into_iter(self) -> Self::IntoIter {
1413 match self {
1414 TinyVec::Inline(a) => TinyVecIterator::Inline(a.into_iter()),
1415 TinyVec::Heap(v) => TinyVecIterator::Heap(v.into_iter()),
1416 }
1417 }
1418}
1419
1420impl<'a, A: Array> IntoIterator for &'a mut TinyVec<A> {
1421 type Item = &'a mut A::Item;
1422 type IntoIter = core::slice::IterMut<'a, A::Item>;
1423 #[inline(always)]
1424 #[must_use]
1425 fn into_iter(self) -> Self::IntoIter {
1426 self.iter_mut()
1427 }
1428}
1429
1430impl<'a, A: Array> IntoIterator for &'a TinyVec<A> {
1431 type Item = &'a A::Item;
1432 type IntoIter = core::slice::Iter<'a, A::Item>;
1433 #[inline(always)]
1434 #[must_use]
1435 fn into_iter(self) -> Self::IntoIter {
1436 self.iter()
1437 }
1438}
1439
1440impl<A: Array> PartialEq for TinyVec<A>
1441where
1442 A::Item: PartialEq,
1443{
1444 #[inline]
1445 #[must_use]
1446 fn eq(&self, other: &Self) -> bool {
1447 self.as_slice().eq(other.as_slice())
1448 }
1449}
1450impl<A: Array> Eq for TinyVec<A> where A::Item: Eq {}
1451
1452impl<A: Array> PartialOrd for TinyVec<A>
1453where
1454 A::Item: PartialOrd,
1455{
1456 #[inline]
1457 #[must_use]
1458 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1459 self.as_slice().partial_cmp(other.as_slice())
1460 }
1461}
1462impl<A: Array> Ord for TinyVec<A>
1463where
1464 A::Item: Ord,
1465{
1466 #[inline]
1467 #[must_use]
1468 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1469 self.as_slice().cmp(other.as_slice())
1470 }
1471}
1472
1473impl<A: Array> PartialEq<&A> for TinyVec<A>
1474where
1475 A::Item: PartialEq,
1476{
1477 #[inline]
1478 #[must_use]
1479 fn eq(&self, other: &&A) -> bool {
1480 self.as_slice().eq(other.as_slice())
1481 }
1482}
1483
1484impl<A: Array> PartialEq<&[A::Item]> for TinyVec<A>
1485where
1486 A::Item: PartialEq,
1487{
1488 #[inline]
1489 #[must_use]
1490 fn eq(&self, other: &&[A::Item]) -> bool {
1491 self.as_slice().eq(*other)
1492 }
1493}
1494
1495impl<A: Array> Hash for TinyVec<A>
1496where
1497 A::Item: Hash,
1498{
1499 #[inline]
1500 fn hash<H: Hasher>(&self, state: &mut H) {
1501 self.as_slice().hash(state)
1502 }
1503}
1504
1505impl<A: Array> Binary for TinyVec<A>
1510where
1511 A::Item: Binary,
1512{
1513 #[allow(clippy::missing_inline_in_public_items)]
1514 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1515 write!(f, "[")?;
1516 if f.alternate() {
1517 write!(f, "\n ")?;
1518 }
1519 for (i, elem) in self.iter().enumerate() {
1520 if i > 0 {
1521 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1522 }
1523 Binary::fmt(elem, f)?;
1524 }
1525 if f.alternate() {
1526 write!(f, ",\n")?;
1527 }
1528 write!(f, "]")
1529 }
1530}
1531
1532impl<A: Array> Debug for TinyVec<A>
1533where
1534 A::Item: Debug,
1535{
1536 #[allow(clippy::missing_inline_in_public_items)]
1537 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1538 write!(f, "[")?;
1539 if f.alternate() && !self.is_empty() {
1540 write!(f, "\n ")?;
1541 }
1542 for (i, elem) in self.iter().enumerate() {
1543 if i > 0 {
1544 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1545 }
1546 Debug::fmt(elem, f)?;
1547 }
1548 if f.alternate() && !self.is_empty() {
1549 write!(f, ",\n")?;
1550 }
1551 write!(f, "]")
1552 }
1553}
1554
1555impl<A: Array> Display for TinyVec<A>
1556where
1557 A::Item: Display,
1558{
1559 #[allow(clippy::missing_inline_in_public_items)]
1560 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1561 write!(f, "[")?;
1562 if f.alternate() {
1563 write!(f, "\n ")?;
1564 }
1565 for (i, elem) in self.iter().enumerate() {
1566 if i > 0 {
1567 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1568 }
1569 Display::fmt(elem, f)?;
1570 }
1571 if f.alternate() {
1572 write!(f, ",\n")?;
1573 }
1574 write!(f, "]")
1575 }
1576}
1577
1578impl<A: Array> LowerExp for TinyVec<A>
1579where
1580 A::Item: LowerExp,
1581{
1582 #[allow(clippy::missing_inline_in_public_items)]
1583 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1584 write!(f, "[")?;
1585 if f.alternate() {
1586 write!(f, "\n ")?;
1587 }
1588 for (i, elem) in self.iter().enumerate() {
1589 if i > 0 {
1590 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1591 }
1592 LowerExp::fmt(elem, f)?;
1593 }
1594 if f.alternate() {
1595 write!(f, ",\n")?;
1596 }
1597 write!(f, "]")
1598 }
1599}
1600
1601impl<A: Array> LowerHex for TinyVec<A>
1602where
1603 A::Item: LowerHex,
1604{
1605 #[allow(clippy::missing_inline_in_public_items)]
1606 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1607 write!(f, "[")?;
1608 if f.alternate() {
1609 write!(f, "\n ")?;
1610 }
1611 for (i, elem) in self.iter().enumerate() {
1612 if i > 0 {
1613 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1614 }
1615 LowerHex::fmt(elem, f)?;
1616 }
1617 if f.alternate() {
1618 write!(f, ",\n")?;
1619 }
1620 write!(f, "]")
1621 }
1622}
1623
1624impl<A: Array> Octal for TinyVec<A>
1625where
1626 A::Item: Octal,
1627{
1628 #[allow(clippy::missing_inline_in_public_items)]
1629 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1630 write!(f, "[")?;
1631 if f.alternate() {
1632 write!(f, "\n ")?;
1633 }
1634 for (i, elem) in self.iter().enumerate() {
1635 if i > 0 {
1636 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1637 }
1638 Octal::fmt(elem, f)?;
1639 }
1640 if f.alternate() {
1641 write!(f, ",\n")?;
1642 }
1643 write!(f, "]")
1644 }
1645}
1646
1647impl<A: Array> Pointer for TinyVec<A>
1648where
1649 A::Item: Pointer,
1650{
1651 #[allow(clippy::missing_inline_in_public_items)]
1652 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1653 write!(f, "[")?;
1654 if f.alternate() {
1655 write!(f, "\n ")?;
1656 }
1657 for (i, elem) in self.iter().enumerate() {
1658 if i > 0 {
1659 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1660 }
1661 Pointer::fmt(elem, f)?;
1662 }
1663 if f.alternate() {
1664 write!(f, ",\n")?;
1665 }
1666 write!(f, "]")
1667 }
1668}
1669
1670impl<A: Array> UpperExp for TinyVec<A>
1671where
1672 A::Item: UpperExp,
1673{
1674 #[allow(clippy::missing_inline_in_public_items)]
1675 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1676 write!(f, "[")?;
1677 if f.alternate() {
1678 write!(f, "\n ")?;
1679 }
1680 for (i, elem) in self.iter().enumerate() {
1681 if i > 0 {
1682 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1683 }
1684 UpperExp::fmt(elem, f)?;
1685 }
1686 if f.alternate() {
1687 write!(f, ",\n")?;
1688 }
1689 write!(f, "]")
1690 }
1691}
1692
1693impl<A: Array> UpperHex for TinyVec<A>
1694where
1695 A::Item: UpperHex,
1696{
1697 #[allow(clippy::missing_inline_in_public_items)]
1698 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1699 write!(f, "[")?;
1700 if f.alternate() {
1701 write!(f, "\n ")?;
1702 }
1703 for (i, elem) in self.iter().enumerate() {
1704 if i > 0 {
1705 write!(f, ",{}", if f.alternate() { "\n " } else { " " })?;
1706 }
1707 UpperHex::fmt(elem, f)?;
1708 }
1709 if f.alternate() {
1710 write!(f, ",\n")?;
1711 }
1712 write!(f, "]")
1713 }
1714}
1715
1716#[cfg(feature = "serde")]
1717#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1718struct TinyVecVisitor<A: Array>(PhantomData<A>);
1719
1720#[cfg(feature = "serde")]
1721impl<'de, A: Array> Visitor<'de> for TinyVecVisitor<A>
1722where
1723 A::Item: Deserialize<'de>,
1724{
1725 type Value = TinyVec<A>;
1726
1727 fn expecting(
1728 &self, formatter: &mut core::fmt::Formatter,
1729 ) -> core::fmt::Result {
1730 formatter.write_str("a sequence")
1731 }
1732
1733 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
1734 where
1735 S: SeqAccess<'de>,
1736 {
1737 let mut new_tinyvec = match seq.size_hint() {
1738 Some(expected_size) => TinyVec::with_capacity(expected_size),
1739 None => Default::default(),
1740 };
1741
1742 while let Some(value) = seq.next_element()? {
1743 new_tinyvec.push(value);
1744 }
1745
1746 Ok(new_tinyvec)
1747 }
1748}