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 = "serde")]
117use core::marker::PhantomData;
118#[cfg(feature = "drain_keep_rest")]
119use core::mem::ManuallyDrop;
120#[cfg(feature = "malloc_size_of")]
121use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
122#[cfg(feature = "serde")]
123use serde::{
124 de::{Deserialize, Deserializer, SeqAccess, Visitor},
125 ser::{Serialize, SerializeSeq, Serializer},
126};
127#[cfg(feature = "write")]
128use std::io;
129#[allow(deprecated)]
130use {
131 alloc::{
132 alloc::{Layout, LayoutErr},
133 boxed::Box,
134 vec,
135 vec::Vec,
136 },
137 core::{
138 borrow::{Borrow, BorrowMut},
139 cmp, fmt,
140 hash::{Hash, Hasher},
141 hint::unreachable_unchecked,
142 iter::{repeat, FromIterator, FusedIterator, IntoIterator},
143 mem::{self, MaybeUninit},
144 ops::{self, Range, RangeBounds},
145 ptr::{self, NonNull},
146 slice::{self, SliceIndex},
147 },
148};
149
150#[macro_export]
187macro_rules! smallvec {
188 (@one $x:expr) => (1usize);
190 () => (
191 $crate::SmallVec::new()
192 );
193 ($elem:expr; $n:expr) => ({
194 $crate::SmallVec::from_elem($elem, $n)
195 });
196 ($($x:expr),+$(,)?) => ({
197 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
198 let mut vec = $crate::SmallVec::new();
199 if count <= vec.inline_size() {
200 $(vec.push($x);)*
201 vec
202 } else {
203 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
204 }
205 });
206}
207
208#[cfg(feature = "const_new")]
241#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
242#[macro_export]
243macro_rules! smallvec_inline {
244 (@one $x:expr) => (1usize);
246 ($elem:expr; $n:expr) => ({
247 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
248 });
249 ($($x:expr),+ $(,)?) => ({
250 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
251 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
252 });
253}
254
255#[cfg(not(feature = "union"))]
257macro_rules! debug_unreachable {
258 () => {
259 debug_unreachable!("entered unreachable code")
260 };
261 ($e:expr) => {
262 if cfg!(debug_assertions) {
263 panic!($e);
264 } else {
265 unreachable_unchecked();
266 }
267 };
268}
269
270#[doc(hidden)]
290#[deprecated]
291pub trait ExtendFromSlice<T> {
292 fn extend_from_slice(&mut self, other: &[T]);
294}
295
296#[allow(deprecated)]
297impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
298 fn extend_from_slice(&mut self, other: &[T]) {
299 Vec::extend_from_slice(self, other)
300 }
301}
302
303#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectionAllocErr {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CollectionAllocErr::CapacityOverflow =>
::core::fmt::Formatter::write_str(f, "CapacityOverflow"),
CollectionAllocErr::AllocErr { layout: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllocErr", "layout", &__self_0),
}
}
}Debug)]
305pub enum CollectionAllocErr {
306 CapacityOverflow,
308 AllocErr {
310 layout: Layout,
312 },
313}
314
315impl fmt::Display for CollectionAllocErr {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 f.write_fmt(format_args!("Allocation error: {0:?}", self))write!(f, "Allocation error: {:?}", self)
318 }
319}
320
321#[allow(deprecated)]
322impl From<LayoutErr> for CollectionAllocErr {
323 fn from(_: LayoutErr) -> Self {
324 CollectionAllocErr::CapacityOverflow
325 }
326}
327
328fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
329 match result {
330 Ok(x) => x,
331 Err(CollectionAllocErr::CapacityOverflow) => ::core::panicking::panic("capacity overflow")panic!("capacity overflow"),
332 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
333 }
334}
335
336fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
339 let size = mem::size_of::<T>()
340 .checked_mul(n)
341 .ok_or(CollectionAllocErr::CapacityOverflow)?;
342 let align = mem::align_of::<T>();
343 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
344}
345
346unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
347 let layout = layout_array::<T>(capacity).unwrap();
349 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
350}
351
352pub struct Drain<'a, T: 'a + Array> {
359 tail_start: usize,
360 tail_len: usize,
361 iter: slice::Iter<'a, T::Item>,
362 vec: NonNull<SmallVec<T>>,
363}
364
365impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
366where
367 T::Item: fmt::Debug,
368{
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
371 }
372}
373
374unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
375unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
376
377impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
378 type Item = T::Item;
379
380 #[inline]
381 fn next(&mut self) -> Option<T::Item> {
382 self.iter
383 .next()
384 .map(|reference| unsafe { ptr::read(reference) })
385 }
386
387 #[inline]
388 fn size_hint(&self) -> (usize, Option<usize>) {
389 self.iter.size_hint()
390 }
391}
392
393impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
394 #[inline]
395 fn next_back(&mut self) -> Option<T::Item> {
396 self.iter
397 .next_back()
398 .map(|reference| unsafe { ptr::read(reference) })
399 }
400}
401
402impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
403 #[inline]
404 fn len(&self) -> usize {
405 self.iter.len()
406 }
407}
408
409impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
410
411impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
412 fn drop(&mut self) {
413 self.for_each(drop);
414
415 if self.tail_len > 0 {
416 unsafe {
417 let source_vec = self.vec.as_mut();
418
419 let start = source_vec.len();
421 let tail = self.tail_start;
422 if tail != start {
423 let ptr = source_vec.as_mut_ptr();
427 let src = ptr.add(tail);
428 let dst = ptr.add(start);
429 ptr::copy(src, dst, self.tail_len);
430 }
431 source_vec.set_len(start + self.tail_len);
432 }
433 }
434 }
435}
436
437#[cfg(feature = "drain_filter")]
438pub struct DrainFilter<'a, T, F>
445where
446 F: FnMut(&mut T::Item) -> bool,
447 T: Array,
448{
449 vec: &'a mut SmallVec<T>,
450 idx: usize,
452 del: usize,
454 old_len: usize,
456 pred: F,
458 panic_flag: bool,
464}
465
466#[cfg(feature = "drain_filter")]
467impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
468where
469 F: FnMut(&mut T::Item) -> bool,
470 T: Array,
471 T::Item: fmt::Debug,
472{
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.debug_tuple("DrainFilter")
475 .field(&self.vec.as_slice())
476 .finish()
477 }
478}
479
480#[cfg(feature = "drain_filter")]
481impl<T, F> Iterator for DrainFilter<'_, T, F>
482where
483 F: FnMut(&mut T::Item) -> bool,
484 T: Array,
485{
486 type Item = T::Item;
487
488 fn next(&mut self) -> Option<T::Item> {
489 unsafe {
490 while self.idx < self.old_len {
491 let i = self.idx;
492 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
493 self.panic_flag = true;
494 let drained = (self.pred)(&mut v[i]);
495 self.panic_flag = false;
496 self.idx += 1;
501 if drained {
502 self.del += 1;
503 return Some(ptr::read(&v[i]));
504 } else if self.del > 0 {
505 let del = self.del;
506 let src: *const Self::Item = &v[i];
507 let dst: *mut Self::Item = &mut v[i - del];
508 ptr::copy_nonoverlapping(src, dst, 1);
509 }
510 }
511 None
512 }
513 }
514
515 fn size_hint(&self) -> (usize, Option<usize>) {
516 (0, Some(self.old_len - self.idx))
517 }
518}
519
520#[cfg(feature = "drain_filter")]
521impl<T, F> Drop for DrainFilter<'_, T, F>
522where
523 F: FnMut(&mut T::Item) -> bool,
524 T: Array,
525{
526 fn drop(&mut self) {
527 struct BackshiftOnDrop<'a, 'b, T, F>
528 where
529 F: FnMut(&mut T::Item) -> bool,
530 T: Array,
531 {
532 drain: &'b mut DrainFilter<'a, T, F>,
533 }
534
535 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
536 where
537 F: FnMut(&mut T::Item) -> bool,
538 T: Array,
539 {
540 fn drop(&mut self) {
541 unsafe {
542 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
543 let ptr = self.drain.vec.as_mut_ptr();
553 let src = ptr.add(self.drain.idx);
554 let dst = src.sub(self.drain.del);
555 let tail_len = self.drain.old_len - self.drain.idx;
556 src.copy_to(dst, tail_len);
557 }
558 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
559 }
560 }
561 }
562
563 let backshift = BackshiftOnDrop { drain: self };
564
565 if !backshift.drain.panic_flag {
569 backshift.drain.for_each(drop);
570 }
571 }
572}
573
574#[cfg(feature = "drain_keep_rest")]
575impl<T, F> DrainFilter<'_, T, F>
576where
577 F: FnMut(&mut T::Item) -> bool,
578 T: Array,
579{
580 pub fn keep_rest(self) {
600 let mut this = ManuallyDrop::new(self);
617
618 unsafe {
619 let needs_move = mem::size_of::<T::Item>() != 0;
621
622 if needs_move && this.idx < this.old_len && this.del > 0 {
623 let ptr = this.vec.as_mut_ptr();
624 let src = ptr.add(this.idx);
625 let dst = src.sub(this.del);
626 let tail_len = this.old_len - this.idx;
627 src.copy_to(dst, tail_len);
628 }
629
630 let new_len = this.old_len - this.del;
631 this.vec.set_len(new_len);
632 }
633 }
634}
635
636#[cfg(feature = "union")]
637union SmallVecData<A: Array> {
638 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
639 heap: (NonNull<A::Item>, usize),
640}
641
642#[cfg(all(feature = "union", feature = "const_new"))]
643impl<T, const N: usize> SmallVecData<[T; N]> {
644 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
645 #[inline]
646 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
647 SmallVecData {
648 inline: core::mem::ManuallyDrop::new(inline),
649 }
650 }
651}
652
653#[cfg(feature = "union")]
654impl<A: Array> SmallVecData<A> {
655 #[inline]
656 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
657 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
658 }
659 #[inline]
660 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
661 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
662 }
663 #[inline]
664 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
665 SmallVecData {
666 inline: core::mem::ManuallyDrop::new(inline),
667 }
668 }
669 #[inline]
679 fn empty() -> SmallVecData<A> {
680 SmallVecData {
684 inline: unsafe { MaybeUninit::uninit().assume_init() },
685 }
686 }
687 #[inline]
688 unsafe fn into_inline(self) -> MaybeUninit<A> {
689 core::mem::ManuallyDrop::into_inner(self.inline)
690 }
691 #[inline]
692 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
693 (ConstNonNull(self.heap.0), self.heap.1)
694 }
695 #[inline]
696 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
697 let h = &mut self.heap;
698 (h.0, &mut h.1)
699 }
700 #[inline]
701 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
702 SmallVecData { heap: (ptr, len) }
703 }
704}
705
706#[cfg(not(feature = "union"))]
707enum SmallVecData<A: Array> {
708 Inline(MaybeUninit<A>),
709 Heap {
711 ptr: NonNull<A::Item>,
716 len: usize,
717 },
718}
719
720#[cfg(all(not(feature = "union"), feature = "const_new"))]
721impl<T, const N: usize> SmallVecData<[T; N]> {
722 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
723 #[inline]
724 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
725 SmallVecData::Inline(inline)
726 }
727}
728
729#[cfg(not(feature = "union"))]
730impl<A: Array> SmallVecData<A> {
731 #[inline]
732 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
733 match self {
734 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
735 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
736 }
737 }
738 #[inline]
739 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
740 match self {
741 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
742 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
743 }
744 }
745 #[inline]
746 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
747 SmallVecData::Inline(inline)
748 }
749 #[inline]
751 fn empty() -> SmallVecData<A> {
752 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
756 }
757 #[inline]
758 unsafe fn into_inline(self) -> MaybeUninit<A> {
759 match self {
760 SmallVecData::Inline(a) => a,
761 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
762 }
763 }
764 #[inline]
765 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
766 match self {
767 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
768 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
769 }
770 }
771 #[inline]
772 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
773 match self {
774 SmallVecData::Heap { ptr, len } => (*ptr, len),
775 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
776 }
777 }
778 #[inline]
779 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
780 SmallVecData::Heap { ptr, len }
781 }
782}
783
784unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
785unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
786
787pub struct SmallVec<A: Array> {
816 capacity: usize,
822 data: SmallVecData<A>,
823}
824
825impl<A: Array> SmallVec<A> {
826 #[inline]
828 pub fn new() -> SmallVec<A> {
829 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!(
832 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
833 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
834 );
835 SmallVec {
836 capacity: 0,
837 data: SmallVecData::empty(),
838 }
839 }
840
841 #[inline]
856 pub fn with_capacity(n: usize) -> Self {
857 let mut v = SmallVec::new();
858 v.reserve_exact(n);
859 v
860 }
861
862 #[inline]
876 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
877 if vec.capacity() <= Self::inline_capacity() {
878 unsafe {
881 let mut data = SmallVecData::<A>::empty();
882 let len = vec.len();
883 vec.set_len(0);
884 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
885
886 SmallVec {
887 capacity: len,
888 data,
889 }
890 }
891 } else {
892 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
893 mem::forget(vec);
894 let ptr = NonNull::new(ptr)
895 .expect("Cannot be null by `Vec` invariant");
897
898 SmallVec {
899 capacity: cap,
900 data: SmallVecData::from_heap(ptr, len),
901 }
902 }
903 }
904
905 #[inline]
917 pub fn from_buf(buf: A) -> SmallVec<A> {
918 SmallVec {
919 capacity: A::size(),
920 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
921 }
922 }
923
924 #[inline]
937 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
938 if !(len <= A::size()) {
::core::panicking::panic("assertion failed: len <= A::size()")
};assert!(len <= A::size());
939 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
940 }
941
942 #[inline]
956 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
957 SmallVec {
958 capacity: len,
959 data: SmallVecData::from_inline(buf),
960 }
961 }
962
963 pub unsafe fn set_len(&mut self, new_len: usize) {
969 let (_, len_ptr, _) = self.triple_mut();
970 *len_ptr = new_len;
971 }
972
973 #[inline]
975 fn inline_capacity() -> usize {
976 if mem::size_of::<A::Item>() > 0 {
977 A::size()
978 } else {
979 #[allow(deprecated)]
992 core::usize::MAX
993 }
994 }
995
996 #[inline]
998 pub fn inline_size(&self) -> usize {
999 Self::inline_capacity()
1000 }
1001
1002 #[inline]
1004 pub fn len(&self) -> usize {
1005 self.triple().1
1006 }
1007
1008 #[inline]
1010 pub fn is_empty(&self) -> bool {
1011 self.len() == 0
1012 }
1013
1014 #[inline]
1016 pub fn capacity(&self) -> usize {
1017 self.triple().2
1018 }
1019
1020 #[inline]
1024 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1025 unsafe {
1026 if self.spilled() {
1027 let (ptr, len) = self.data.heap();
1028 (ptr, len, self.capacity)
1029 } else {
1030 (self.data.inline(), self.capacity, Self::inline_capacity())
1031 }
1032 }
1033 }
1034
1035 #[inline]
1037 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1038 unsafe {
1039 if self.spilled() {
1040 let (ptr, len_ptr) = self.data.heap_mut();
1041 (ptr, len_ptr, self.capacity)
1042 } else {
1043 (
1044 self.data.inline_mut(),
1045 &mut self.capacity,
1046 Self::inline_capacity(),
1047 )
1048 }
1049 }
1050 }
1051
1052 #[inline]
1055 pub fn spilled(&self) -> bool {
1056 self.capacity > Self::inline_capacity()
1057 }
1058
1059 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1073 where
1074 R: RangeBounds<usize>,
1075 {
1076 use core::ops::Bound::*;
1077
1078 let len = self.len();
1079 let start = match range.start_bound() {
1080 Included(&n) => n,
1081 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1082 Unbounded => 0,
1083 };
1084 let end = match range.end_bound() {
1085 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1086 Excluded(&n) => n,
1087 Unbounded => len,
1088 };
1089
1090 if !(start <= end) {
::core::panicking::panic("assertion failed: start <= end")
};assert!(start <= end);
1091 if !(end <= len) { ::core::panicking::panic("assertion failed: end <= len") };assert!(end <= len);
1092
1093 unsafe {
1094 self.set_len(start);
1095
1096 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1097
1098 Drain {
1099 tail_start: end,
1100 tail_len: len - end,
1101 iter: range_slice.iter(),
1102 vec: NonNull::new_unchecked(self as *mut _),
1105 }
1106 }
1107 }
1108
1109 #[cfg(feature = "drain_filter")]
1110 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1167 where
1168 F: FnMut(&mut A::Item) -> bool,
1169 {
1170 let old_len = self.len();
1171
1172 unsafe {
1174 self.set_len(0);
1175 }
1176
1177 DrainFilter {
1178 vec: self,
1179 idx: 0,
1180 del: 0,
1181 old_len,
1182 pred: filter,
1183 panic_flag: false,
1184 }
1185 }
1186
1187 #[inline]
1189 pub fn push(&mut self, value: A::Item) {
1190 unsafe {
1191 if self.spilled() {
1192 let (mut ptr, mut len_ptr) = self.data.heap_mut();
1193 if *len_ptr == self.capacity {
1194 self.reserve_one_unchecked();
1195 let (heap_ptr, heap_len) = self.data.heap_mut();
1196 ptr = heap_ptr;
1197 len_ptr = heap_len;
1198 }
1199 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1200 *len_ptr += 1;
1201 } else {
1202 let mut ptr = self.data.inline_mut();
1203 let mut len_ptr = &mut self.capacity;
1204 if *len_ptr == Self::inline_capacity() {
1205 self.reserve_one_unchecked();
1206 let (heap_ptr, heap_len) = self.data.heap_mut();
1207 ptr = heap_ptr;
1208 len_ptr = heap_len;
1209 }
1210 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1211 *len_ptr += 1;
1212 };
1213 }
1214 }
1215
1216 #[inline]
1219 pub fn pop(&mut self) -> Option<A::Item> {
1220 unsafe {
1221 let (ptr, len_ptr, _) = self.triple_mut();
1222 let ptr: *const _ = ptr.as_ptr();
1223 if *len_ptr == 0 {
1224 return None;
1225 }
1226 let last_index = *len_ptr - 1;
1227 *len_ptr = last_index;
1228 Some(ptr::read(ptr.add(last_index)))
1229 }
1230 }
1231
1232 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1245 where
1246 B: Array<Item = A::Item>,
1247 {
1248 self.extend(other.drain(..))
1249 }
1250
1251 pub fn grow(&mut self, new_cap: usize) {
1256 infallible(self.try_grow(new_cap))
1257 }
1258
1259 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1263 unsafe {
1264 let unspilled = !self.spilled();
1265 let (ptr, &mut len, cap) = self.triple_mut();
1266 if !(new_cap >= len) {
::core::panicking::panic("assertion failed: new_cap >= len")
};assert!(new_cap >= len);
1267 if new_cap <= Self::inline_capacity() {
1268 if unspilled {
1269 return Ok(());
1270 }
1271 self.data = SmallVecData::empty();
1272 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1273 self.capacity = len;
1274 deallocate(ptr, cap);
1275 } else if new_cap != cap {
1276 let layout = layout_array::<A::Item>(new_cap)?;
1277 if true {
if !(layout.size() > 0) {
::core::panicking::panic("assertion failed: layout.size() > 0")
};
};debug_assert!(layout.size() > 0);
1278 let new_alloc;
1279 if unspilled {
1280 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1281 .ok_or(CollectionAllocErr::AllocErr { layout })?
1282 .cast();
1283 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1284 } else {
1285 let old_layout = layout_array::<A::Item>(cap)?;
1288
1289 let new_ptr =
1290 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1291 new_alloc = NonNull::new(new_ptr)
1292 .ok_or(CollectionAllocErr::AllocErr { layout })?
1293 .cast();
1294 }
1295 self.data = SmallVecData::from_heap(new_alloc, len);
1296 self.capacity = new_cap;
1297 }
1298 Ok(())
1299 }
1300 }
1301
1302 #[inline]
1308 pub fn reserve(&mut self, additional: usize) {
1309 infallible(self.try_reserve(additional))
1310 }
1311
1312 #[cold]
1315 fn reserve_one_unchecked(&mut self) {
1316 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());
1317 let new_cap = self
1318 .len()
1319 .checked_add(1)
1320 .and_then(usize::checked_next_power_of_two)
1321 .expect("capacity overflow");
1322 infallible(self.try_grow(new_cap))
1323 }
1324
1325 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1329 let (_, &mut len, cap) = self.triple_mut();
1332 if cap - len >= additional {
1333 return Ok(());
1334 }
1335 let new_cap = len
1336 .checked_add(additional)
1337 .and_then(usize::checked_next_power_of_two)
1338 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1339 self.try_grow(new_cap)
1340 }
1341
1342 pub fn reserve_exact(&mut self, additional: usize) {
1347 infallible(self.try_reserve_exact(additional))
1348 }
1349
1350 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1353 let (_, &mut len, cap) = self.triple_mut();
1354 if cap - len >= additional {
1355 return Ok(());
1356 }
1357 let new_cap = len
1358 .checked_add(additional)
1359 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1360 self.try_grow(new_cap)
1361 }
1362
1363 pub fn shrink_to_fit(&mut self) {
1368 if !self.spilled() {
1369 return;
1370 }
1371 let len = self.len();
1372 if self.inline_size() >= len {
1373 unsafe {
1374 let (ptr, len) = self.data.heap();
1375 self.data = SmallVecData::empty();
1376 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1377 deallocate(ptr.0, self.capacity);
1378 self.capacity = len;
1379 }
1380 } else if self.capacity() > len {
1381 self.grow(len);
1382 }
1383 }
1384
1385 pub fn truncate(&mut self, len: usize) {
1394 unsafe {
1395 let (ptr, len_ptr, _) = self.triple_mut();
1396 let ptr = ptr.as_ptr();
1397 while len < *len_ptr {
1398 let last_index = *len_ptr - 1;
1399 *len_ptr = last_index;
1400 ptr::drop_in_place(ptr.add(last_index));
1401 }
1402 }
1403 }
1404
1405 pub fn as_slice(&self) -> &[A::Item] {
1409 self
1410 }
1411
1412 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1416 self
1417 }
1418
1419 #[inline]
1426 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1427 let len = self.len();
1428 self.swap(len - 1, index);
1429 self.pop()
1430 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1431 }
1432
1433 #[inline]
1435 pub fn clear(&mut self) {
1436 self.truncate(0);
1437 }
1438
1439 pub fn remove(&mut self, index: usize) -> A::Item {
1444 unsafe {
1445 let (ptr, len_ptr, _) = self.triple_mut();
1446 let len = *len_ptr;
1447 if !(index < len) {
::core::panicking::panic("assertion failed: index < len")
};assert!(index < len);
1448 *len_ptr = len - 1;
1449 let ptr = ptr.as_ptr().add(index);
1450 let item = ptr::read(ptr);
1451 ptr::copy(ptr.add(1), ptr, len - index - 1);
1452 item
1453 }
1454 }
1455
1456 pub fn insert(&mut self, index: usize, element: A::Item) {
1461 unsafe {
1462 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1463 if *len_ptr == cap {
1464 self.reserve_one_unchecked();
1465 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1466 ptr = heap_ptr;
1467 len_ptr = heap_len_ptr;
1468 }
1469 let mut ptr = ptr.as_ptr();
1470 let len = *len_ptr;
1471 if index > len {
1472 ::core::panicking::panic("index exceeds length");panic!("index exceeds length");
1473 }
1474 ptr = ptr.add(index);
1476 if index < len {
1477 ptr::copy(ptr, ptr.add(1), len - index);
1479 }
1480 *len_ptr = len + 1;
1481 ptr::write(ptr, element);
1482 }
1483 }
1484
1485 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1488 let mut iter = iterable.into_iter();
1489 if index == self.len() {
1490 return self.extend(iter);
1491 }
1492
1493 let (lower_size_bound, _) = iter.size_hint();
1494 #[allow(deprecated)]
1495 {
1496 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)
1497 } 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;
1501 let old_len = self.len();
1502 if !(index <= old_len) {
::core::panicking::panic("assertion failed: index <= old_len")
};assert!(index <= old_len);
1503
1504 unsafe {
1505 self.reserve(lower_size_bound);
1507 let start = self.as_mut_ptr();
1508 let ptr = start.add(index);
1509
1510 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1512
1513 self.set_len(0);
1516 let mut guard = DropOnPanic {
1517 start,
1518 skip: index..(index + lower_size_bound),
1519 len: old_len + lower_size_bound,
1520 };
1521
1522 let start = self.as_mut_ptr();
1525 let ptr = start.add(index);
1526
1527 while num_added < lower_size_bound {
1528 let element = match iter.next() {
1529 Some(x) => x,
1530 None => break,
1531 };
1532 let cur = ptr.add(num_added);
1533 ptr::write(cur, element);
1534 guard.skip.start += 1;
1535 num_added += 1;
1536 }
1537
1538 if num_added < lower_size_bound {
1539 ptr::copy(
1542 ptr.add(lower_size_bound),
1543 ptr.add(num_added),
1544 old_len - index,
1545 );
1546 }
1547 self.set_len(old_len + num_added);
1550 mem::forget(guard);
1551 }
1552
1553 for element in iter {
1555 self.insert(index + num_added, element);
1556 num_added += 1;
1557 }
1558
1559 struct DropOnPanic<T> {
1560 start: *mut T,
1561 skip: Range<usize>, len: usize,
1563 }
1564
1565 impl<T> Drop for DropOnPanic<T> {
1566 fn drop(&mut self) {
1567 for i in 0..self.len {
1568 if !self.skip.contains(&i) {
1569 unsafe {
1570 ptr::drop_in_place(self.start.add(i));
1571 }
1572 }
1573 }
1574 }
1575 }
1576 }
1577
1578 pub fn into_vec(mut self) -> Vec<A::Item> {
1581 if self.spilled() {
1582 unsafe {
1583 let (ptr, &mut len) = self.data.heap_mut();
1584 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1585 mem::forget(self);
1586 v
1587 }
1588 } else {
1589 self.into_iter().collect()
1590 }
1591 }
1592
1593 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1598 self.into_vec().into_boxed_slice()
1599 }
1600
1601 pub fn into_inner(self) -> Result<A, Self> {
1608 if self.spilled() || self.len() != A::size() {
1609 Err(self)
1611 } else {
1612 unsafe {
1613 let data = ptr::read(&self.data);
1614 mem::forget(self);
1615 Ok(data.into_inline().assume_init())
1616 }
1617 }
1618 }
1619
1620 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1626 let mut del = 0;
1627 let len = self.len();
1628 for i in 0..len {
1629 if !f(&mut self[i]) {
1630 del += 1;
1631 } else if del > 0 {
1632 self.swap(i - del, i);
1633 }
1634 }
1635 self.truncate(len - del);
1636 }
1637
1638 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1644 self.retain(f)
1645 }
1646
1647 pub fn dedup(&mut self)
1649 where
1650 A::Item: PartialEq<A::Item>,
1651 {
1652 self.dedup_by(|a, b| a == b);
1653 }
1654
1655 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1658 where
1659 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1660 {
1661 let len = self.len();
1664 if len <= 1 {
1665 return;
1666 }
1667
1668 let ptr = self.as_mut_ptr();
1669 let mut w: usize = 1;
1670
1671 unsafe {
1672 for r in 1..len {
1673 let p_r = ptr.add(r);
1674 let p_wm1 = ptr.add(w - 1);
1675 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1676 if r != w {
1677 let p_w = p_wm1.add(1);
1678 mem::swap(&mut *p_r, &mut *p_w);
1679 }
1680 w += 1;
1681 }
1682 }
1683 }
1684
1685 self.truncate(w);
1686 }
1687
1688 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1690 where
1691 F: FnMut(&mut A::Item) -> K,
1692 K: PartialEq<K>,
1693 {
1694 self.dedup_by(|a, b| key(a) == key(b));
1695 }
1696
1697 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1728 where
1729 F: FnMut() -> A::Item,
1730 {
1731 let old_len = self.len();
1732 if old_len < new_len {
1733 let mut f = f;
1734 let additional = new_len - old_len;
1735 self.reserve(additional);
1736 for _ in 0..additional {
1737 self.push(f());
1738 }
1739 } else if old_len > new_len {
1740 self.truncate(new_len);
1741 }
1742 }
1743
1744 #[inline]
1812 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1813 let ptr = unsafe {
1816 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.");
1817 NonNull::new_unchecked(ptr)
1818 };
1819 if !(capacity > Self::inline_capacity()) {
::core::panicking::panic("assertion failed: capacity > Self::inline_capacity()")
};assert!(capacity > Self::inline_capacity());
1820 SmallVec {
1821 capacity,
1822 data: SmallVecData::from_heap(ptr, length),
1823 }
1824 }
1825
1826 pub fn as_ptr(&self) -> *const A::Item {
1828 self.triple().0.as_ptr()
1832 }
1833
1834 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1836 self.triple_mut().0.as_ptr()
1840 }
1841}
1842
1843impl<A: Array> SmallVec<A>
1844where
1845 A::Item: Copy,
1846{
1847 pub fn from_slice(slice: &[A::Item]) -> Self {
1852 let len = slice.len();
1853 if len <= Self::inline_capacity() {
1854 SmallVec {
1855 capacity: len,
1856 data: SmallVecData::from_inline(unsafe {
1857 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1858 ptr::copy_nonoverlapping(
1859 slice.as_ptr(),
1860 data.as_mut_ptr() as *mut A::Item,
1861 len,
1862 );
1863 data
1864 }),
1865 }
1866 } else {
1867 let mut b = slice.to_vec();
1868 let cap = b.capacity();
1869 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1870 mem::forget(b);
1871 SmallVec {
1872 capacity: cap,
1873 data: SmallVecData::from_heap(ptr, len),
1874 }
1875 }
1876 }
1877
1878 #[inline]
1883 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1884 self.reserve(slice.len());
1885
1886 let len = self.len();
1887 if !(index <= len) {
::core::panicking::panic("assertion failed: index <= len")
};assert!(index <= len);
1888
1889 unsafe {
1890 let slice_ptr = slice.as_ptr();
1891 let ptr = self.as_mut_ptr().add(index);
1892 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1893 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1894 self.set_len(len + slice.len());
1895 }
1896 }
1897
1898 #[inline]
1902 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1903 let len = self.len();
1904 self.insert_from_slice(len, slice);
1905 }
1906}
1907
1908impl<A: Array> SmallVec<A>
1909where
1910 A::Item: Clone,
1911{
1912 pub fn resize(&mut self, len: usize, value: A::Item) {
1919 let old_len = self.len();
1920
1921 if len > old_len {
1922 self.extend(repeat(value).take(len - old_len));
1923 } else {
1924 self.truncate(len);
1925 }
1926 }
1927
1928 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1936 if n > Self::inline_capacity() {
1937 ::alloc::vec::from_elem(elem, n)vec![elem; n].into()
1938 } else {
1939 let mut v = SmallVec::<A>::new();
1940 unsafe {
1941 let (ptr, len_ptr, _) = v.triple_mut();
1942 let ptr = ptr.as_ptr();
1943 let mut local_len = SetLenOnDrop::new(len_ptr);
1944
1945 for i in 0..n {
1946 ::core::ptr::write(ptr.add(i), elem.clone());
1947 local_len.increment_len(1);
1948 }
1949 }
1950 v
1951 }
1952 }
1953}
1954
1955impl<A: Array> ops::Deref for SmallVec<A> {
1956 type Target = [A::Item];
1957 #[inline]
1958 fn deref(&self) -> &[A::Item] {
1959 unsafe {
1960 let (ptr, len, _) = self.triple();
1961 slice::from_raw_parts(ptr.as_ptr(), len)
1962 }
1963 }
1964}
1965
1966impl<A: Array> ops::DerefMut for SmallVec<A> {
1967 #[inline]
1968 fn deref_mut(&mut self) -> &mut [A::Item] {
1969 unsafe {
1970 let (ptr, &mut len, _) = self.triple_mut();
1971 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1972 }
1973 }
1974}
1975
1976impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1977 #[inline]
1978 fn as_ref(&self) -> &[A::Item] {
1979 self
1980 }
1981}
1982
1983impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1984 #[inline]
1985 fn as_mut(&mut self) -> &mut [A::Item] {
1986 self
1987 }
1988}
1989
1990impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1991 #[inline]
1992 fn borrow(&self) -> &[A::Item] {
1993 self
1994 }
1995}
1996
1997impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1998 #[inline]
1999 fn borrow_mut(&mut self) -> &mut [A::Item] {
2000 self
2001 }
2002}
2003
2004#[cfg(feature = "write")]
2005#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
2006impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
2007 #[inline]
2008 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2009 self.extend_from_slice(buf);
2010 Ok(buf.len())
2011 }
2012
2013 #[inline]
2014 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2015 self.extend_from_slice(buf);
2016 Ok(())
2017 }
2018
2019 #[inline]
2020 fn flush(&mut self) -> io::Result<()> {
2021 Ok(())
2022 }
2023}
2024
2025#[cfg(feature = "serde")]
2026#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2027impl<A: Array> Serialize for SmallVec<A>
2028where
2029 A::Item: Serialize,
2030{
2031 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2032 let mut state = serializer.serialize_seq(Some(self.len()))?;
2033 for item in self {
2034 state.serialize_element(&item)?;
2035 }
2036 state.end()
2037 }
2038}
2039
2040#[cfg(feature = "serde")]
2041#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2042impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2043where
2044 A::Item: Deserialize<'de>,
2045{
2046 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2047 deserializer.deserialize_seq(SmallVecVisitor {
2048 phantom: PhantomData,
2049 })
2050 }
2051}
2052
2053#[cfg(feature = "serde")]
2054struct SmallVecVisitor<A> {
2055 phantom: PhantomData<A>,
2056}
2057
2058#[cfg(feature = "serde")]
2059impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2060where
2061 A::Item: Deserialize<'de>,
2062{
2063 type Value = SmallVec<A>;
2064
2065 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2066 formatter.write_str("a sequence")
2067 }
2068
2069 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2070 where
2071 B: SeqAccess<'de>,
2072 {
2073 use serde::de::Error;
2074 let len = seq.size_hint().unwrap_or(0);
2075 let mut values = SmallVec::new();
2076 values.try_reserve(len).map_err(B::Error::custom)?;
2077
2078 while let Some(value) = seq.next_element()? {
2079 values.push(value);
2080 }
2081
2082 Ok(values)
2083 }
2084}
2085
2086#[cfg(feature = "malloc_size_of")]
2087impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2088 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2089 if self.spilled() {
2090 unsafe { ops.malloc_size_of(self.as_ptr()) }
2091 } else {
2092 0
2093 }
2094 }
2095}
2096
2097#[cfg(feature = "malloc_size_of")]
2098impl<A> MallocSizeOf for SmallVec<A>
2099where
2100 A: Array,
2101 A::Item: MallocSizeOf,
2102{
2103 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2104 let mut n = self.shallow_size_of(ops);
2105 for elem in self.iter() {
2106 n += elem.size_of(ops);
2107 }
2108 n
2109 }
2110}
2111
2112#[cfg(feature = "specialization")]
2113trait SpecFrom<A: Array, S> {
2114 fn spec_from(slice: S) -> SmallVec<A>;
2115}
2116
2117#[cfg(feature = "specialization")]
2118mod specialization;
2119
2120#[cfg(feature = "arbitrary")]
2121mod arbitrary;
2122
2123#[cfg(feature = "specialization")]
2124impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2125where
2126 A::Item: Copy,
2127{
2128 #[inline]
2129 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2130 SmallVec::from_slice(slice)
2131 }
2132}
2133
2134impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2135where
2136 A::Item: Clone,
2137{
2138 #[cfg(not(feature = "specialization"))]
2139 #[inline]
2140 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2141 slice.iter().cloned().collect()
2142 }
2143
2144 #[cfg(feature = "specialization")]
2145 #[inline]
2146 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2147 SmallVec::spec_from(slice)
2148 }
2149}
2150
2151impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2152 #[inline]
2153 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2154 SmallVec::from_vec(vec)
2155 }
2156}
2157
2158impl<A: Array> From<A> for SmallVec<A> {
2159 #[inline]
2160 fn from(array: A) -> SmallVec<A> {
2161 SmallVec::from_buf(array)
2162 }
2163}
2164
2165impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2166 type Output = I::Output;
2167
2168 fn index(&self, index: I) -> &I::Output {
2169 &(**self)[index]
2170 }
2171}
2172
2173impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2174 fn index_mut(&mut self, index: I) -> &mut I::Output {
2175 &mut (&mut **self)[index]
2176 }
2177}
2178
2179#[allow(deprecated)]
2180impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2181where
2182 A::Item: Copy,
2183{
2184 fn extend_from_slice(&mut self, other: &[A::Item]) {
2185 SmallVec::extend_from_slice(self, other)
2186 }
2187}
2188
2189impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2190 #[inline]
2191 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2192 let mut v = SmallVec::new();
2193 v.extend(iterable);
2194 v
2195 }
2196}
2197
2198impl<A: Array> Extend<A::Item> for SmallVec<A> {
2199 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2200 let mut iter = iterable.into_iter();
2201 let (lower_size_bound, _) = iter.size_hint();
2202 self.reserve(lower_size_bound);
2203
2204 unsafe {
2205 let (ptr, len_ptr, cap) = self.triple_mut();
2206 let ptr = ptr.as_ptr();
2207 let mut len = SetLenOnDrop::new(len_ptr);
2208 while len.get() < cap {
2209 if let Some(out) = iter.next() {
2210 ptr::write(ptr.add(len.get()), out);
2211 len.increment_len(1);
2212 } else {
2213 return;
2214 }
2215 }
2216 }
2217
2218 for elem in iter {
2219 self.push(elem);
2220 }
2221 }
2222}
2223
2224impl<A: Array> fmt::Debug for SmallVec<A>
2225where
2226 A::Item: fmt::Debug,
2227{
2228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2229 f.debug_list().entries(self.iter()).finish()
2230 }
2231}
2232
2233impl<A: Array> Default for SmallVec<A> {
2234 #[inline]
2235 fn default() -> SmallVec<A> {
2236 SmallVec::new()
2237 }
2238}
2239
2240#[cfg(feature = "may_dangle")]
2241unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2242 fn drop(&mut self) {
2243 unsafe {
2244 if self.spilled() {
2245 let (ptr, &mut len) = self.data.heap_mut();
2246 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2247 } else {
2248 ptr::drop_in_place(&mut self[..]);
2249 }
2250 }
2251 }
2252}
2253
2254#[cfg(not(feature = "may_dangle"))]
2255impl<A: Array> Drop for SmallVec<A> {
2256 fn drop(&mut self) {
2257 unsafe {
2258 if self.spilled() {
2259 let (ptr, &mut len) = self.data.heap_mut();
2260 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2261 } else {
2262 ptr::drop_in_place(&mut self[..]);
2263 }
2264 }
2265 }
2266}
2267
2268impl<A: Array> Clone for SmallVec<A>
2269where
2270 A::Item: Clone,
2271{
2272 #[inline]
2273 fn clone(&self) -> SmallVec<A> {
2274 SmallVec::from(self.as_slice())
2275 }
2276
2277 fn clone_from(&mut self, source: &Self) {
2278 self.truncate(source.len());
2282
2283 let (init, tail) = source.split_at(self.len());
2286
2287 self.clone_from_slice(init);
2289 self.extend(tail.iter().cloned());
2290 }
2291}
2292
2293impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2294where
2295 A::Item: PartialEq<B::Item>,
2296{
2297 #[inline]
2298 fn eq(&self, other: &SmallVec<B>) -> bool {
2299 self[..] == other[..]
2300 }
2301}
2302
2303impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2304
2305impl<A: Array> PartialOrd for SmallVec<A>
2306where
2307 A::Item: PartialOrd,
2308{
2309 #[inline]
2310 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2311 PartialOrd::partial_cmp(&**self, &**other)
2312 }
2313}
2314
2315impl<A: Array> Ord for SmallVec<A>
2316where
2317 A::Item: Ord,
2318{
2319 #[inline]
2320 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2321 Ord::cmp(&**self, &**other)
2322 }
2323}
2324
2325impl<A: Array> Hash for SmallVec<A>
2326where
2327 A::Item: Hash,
2328{
2329 fn hash<H: Hasher>(&self, state: &mut H) {
2330 (**self).hash(state)
2331 }
2332}
2333
2334unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2335
2336pub struct IntoIter<A: Array> {
2342 data: SmallVec<A>,
2343 current: usize,
2344 end: usize,
2345}
2346
2347impl<A: Array> fmt::Debug for IntoIter<A>
2348where
2349 A::Item: fmt::Debug,
2350{
2351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2352 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2353 }
2354}
2355
2356impl<A: Array + Clone> Clone for IntoIter<A>
2357where
2358 A::Item: Clone,
2359{
2360 fn clone(&self) -> IntoIter<A> {
2361 SmallVec::from(self.as_slice()).into_iter()
2362 }
2363}
2364
2365impl<A: Array> Drop for IntoIter<A> {
2366 fn drop(&mut self) {
2367 for _ in self {}
2368 }
2369}
2370
2371impl<A: Array> Iterator for IntoIter<A> {
2372 type Item = A::Item;
2373
2374 #[inline]
2375 fn next(&mut self) -> Option<A::Item> {
2376 if self.current == self.end {
2377 None
2378 } else {
2379 unsafe {
2380 let current = self.current;
2381 self.current += 1;
2382 Some(ptr::read(self.data.as_ptr().add(current)))
2383 }
2384 }
2385 }
2386
2387 #[inline]
2388 fn size_hint(&self) -> (usize, Option<usize>) {
2389 let size = self.end - self.current;
2390 (size, Some(size))
2391 }
2392}
2393
2394impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2395 #[inline]
2396 fn next_back(&mut self) -> Option<A::Item> {
2397 if self.current == self.end {
2398 None
2399 } else {
2400 unsafe {
2401 self.end -= 1;
2402 Some(ptr::read(self.data.as_ptr().add(self.end)))
2403 }
2404 }
2405 }
2406}
2407
2408impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2409impl<A: Array> FusedIterator for IntoIter<A> {}
2410
2411impl<A: Array> IntoIter<A> {
2412 pub fn as_slice(&self) -> &[A::Item] {
2414 let len = self.end - self.current;
2415 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2416 }
2417
2418 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2420 let len = self.end - self.current;
2421 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2422 }
2423}
2424
2425impl<A: Array> IntoIterator for SmallVec<A> {
2426 type IntoIter = IntoIter<A>;
2427 type Item = A::Item;
2428 fn into_iter(mut self) -> Self::IntoIter {
2429 unsafe {
2430 let len = self.len();
2433 self.set_len(0);
2434 IntoIter {
2435 data: self,
2436 current: 0,
2437 end: len,
2438 }
2439 }
2440 }
2441}
2442
2443impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2444 type IntoIter = slice::Iter<'a, A::Item>;
2445 type Item = &'a A::Item;
2446 fn into_iter(self) -> Self::IntoIter {
2447 self.iter()
2448 }
2449}
2450
2451impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2452 type IntoIter = slice::IterMut<'a, A::Item>;
2453 type Item = &'a mut A::Item;
2454 fn into_iter(self) -> Self::IntoIter {
2455 self.iter_mut()
2456 }
2457}
2458
2459pub unsafe trait Array {
2461 type Item;
2463 fn size() -> usize;
2465}
2466
2467struct SetLenOnDrop<'a> {
2471 len: &'a mut usize,
2472 local_len: usize,
2473}
2474
2475impl<'a> SetLenOnDrop<'a> {
2476 #[inline]
2477 fn new(len: &'a mut usize) -> Self {
2478 SetLenOnDrop {
2479 local_len: *len,
2480 len,
2481 }
2482 }
2483
2484 #[inline]
2485 fn get(&self) -> usize {
2486 self.local_len
2487 }
2488
2489 #[inline]
2490 fn increment_len(&mut self, increment: usize) {
2491 self.local_len += increment;
2492 }
2493}
2494
2495impl<'a> Drop for SetLenOnDrop<'a> {
2496 #[inline]
2497 fn drop(&mut self) {
2498 *self.len = self.local_len;
2499 }
2500}
2501
2502#[cfg(feature = "const_new")]
2503impl<T, const N: usize> SmallVec<[T; N]> {
2504 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2509 #[inline]
2510 pub const fn new_const() -> Self {
2511 SmallVec {
2512 capacity: 0,
2513 data: SmallVecData::from_const(MaybeUninit::uninit()),
2514 }
2515 }
2516
2517 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2524 #[inline]
2525 pub const fn from_const(items: [T; N]) -> Self {
2526 SmallVec {
2527 capacity: N,
2528 data: SmallVecData::from_const(MaybeUninit::new(items)),
2529 }
2530 }
2531
2532 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2540 #[inline]
2541 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2542 SmallVec {
2543 capacity: len,
2544 data: SmallVecData::from_const(MaybeUninit::new(items)),
2545 }
2546 }
2547}
2548
2549#[cfg(feature = "const_generics")]
2550#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2551unsafe impl<T, const N: usize> Array for [T; N] {
2552 type Item = T;
2553 #[inline]
2554 fn size() -> usize {
2555 N
2556 }
2557}
2558
2559#[cfg(not(feature = "const_generics"))]
2560macro_rules! impl_array(
2561 ($($size:expr),+) => {
2562 $(
2563 unsafe impl<T> Array for [T; $size] {
2564 type Item = T;
2565 #[inline]
2566 fn size() -> usize { $size }
2567 }
2568 )+
2569 }
2570);
2571
2572#[cfg(not(feature = "const_generics"))]
2573impl_array!(
2574 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,
2575 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2576 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2577);
2578
2579pub trait ToSmallVec<A: Array> {
2581 fn to_smallvec(&self) -> SmallVec<A>;
2583}
2584
2585impl<A: Array> ToSmallVec<A> for [A::Item]
2586where
2587 A::Item: Copy,
2588{
2589 #[inline]
2590 fn to_smallvec(&self) -> SmallVec<A> {
2591 SmallVec::from_slice(self)
2592 }
2593}
2594
2595#[repr(transparent)]
2597struct ConstNonNull<T>(NonNull<T>);
2598
2599impl<T> ConstNonNull<T> {
2600 #[inline]
2601 fn new(ptr: *const T) -> Option<Self> {
2602 NonNull::new(ptr as *mut T).map(Self)
2603 }
2604 #[inline]
2605 fn as_ptr(self) -> *const T {
2606 self.0.as_ptr()
2607 }
2608}
2609
2610impl<T> Clone for ConstNonNull<T> {
2611 #[inline]
2612 fn clone(&self) -> Self {
2613 *self
2614 }
2615}
2616
2617impl<T> Copy for ConstNonNull<T> {}
2618
2619#[cfg(feature = "impl_bincode")]
2620use bincode::{
2621 de::{read::Reader, BorrowDecoder, Decode, Decoder},
2622 enc::{write::Writer, Encode, Encoder},
2623 error::{DecodeError, EncodeError},
2624 BorrowDecode,
2625};
2626
2627#[cfg(feature = "impl_bincode")]
2628impl<A, Context> Decode<Context> for SmallVec<A>
2629where
2630 A: Array,
2631 A::Item: Decode<Context>,
2632{
2633 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2634 use core::convert::TryInto;
2635 let len = u64::decode(decoder)?;
2636 let len = len
2637 .try_into()
2638 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2639 decoder.claim_container_read::<A::Item>(len)?;
2640
2641 let mut vec = SmallVec::with_capacity(len);
2642 if unty::type_equal::<A::Item, u8>() {
2643 let ptr = vec.as_mut_ptr();
2647 unsafe {
2650 core::ptr::write_bytes(ptr, 0, len);
2651 vec.set_len(len);
2652 }
2653 let slice = vec.as_mut_slice();
2655 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2657 decoder.reader().read(slice)?;
2658 } else {
2659 for _ in 0..len {
2660 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2661 vec.push(A::Item::decode(decoder)?);
2662 }
2663 }
2664 Ok(vec)
2665 }
2666}
2667
2668#[cfg(feature = "impl_bincode")]
2669impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2670where
2671 A: Array,
2672 A::Item: BorrowDecode<'de, Context>,
2673{
2674 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2675 decoder: &mut D,
2676 ) -> Result<Self, DecodeError> {
2677 use core::convert::TryInto;
2678 let len = u64::decode(decoder)?;
2679 let len = len
2680 .try_into()
2681 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2682 decoder.claim_container_read::<A::Item>(len)?;
2683
2684 let mut vec = SmallVec::with_capacity(len);
2685 if unty::type_equal::<A::Item, u8>() {
2686 let ptr = vec.as_mut_ptr();
2690 unsafe {
2693 core::ptr::write_bytes(ptr, 0, len);
2694 vec.set_len(len);
2695 }
2696 let slice = vec.as_mut_slice();
2698 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2700 decoder.reader().read(slice)?;
2701 } else {
2702 for _ in 0..len {
2703 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2704 vec.push(A::Item::borrow_decode(decoder)?);
2705 }
2706 }
2707 Ok(vec)
2708 }
2709}
2710
2711#[cfg(feature = "impl_bincode")]
2712impl<A> Encode for SmallVec<A>
2713where
2714 A: Array,
2715 A::Item: Encode,
2716{
2717 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2718 (self.len() as u64).encode(encoder)?;
2719 if unty::type_equal::<A::Item, u8>() {
2720 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2722 encoder.writer().write(slice)?;
2723 } else {
2724 for item in self.iter() {
2725 item.encode(encoder)?;
2726 }
2727 }
2728 Ok(())
2729 }
2730}