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 = "serde")]
10use core::marker::PhantomData;
11#[cfg(feature = "serde")]
12use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
13#[cfg(feature = "serde")]
14use serde::ser::{Serialize, SerializeSeq, Serializer};
15
16#[macro_export]
35#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
36macro_rules! tiny_vec {
37 ($array_type:ty => $($elem:expr),* $(,)?) => {
38 {
39 const INVOKED_ELEM_COUNT: usize = 0 $( + { let _ = stringify!($elem); 1 })*;
41 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)] pub enum TinyVecConstructor<A: Array> {
69 Inline(fn(ArrayVec<A>) -> TinyVec<A>),
70 Heap(fn(Vec<A::Item>) -> TinyVec<A>),
71}
72
73#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
95pub enum TinyVec<A: Array> {
96 #[allow(missing_docs)]
97 Inline(ArrayVec<A>),
98 #[allow(missing_docs)]
99 Heap(Vec<A::Item>),
100}
101
102impl<A> Clone for TinyVec<A>
103where
104 A: Array + Clone,
105 A::Item: Clone,
106{
107 #[inline]
108 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]
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
130impl<A: Array> Default for TinyVec<A> {
131 #[inline]
132 #[must_use]
133 fn default() -> Self {
134 TinyVec::Inline(ArrayVec::default())
135 }
136}
137
138impl<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
149impl<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
158impl<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]
162 fn index(&self, index: I) -> &Self::Output {
163 &self.deref()[index]
164 }
165}
166
167impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for TinyVec<A> {
168 #[inline(always)]
169 #[must_use]
170 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")))]
177impl<A: Array> Serialize for TinyVec<A>
178where
179 A::Item: Serialize,
180{
181 #[must_use]
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")))]
196impl<'de, A: Array> Deserialize<'de> for TinyVec<A>
197where
198 A::Item: Deserialize<'de>,
199{
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")))]
210impl<'a, A> arbitrary::Arbitrary<'a> for TinyVec<A>
211where
212 A: Array,
213 A::Item: arbitrary::Arbitrary<'a>,
214{
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
223impl<A: Array> TinyVec<A> {
224 #[inline(always)]
226 #[must_use]
227 pub fn is_heap(&self) -> bool {
228 match self {
229 TinyVec::Heap(_) => true,
230 TinyVec::Inline(_) => false,
231 }
232 }
233 #[inline(always)]
235 #[must_use]
236 pub fn is_inline(&self) -> bool {
237 !self.is_heap()
238 }
239
240 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 #[allow(clippy::missing_inline_in_public_items)]
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 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 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 return;
331 }
332
333 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 return;
363 }
364
365 #[inline]
380 #[must_use]
381 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
390impl<A: Array> TinyVec<A> {
391 #[cfg(feature = "rustc_1_40")]
393 #[inline]
394 pub fn append(&mut self, other: &mut Self) {
395 self.reserve(other.len());
396
397 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 #[cfg(not(feature = "rustc_1_40"))]
407 #[inline]
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 #[inline]
435 pub fn swap_remove(self: &mut Self, index: usize) -> A::Item;
436
437 #[inline]
442 pub fn pop(self: &mut Self) -> Option<A::Item>;
443
444 #[inline]
461 pub fn remove(self: &mut Self, index: usize) -> A::Item;
462
463 #[inline(always)]
465 #[must_use]
466 pub fn len(self: &Self) -> usize;
467
468 #[inline(always)]
473 #[must_use]
474 pub fn capacity(self: &Self) -> usize;
475
476 #[inline]
480 pub fn truncate(self: &mut Self, new_len: usize);
481
482 #[inline(always)]
488 #[must_use]
489 pub fn as_mut_ptr(self: &mut Self) -> *mut A::Item;
490
491 #[inline(always)]
497 #[must_use]
498 pub fn as_ptr(self: &Self) -> *const A::Item;
499 }
500
501 #[inline]
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 #[inline(always)]
522 #[must_use]
523 pub fn as_mut_slice(self: &mut Self) -> &mut [A::Item] {
524 self.deref_mut()
525 }
526
527 #[inline(always)]
529 #[must_use]
530 pub fn as_slice(self: &Self) -> &[A::Item] {
531 self.deref()
532 }
533
534 #[inline(always)]
536 pub fn clear(&mut self) {
537 self.truncate(0)
538 }
539
540 #[cfg(feature = "nightly_slice_partition_dedup")]
542 #[inline(always)]
543 pub fn dedup(&mut self)
544 where
545 A::Item: PartialEq,
546 {
547 self.dedup_by(|a, b| a == b)
548 }
549
550 #[cfg(feature = "nightly_slice_partition_dedup")]
552 #[inline(always)]
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 #[cfg(feature = "nightly_slice_partition_dedup")]
566 #[inline(always)]
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 #[inline]
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 #[inline]
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 #[inline]
635 #[must_use]
636 #[allow(clippy::match_wild_err_arm)]
637 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 #[inline(always)]
650 #[doc(hidden)]
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 #[inline]
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 #[inline(always)]
701 #[must_use]
702 pub fn is_empty(&self) -> bool {
703 self.len() == 0
704 }
705
706 #[inline(always)]
708 #[must_use]
709 pub fn new() -> Self {
710 Self::default()
711 }
712
713 #[inline]
723 pub fn push(&mut self, val: A::Item) {
724 #[cold]
734 fn drain_to_heap_and_push<A: Array>(
735 arr: &mut ArrayVec<A>, val: A::Item,
736 ) -> TinyVec<A> {
737 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 #[inline]
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 #[inline]
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 #[inline]
832 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 #[inline]
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 #[inline]
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#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
922pub 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
929impl<'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]
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
956impl<'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#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
972pub 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
979impl<'p, A, I> Iterator for TinyVecSplice<'p, A, I>
980where
981 A: Array,
982 I: Iterator<Item = A::Item>,
983{
984 type Item = A::Item;
985
986 #[inline]
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]
1010 fn size_hint(&self) -> (usize, Option<usize>) {
1011 let len = self.len();
1012 (len, Some(len))
1013 }
1014}
1015
1016impl<'p, A, I> ExactSizeIterator for TinyVecSplice<'p, A, I>
1017where
1018 A: Array,
1019 I: Iterator<Item = A::Item>,
1020{
1021 #[inline]
1022 fn len(&self) -> usize {
1023 self.removal_end - self.removal_start
1024 }
1025}
1026
1027impl<'p, A, I> FusedIterator for TinyVecSplice<'p, A, I>
1028where
1029 A: Array,
1030 I: Iterator<Item = A::Item>,
1031{
1032}
1033
1034impl<'p, A, I> DoubleEndedIterator for TinyVecSplice<'p, A, I>
1035where
1036 A: Array,
1037 I: Iterator<Item = A::Item> + DoubleEndedIterator,
1038{
1039 #[inline]
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
1063impl<'p, A: Array, I: Iterator<Item = A::Item>> Drop
1064 for TinyVecSplice<'p, A, I>
1065{
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
1079impl<A: Array> AsMut<[A::Item]> for TinyVec<A> {
1080 #[inline(always)]
1081 #[must_use]
1082 fn as_mut(&mut self) -> &mut [A::Item] {
1083 &mut *self
1084 }
1085}
1086
1087impl<A: Array> AsRef<[A::Item]> for TinyVec<A> {
1088 #[inline(always)]
1089 #[must_use]
1090 fn as_ref(&self) -> &[A::Item] {
1091 &*self
1092 }
1093}
1094
1095impl<A: Array> Borrow<[A::Item]> for TinyVec<A> {
1096 #[inline(always)]
1097 #[must_use]
1098 fn borrow(&self) -> &[A::Item] {
1099 &*self
1100 }
1101}
1102
1103impl<A: Array> BorrowMut<[A::Item]> for TinyVec<A> {
1104 #[inline(always)]
1105 #[must_use]
1106 fn borrow_mut(&mut self) -> &mut [A::Item] {
1107 &mut *self
1108 }
1109}
1110
1111impl<A: Array> Extend<A::Item> for TinyVec<A> {
1112 #[inline]
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
1138impl<A: Array> From<ArrayVec<A>> for TinyVec<A> {
1139 #[inline(always)]
1140 #[must_use]
1141 fn from(arr: ArrayVec<A>) -> Self {
1142 TinyVec::Inline(arr)
1143 }
1144}
1145
1146impl<A: Array> From<A> for TinyVec<A> {
1147 fn from(array: A) -> Self {
1148 TinyVec::Inline(ArrayVec::from(array))
1149 }
1150}
1151
1152impl<T, A> From<&'_ [T]> for TinyVec<A>
1153where
1154 T: Clone + Default,
1155 A: Array<Item = T>,
1156{
1157 #[inline]
1158 #[must_use]
1159 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
1168impl<T, A> From<&'_ mut [T]> for TinyVec<A>
1169where
1170 T: Clone + Default,
1171 A: Array<Item = T>,
1172{
1173 #[inline]
1174 #[must_use]
1175 fn from(slice: &mut [T]) -> Self {
1176 Self::from(&*slice)
1177 }
1178}
1179
1180impl<A: Array> FromIterator<A::Item> for TinyVec<A> {
1181 #[inline]
1182 #[must_use]
1183 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#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
1192pub 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
1199impl<A: Array> TinyVecIterator<A> {
1200 impl_mirrored! {
1201 type Mirror = TinyVecIterator;
1202 #[inline]
1204 #[must_use]
1205 pub fn as_slice(self: &Self) -> &[A::Item];
1206 }
1207}
1208
1209impl<A: Array> FusedIterator for TinyVecIterator<A> {}
1210
1211impl<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
1235impl<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
1248impl<A: Array> Debug for TinyVecIterator<A>
1249where
1250 A::Item: Debug,
1251{
1252 #[allow(clippy::missing_inline_in_public_items)]
1253 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
1254 f.debug_tuple("TinyVecIterator").field(&self.as_slice()).finish()
1255 }
1256}
1257
1258impl<A: Array> IntoIterator for TinyVec<A> {
1259 type Item = A::Item;
1260 type IntoIter = TinyVecIterator<A>;
1261 #[inline(always)]
1262 #[must_use]
1263 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
1271impl<'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]
1276 fn into_iter(self) -> Self::IntoIter {
1277 self.iter_mut()
1278 }
1279}
1280
1281impl<'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]
1286 fn into_iter(self) -> Self::IntoIter {
1287 self.iter()
1288 }
1289}
1290
1291impl<A: Array> PartialEq for TinyVec<A>
1292where
1293 A::Item: PartialEq,
1294{
1295 #[inline]
1296 #[must_use]
1297 fn eq(&self, other: &Self) -> bool {
1298 self.as_slice().eq(other.as_slice())
1299 }
1300}
1301impl<A: Array> Eq for TinyVec<A> where A::Item: Eq {}
1302
1303impl<A: Array> PartialOrd for TinyVec<A>
1304where
1305 A::Item: PartialOrd,
1306{
1307 #[inline]
1308 #[must_use]
1309 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
1310 self.as_slice().partial_cmp(other.as_slice())
1311 }
1312}
1313impl<A: Array> Ord for TinyVec<A>
1314where
1315 A::Item: Ord,
1316{
1317 #[inline]
1318 #[must_use]
1319 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
1320 self.as_slice().cmp(other.as_slice())
1321 }
1322}
1323
1324impl<A: Array> PartialEq<&A> for TinyVec<A>
1325where
1326 A::Item: PartialEq,
1327{
1328 #[inline]
1329 #[must_use]
1330 fn eq(&self, other: &&A) -> bool {
1331 self.as_slice().eq(other.as_slice())
1332 }
1333}
1334
1335impl<A: Array> PartialEq<&[A::Item]> for TinyVec<A>
1336where
1337 A::Item: PartialEq,
1338{
1339 #[inline]
1340 #[must_use]
1341 fn eq(&self, other: &&[A::Item]) -> bool {
1342 self.as_slice().eq(*other)
1343 }
1344}
1345
1346impl<A: Array> Hash for TinyVec<A>
1347where
1348 A::Item: Hash,
1349{
1350 #[inline]
1351 fn hash<H: Hasher>(&self, state: &mut H) {
1352 self.as_slice().hash(state)
1353 }
1354}
1355
1356impl<A: Array> Binary for TinyVec<A>
1361where
1362 A::Item: Binary,
1363{
1364 #[allow(clippy::missing_inline_in_public_items)]
1365 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
1383impl<A: Array> Debug for TinyVec<A>
1384where
1385 A::Item: Debug,
1386{
1387 #[allow(clippy::missing_inline_in_public_items)]
1388 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
1406impl<A: Array> Display for TinyVec<A>
1407where
1408 A::Item: Display,
1409{
1410 #[allow(clippy::missing_inline_in_public_items)]
1411 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
1429impl<A: Array> LowerExp for TinyVec<A>
1430where
1431 A::Item: LowerExp,
1432{
1433 #[allow(clippy::missing_inline_in_public_items)]
1434 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
1452impl<A: Array> LowerHex for TinyVec<A>
1453where
1454 A::Item: LowerHex,
1455{
1456 #[allow(clippy::missing_inline_in_public_items)]
1457 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
1475impl<A: Array> Octal for TinyVec<A>
1476where
1477 A::Item: Octal,
1478{
1479 #[allow(clippy::missing_inline_in_public_items)]
1480 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
1498impl<A: Array> Pointer for TinyVec<A>
1499where
1500 A::Item: Pointer,
1501{
1502 #[allow(clippy::missing_inline_in_public_items)]
1503 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
1521impl<A: Array> UpperExp for TinyVec<A>
1522where
1523 A::Item: UpperExp,
1524{
1525 #[allow(clippy::missing_inline_in_public_items)]
1526 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
1544impl<A: Array> UpperHex for TinyVec<A>
1545where
1546 A::Item: UpperHex,
1547{
1548 #[allow(clippy::missing_inline_in_public_items)]
1549 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")))]
1569struct TinyVecVisitor<A: Array>(PhantomData<A>);
1570
1571#[cfg(feature = "serde")]
1572impl<'de, A: Array> Visitor<'de> for TinyVecVisitor<A>
1573where
1574 A::Item: Deserialize<'de>,
1575{
1576 type Value = TinyVec<A>;
1577
1578 fn expecting(
1579 &self, formatter: &mut core::fmt::Formatter,
1580 ) -> core::fmt::Result {
1581 formatter.write_str("a sequence")
1582 }
1583
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}