1#![no_std]
101#![cfg_attr(docsrs, feature(doc_cfg))]
102#![cfg_attr(feature = "specialization", allow(incomplete_features))]
103#![cfg_attr(feature = "specialization", feature(specialization))]
104#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
105#![deny(missing_docs)]
106
107#[doc(hidden)]
108pub extern crate alloc;
109
110#[cfg(any(test, feature = "write"))]
111extern crate std;
112
113#[cfg(test)]
114mod tests;
115
116#[cfg(feature = "drain_keep_rest")]
117use core::mem::ManuallyDrop;
118#[cfg(feature = "malloc_size_of")]
119use malloc_size_of::{
120 MallocShallowSizeOf,
121 MallocSizeOf,
122 MallocSizeOfOps
123};
124#[cfg(feature = "serde")]
125use serde::{
126 de::{
127 Deserialize,
128 Deserializer,
129 SeqAccess,
130 Visitor
131 },
132 ser::{
133 Serialize,
134 SerializeSeq,
135 Serializer
136 }
137};
138#[cfg(feature = "write")]
139use std::io;
140#[allow(deprecated)]
141use {
142 alloc::{
143 alloc::{
144 Layout,
145 LayoutErr
146 },
147 boxed::Box,
148 vec,
149 vec::Vec
150 },
151 core::{
152 borrow::{
153 Borrow,
154 BorrowMut
155 },
156 cmp,
157 fmt,
158 hash::{
159 Hash,
160 Hasher
161 },
162 hint::unreachable_unchecked,
163 iter::{
164 FromIterator,
165 FusedIterator,
166 IntoIterator,
167 repeat
168 },
169 marker::PhantomData,
170 mem::{
171 self,
172 MaybeUninit
173 },
174 ops::{
175 self,
176 Range,
177 RangeBounds
178 },
179 ptr::{
180 self,
181 NonNull
182 },
183 slice::{
184 self,
185 SliceIndex
186 }
187 }
188};
189
190#[macro_export]
227macro_rules! smallvec {
228 (@one $x:expr) => (1usize);
230 () => (
231 $crate::SmallVec::new()
232 );
233 ($elem:expr; $n:expr) => ({
234 $crate::SmallVec::from_elem($elem, $n)
235 });
236 ($($x:expr),+$(,)?) => ({
237 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
238 let mut vec = $crate::SmallVec::new();
239 if count <= vec.inline_size() {
240 $(vec.push($x);)*
241 vec
242 } else {
243 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
244 }
245 });
246}
247
248#[cfg(feature = "const_new")]
281#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
282#[macro_export]
283macro_rules! smallvec_inline {
284 (@one $x:expr) => (1usize);
286 ($elem:expr; $n:expr) => ({
287 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
288 });
289 ($($x:expr),+ $(,)?) => ({
290 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
291 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
292 });
293}
294
295#[cfg(not(feature = "union"))]
297macro_rules! debug_unreachable {
298 () => {
299 debug_unreachable!("entered unreachable code")
300 };
301 ($e:expr) => {
302 if cfg!(debug_assertions) {
303 panic!($e);
304 } else {
305 unreachable_unchecked();
306 }
307 };
308}
309
310#[doc(hidden)]
331#[deprecated]
332pub trait ExtendFromSlice<T> {
333 fn extend_from_slice(&mut self, other: &[T]);
335}
336
337#[allow(deprecated)]
338impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
339 fn extend_from_slice(&mut self, other: &[T]) { Vec::extend_from_slice(self, other) }
340}
341
342#[derive(#[automatically_derived]impl ::core::fmt::Debug for CollectionAllocErr {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::CapacityOverflow =>
::core::fmt::Formatter::write_str(f, "CapacityOverflow"),
Self::AllocErr { layout: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllocErr layout", &__self_0),
}
}
}Debug)]
344pub enum CollectionAllocErr {
345 CapacityOverflow,
347 AllocErr {
349 layout: Layout
351 }
352}
353
354impl fmt::Display for CollectionAllocErr {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.write_fmt(format_args!("Allocation error: {0:?}", self))write!(f, "Allocation error: {:?}", self)
357 }
358}
359
360#[allow(deprecated)]
361impl From<LayoutErr> for CollectionAllocErr {
362 fn from(_: LayoutErr) -> Self { CollectionAllocErr::CapacityOverflow }
363}
364
365fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
366 match result {
367 Ok(x) => x,
368 Err(CollectionAllocErr::CapacityOverflow) => ::core::panicking::panic("capacity overflow")panic!("capacity overflow"),
369 Err(CollectionAllocErr::AllocErr {
370 layout
371 }) => alloc::alloc::handle_alloc_error(layout)
372 }
373}
374
375fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
378 let size = mem::size_of::<T>()
379 .checked_mul(n)
380 .ok_or(CollectionAllocErr::CapacityOverflow)?;
381 let align = mem::align_of::<T>();
382 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
383}
384
385unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
386 let layout = layout_array::<T>(capacity).unwrap();
388 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
389}
390
391pub struct Drain<'a, T: 'a + Array> {
398 tail_start: usize,
399 tail_len: usize,
400 iter: slice::Iter<'a, T::Item>,
401 vec: NonNull<SmallVec<T>>
402}
403
404impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
405where T::Item: fmt::Debug
406{
407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
409 }
410}
411
412unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
413unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
414
415impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
416 type Item = T::Item;
417
418 #[inline]
419 fn next(&mut self) -> Option<T::Item> {
420 self.iter
421 .next()
422 .map(|reference| unsafe { ptr::read(reference) })
423 }
424
425 #[inline]
426 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
427}
428
429impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
430 #[inline]
431 fn next_back(&mut self) -> Option<T::Item> {
432 self.iter
433 .next_back()
434 .map(|reference| unsafe { ptr::read(reference) })
435 }
436}
437
438impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
439 #[inline]
440 fn len(&self) -> usize { self.iter.len() }
441}
442
443impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
444
445impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
446 fn drop(&mut self) {
447 self.for_each(drop);
448
449 if self.tail_len > 0 {
450 unsafe {
451 let source_vec = self.vec.as_mut();
452
453 let start = source_vec.len();
455 let tail = self.tail_start;
456 if tail != start {
457 let ptr = source_vec.as_mut_ptr();
461 let src = ptr.add(tail);
462 let dst = ptr.add(start);
463 ptr::copy(src, dst, self.tail_len);
464 }
465 source_vec.set_len(start + self.tail_len);
466 }
467 }
468 }
469}
470
471#[cfg(feature = "drain_filter")]
472pub struct DrainFilter<'a, T, F>
479where
480 F: FnMut(&mut T::Item) -> bool,
481 T: Array
482{
483 vec: &'a mut SmallVec<T>,
484 idx: usize,
486 del: usize,
488 old_len: usize,
490 pred: F,
492 panic_flag: bool
498}
499
500#[cfg(feature = "drain_filter")]
501impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
502where
503 F: FnMut(&mut T::Item) -> bool,
504 T: Array,
505 T::Item: fmt::Debug
506{
507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508 f.debug_tuple("DrainFilter")
509 .field(&self.vec.as_slice())
510 .finish()
511 }
512}
513
514#[cfg(feature = "drain_filter")]
515impl<T, F> Iterator for DrainFilter<'_, T, F>
516where
517 F: FnMut(&mut T::Item) -> bool,
518 T: Array
519{
520 type Item = T::Item;
521
522 fn next(&mut self) -> Option<T::Item> {
523 unsafe {
524 while self.idx < self.old_len {
525 let i = self.idx;
526 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
527 self.panic_flag = true;
528 let drained = (self.pred)(&mut v[i]);
529 self.panic_flag = false;
530 self.idx += 1;
535 if drained {
536 self.del += 1;
537 return Some(ptr::read(&v[i]));
538 } else if self.del > 0 {
539 let del = self.del;
540 let src: *const Self::Item = &v[i];
541 let dst: *mut Self::Item = &mut v[i - del];
542 ptr::copy_nonoverlapping(src, dst, 1);
543 }
544 }
545 None
546 }
547 }
548
549 fn size_hint(&self) -> (usize, Option<usize>) { (0, Some(self.old_len - self.idx)) }
550}
551
552#[cfg(feature = "drain_filter")]
553impl<T, F> Drop for DrainFilter<'_, T, F>
554where
555 F: FnMut(&mut T::Item) -> bool,
556 T: Array
557{
558 fn drop(&mut self) {
559 struct BackshiftOnDrop<'a, 'b, T, F>
560 where
561 F: FnMut(&mut T::Item) -> bool,
562 T: Array
563 {
564 drain: &'b mut DrainFilter<'a, T, F>
565 }
566
567 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
568 where
569 F: FnMut(&mut T::Item) -> bool,
570 T: Array
571 {
572 fn drop(&mut self) {
573 unsafe {
574 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
575 let ptr = self.drain.vec.as_mut_ptr();
585 let src = ptr.add(self.drain.idx);
586 let dst = src.sub(self.drain.del);
587 let tail_len = self.drain.old_len - self.drain.idx;
588 src.copy_to(dst, tail_len);
589 }
590 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
591 }
592 }
593 }
594
595 let backshift = BackshiftOnDrop {
596 drain: self
597 };
598
599 if !backshift.drain.panic_flag {
603 backshift.drain.for_each(drop);
604 }
605 }
606}
607
608#[cfg(feature = "drain_keep_rest")]
609impl<T, F> DrainFilter<'_, T, F>
610where
611 F: FnMut(&mut T::Item) -> bool,
612 T: Array
613{
614 pub fn keep_rest(self) {
634 let mut this = ManuallyDrop::new(self);
651
652 unsafe {
653 let needs_move = mem::size_of::<T::Item>() != 0;
655
656 if needs_move && this.idx < this.old_len && this.del > 0 {
657 let ptr = this.vec.as_mut_ptr();
658 let src = ptr.add(this.idx);
659 let dst = src.sub(this.del);
660 let tail_len = this.old_len - this.idx;
661 src.copy_to(dst, tail_len);
662 }
663
664 let new_len = this.old_len - this.del;
665 this.vec.set_len(new_len);
666 }
667 }
668}
669
670#[cfg(feature = "union")]
671union SmallVecData<A: Array> {
672 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
673 heap: (NonNull<A::Item>, usize)
674}
675
676#[cfg(all(feature = "union", feature = "const_new"))]
677impl<T, const N: usize> SmallVecData<[T; N]> {
678 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
679 #[inline]
680 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
681 SmallVecData {
682 inline: core::mem::ManuallyDrop::new(inline)
683 }
684 }
685}
686
687#[cfg(feature = "union")]
688impl<A: Array> SmallVecData<A> {
689 #[inline]
690 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
691 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
692 }
693
694 #[inline]
695 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
696 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
697 }
698
699 #[inline]
700 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
701 SmallVecData {
702 inline: core::mem::ManuallyDrop::new(inline)
703 }
704 }
705
706 #[inline]
716 fn empty() -> SmallVecData<A> {
717 SmallVecData {
721 inline: unsafe { MaybeUninit::uninit().assume_init() }
722 }
723 }
724
725 #[inline]
726 unsafe fn into_inline(self) -> MaybeUninit<A> {
727 core::mem::ManuallyDrop::into_inner(self.inline)
728 }
729
730 #[inline]
731 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
732 (ConstNonNull(self.heap.0), self.heap.1)
733 }
734
735 #[inline]
736 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
737 let h = &mut self.heap;
738 (h.0, &mut h.1)
739 }
740
741 #[inline]
742 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
743 SmallVecData {
744 heap: (ptr, len)
745 }
746 }
747}
748
749#[cfg(not(feature = "union"))]
750enum SmallVecData<A: Array> {
751 Inline(MaybeUninit<A>),
752 Heap {
754 ptr: NonNull<A::Item>,
759 len: usize
760 }
761}
762
763#[cfg(all(not(feature = "union"), feature = "const_new"))]
764impl<T, const N: usize> SmallVecData<[T; N]> {
765 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
766 #[inline]
767 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self { SmallVecData::Inline(inline) }
768}
769
770#[cfg(not(feature = "union"))]
771impl<A: Array> SmallVecData<A> {
772 #[inline]
773 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
774 match self {
775 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
776 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!()
777 }
778 }
779
780 #[inline]
781 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
782 match self {
783 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
784 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!()
785 }
786 }
787
788 #[inline]
789 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> { SmallVecData::Inline(inline) }
790
791 #[inline]
793 fn empty() -> SmallVecData<A> {
794 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
798 }
799
800 #[inline]
801 unsafe fn into_inline(self) -> MaybeUninit<A> {
802 match self {
803 SmallVecData::Inline(a) => a,
804 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!()
805 }
806 }
807
808 #[inline]
809 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
810 match self {
811 SmallVecData::Heap {
812 ptr,
813 len
814 } => (ConstNonNull(*ptr), *len),
815 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!()
816 }
817 }
818
819 #[inline]
820 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
821 match self {
822 SmallVecData::Heap {
823 ptr,
824 len
825 } => (*ptr, len),
826 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!()
827 }
828 }
829
830 #[inline]
831 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
832 SmallVecData::Heap {
833 ptr,
834 len
835 }
836 }
837}
838
839unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
840unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
841
842pub struct SmallVec<A: Array> {
890 capacity: usize,
897 data: SmallVecData<A>,
898 _marker: PhantomData<A::Item>
901}
902
903impl<A: Array> SmallVec<A> {
904 #[inline]
906 pub fn new() -> SmallVec<A> {
907 if !(mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() &&
mem::align_of::<A>() >= mem::align_of::<A::Item>()) {
::core::panicking::panic("assertion failed: mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() &&\n mem::align_of::<A>() >= mem::align_of::<A::Item>()")
};assert!(
910 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
911 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
912 );
913 SmallVec {
914 capacity: 0,
915 data: SmallVecData::empty(),
916 _marker: PhantomData
917 }
918 }
919
920 #[inline]
935 pub fn with_capacity(n: usize) -> Self {
936 let mut v = SmallVec::new();
937 v.reserve_exact(n);
938 v
939 }
940
941 #[inline]
955 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
956 if vec.capacity() <= Self::inline_capacity() {
957 unsafe {
960 let mut data = SmallVecData::<A>::empty();
961 let len = vec.len();
962 vec.set_len(0);
963 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
964
965 SmallVec {
966 capacity: len,
967 data,
968 _marker: PhantomData
969 }
970 }
971 } else {
972 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
973 mem::forget(vec);
974 let ptr = NonNull::new(ptr)
975 .expect("Cannot be null by `Vec` invariant");
977
978 SmallVec {
979 capacity: cap,
980 data: SmallVecData::from_heap(ptr, len),
981 _marker: PhantomData
982 }
983 }
984 }
985
986 #[inline]
998 pub fn from_buf(buf: A) -> SmallVec<A> {
999 SmallVec {
1000 capacity: A::size(),
1001 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
1002 _marker: PhantomData
1003 }
1004 }
1005
1006 #[inline]
1019 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
1020 if !(len <= A::size()) {
::core::panicking::panic("assertion failed: len <= A::size()")
};assert!(len <= A::size());
1021 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
1022 }
1023
1024 #[inline]
1041 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
1042 SmallVec {
1043 capacity: len,
1044 data: SmallVecData::from_inline(buf),
1045 _marker: PhantomData
1046 }
1047 }
1048
1049 pub unsafe fn set_len(&mut self, new_len: usize) {
1055 let (_, len_ptr, _) = self.triple_mut();
1056 *len_ptr = new_len;
1057 }
1058
1059 #[inline]
1061 fn inline_capacity() -> usize {
1062 if mem::size_of::<A::Item>() > 0 {
1063 A::size()
1064 } else {
1065 #[allow(deprecated)]
1078 core::usize::MAX
1079 }
1080 }
1081
1082 #[inline]
1084 pub fn inline_size(&self) -> usize { Self::inline_capacity() }
1085
1086 #[inline]
1088 pub fn len(&self) -> usize { self.triple().1 }
1089
1090 #[inline]
1092 pub fn is_empty(&self) -> bool { self.len() == 0 }
1093
1094 #[inline]
1096 pub fn capacity(&self) -> usize { self.triple().2 }
1097
1098 #[inline]
1102 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1103 unsafe {
1104 if self.spilled() {
1105 let (ptr, len) = self.data.heap();
1106 (ptr, len, self.capacity)
1107 } else {
1108 (self.data.inline(), self.capacity, Self::inline_capacity())
1109 }
1110 }
1111 }
1112
1113 #[inline]
1115 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1116 unsafe {
1117 if self.spilled() {
1118 let (ptr, len_ptr) = self.data.heap_mut();
1119 (ptr, len_ptr, self.capacity)
1120 } else {
1121 (
1122 self.data.inline_mut(),
1123 &mut self.capacity,
1124 Self::inline_capacity()
1125 )
1126 }
1127 }
1128 }
1129
1130 #[inline]
1133 pub fn spilled(&self) -> bool { self.capacity > Self::inline_capacity() }
1134
1135 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1149 where R: RangeBounds<usize> {
1150 use core::ops::Bound::*;
1151
1152 let len = self.len();
1153 let start = match range.start_bound() {
1154 Included(&n) => n,
1155 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1156 Unbounded => 0
1157 };
1158 let end = match range.end_bound() {
1159 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1160 Excluded(&n) => n,
1161 Unbounded => len
1162 };
1163
1164 if !(start <= end) {
::core::panicking::panic("assertion failed: start <= end")
};assert!(start <= end);
1165 if !(end <= len) { ::core::panicking::panic("assertion failed: end <= len") };assert!(end <= len);
1166
1167 unsafe {
1168 self.set_len(start);
1169
1170 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1171
1172 Drain {
1173 tail_start: end,
1174 tail_len: len - end,
1175 iter: range_slice.iter(),
1176 vec: NonNull::new_unchecked(self as *mut _)
1179 }
1180 }
1181 }
1182
1183 #[cfg(feature = "drain_filter")]
1184 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1241 where F: FnMut(&mut A::Item) -> bool {
1242 let old_len = self.len();
1243
1244 unsafe {
1246 self.set_len(0);
1247 }
1248
1249 DrainFilter {
1250 vec: self,
1251 idx: 0,
1252 del: 0,
1253 old_len,
1254 pred: filter,
1255 panic_flag: false
1256 }
1257 }
1258
1259 #[inline]
1261 pub fn push(&mut self, value: A::Item) {
1262 unsafe {
1263 if self.spilled() {
1264 let (mut ptr, mut len_ptr) = self.data.heap_mut();
1265 if *len_ptr == self.capacity {
1266 self.reserve_one_unchecked();
1267 let (heap_ptr, heap_len) = self.data.heap_mut();
1268 ptr = heap_ptr;
1269 len_ptr = heap_len;
1270 }
1271 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1272 *len_ptr += 1;
1273 } else {
1274 let mut ptr = self.data.inline_mut();
1275 let mut len_ptr = &mut self.capacity;
1276 if *len_ptr == Self::inline_capacity() {
1277 self.reserve_one_unchecked();
1278 let (heap_ptr, heap_len) = self.data.heap_mut();
1279 ptr = heap_ptr;
1280 len_ptr = heap_len;
1281 }
1282 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1283 *len_ptr += 1;
1284 };
1285 }
1286 }
1287
1288 #[inline]
1291 pub fn pop(&mut self) -> Option<A::Item> {
1292 unsafe {
1293 let (ptr, len_ptr, _) = self.triple_mut();
1294 let ptr: *const _ = ptr.as_ptr();
1295 if *len_ptr == 0 {
1296 return None;
1297 }
1298 let last_index = *len_ptr - 1;
1299 *len_ptr = last_index;
1300 Some(ptr::read(ptr.add(last_index)))
1301 }
1302 }
1303
1304 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1317 where B: Array<Item = A::Item> {
1318 self.extend(other.drain(..))
1319 }
1320
1321 pub fn grow(&mut self, new_cap: usize) { infallible(self.try_grow(new_cap)) }
1326
1327 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1331 unsafe {
1332 let unspilled = !self.spilled();
1333 let (ptr, &mut len, cap) = self.triple_mut();
1334 if new_cap < len {
1335 return Ok(());
1336 }
1337 if new_cap <= Self::inline_capacity() {
1338 if unspilled {
1339 return Ok(());
1340 }
1341 self.data = SmallVecData::empty();
1342 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1343 self.capacity = len;
1344 deallocate(ptr, cap);
1345 } else if new_cap != cap {
1346 let layout = layout_array::<A::Item>(new_cap)?;
1347 if true {
if !(layout.size() > 0) {
::core::panicking::panic("assertion failed: layout.size() > 0")
};
};debug_assert!(layout.size() > 0);
1348 let new_alloc;
1349 if unspilled {
1350 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1351 .ok_or(CollectionAllocErr::AllocErr {
1352 layout
1353 })?
1354 .cast();
1355 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1356 } else {
1357 let old_layout = layout_array::<A::Item>(cap)?;
1360
1361 let new_ptr =
1362 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1363 new_alloc = NonNull::new(new_ptr)
1364 .ok_or(CollectionAllocErr::AllocErr {
1365 layout
1366 })?
1367 .cast();
1368 }
1369 self.data = SmallVecData::from_heap(new_alloc, len);
1370 self.capacity = new_cap;
1371 }
1372 Ok(())
1373 }
1374 }
1375
1376 #[inline]
1382 pub fn reserve(&mut self, additional: usize) { infallible(self.try_reserve(additional)) }
1383
1384 #[cold]
1387 fn reserve_one_unchecked(&mut self) {
1388 if true {
{
match (&self.len(), &self.capacity()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.len(), self.capacity());
1389 let new_cap = self
1390 .len()
1391 .checked_add(1)
1392 .and_then(usize::checked_next_power_of_two)
1393 .expect("capacity overflow");
1394 infallible(self.try_grow(new_cap))
1395 }
1396
1397 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1401 let (_, &mut len, cap) = self.triple_mut();
1404 if cap - len >= additional {
1405 return Ok(());
1406 }
1407 let new_cap = len
1408 .checked_add(additional)
1409 .and_then(usize::checked_next_power_of_two)
1410 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1411 self.try_grow(new_cap)
1412 }
1413
1414 pub fn reserve_exact(&mut self, additional: usize) {
1419 infallible(self.try_reserve_exact(additional))
1420 }
1421
1422 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1425 let (_, &mut len, cap) = self.triple_mut();
1426 if cap - len >= additional {
1427 return Ok(());
1428 }
1429 let new_cap = len
1430 .checked_add(additional)
1431 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1432 self.try_grow(new_cap)
1433 }
1434
1435 pub fn shrink_to_fit(&mut self) {
1440 if !self.spilled() {
1441 return;
1442 }
1443 let len = self.len();
1444 if self.inline_size() >= len {
1445 unsafe {
1446 let (ptr, len) = self.data.heap();
1447 self.data = SmallVecData::empty();
1448 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1449 deallocate(ptr.0, self.capacity);
1450 self.capacity = len;
1451 }
1452 } else if self.capacity() > len {
1453 self.grow(len);
1454 }
1455 }
1456
1457 pub fn truncate(&mut self, len: usize) {
1466 unsafe {
1467 let (ptr, len_ptr, _) = self.triple_mut();
1468 let ptr = ptr.as_ptr();
1469 while len < *len_ptr {
1470 let last_index = *len_ptr - 1;
1471 *len_ptr = last_index;
1472 ptr::drop_in_place(ptr.add(last_index));
1473 }
1474 }
1475 }
1476
1477 pub fn as_slice(&self) -> &[A::Item] { self }
1481
1482 pub fn as_mut_slice(&mut self) -> &mut [A::Item] { self }
1486
1487 #[inline]
1494 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1495 let len = self.len();
1496 self.swap(len - 1, index);
1497 self.pop()
1498 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1499 }
1500
1501 #[inline]
1503 pub fn clear(&mut self) { self.truncate(0); }
1504
1505 pub fn remove(&mut self, index: usize) -> A::Item {
1510 unsafe {
1511 let (ptr, len_ptr, _) = self.triple_mut();
1512 let len = *len_ptr;
1513 if !(index < len) {
::core::panicking::panic("assertion failed: index < len")
};assert!(index < len);
1514 *len_ptr = len - 1;
1515 let ptr = ptr.as_ptr().add(index);
1516 let item = ptr::read(ptr);
1517 ptr::copy(ptr.add(1), ptr, len - index - 1);
1518 item
1519 }
1520 }
1521
1522 pub fn insert(&mut self, index: usize, element: A::Item) {
1527 unsafe {
1528 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1529 if *len_ptr == cap {
1530 self.reserve_one_unchecked();
1531 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1532 ptr = heap_ptr;
1533 len_ptr = heap_len_ptr;
1534 }
1535 let mut ptr = ptr.as_ptr();
1536 let len = *len_ptr;
1537 if index > len {
1538 ::core::panicking::panic("index exceeds length");panic!("index exceeds length");
1539 }
1540 ptr = ptr.add(index);
1542 if index < len {
1543 ptr::copy(ptr, ptr.add(1), len - index);
1545 }
1546 *len_ptr = len + 1;
1547 ptr::write(ptr, element);
1548 }
1549 }
1550
1551 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1554 let mut iter = iterable.into_iter();
1555 if index == self.len() {
1556 return self.extend(iter);
1557 }
1558
1559 let (lower_size_bound, _) = iter.size_hint();
1560 #[allow(deprecated)]
1561 {
1562 if !(lower_size_bound <= core::isize::MAX as usize) {
::core::panicking::panic("assertion failed: lower_size_bound <= core::isize::MAX as usize")
}assert!(lower_size_bound <= core::isize::MAX as usize)
1563 } if !(index + lower_size_bound >= index) {
::core::panicking::panic("assertion failed: index + lower_size_bound >= index")
};assert!(index + lower_size_bound >= index); let mut num_added = 0;
1567 let old_len = self.len();
1568 if !(index <= old_len) {
::core::panicking::panic("assertion failed: index <= old_len")
};assert!(index <= old_len);
1569
1570 unsafe {
1571 self.reserve(lower_size_bound);
1573 let start = self.as_mut_ptr();
1574 let ptr = start.add(index);
1575
1576 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1578
1579 self.set_len(0);
1582 let mut guard = DropOnPanic {
1583 start,
1584 skip: index..(index + lower_size_bound),
1585 len: old_len + lower_size_bound
1586 };
1587
1588 let start = self.as_mut_ptr();
1591 let ptr = start.add(index);
1592
1593 while num_added < lower_size_bound {
1594 let element = match iter.next() {
1595 Some(x) => x,
1596 None => break
1597 };
1598 let cur = ptr.add(num_added);
1599 ptr::write(cur, element);
1600 guard.skip.start += 1;
1601 num_added += 1;
1602 }
1603
1604 if num_added < lower_size_bound {
1605 ptr::copy(
1608 ptr.add(lower_size_bound),
1609 ptr.add(num_added),
1610 old_len - index
1611 );
1612 }
1613 self.set_len(old_len + num_added);
1616 mem::forget(guard);
1617 }
1618
1619 for element in iter {
1621 self.insert(index + num_added, element);
1622 num_added += 1;
1623 }
1624
1625 struct DropOnPanic<T> {
1626 start: *mut T,
1627 skip: Range<usize>, len: usize
1629 }
1630
1631 impl<T> Drop for DropOnPanic<T> {
1632 fn drop(&mut self) {
1633 for i in 0..self.len {
1634 if !self.skip.contains(&i) {
1635 unsafe {
1636 ptr::drop_in_place(self.start.add(i));
1637 }
1638 }
1639 }
1640 }
1641 }
1642 }
1643
1644 pub fn into_vec(mut self) -> Vec<A::Item> {
1647 if self.spilled() {
1648 unsafe {
1649 let (ptr, &mut len) = self.data.heap_mut();
1650 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1651 mem::forget(self);
1652 v
1653 }
1654 } else {
1655 self.into_iter().collect()
1656 }
1657 }
1658
1659 pub fn into_boxed_slice(self) -> Box<[A::Item]> { self.into_vec().into_boxed_slice() }
1664
1665 pub fn into_inner(self) -> Result<A, Self> {
1672 if self.spilled() || self.len() != A::size() {
1673 Err(self)
1675 } else {
1676 unsafe {
1677 let data = ptr::read(&self.data);
1678 mem::forget(self);
1679 Ok(data.into_inline().assume_init())
1680 }
1681 }
1682 }
1683
1684 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1690 let original_len = self.len();
1691
1692 if original_len == 0 {
1693 return;
1696 }
1697
1698 struct PanicGuard<'a, A: Array> {
1710 v: &'a mut SmallVec<A>,
1711 read: usize,
1712 write: usize,
1713 original_len: usize
1714 }
1715
1716 impl<A: Array> Drop for PanicGuard<'_, A> {
1717 #[cold]
1718 fn drop(&mut self) {
1719 let remaining = self.original_len - self.read;
1720 unsafe {
1723 let ptr = self.v.as_mut_ptr();
1724 ptr::copy(ptr.add(self.read), ptr.add(self.write), remaining);
1725 }
1726 unsafe {
1729 self.v.set_len(self.write + remaining);
1730 }
1731 }
1732 }
1733
1734 let mut read = 0;
1735 loop {
1736 let cur = unsafe { self.get_unchecked_mut(read) };
1738 if !f(cur) {
1739 break;
1740 }
1741 read += 1;
1742 if read == original_len {
1743 return;
1745 }
1746 }
1747
1748 let mut g = PanicGuard {
1752 v: self,
1753 read: read + 1,
1754 write: read,
1755 original_len
1756 };
1757 unsafe { ptr::drop_in_place(g.v.as_mut_ptr().add(read)) }
1759
1760 let ptr = g.v.as_mut_ptr();
1761 while g.read < g.original_len {
1762 let cur = unsafe { &mut *ptr.add(g.read) };
1764 if !f(cur) {
1765 g.read += 1;
1768 unsafe { ptr::drop_in_place(cur) };
1770 } else {
1771 unsafe {
1775 let hole = ptr.add(g.write);
1776 ptr::copy_nonoverlapping(cur, hole, 1);
1777 }
1778 g.write += 1;
1779 g.read += 1;
1780 }
1781 }
1782
1783 unsafe { g.v.set_len(g.write) };
1787 core::mem::forget(g);
1788 }
1789
1790 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) { self.retain(f) }
1796
1797 pub fn dedup(&mut self)
1799 where A::Item: PartialEq<A::Item> {
1800 self.dedup_by(|a, b| a == b);
1801 }
1802
1803 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1806 where F: FnMut(&mut A::Item, &mut A::Item) -> bool {
1807 let len = self.len();
1810 if len <= 1 {
1811 return;
1812 }
1813
1814 let ptr = self.as_mut_ptr();
1815 let mut w: usize = 1;
1816
1817 unsafe {
1818 for r in 1..len {
1819 let p_r = ptr.add(r);
1820 let p_wm1 = ptr.add(w - 1);
1821 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1822 if r != w {
1823 let p_w = p_wm1.add(1);
1824 mem::swap(&mut *p_r, &mut *p_w);
1825 }
1826 w += 1;
1827 }
1828 }
1829 }
1830
1831 self.truncate(w);
1832 }
1833
1834 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1836 where
1837 F: FnMut(&mut A::Item) -> K,
1838 K: PartialEq<K>
1839 {
1840 self.dedup_by(|a, b| key(a) == key(b));
1841 }
1842
1843 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1874 where F: FnMut() -> A::Item {
1875 let old_len = self.len();
1876 if old_len < new_len {
1877 let mut f = f;
1878 let additional = new_len - old_len;
1879 self.reserve(additional);
1880 for _ in 0..additional {
1881 self.push(f());
1882 }
1883 } else if old_len > new_len {
1884 self.truncate(new_len);
1885 }
1886 }
1887
1888 #[inline]
1956 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1957 let ptr = unsafe {
1960 if true {
if !!ptr.is_null() {
::core::panicking::panic("Called `from_raw_parts` with null pointer.")
};
};debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1961 NonNull::new_unchecked(ptr)
1962 };
1963 if !(capacity > Self::inline_capacity()) {
::core::panicking::panic("assertion failed: capacity > Self::inline_capacity()")
};assert!(capacity > Self::inline_capacity());
1964 SmallVec {
1965 capacity,
1966 data: SmallVecData::from_heap(ptr, length),
1967 _marker: PhantomData
1968 }
1969 }
1970
1971 pub fn as_ptr(&self) -> *const A::Item {
1973 self.triple().0.as_ptr()
1977 }
1978
1979 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1981 self.triple_mut().0.as_ptr()
1985 }
1986}
1987
1988impl<A: Array> SmallVec<A>
1989where A::Item: Copy
1990{
1991 pub fn from_slice(slice: &[A::Item]) -> Self {
1996 let len = slice.len();
1997 if len <= Self::inline_capacity() {
1998 SmallVec {
1999 capacity: len,
2000 data: SmallVecData::from_inline(unsafe {
2001 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
2002 ptr::copy_nonoverlapping(
2003 slice.as_ptr(),
2004 data.as_mut_ptr() as *mut A::Item,
2005 len
2006 );
2007 data
2008 }),
2009 _marker: PhantomData
2010 }
2011 } else {
2012 let mut b = slice.to_vec();
2013 let cap = b.capacity();
2014 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
2015 mem::forget(b);
2016 SmallVec {
2017 capacity: cap,
2018 data: SmallVecData::from_heap(ptr, len),
2019 _marker: PhantomData
2020 }
2021 }
2022 }
2023
2024 #[inline]
2029 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
2030 self.reserve(slice.len());
2031
2032 let len = self.len();
2033 if !(index <= len) {
::core::panicking::panic("assertion failed: index <= len")
};assert!(index <= len);
2034
2035 unsafe {
2036 let slice_ptr = slice.as_ptr();
2037 let ptr = self.as_mut_ptr().add(index);
2038 ptr::copy(ptr, ptr.add(slice.len()), len - index);
2039 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
2040 self.set_len(len + slice.len());
2041 }
2042 }
2043
2044 #[inline]
2048 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
2049 let len = self.len();
2050 self.insert_from_slice(len, slice);
2051 }
2052}
2053
2054impl<A: Array> SmallVec<A>
2055where A::Item: Clone
2056{
2057 pub fn resize(&mut self, len: usize, value: A::Item) {
2064 let old_len = self.len();
2065
2066 if len > old_len {
2067 self.extend(repeat(value).take(len - old_len));
2068 } else {
2069 self.truncate(len);
2070 }
2071 }
2072
2073 pub fn from_elem(elem: A::Item, n: usize) -> Self {
2081 if n > Self::inline_capacity() {
2082 ::alloc::vec::from_elem_global(elem, n)vec![elem; n].into()
2083 } else {
2084 let mut v = SmallVec::<A>::new();
2085 unsafe {
2086 let (ptr, len_ptr, _) = v.triple_mut();
2087 let ptr = ptr.as_ptr();
2088 let mut local_len = SetLenOnDrop::new(len_ptr);
2089
2090 for i in 0..n {
2091 ::core::ptr::write(ptr.add(i), elem.clone());
2092 local_len.increment_len(1);
2093 }
2094 }
2095 v
2096 }
2097 }
2098}
2099
2100impl<A: Array> ops::Deref for SmallVec<A> {
2101 type Target = [A::Item];
2102
2103 #[inline]
2104 fn deref(&self) -> &[A::Item] {
2105 unsafe {
2106 let (ptr, len, _) = self.triple();
2107 slice::from_raw_parts(ptr.as_ptr(), len)
2108 }
2109 }
2110}
2111
2112impl<A: Array> ops::DerefMut for SmallVec<A> {
2113 #[inline]
2114 fn deref_mut(&mut self) -> &mut [A::Item] {
2115 unsafe {
2116 let (ptr, &mut len, _) = self.triple_mut();
2117 slice::from_raw_parts_mut(ptr.as_ptr(), len)
2118 }
2119 }
2120}
2121
2122impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
2123 #[inline]
2124 fn as_ref(&self) -> &[A::Item] { self }
2125}
2126
2127impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
2128 #[inline]
2129 fn as_mut(&mut self) -> &mut [A::Item] { self }
2130}
2131
2132impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
2133 #[inline]
2134 fn borrow(&self) -> &[A::Item] { self }
2135}
2136
2137impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
2138 #[inline]
2139 fn borrow_mut(&mut self) -> &mut [A::Item] { self }
2140}
2141
2142#[cfg(feature = "write")]
2143#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
2144impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
2145 #[inline]
2146 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2147 self.extend_from_slice(buf);
2148 Ok(buf.len())
2149 }
2150
2151 #[inline]
2152 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2153 self.extend_from_slice(buf);
2154 Ok(())
2155 }
2156
2157 #[inline]
2158 fn flush(&mut self) -> io::Result<()> { Ok(()) }
2159}
2160
2161#[cfg(feature = "serde")]
2162#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2163impl<A: Array> Serialize for SmallVec<A>
2164where A::Item: Serialize
2165{
2166 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2167 let mut state = serializer.serialize_seq(Some(self.len()))?;
2168 for item in self {
2169 state.serialize_element(&item)?;
2170 }
2171 state.end()
2172 }
2173}
2174
2175#[cfg(feature = "serde")]
2176#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2177impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2178where A::Item: Deserialize<'de>
2179{
2180 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2181 deserializer.deserialize_seq(SmallVecVisitor {
2182 phantom: PhantomData
2183 })
2184 }
2185}
2186
2187#[cfg(feature = "serde")]
2188struct SmallVecVisitor<A> {
2189 phantom: PhantomData<A>
2190}
2191
2192#[cfg(feature = "serde")]
2193impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2194where A::Item: Deserialize<'de>
2195{
2196 type Value = SmallVec<A>;
2197
2198 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2199 formatter.write_str("a sequence")
2200 }
2201
2202 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2203 where B: SeqAccess<'de> {
2204 use serde::de::Error;
2205 let len = seq.size_hint().unwrap_or(0);
2206 let mut values = SmallVec::new();
2207 values.try_reserve(len).map_err(B::Error::custom)?;
2208
2209 while let Some(value) = seq.next_element()? {
2210 values.push(value);
2211 }
2212
2213 Ok(values)
2214 }
2215}
2216
2217#[cfg(feature = "malloc_size_of")]
2218impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2219 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2220 if self.spilled() {
2221 unsafe { ops.malloc_size_of(self.as_ptr()) }
2222 } else {
2223 0
2224 }
2225 }
2226}
2227
2228#[cfg(feature = "malloc_size_of")]
2229impl<A> MallocSizeOf for SmallVec<A>
2230where
2231 A: Array,
2232 A::Item: MallocSizeOf
2233{
2234 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2235 let mut n = self.shallow_size_of(ops);
2236 for elem in self.iter() {
2237 n += elem.size_of(ops);
2238 }
2239 n
2240 }
2241}
2242
2243#[cfg(feature = "specialization")]
2244trait SpecFrom<A: Array, S> {
2245 fn spec_from(slice: S) -> SmallVec<A>;
2246}
2247
2248#[cfg(feature = "specialization")]
2249mod specialization;
2250
2251#[cfg(feature = "arbitrary")]
2252mod arbitrary;
2253
2254#[cfg(feature = "specialization")]
2255impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2256where A::Item: Copy
2257{
2258 #[inline]
2259 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> { SmallVec::from_slice(slice) }
2260}
2261
2262impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2263where A::Item: Clone
2264{
2265 #[cfg(not(feature = "specialization"))]
2266 #[inline]
2267 fn from(slice: &'a [A::Item]) -> SmallVec<A> { slice.iter().cloned().collect() }
2268
2269 #[cfg(feature = "specialization")]
2270 #[inline]
2271 fn from(slice: &'a [A::Item]) -> SmallVec<A> { SmallVec::spec_from(slice) }
2272}
2273
2274impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2275 #[inline]
2276 fn from(vec: Vec<A::Item>) -> SmallVec<A> { SmallVec::from_vec(vec) }
2277}
2278
2279impl<A: Array> From<A> for SmallVec<A> {
2280 #[inline]
2281 fn from(array: A) -> SmallVec<A> { SmallVec::from_buf(array) }
2282}
2283
2284impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2285 type Output = I::Output;
2286
2287 fn index(&self, index: I) -> &I::Output { &(**self)[index] }
2288}
2289
2290impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2291 fn index_mut(&mut self, index: I) -> &mut I::Output { &mut (&mut **self)[index] }
2292}
2293
2294#[allow(deprecated)]
2295impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2296where A::Item: Copy
2297{
2298 fn extend_from_slice(&mut self, other: &[A::Item]) { SmallVec::extend_from_slice(self, other) }
2299}
2300
2301impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2302 #[inline]
2303 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2304 let mut v = SmallVec::new();
2305 v.extend(iterable);
2306 v
2307 }
2308}
2309
2310impl<A: Array> Extend<A::Item> for SmallVec<A> {
2311 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2312 let mut iter = iterable.into_iter();
2313 let (lower_size_bound, _) = iter.size_hint();
2314 self.reserve(lower_size_bound);
2315
2316 unsafe {
2317 let (ptr, len_ptr, cap) = self.triple_mut();
2318 let ptr = ptr.as_ptr();
2319 let mut len = SetLenOnDrop::new(len_ptr);
2320 while len.get() < cap {
2321 if let Some(out) = iter.next() {
2322 ptr::write(ptr.add(len.get()), out);
2323 len.increment_len(1);
2324 } else {
2325 return;
2326 }
2327 }
2328 }
2329
2330 for elem in iter {
2331 self.push(elem);
2332 }
2333 }
2334}
2335
2336impl<A: Array> fmt::Debug for SmallVec<A>
2337where A::Item: fmt::Debug
2338{
2339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2340 f.debug_list().entries(self.iter()).finish()
2341 }
2342}
2343
2344impl<A: Array> Default for SmallVec<A> {
2345 #[inline]
2346 fn default() -> SmallVec<A> { SmallVec::new() }
2347}
2348
2349#[cfg(feature = "may_dangle")]
2350unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2351 fn drop(&mut self) {
2352 unsafe {
2353 if self.spilled() {
2354 let (ptr, &mut len) = self.data.heap_mut();
2355 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2356 } else {
2357 ptr::drop_in_place(&mut self[..]);
2358 }
2359 }
2360 }
2361}
2362
2363#[cfg(not(feature = "may_dangle"))]
2364impl<A: Array> Drop for SmallVec<A> {
2365 fn drop(&mut self) {
2366 unsafe {
2367 if self.spilled() {
2368 let (ptr, &mut len) = self.data.heap_mut();
2369 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2370 } else {
2371 ptr::drop_in_place(&mut self[..]);
2372 }
2373 }
2374 }
2375}
2376
2377impl<A: Array> Clone for SmallVec<A>
2378where A::Item: Clone
2379{
2380 #[inline]
2381 fn clone(&self) -> SmallVec<A> { SmallVec::from(self.as_slice()) }
2382
2383 fn clone_from(&mut self, source: &Self) {
2384 self.truncate(source.len());
2388
2389 let (init, tail) = source.split_at(self.len());
2392
2393 self.clone_from_slice(init);
2395 self.extend(tail.iter().cloned());
2396 }
2397}
2398
2399impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2400where A::Item: PartialEq<B::Item>
2401{
2402 #[inline]
2403 fn eq(&self, other: &SmallVec<B>) -> bool { self[..] == other[..] }
2404}
2405
2406impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2407
2408impl<A: Array> PartialOrd for SmallVec<A>
2409where A::Item: PartialOrd
2410{
2411 #[inline]
2412 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2413 PartialOrd::partial_cmp(&**self, &**other)
2414 }
2415}
2416
2417impl<A: Array> Ord for SmallVec<A>
2418where A::Item: Ord
2419{
2420 #[inline]
2421 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering { Ord::cmp(&**self, &**other) }
2422}
2423
2424impl<A: Array> Hash for SmallVec<A>
2425where A::Item: Hash
2426{
2427 fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state) }
2428}
2429
2430unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2431
2432pub struct IntoIter<A: Array> {
2438 data: SmallVec<A>,
2439 current: usize,
2440 end: usize
2441}
2442
2443impl<A: Array> fmt::Debug for IntoIter<A>
2444where A::Item: fmt::Debug
2445{
2446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2447 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2448 }
2449}
2450
2451impl<A: Array + Clone> Clone for IntoIter<A>
2452where A::Item: Clone
2453{
2454 fn clone(&self) -> IntoIter<A> { SmallVec::from(self.as_slice()).into_iter() }
2455}
2456
2457impl<A: Array> Drop for IntoIter<A> {
2458 fn drop(&mut self) { for _ in self {} }
2459}
2460
2461impl<A: Array> Iterator for IntoIter<A> {
2462 type Item = A::Item;
2463
2464 #[inline]
2465 fn next(&mut self) -> Option<A::Item> {
2466 if self.current == self.end {
2467 None
2468 } else {
2469 unsafe {
2470 let current = self.current;
2471 self.current += 1;
2472 Some(ptr::read(self.data.as_ptr().add(current)))
2473 }
2474 }
2475 }
2476
2477 #[inline]
2478 fn size_hint(&self) -> (usize, Option<usize>) {
2479 let size = self.end - self.current;
2480 (size, Some(size))
2481 }
2482}
2483
2484impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2485 #[inline]
2486 fn next_back(&mut self) -> Option<A::Item> {
2487 if self.current == self.end {
2488 None
2489 } else {
2490 unsafe {
2491 self.end -= 1;
2492 Some(ptr::read(self.data.as_ptr().add(self.end)))
2493 }
2494 }
2495 }
2496}
2497
2498impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2499impl<A: Array> FusedIterator for IntoIter<A> {}
2500
2501impl<A: Array> IntoIter<A> {
2502 pub fn as_slice(&self) -> &[A::Item] {
2504 let len = self.end - self.current;
2505 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2506 }
2507
2508 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2510 let len = self.end - self.current;
2511 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2512 }
2513}
2514
2515impl<A: Array> IntoIterator for SmallVec<A> {
2516 type IntoIter = IntoIter<A>;
2517 type Item = A::Item;
2518
2519 fn into_iter(mut self) -> Self::IntoIter {
2520 unsafe {
2521 let len = self.len();
2524 self.set_len(0);
2525 IntoIter {
2526 data: self,
2527 current: 0,
2528 end: len
2529 }
2530 }
2531 }
2532}
2533
2534impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2535 type IntoIter = slice::Iter<'a, A::Item>;
2536 type Item = &'a A::Item;
2537
2538 fn into_iter(self) -> Self::IntoIter { self.iter() }
2539}
2540
2541impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2542 type IntoIter = slice::IterMut<'a, A::Item>;
2543 type Item = &'a mut A::Item;
2544
2545 fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
2546}
2547
2548pub unsafe trait Array {
2550 type Item;
2552 fn size() -> usize;
2554}
2555
2556struct SetLenOnDrop<'a> {
2560 len: &'a mut usize,
2561 local_len: usize
2562}
2563
2564impl<'a> SetLenOnDrop<'a> {
2565 #[inline]
2566 fn new(len: &'a mut usize) -> Self {
2567 SetLenOnDrop {
2568 local_len: *len,
2569 len
2570 }
2571 }
2572
2573 #[inline]
2574 fn get(&self) -> usize { self.local_len }
2575
2576 #[inline]
2577 fn increment_len(&mut self, increment: usize) { self.local_len += increment; }
2578}
2579
2580impl<'a> Drop for SetLenOnDrop<'a> {
2581 #[inline]
2582 fn drop(&mut self) { *self.len = self.local_len; }
2583}
2584
2585#[cfg(feature = "const_new")]
2586impl<T, const N: usize> SmallVec<[T; N]> {
2587 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2592 #[inline]
2593 pub const fn new_const() -> Self {
2594 SmallVec {
2595 capacity: 0,
2596 data: SmallVecData::from_const(MaybeUninit::uninit()),
2597 _marker: PhantomData
2598 }
2599 }
2600
2601 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2608 #[inline]
2609 pub const fn from_const(items: [T; N]) -> Self {
2610 SmallVec {
2611 capacity: N,
2612 data: SmallVecData::from_const(MaybeUninit::new(items)),
2613 _marker: PhantomData
2614 }
2615 }
2616
2617 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2625 #[inline]
2626 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2627 SmallVec {
2628 capacity: len,
2629 data: SmallVecData::from_const(MaybeUninit::new(items)),
2630 _marker: PhantomData
2631 }
2632 }
2633}
2634
2635#[cfg(feature = "const_generics")]
2636#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2637unsafe impl<T, const N: usize> Array for [T; N] {
2638 type Item = T;
2639
2640 #[inline]
2641 fn size() -> usize { N }
2642}
2643
2644#[cfg(not(feature = "const_generics"))]
2645macro_rules! impl_array(
2646 ($($size:expr),+) => {
2647 $(
2648 unsafe impl<T> Array for [T; $size] {
2649 type Item = T;
2650 #[inline]
2651 fn size() -> usize { $size }
2652 }
2653 )+
2654 }
2655);
2656
2657#[cfg(not(feature = "const_generics"))]
2658impl_array!(
2659 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
2660 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2661 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2662);
2663
2664pub trait ToSmallVec<A: Array> {
2666 fn to_smallvec(&self) -> SmallVec<A>;
2668}
2669
2670impl<A: Array> ToSmallVec<A> for [A::Item]
2671where A::Item: Copy
2672{
2673 #[inline]
2674 fn to_smallvec(&self) -> SmallVec<A> { SmallVec::from_slice(self) }
2675}
2676
2677#[repr(transparent)]
2679struct ConstNonNull<T>(NonNull<T>);
2680
2681impl<T> ConstNonNull<T> {
2682 #[inline]
2683 fn new(ptr: *const T) -> Option<Self> { NonNull::new(ptr as *mut T).map(Self) }
2684
2685 #[inline]
2686 fn as_ptr(self) -> *const T { self.0.as_ptr() }
2687}
2688
2689impl<T> Clone for ConstNonNull<T> {
2690 #[inline]
2691 fn clone(&self) -> Self { *self }
2692}
2693
2694impl<T> Copy for ConstNonNull<T> {}
2695
2696#[cfg(feature = "impl_bincode")]
2697use bincode::{
2698 BorrowDecode,
2699 de::{
2700 BorrowDecoder,
2701 Decode,
2702 Decoder,
2703 read::Reader
2704 },
2705 enc::{
2706 Encode,
2707 Encoder,
2708 write::Writer
2709 },
2710 error::{
2711 DecodeError,
2712 EncodeError
2713 }
2714};
2715
2716#[cfg(feature = "impl_bincode")]
2717impl<A, Context> Decode<Context> for SmallVec<A>
2718where
2719 A: Array,
2720 A::Item: Decode<Context>
2721{
2722 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2723 use core::convert::TryInto;
2724 let len = u64::decode(decoder)?;
2725 let len = len
2726 .try_into()
2727 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2728 decoder.claim_container_read::<A::Item>(len)?;
2729
2730 let mut vec = SmallVec::with_capacity(len);
2731 if unty::type_equal::<A::Item, u8>() {
2732 let ptr = vec.as_mut_ptr();
2736 unsafe {
2739 core::ptr::write_bytes(ptr, 0, len);
2740 vec.set_len(len);
2741 }
2742 let slice = vec.as_mut_slice();
2744 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2746 decoder.reader().read(slice)?;
2747 } else {
2748 for _ in 0..len {
2749 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2750 vec.push(A::Item::decode(decoder)?);
2751 }
2752 }
2753 Ok(vec)
2754 }
2755}
2756
2757#[cfg(feature = "impl_bincode")]
2758impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2759where
2760 A: Array,
2761 A::Item: BorrowDecode<'de, Context>
2762{
2763 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2764 decoder: &mut D
2765 ) -> Result<Self, DecodeError> {
2766 use core::convert::TryInto;
2767 let len = u64::decode(decoder)?;
2768 let len = len
2769 .try_into()
2770 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2771 decoder.claim_container_read::<A::Item>(len)?;
2772
2773 let mut vec = SmallVec::with_capacity(len);
2774 if unty::type_equal::<A::Item, u8>() {
2775 let ptr = vec.as_mut_ptr();
2779 unsafe {
2782 core::ptr::write_bytes(ptr, 0, len);
2783 vec.set_len(len);
2784 }
2785 let slice = vec.as_mut_slice();
2787 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2789 decoder.reader().read(slice)?;
2790 } else {
2791 for _ in 0..len {
2792 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2793 vec.push(A::Item::borrow_decode(decoder)?);
2794 }
2795 }
2796 Ok(vec)
2797 }
2798}
2799
2800#[cfg(feature = "impl_bincode")]
2801impl<A> Encode for SmallVec<A>
2802where
2803 A: Array,
2804 A::Item: Encode
2805{
2806 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2807 (self.len() as u64).encode(encoder)?;
2808 if unty::type_equal::<A::Item, u8>() {
2809 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2811 encoder.writer().write(slice)?;
2812 } else {
2813 for item in self.iter() {
2814 item.encode(encoder)?;
2815 }
2816 }
2817 Ok(())
2818 }
2819}