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::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
120#[cfg(feature = "serde")]
121use serde::{
122 de::{Deserialize, Deserializer, SeqAccess, Visitor},
123 ser::{Serialize, SerializeSeq, Serializer},
124};
125#[cfg(feature = "write")]
126use std::io;
127#[allow(deprecated)]
128use {
129 alloc::{
130 alloc::{Layout, LayoutErr},
131 boxed::Box,
132 vec,
133 vec::Vec,
134 },
135 core::{
136 borrow::{Borrow, BorrowMut},
137 cmp, fmt,
138 hash::{Hash, Hasher},
139 hint::unreachable_unchecked,
140 iter::{repeat, FromIterator, FusedIterator, IntoIterator},
141 marker::PhantomData,
142 mem::{self, MaybeUninit},
143 ops::{self, Range, RangeBounds},
144 ptr::{self, NonNull},
145 slice::{self, SliceIndex},
146 },
147};
148
149#[macro_export]
186macro_rules! smallvec {
187 (@one $x:expr) => (1usize);
189 () => (
190 $crate::SmallVec::new()
191 );
192 ($elem:expr; $n:expr) => ({
193 $crate::SmallVec::from_elem($elem, $n)
194 });
195 ($($x:expr),+$(,)?) => ({
196 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
197 let mut vec = $crate::SmallVec::new();
198 if count <= vec.inline_size() {
199 $(vec.push($x);)*
200 vec
201 } else {
202 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
203 }
204 });
205}
206
207#[cfg(feature = "const_new")]
240#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
241#[macro_export]
242macro_rules! smallvec_inline {
243 (@one $x:expr) => (1usize);
245 ($elem:expr; $n:expr) => ({
246 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
247 });
248 ($($x:expr),+ $(,)?) => ({
249 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
250 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
251 });
252}
253
254#[cfg(not(feature = "union"))]
256macro_rules! debug_unreachable {
257 () => {
258 debug_unreachable!("entered unreachable code")
259 };
260 ($e:expr) => {
261 if cfg!(debug_assertions) {
262 panic!($e);
263 } else {
264 unreachable_unchecked();
265 }
266 };
267}
268
269#[doc(hidden)]
289#[deprecated]
290pub trait ExtendFromSlice<T> {
291 fn extend_from_slice(&mut self, other: &[T]);
293}
294
295#[allow(deprecated)]
296impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
297 fn extend_from_slice(&mut self, other: &[T]) {
298 Vec::extend_from_slice(self, other)
299 }
300}
301
302#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectionAllocErr {
#[inline]
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)]
304pub enum CollectionAllocErr {
305 CapacityOverflow,
307 AllocErr {
309 layout: Layout,
311 },
312}
313
314impl fmt::Display for CollectionAllocErr {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 f.write_fmt(format_args!("Allocation error: {0:?}", self))write!(f, "Allocation error: {:?}", self)
317 }
318}
319
320#[allow(deprecated)]
321impl From<LayoutErr> for CollectionAllocErr {
322 fn from(_: LayoutErr) -> Self {
323 CollectionAllocErr::CapacityOverflow
324 }
325}
326
327fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
328 match result {
329 Ok(x) => x,
330 Err(CollectionAllocErr::CapacityOverflow) => ::core::panicking::panic("capacity overflow")panic!("capacity overflow"),
331 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
332 }
333}
334
335fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
338 let size = mem::size_of::<T>()
339 .checked_mul(n)
340 .ok_or(CollectionAllocErr::CapacityOverflow)?;
341 let align = mem::align_of::<T>();
342 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
343}
344
345unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
346 let layout = layout_array::<T>(capacity).unwrap();
348 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
349}
350
351pub struct Drain<'a, T: 'a + Array> {
358 tail_start: usize,
359 tail_len: usize,
360 iter: slice::Iter<'a, T::Item>,
361 vec: NonNull<SmallVec<T>>,
362}
363
364impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
365where
366 T::Item: fmt::Debug,
367{
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
370 }
371}
372
373unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
374unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
375
376impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
377 type Item = T::Item;
378
379 #[inline]
380 fn next(&mut self) -> Option<T::Item> {
381 self.iter
382 .next()
383 .map(|reference| unsafe { ptr::read(reference) })
384 }
385
386 #[inline]
387 fn size_hint(&self) -> (usize, Option<usize>) {
388 self.iter.size_hint()
389 }
390}
391
392impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
393 #[inline]
394 fn next_back(&mut self) -> Option<T::Item> {
395 self.iter
396 .next_back()
397 .map(|reference| unsafe { ptr::read(reference) })
398 }
399}
400
401impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
402 #[inline]
403 fn len(&self) -> usize {
404 self.iter.len()
405 }
406}
407
408impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
409
410impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
411 fn drop(&mut self) {
412 self.for_each(drop);
413
414 if self.tail_len > 0 {
415 unsafe {
416 let source_vec = self.vec.as_mut();
417
418 let start = source_vec.len();
420 let tail = self.tail_start;
421 if tail != start {
422 let ptr = source_vec.as_mut_ptr();
426 let src = ptr.add(tail);
427 let dst = ptr.add(start);
428 ptr::copy(src, dst, self.tail_len);
429 }
430 source_vec.set_len(start + self.tail_len);
431 }
432 }
433 }
434}
435
436#[cfg(feature = "drain_filter")]
437pub struct DrainFilter<'a, T, F>
444where
445 F: FnMut(&mut T::Item) -> bool,
446 T: Array,
447{
448 vec: &'a mut SmallVec<T>,
449 idx: usize,
451 del: usize,
453 old_len: usize,
455 pred: F,
457 panic_flag: bool,
463}
464
465#[cfg(feature = "drain_filter")]
466impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
467where
468 F: FnMut(&mut T::Item) -> bool,
469 T: Array,
470 T::Item: fmt::Debug,
471{
472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473 f.debug_tuple("DrainFilter")
474 .field(&self.vec.as_slice())
475 .finish()
476 }
477}
478
479#[cfg(feature = "drain_filter")]
480impl<T, F> Iterator for DrainFilter<'_, T, F>
481where
482 F: FnMut(&mut T::Item) -> bool,
483 T: Array,
484{
485 type Item = T::Item;
486
487 fn next(&mut self) -> Option<T::Item> {
488 unsafe {
489 while self.idx < self.old_len {
490 let i = self.idx;
491 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
492 self.panic_flag = true;
493 let drained = (self.pred)(&mut v[i]);
494 self.panic_flag = false;
495 self.idx += 1;
500 if drained {
501 self.del += 1;
502 return Some(ptr::read(&v[i]));
503 } else if self.del > 0 {
504 let del = self.del;
505 let src: *const Self::Item = &v[i];
506 let dst: *mut Self::Item = &mut v[i - del];
507 ptr::copy_nonoverlapping(src, dst, 1);
508 }
509 }
510 None
511 }
512 }
513
514 fn size_hint(&self) -> (usize, Option<usize>) {
515 (0, Some(self.old_len - self.idx))
516 }
517}
518
519#[cfg(feature = "drain_filter")]
520impl<T, F> Drop for DrainFilter<'_, T, F>
521where
522 F: FnMut(&mut T::Item) -> bool,
523 T: Array,
524{
525 fn drop(&mut self) {
526 struct BackshiftOnDrop<'a, 'b, T, F>
527 where
528 F: FnMut(&mut T::Item) -> bool,
529 T: Array,
530 {
531 drain: &'b mut DrainFilter<'a, T, F>,
532 }
533
534 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
535 where
536 F: FnMut(&mut T::Item) -> bool,
537 T: Array,
538 {
539 fn drop(&mut self) {
540 unsafe {
541 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
542 let ptr = self.drain.vec.as_mut_ptr();
552 let src = ptr.add(self.drain.idx);
553 let dst = src.sub(self.drain.del);
554 let tail_len = self.drain.old_len - self.drain.idx;
555 src.copy_to(dst, tail_len);
556 }
557 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
558 }
559 }
560 }
561
562 let backshift = BackshiftOnDrop { drain: self };
563
564 if !backshift.drain.panic_flag {
568 backshift.drain.for_each(drop);
569 }
570 }
571}
572
573#[cfg(feature = "drain_keep_rest")]
574impl<T, F> DrainFilter<'_, T, F>
575where
576 F: FnMut(&mut T::Item) -> bool,
577 T: Array,
578{
579 pub fn keep_rest(self) {
599 let mut this = ManuallyDrop::new(self);
616
617 unsafe {
618 let needs_move = mem::size_of::<T::Item>() != 0;
620
621 if needs_move && this.idx < this.old_len && this.del > 0 {
622 let ptr = this.vec.as_mut_ptr();
623 let src = ptr.add(this.idx);
624 let dst = src.sub(this.del);
625 let tail_len = this.old_len - this.idx;
626 src.copy_to(dst, tail_len);
627 }
628
629 let new_len = this.old_len - this.del;
630 this.vec.set_len(new_len);
631 }
632 }
633}
634
635#[cfg(feature = "union")]
636union SmallVecData<A: Array> {
637 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
638 heap: (NonNull<A::Item>, usize),
639}
640
641#[cfg(all(feature = "union", feature = "const_new"))]
642impl<T, const N: usize> SmallVecData<[T; N]> {
643 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
644 #[inline]
645 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
646 SmallVecData {
647 inline: core::mem::ManuallyDrop::new(inline),
648 }
649 }
650}
651
652#[cfg(feature = "union")]
653impl<A: Array> SmallVecData<A> {
654 #[inline]
655 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
656 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
657 }
658 #[inline]
659 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
660 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
661 }
662 #[inline]
663 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
664 SmallVecData {
665 inline: core::mem::ManuallyDrop::new(inline),
666 }
667 }
668 #[inline]
678 fn empty() -> SmallVecData<A> {
679 SmallVecData {
683 inline: unsafe { MaybeUninit::uninit().assume_init() },
684 }
685 }
686 #[inline]
687 unsafe fn into_inline(self) -> MaybeUninit<A> {
688 core::mem::ManuallyDrop::into_inner(self.inline)
689 }
690 #[inline]
691 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
692 (ConstNonNull(self.heap.0), self.heap.1)
693 }
694 #[inline]
695 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
696 let h = &mut self.heap;
697 (h.0, &mut h.1)
698 }
699 #[inline]
700 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
701 SmallVecData { heap: (ptr, len) }
702 }
703}
704
705#[cfg(not(feature = "union"))]
706enum SmallVecData<A: Array> {
707 Inline(MaybeUninit<A>),
708 Heap {
710 ptr: NonNull<A::Item>,
715 len: usize,
716 },
717}
718
719#[cfg(all(not(feature = "union"), feature = "const_new"))]
720impl<T, const N: usize> SmallVecData<[T; N]> {
721 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
722 #[inline]
723 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
724 SmallVecData::Inline(inline)
725 }
726}
727
728#[cfg(not(feature = "union"))]
729impl<A: Array> SmallVecData<A> {
730 #[inline]
731 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
732 match self {
733 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
734 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
735 }
736 }
737 #[inline]
738 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
739 match self {
740 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
741 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
742 }
743 }
744 #[inline]
745 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
746 SmallVecData::Inline(inline)
747 }
748 #[inline]
750 fn empty() -> SmallVecData<A> {
751 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
755 }
756 #[inline]
757 unsafe fn into_inline(self) -> MaybeUninit<A> {
758 match self {
759 SmallVecData::Inline(a) => a,
760 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
761 }
762 }
763 #[inline]
764 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
765 match self {
766 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
767 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
768 }
769 }
770 #[inline]
771 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
772 match self {
773 SmallVecData::Heap { ptr, len } => (*ptr, len),
774 _ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
775 }
776 }
777 #[inline]
778 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
779 SmallVecData::Heap { ptr, len }
780 }
781}
782
783unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
784unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
785
786pub struct SmallVec<A: Array> {
834 capacity: usize,
840 data: SmallVecData<A>,
841 _marker: PhantomData<A::Item>,
844}
845
846impl<A: Array> SmallVec<A> {
847 #[inline]
849 pub fn new() -> SmallVec<A> {
850 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!(
853 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
854 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
855 );
856 SmallVec {
857 capacity: 0,
858 data: SmallVecData::empty(),
859 _marker: PhantomData,
860 }
861 }
862
863 #[inline]
878 pub fn with_capacity(n: usize) -> Self {
879 let mut v = SmallVec::new();
880 v.reserve_exact(n);
881 v
882 }
883
884 #[inline]
898 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
899 if vec.capacity() <= Self::inline_capacity() {
900 unsafe {
903 let mut data = SmallVecData::<A>::empty();
904 let len = vec.len();
905 vec.set_len(0);
906 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
907
908 SmallVec {
909 capacity: len,
910 data,
911 _marker: PhantomData,
912 }
913 }
914 } else {
915 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
916 mem::forget(vec);
917 let ptr = NonNull::new(ptr)
918 .expect("Cannot be null by `Vec` invariant");
920
921 SmallVec {
922 capacity: cap,
923 data: SmallVecData::from_heap(ptr, len),
924 _marker: PhantomData,
925 }
926 }
927 }
928
929 #[inline]
941 pub fn from_buf(buf: A) -> SmallVec<A> {
942 SmallVec {
943 capacity: A::size(),
944 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
945 _marker: PhantomData,
946 }
947 }
948
949 #[inline]
962 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
963 if !(len <= A::size()) {
::core::panicking::panic("assertion failed: len <= A::size()")
};assert!(len <= A::size());
964 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
965 }
966
967 #[inline]
981 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
982 SmallVec {
983 capacity: len,
984 data: SmallVecData::from_inline(buf),
985 _marker: PhantomData,
986 }
987 }
988
989 pub unsafe fn set_len(&mut self, new_len: usize) {
995 let (_, len_ptr, _) = self.triple_mut();
996 *len_ptr = new_len;
997 }
998
999 #[inline]
1001 fn inline_capacity() -> usize {
1002 if mem::size_of::<A::Item>() > 0 {
1003 A::size()
1004 } else {
1005 #[allow(deprecated)]
1018 core::usize::MAX
1019 }
1020 }
1021
1022 #[inline]
1024 pub fn inline_size(&self) -> usize {
1025 Self::inline_capacity()
1026 }
1027
1028 #[inline]
1030 pub fn len(&self) -> usize {
1031 self.triple().1
1032 }
1033
1034 #[inline]
1036 pub fn is_empty(&self) -> bool {
1037 self.len() == 0
1038 }
1039
1040 #[inline]
1042 pub fn capacity(&self) -> usize {
1043 self.triple().2
1044 }
1045
1046 #[inline]
1050 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1051 unsafe {
1052 if self.spilled() {
1053 let (ptr, len) = self.data.heap();
1054 (ptr, len, self.capacity)
1055 } else {
1056 (self.data.inline(), self.capacity, Self::inline_capacity())
1057 }
1058 }
1059 }
1060
1061 #[inline]
1063 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1064 unsafe {
1065 if self.spilled() {
1066 let (ptr, len_ptr) = self.data.heap_mut();
1067 (ptr, len_ptr, self.capacity)
1068 } else {
1069 (
1070 self.data.inline_mut(),
1071 &mut self.capacity,
1072 Self::inline_capacity(),
1073 )
1074 }
1075 }
1076 }
1077
1078 #[inline]
1081 pub fn spilled(&self) -> bool {
1082 self.capacity > Self::inline_capacity()
1083 }
1084
1085 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1099 where
1100 R: RangeBounds<usize>,
1101 {
1102 use core::ops::Bound::*;
1103
1104 let len = self.len();
1105 let start = match range.start_bound() {
1106 Included(&n) => n,
1107 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1108 Unbounded => 0,
1109 };
1110 let end = match range.end_bound() {
1111 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1112 Excluded(&n) => n,
1113 Unbounded => len,
1114 };
1115
1116 if !(start <= end) {
::core::panicking::panic("assertion failed: start <= end")
};assert!(start <= end);
1117 if !(end <= len) { ::core::panicking::panic("assertion failed: end <= len") };assert!(end <= len);
1118
1119 unsafe {
1120 self.set_len(start);
1121
1122 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1123
1124 Drain {
1125 tail_start: end,
1126 tail_len: len - end,
1127 iter: range_slice.iter(),
1128 vec: NonNull::new_unchecked(self as *mut _),
1131 }
1132 }
1133 }
1134
1135 #[cfg(feature = "drain_filter")]
1136 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1193 where
1194 F: FnMut(&mut A::Item) -> bool,
1195 {
1196 let old_len = self.len();
1197
1198 unsafe {
1200 self.set_len(0);
1201 }
1202
1203 DrainFilter {
1204 vec: self,
1205 idx: 0,
1206 del: 0,
1207 old_len,
1208 pred: filter,
1209 panic_flag: false,
1210 }
1211 }
1212
1213 #[inline]
1215 pub fn push(&mut self, value: A::Item) {
1216 unsafe {
1217 if self.spilled() {
1218 let (mut ptr, mut len_ptr) = self.data.heap_mut();
1219 if *len_ptr == self.capacity {
1220 self.reserve_one_unchecked();
1221 let (heap_ptr, heap_len) = self.data.heap_mut();
1222 ptr = heap_ptr;
1223 len_ptr = heap_len;
1224 }
1225 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1226 *len_ptr += 1;
1227 } else {
1228 let mut ptr = self.data.inline_mut();
1229 let mut len_ptr = &mut self.capacity;
1230 if *len_ptr == Self::inline_capacity() {
1231 self.reserve_one_unchecked();
1232 let (heap_ptr, heap_len) = self.data.heap_mut();
1233 ptr = heap_ptr;
1234 len_ptr = heap_len;
1235 }
1236 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1237 *len_ptr += 1;
1238 };
1239 }
1240 }
1241
1242 #[inline]
1245 pub fn pop(&mut self) -> Option<A::Item> {
1246 unsafe {
1247 let (ptr, len_ptr, _) = self.triple_mut();
1248 let ptr: *const _ = ptr.as_ptr();
1249 if *len_ptr == 0 {
1250 return None;
1251 }
1252 let last_index = *len_ptr - 1;
1253 *len_ptr = last_index;
1254 Some(ptr::read(ptr.add(last_index)))
1255 }
1256 }
1257
1258 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1271 where
1272 B: Array<Item = A::Item>,
1273 {
1274 self.extend(other.drain(..))
1275 }
1276
1277 pub fn grow(&mut self, new_cap: usize) {
1282 infallible(self.try_grow(new_cap))
1283 }
1284
1285 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1289 unsafe {
1290 let unspilled = !self.spilled();
1291 let (ptr, &mut len, cap) = self.triple_mut();
1292 if !(new_cap >= len) {
::core::panicking::panic("assertion failed: new_cap >= len")
};assert!(new_cap >= len);
1293 if new_cap <= Self::inline_capacity() {
1294 if unspilled {
1295 return Ok(());
1296 }
1297 self.data = SmallVecData::empty();
1298 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1299 self.capacity = len;
1300 deallocate(ptr, cap);
1301 } else if new_cap != cap {
1302 let layout = layout_array::<A::Item>(new_cap)?;
1303 if true {
if !(layout.size() > 0) {
::core::panicking::panic("assertion failed: layout.size() > 0")
};
};debug_assert!(layout.size() > 0);
1304 let new_alloc;
1305 if unspilled {
1306 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1307 .ok_or(CollectionAllocErr::AllocErr { layout })?
1308 .cast();
1309 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1310 } else {
1311 let old_layout = layout_array::<A::Item>(cap)?;
1314
1315 let new_ptr =
1316 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1317 new_alloc = NonNull::new(new_ptr)
1318 .ok_or(CollectionAllocErr::AllocErr { layout })?
1319 .cast();
1320 }
1321 self.data = SmallVecData::from_heap(new_alloc, len);
1322 self.capacity = new_cap;
1323 }
1324 Ok(())
1325 }
1326 }
1327
1328 #[inline]
1334 pub fn reserve(&mut self, additional: usize) {
1335 infallible(self.try_reserve(additional))
1336 }
1337
1338 #[cold]
1341 fn reserve_one_unchecked(&mut self) {
1342 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());
1343 let new_cap = self
1344 .len()
1345 .checked_add(1)
1346 .and_then(usize::checked_next_power_of_two)
1347 .expect("capacity overflow");
1348 infallible(self.try_grow(new_cap))
1349 }
1350
1351 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1355 let (_, &mut len, cap) = self.triple_mut();
1358 if cap - len >= additional {
1359 return Ok(());
1360 }
1361 let new_cap = len
1362 .checked_add(additional)
1363 .and_then(usize::checked_next_power_of_two)
1364 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1365 self.try_grow(new_cap)
1366 }
1367
1368 pub fn reserve_exact(&mut self, additional: usize) {
1373 infallible(self.try_reserve_exact(additional))
1374 }
1375
1376 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1379 let (_, &mut len, cap) = self.triple_mut();
1380 if cap - len >= additional {
1381 return Ok(());
1382 }
1383 let new_cap = len
1384 .checked_add(additional)
1385 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1386 self.try_grow(new_cap)
1387 }
1388
1389 pub fn shrink_to_fit(&mut self) {
1394 if !self.spilled() {
1395 return;
1396 }
1397 let len = self.len();
1398 if self.inline_size() >= len {
1399 unsafe {
1400 let (ptr, len) = self.data.heap();
1401 self.data = SmallVecData::empty();
1402 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1403 deallocate(ptr.0, self.capacity);
1404 self.capacity = len;
1405 }
1406 } else if self.capacity() > len {
1407 self.grow(len);
1408 }
1409 }
1410
1411 pub fn truncate(&mut self, len: usize) {
1420 unsafe {
1421 let (ptr, len_ptr, _) = self.triple_mut();
1422 let ptr = ptr.as_ptr();
1423 while len < *len_ptr {
1424 let last_index = *len_ptr - 1;
1425 *len_ptr = last_index;
1426 ptr::drop_in_place(ptr.add(last_index));
1427 }
1428 }
1429 }
1430
1431 pub fn as_slice(&self) -> &[A::Item] {
1435 self
1436 }
1437
1438 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1442 self
1443 }
1444
1445 #[inline]
1452 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1453 let len = self.len();
1454 self.swap(len - 1, index);
1455 self.pop()
1456 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1457 }
1458
1459 #[inline]
1461 pub fn clear(&mut self) {
1462 self.truncate(0);
1463 }
1464
1465 pub fn remove(&mut self, index: usize) -> A::Item {
1470 unsafe {
1471 let (ptr, len_ptr, _) = self.triple_mut();
1472 let len = *len_ptr;
1473 if !(index < len) {
::core::panicking::panic("assertion failed: index < len")
};assert!(index < len);
1474 *len_ptr = len - 1;
1475 let ptr = ptr.as_ptr().add(index);
1476 let item = ptr::read(ptr);
1477 ptr::copy(ptr.add(1), ptr, len - index - 1);
1478 item
1479 }
1480 }
1481
1482 pub fn insert(&mut self, index: usize, element: A::Item) {
1487 unsafe {
1488 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1489 if *len_ptr == cap {
1490 self.reserve_one_unchecked();
1491 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1492 ptr = heap_ptr;
1493 len_ptr = heap_len_ptr;
1494 }
1495 let mut ptr = ptr.as_ptr();
1496 let len = *len_ptr;
1497 if index > len {
1498 ::core::panicking::panic("index exceeds length");panic!("index exceeds length");
1499 }
1500 ptr = ptr.add(index);
1502 if index < len {
1503 ptr::copy(ptr, ptr.add(1), len - index);
1505 }
1506 *len_ptr = len + 1;
1507 ptr::write(ptr, element);
1508 }
1509 }
1510
1511 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1514 let mut iter = iterable.into_iter();
1515 if index == self.len() {
1516 return self.extend(iter);
1517 }
1518
1519 let (lower_size_bound, _) = iter.size_hint();
1520 #[allow(deprecated)]
1521 {
1522 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)
1523 } 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;
1527 let old_len = self.len();
1528 if !(index <= old_len) {
::core::panicking::panic("assertion failed: index <= old_len")
};assert!(index <= old_len);
1529
1530 unsafe {
1531 self.reserve(lower_size_bound);
1533 let start = self.as_mut_ptr();
1534 let ptr = start.add(index);
1535
1536 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1538
1539 self.set_len(0);
1542 let mut guard = DropOnPanic {
1543 start,
1544 skip: index..(index + lower_size_bound),
1545 len: old_len + lower_size_bound,
1546 };
1547
1548 let start = self.as_mut_ptr();
1551 let ptr = start.add(index);
1552
1553 while num_added < lower_size_bound {
1554 let element = match iter.next() {
1555 Some(x) => x,
1556 None => break,
1557 };
1558 let cur = ptr.add(num_added);
1559 ptr::write(cur, element);
1560 guard.skip.start += 1;
1561 num_added += 1;
1562 }
1563
1564 if num_added < lower_size_bound {
1565 ptr::copy(
1568 ptr.add(lower_size_bound),
1569 ptr.add(num_added),
1570 old_len - index,
1571 );
1572 }
1573 self.set_len(old_len + num_added);
1576 mem::forget(guard);
1577 }
1578
1579 for element in iter {
1581 self.insert(index + num_added, element);
1582 num_added += 1;
1583 }
1584
1585 struct DropOnPanic<T> {
1586 start: *mut T,
1587 skip: Range<usize>, len: usize,
1589 }
1590
1591 impl<T> Drop for DropOnPanic<T> {
1592 fn drop(&mut self) {
1593 for i in 0..self.len {
1594 if !self.skip.contains(&i) {
1595 unsafe {
1596 ptr::drop_in_place(self.start.add(i));
1597 }
1598 }
1599 }
1600 }
1601 }
1602 }
1603
1604 pub fn into_vec(mut self) -> Vec<A::Item> {
1607 if self.spilled() {
1608 unsafe {
1609 let (ptr, &mut len) = self.data.heap_mut();
1610 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1611 mem::forget(self);
1612 v
1613 }
1614 } else {
1615 self.into_iter().collect()
1616 }
1617 }
1618
1619 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1624 self.into_vec().into_boxed_slice()
1625 }
1626
1627 pub fn into_inner(self) -> Result<A, Self> {
1634 if self.spilled() || self.len() != A::size() {
1635 Err(self)
1637 } else {
1638 unsafe {
1639 let data = ptr::read(&self.data);
1640 mem::forget(self);
1641 Ok(data.into_inline().assume_init())
1642 }
1643 }
1644 }
1645
1646 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1652 let original_len = self.len();
1653
1654 if original_len == 0 {
1655 return;
1658 }
1659
1660 struct PanicGuard<'a, A: Array> {
1672 v: &'a mut SmallVec<A>,
1673 read: usize,
1674 write: usize,
1675 original_len: usize,
1676 }
1677
1678 impl<A: Array> Drop for PanicGuard<'_, A> {
1679 #[cold]
1680 fn drop(&mut self) {
1681 let remaining = self.original_len - self.read;
1682 unsafe {
1685 let ptr = self.v.as_mut_ptr();
1686 ptr::copy(ptr.add(self.read), ptr.add(self.write), remaining);
1687 }
1688 unsafe {
1691 self.v.set_len(self.write + remaining);
1692 }
1693 }
1694 }
1695
1696 let mut read = 0;
1697 loop {
1698 let cur = unsafe { self.get_unchecked_mut(read) };
1700 if !f(cur) {
1701 break;
1702 }
1703 read += 1;
1704 if read == original_len {
1705 return;
1707 }
1708 }
1709
1710 let mut g = PanicGuard {
1714 v: self,
1715 read: read + 1,
1716 write: read,
1717 original_len,
1718 };
1719 unsafe { ptr::drop_in_place(g.v.as_mut_ptr().add(read)) }
1721
1722 let ptr = g.v.as_mut_ptr();
1723 while g.read < g.original_len {
1724 let cur = unsafe { &mut *ptr.add(g.read) };
1726 if !f(cur) {
1727 g.read += 1;
1730 unsafe { ptr::drop_in_place(cur) };
1732 } else {
1733 unsafe {
1737 let hole = ptr.add(g.write);
1738 ptr::copy_nonoverlapping(cur, hole, 1);
1739 }
1740 g.write += 1;
1741 g.read += 1;
1742 }
1743 }
1744
1745 unsafe { g.v.set_len(g.write) };
1749 core::mem::forget(g);
1750 }
1751
1752 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1758 self.retain(f)
1759 }
1760
1761 pub fn dedup(&mut self)
1763 where
1764 A::Item: PartialEq<A::Item>,
1765 {
1766 self.dedup_by(|a, b| a == b);
1767 }
1768
1769 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1772 where
1773 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1774 {
1775 let len = self.len();
1778 if len <= 1 {
1779 return;
1780 }
1781
1782 let ptr = self.as_mut_ptr();
1783 let mut w: usize = 1;
1784
1785 unsafe {
1786 for r in 1..len {
1787 let p_r = ptr.add(r);
1788 let p_wm1 = ptr.add(w - 1);
1789 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1790 if r != w {
1791 let p_w = p_wm1.add(1);
1792 mem::swap(&mut *p_r, &mut *p_w);
1793 }
1794 w += 1;
1795 }
1796 }
1797 }
1798
1799 self.truncate(w);
1800 }
1801
1802 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1804 where
1805 F: FnMut(&mut A::Item) -> K,
1806 K: PartialEq<K>,
1807 {
1808 self.dedup_by(|a, b| key(a) == key(b));
1809 }
1810
1811 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1842 where
1843 F: FnMut() -> A::Item,
1844 {
1845 let old_len = self.len();
1846 if old_len < new_len {
1847 let mut f = f;
1848 let additional = new_len - old_len;
1849 self.reserve(additional);
1850 for _ in 0..additional {
1851 self.push(f());
1852 }
1853 } else if old_len > new_len {
1854 self.truncate(new_len);
1855 }
1856 }
1857
1858 #[inline]
1926 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1927 let ptr = unsafe {
1930 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.");
1931 NonNull::new_unchecked(ptr)
1932 };
1933 if !(capacity > Self::inline_capacity()) {
::core::panicking::panic("assertion failed: capacity > Self::inline_capacity()")
};assert!(capacity > Self::inline_capacity());
1934 SmallVec {
1935 capacity,
1936 data: SmallVecData::from_heap(ptr, length),
1937 _marker: PhantomData,
1938 }
1939 }
1940
1941 pub fn as_ptr(&self) -> *const A::Item {
1943 self.triple().0.as_ptr()
1947 }
1948
1949 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1951 self.triple_mut().0.as_ptr()
1955 }
1956}
1957
1958impl<A: Array> SmallVec<A>
1959where
1960 A::Item: Copy,
1961{
1962 pub fn from_slice(slice: &[A::Item]) -> Self {
1967 let len = slice.len();
1968 if len <= Self::inline_capacity() {
1969 SmallVec {
1970 capacity: len,
1971 data: SmallVecData::from_inline(unsafe {
1972 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1973 ptr::copy_nonoverlapping(
1974 slice.as_ptr(),
1975 data.as_mut_ptr() as *mut A::Item,
1976 len,
1977 );
1978 data
1979 }),
1980 _marker: PhantomData,
1981 }
1982 } else {
1983 let mut b = slice.to_vec();
1984 let cap = b.capacity();
1985 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1986 mem::forget(b);
1987 SmallVec {
1988 capacity: cap,
1989 data: SmallVecData::from_heap(ptr, len),
1990 _marker: PhantomData,
1991 }
1992 }
1993 }
1994
1995 #[inline]
2000 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
2001 self.reserve(slice.len());
2002
2003 let len = self.len();
2004 if !(index <= len) {
::core::panicking::panic("assertion failed: index <= len")
};assert!(index <= len);
2005
2006 unsafe {
2007 let slice_ptr = slice.as_ptr();
2008 let ptr = self.as_mut_ptr().add(index);
2009 ptr::copy(ptr, ptr.add(slice.len()), len - index);
2010 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
2011 self.set_len(len + slice.len());
2012 }
2013 }
2014
2015 #[inline]
2019 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
2020 let len = self.len();
2021 self.insert_from_slice(len, slice);
2022 }
2023}
2024
2025impl<A: Array> SmallVec<A>
2026where
2027 A::Item: Clone,
2028{
2029 pub fn resize(&mut self, len: usize, value: A::Item) {
2036 let old_len = self.len();
2037
2038 if len > old_len {
2039 self.extend(repeat(value).take(len - old_len));
2040 } else {
2041 self.truncate(len);
2042 }
2043 }
2044
2045 pub fn from_elem(elem: A::Item, n: usize) -> Self {
2053 if n > Self::inline_capacity() {
2054 ::alloc::vec::from_elem(elem, n)vec![elem; n].into()
2055 } else {
2056 let mut v = SmallVec::<A>::new();
2057 unsafe {
2058 let (ptr, len_ptr, _) = v.triple_mut();
2059 let ptr = ptr.as_ptr();
2060 let mut local_len = SetLenOnDrop::new(len_ptr);
2061
2062 for i in 0..n {
2063 ::core::ptr::write(ptr.add(i), elem.clone());
2064 local_len.increment_len(1);
2065 }
2066 }
2067 v
2068 }
2069 }
2070}
2071
2072impl<A: Array> ops::Deref for SmallVec<A> {
2073 type Target = [A::Item];
2074 #[inline]
2075 fn deref(&self) -> &[A::Item] {
2076 unsafe {
2077 let (ptr, len, _) = self.triple();
2078 slice::from_raw_parts(ptr.as_ptr(), len)
2079 }
2080 }
2081}
2082
2083impl<A: Array> ops::DerefMut for SmallVec<A> {
2084 #[inline]
2085 fn deref_mut(&mut self) -> &mut [A::Item] {
2086 unsafe {
2087 let (ptr, &mut len, _) = self.triple_mut();
2088 slice::from_raw_parts_mut(ptr.as_ptr(), len)
2089 }
2090 }
2091}
2092
2093impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
2094 #[inline]
2095 fn as_ref(&self) -> &[A::Item] {
2096 self
2097 }
2098}
2099
2100impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
2101 #[inline]
2102 fn as_mut(&mut self) -> &mut [A::Item] {
2103 self
2104 }
2105}
2106
2107impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
2108 #[inline]
2109 fn borrow(&self) -> &[A::Item] {
2110 self
2111 }
2112}
2113
2114impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
2115 #[inline]
2116 fn borrow_mut(&mut self) -> &mut [A::Item] {
2117 self
2118 }
2119}
2120
2121#[cfg(feature = "write")]
2122#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
2123impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
2124 #[inline]
2125 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2126 self.extend_from_slice(buf);
2127 Ok(buf.len())
2128 }
2129
2130 #[inline]
2131 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2132 self.extend_from_slice(buf);
2133 Ok(())
2134 }
2135
2136 #[inline]
2137 fn flush(&mut self) -> io::Result<()> {
2138 Ok(())
2139 }
2140}
2141
2142#[cfg(feature = "serde")]
2143#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2144impl<A: Array> Serialize for SmallVec<A>
2145where
2146 A::Item: Serialize,
2147{
2148 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2149 let mut state = serializer.serialize_seq(Some(self.len()))?;
2150 for item in self {
2151 state.serialize_element(&item)?;
2152 }
2153 state.end()
2154 }
2155}
2156
2157#[cfg(feature = "serde")]
2158#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2159impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2160where
2161 A::Item: Deserialize<'de>,
2162{
2163 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2164 deserializer.deserialize_seq(SmallVecVisitor {
2165 phantom: PhantomData,
2166 })
2167 }
2168}
2169
2170#[cfg(feature = "serde")]
2171struct SmallVecVisitor<A> {
2172 phantom: PhantomData<A>,
2173}
2174
2175#[cfg(feature = "serde")]
2176impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2177where
2178 A::Item: Deserialize<'de>,
2179{
2180 type Value = SmallVec<A>;
2181
2182 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2183 formatter.write_str("a sequence")
2184 }
2185
2186 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2187 where
2188 B: SeqAccess<'de>,
2189 {
2190 use serde::de::Error;
2191 let len = seq.size_hint().unwrap_or(0);
2192 let mut values = SmallVec::new();
2193 values.try_reserve(len).map_err(B::Error::custom)?;
2194
2195 while let Some(value) = seq.next_element()? {
2196 values.push(value);
2197 }
2198
2199 Ok(values)
2200 }
2201}
2202
2203#[cfg(feature = "malloc_size_of")]
2204impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2205 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2206 if self.spilled() {
2207 unsafe { ops.malloc_size_of(self.as_ptr()) }
2208 } else {
2209 0
2210 }
2211 }
2212}
2213
2214#[cfg(feature = "malloc_size_of")]
2215impl<A> MallocSizeOf for SmallVec<A>
2216where
2217 A: Array,
2218 A::Item: MallocSizeOf,
2219{
2220 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2221 let mut n = self.shallow_size_of(ops);
2222 for elem in self.iter() {
2223 n += elem.size_of(ops);
2224 }
2225 n
2226 }
2227}
2228
2229#[cfg(feature = "specialization")]
2230trait SpecFrom<A: Array, S> {
2231 fn spec_from(slice: S) -> SmallVec<A>;
2232}
2233
2234#[cfg(feature = "specialization")]
2235mod specialization;
2236
2237#[cfg(feature = "arbitrary")]
2238mod arbitrary;
2239
2240#[cfg(feature = "specialization")]
2241impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2242where
2243 A::Item: Copy,
2244{
2245 #[inline]
2246 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2247 SmallVec::from_slice(slice)
2248 }
2249}
2250
2251impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2252where
2253 A::Item: Clone,
2254{
2255 #[cfg(not(feature = "specialization"))]
2256 #[inline]
2257 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2258 slice.iter().cloned().collect()
2259 }
2260
2261 #[cfg(feature = "specialization")]
2262 #[inline]
2263 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2264 SmallVec::spec_from(slice)
2265 }
2266}
2267
2268impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2269 #[inline]
2270 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2271 SmallVec::from_vec(vec)
2272 }
2273}
2274
2275impl<A: Array> From<A> for SmallVec<A> {
2276 #[inline]
2277 fn from(array: A) -> SmallVec<A> {
2278 SmallVec::from_buf(array)
2279 }
2280}
2281
2282impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2283 type Output = I::Output;
2284
2285 fn index(&self, index: I) -> &I::Output {
2286 &(**self)[index]
2287 }
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 {
2292 &mut (&mut **self)[index]
2293 }
2294}
2295
2296#[allow(deprecated)]
2297impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2298where
2299 A::Item: Copy,
2300{
2301 fn extend_from_slice(&mut self, other: &[A::Item]) {
2302 SmallVec::extend_from_slice(self, other)
2303 }
2304}
2305
2306impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2307 #[inline]
2308 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2309 let mut v = SmallVec::new();
2310 v.extend(iterable);
2311 v
2312 }
2313}
2314
2315impl<A: Array> Extend<A::Item> for SmallVec<A> {
2316 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2317 let mut iter = iterable.into_iter();
2318 let (lower_size_bound, _) = iter.size_hint();
2319 self.reserve(lower_size_bound);
2320
2321 unsafe {
2322 let (ptr, len_ptr, cap) = self.triple_mut();
2323 let ptr = ptr.as_ptr();
2324 let mut len = SetLenOnDrop::new(len_ptr);
2325 while len.get() < cap {
2326 if let Some(out) = iter.next() {
2327 ptr::write(ptr.add(len.get()), out);
2328 len.increment_len(1);
2329 } else {
2330 return;
2331 }
2332 }
2333 }
2334
2335 for elem in iter {
2336 self.push(elem);
2337 }
2338 }
2339}
2340
2341impl<A: Array> fmt::Debug for SmallVec<A>
2342where
2343 A::Item: fmt::Debug,
2344{
2345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2346 f.debug_list().entries(self.iter()).finish()
2347 }
2348}
2349
2350impl<A: Array> Default for SmallVec<A> {
2351 #[inline]
2352 fn default() -> SmallVec<A> {
2353 SmallVec::new()
2354 }
2355}
2356
2357#[cfg(feature = "may_dangle")]
2358unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2359 fn drop(&mut self) {
2360 unsafe {
2361 if self.spilled() {
2362 let (ptr, &mut len) = self.data.heap_mut();
2363 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2364 } else {
2365 ptr::drop_in_place(&mut self[..]);
2366 }
2367 }
2368 }
2369}
2370
2371#[cfg(not(feature = "may_dangle"))]
2372impl<A: Array> Drop for SmallVec<A> {
2373 fn drop(&mut self) {
2374 unsafe {
2375 if self.spilled() {
2376 let (ptr, &mut len) = self.data.heap_mut();
2377 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2378 } else {
2379 ptr::drop_in_place(&mut self[..]);
2380 }
2381 }
2382 }
2383}
2384
2385impl<A: Array> Clone for SmallVec<A>
2386where
2387 A::Item: Clone,
2388{
2389 #[inline]
2390 fn clone(&self) -> SmallVec<A> {
2391 SmallVec::from(self.as_slice())
2392 }
2393
2394 fn clone_from(&mut self, source: &Self) {
2395 self.truncate(source.len());
2399
2400 let (init, tail) = source.split_at(self.len());
2403
2404 self.clone_from_slice(init);
2406 self.extend(tail.iter().cloned());
2407 }
2408}
2409
2410impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2411where
2412 A::Item: PartialEq<B::Item>,
2413{
2414 #[inline]
2415 fn eq(&self, other: &SmallVec<B>) -> bool {
2416 self[..] == other[..]
2417 }
2418}
2419
2420impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2421
2422impl<A: Array> PartialOrd for SmallVec<A>
2423where
2424 A::Item: PartialOrd,
2425{
2426 #[inline]
2427 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2428 PartialOrd::partial_cmp(&**self, &**other)
2429 }
2430}
2431
2432impl<A: Array> Ord for SmallVec<A>
2433where
2434 A::Item: Ord,
2435{
2436 #[inline]
2437 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2438 Ord::cmp(&**self, &**other)
2439 }
2440}
2441
2442impl<A: Array> Hash for SmallVec<A>
2443where
2444 A::Item: Hash,
2445{
2446 fn hash<H: Hasher>(&self, state: &mut H) {
2447 (**self).hash(state)
2448 }
2449}
2450
2451unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2452
2453pub struct IntoIter<A: Array> {
2459 data: SmallVec<A>,
2460 current: usize,
2461 end: usize,
2462}
2463
2464impl<A: Array> fmt::Debug for IntoIter<A>
2465where
2466 A::Item: fmt::Debug,
2467{
2468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2469 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2470 }
2471}
2472
2473impl<A: Array + Clone> Clone for IntoIter<A>
2474where
2475 A::Item: Clone,
2476{
2477 fn clone(&self) -> IntoIter<A> {
2478 SmallVec::from(self.as_slice()).into_iter()
2479 }
2480}
2481
2482impl<A: Array> Drop for IntoIter<A> {
2483 fn drop(&mut self) {
2484 for _ in self {}
2485 }
2486}
2487
2488impl<A: Array> Iterator for IntoIter<A> {
2489 type Item = A::Item;
2490
2491 #[inline]
2492 fn next(&mut self) -> Option<A::Item> {
2493 if self.current == self.end {
2494 None
2495 } else {
2496 unsafe {
2497 let current = self.current;
2498 self.current += 1;
2499 Some(ptr::read(self.data.as_ptr().add(current)))
2500 }
2501 }
2502 }
2503
2504 #[inline]
2505 fn size_hint(&self) -> (usize, Option<usize>) {
2506 let size = self.end - self.current;
2507 (size, Some(size))
2508 }
2509}
2510
2511impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2512 #[inline]
2513 fn next_back(&mut self) -> Option<A::Item> {
2514 if self.current == self.end {
2515 None
2516 } else {
2517 unsafe {
2518 self.end -= 1;
2519 Some(ptr::read(self.data.as_ptr().add(self.end)))
2520 }
2521 }
2522 }
2523}
2524
2525impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2526impl<A: Array> FusedIterator for IntoIter<A> {}
2527
2528impl<A: Array> IntoIter<A> {
2529 pub fn as_slice(&self) -> &[A::Item] {
2531 let len = self.end - self.current;
2532 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2533 }
2534
2535 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2537 let len = self.end - self.current;
2538 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2539 }
2540}
2541
2542impl<A: Array> IntoIterator for SmallVec<A> {
2543 type IntoIter = IntoIter<A>;
2544 type Item = A::Item;
2545 fn into_iter(mut self) -> Self::IntoIter {
2546 unsafe {
2547 let len = self.len();
2550 self.set_len(0);
2551 IntoIter {
2552 data: self,
2553 current: 0,
2554 end: len,
2555 }
2556 }
2557 }
2558}
2559
2560impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2561 type IntoIter = slice::Iter<'a, A::Item>;
2562 type Item = &'a A::Item;
2563 fn into_iter(self) -> Self::IntoIter {
2564 self.iter()
2565 }
2566}
2567
2568impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2569 type IntoIter = slice::IterMut<'a, A::Item>;
2570 type Item = &'a mut A::Item;
2571 fn into_iter(self) -> Self::IntoIter {
2572 self.iter_mut()
2573 }
2574}
2575
2576pub unsafe trait Array {
2578 type Item;
2580 fn size() -> usize;
2582}
2583
2584struct SetLenOnDrop<'a> {
2588 len: &'a mut usize,
2589 local_len: usize,
2590}
2591
2592impl<'a> SetLenOnDrop<'a> {
2593 #[inline]
2594 fn new(len: &'a mut usize) -> Self {
2595 SetLenOnDrop {
2596 local_len: *len,
2597 len,
2598 }
2599 }
2600
2601 #[inline]
2602 fn get(&self) -> usize {
2603 self.local_len
2604 }
2605
2606 #[inline]
2607 fn increment_len(&mut self, increment: usize) {
2608 self.local_len += increment;
2609 }
2610}
2611
2612impl<'a> Drop for SetLenOnDrop<'a> {
2613 #[inline]
2614 fn drop(&mut self) {
2615 *self.len = self.local_len;
2616 }
2617}
2618
2619#[cfg(feature = "const_new")]
2620impl<T, const N: usize> SmallVec<[T; N]> {
2621 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2626 #[inline]
2627 pub const fn new_const() -> Self {
2628 SmallVec {
2629 capacity: 0,
2630 data: SmallVecData::from_const(MaybeUninit::uninit()),
2631 _marker: PhantomData,
2632 }
2633 }
2634
2635 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2642 #[inline]
2643 pub const fn from_const(items: [T; N]) -> Self {
2644 SmallVec {
2645 capacity: N,
2646 data: SmallVecData::from_const(MaybeUninit::new(items)),
2647 _marker: PhantomData,
2648 }
2649 }
2650
2651 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2659 #[inline]
2660 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2661 SmallVec {
2662 capacity: len,
2663 data: SmallVecData::from_const(MaybeUninit::new(items)),
2664 _marker: PhantomData,
2665 }
2666 }
2667}
2668
2669#[cfg(feature = "const_generics")]
2670#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2671unsafe impl<T, const N: usize> Array for [T; N] {
2672 type Item = T;
2673 #[inline]
2674 fn size() -> usize {
2675 N
2676 }
2677}
2678
2679#[cfg(not(feature = "const_generics"))]
2680macro_rules! impl_array(
2681 ($($size:expr),+) => {
2682 $(
2683 unsafe impl<T> Array for [T; $size] {
2684 type Item = T;
2685 #[inline]
2686 fn size() -> usize { $size }
2687 }
2688 )+
2689 }
2690);
2691
2692#[cfg(not(feature = "const_generics"))]
2693impl_array!(
2694 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,
2695 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2696 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2697);
2698
2699pub trait ToSmallVec<A: Array> {
2701 fn to_smallvec(&self) -> SmallVec<A>;
2703}
2704
2705impl<A: Array> ToSmallVec<A> for [A::Item]
2706where
2707 A::Item: Copy,
2708{
2709 #[inline]
2710 fn to_smallvec(&self) -> SmallVec<A> {
2711 SmallVec::from_slice(self)
2712 }
2713}
2714
2715#[repr(transparent)]
2717struct ConstNonNull<T>(NonNull<T>);
2718
2719impl<T> ConstNonNull<T> {
2720 #[inline]
2721 fn new(ptr: *const T) -> Option<Self> {
2722 NonNull::new(ptr as *mut T).map(Self)
2723 }
2724 #[inline]
2725 fn as_ptr(self) -> *const T {
2726 self.0.as_ptr()
2727 }
2728}
2729
2730impl<T> Clone for ConstNonNull<T> {
2731 #[inline]
2732 fn clone(&self) -> Self {
2733 *self
2734 }
2735}
2736
2737impl<T> Copy for ConstNonNull<T> {}
2738
2739#[cfg(feature = "impl_bincode")]
2740use bincode::{
2741 de::{read::Reader, BorrowDecoder, Decode, Decoder},
2742 enc::{write::Writer, Encode, Encoder},
2743 error::{DecodeError, EncodeError},
2744 BorrowDecode,
2745};
2746
2747#[cfg(feature = "impl_bincode")]
2748impl<A, Context> Decode<Context> for SmallVec<A>
2749where
2750 A: Array,
2751 A::Item: Decode<Context>,
2752{
2753 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2754 use core::convert::TryInto;
2755 let len = u64::decode(decoder)?;
2756 let len = len
2757 .try_into()
2758 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2759 decoder.claim_container_read::<A::Item>(len)?;
2760
2761 let mut vec = SmallVec::with_capacity(len);
2762 if unty::type_equal::<A::Item, u8>() {
2763 let ptr = vec.as_mut_ptr();
2767 unsafe {
2770 core::ptr::write_bytes(ptr, 0, len);
2771 vec.set_len(len);
2772 }
2773 let slice = vec.as_mut_slice();
2775 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2777 decoder.reader().read(slice)?;
2778 } else {
2779 for _ in 0..len {
2780 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2781 vec.push(A::Item::decode(decoder)?);
2782 }
2783 }
2784 Ok(vec)
2785 }
2786}
2787
2788#[cfg(feature = "impl_bincode")]
2789impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2790where
2791 A: Array,
2792 A::Item: BorrowDecode<'de, Context>,
2793{
2794 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2795 decoder: &mut D,
2796 ) -> Result<Self, DecodeError> {
2797 use core::convert::TryInto;
2798 let len = u64::decode(decoder)?;
2799 let len = len
2800 .try_into()
2801 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2802 decoder.claim_container_read::<A::Item>(len)?;
2803
2804 let mut vec = SmallVec::with_capacity(len);
2805 if unty::type_equal::<A::Item, u8>() {
2806 let ptr = vec.as_mut_ptr();
2810 unsafe {
2813 core::ptr::write_bytes(ptr, 0, len);
2814 vec.set_len(len);
2815 }
2816 let slice = vec.as_mut_slice();
2818 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2820 decoder.reader().read(slice)?;
2821 } else {
2822 for _ in 0..len {
2823 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2824 vec.push(A::Item::borrow_decode(decoder)?);
2825 }
2826 }
2827 Ok(vec)
2828 }
2829}
2830
2831#[cfg(feature = "impl_bincode")]
2832impl<A> Encode for SmallVec<A>
2833where
2834 A: Array,
2835 A::Item: Encode,
2836{
2837 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2838 (self.len() as u64).encode(encoder)?;
2839 if unty::type_equal::<A::Item, u8>() {
2840 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2842 encoder.writer().write(slice)?;
2843 } else {
2844 for item in self.iter() {
2845 item.encode(encoder)?;
2846 }
2847 }
2848 Ok(())
2849 }
2850}