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 core::usize::MAX
992 }
993 }
994
995 #[inline]
997 pub fn inline_size(&self) -> usize {
998 Self::inline_capacity()
999 }
1000
1001 #[inline]
1003 pub fn len(&self) -> usize {
1004 self.triple().1
1005 }
1006
1007 #[inline]
1009 pub fn is_empty(&self) -> bool {
1010 self.len() == 0
1011 }
1012
1013 #[inline]
1015 pub fn capacity(&self) -> usize {
1016 self.triple().2
1017 }
1018
1019 #[inline]
1023 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1024 unsafe {
1025 if self.spilled() {
1026 let (ptr, len) = self.data.heap();
1027 (ptr, len, self.capacity)
1028 } else {
1029 (self.data.inline(), self.capacity, Self::inline_capacity())
1030 }
1031 }
1032 }
1033
1034 #[inline]
1036 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1037 unsafe {
1038 if self.spilled() {
1039 let (ptr, len_ptr) = self.data.heap_mut();
1040 (ptr, len_ptr, self.capacity)
1041 } else {
1042 (
1043 self.data.inline_mut(),
1044 &mut self.capacity,
1045 Self::inline_capacity(),
1046 )
1047 }
1048 }
1049 }
1050
1051 #[inline]
1054 pub fn spilled(&self) -> bool {
1055 self.capacity > Self::inline_capacity()
1056 }
1057
1058 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1072 where
1073 R: RangeBounds<usize>,
1074 {
1075 use core::ops::Bound::*;
1076
1077 let len = self.len();
1078 let start = match range.start_bound() {
1079 Included(&n) => n,
1080 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1081 Unbounded => 0,
1082 };
1083 let end = match range.end_bound() {
1084 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1085 Excluded(&n) => n,
1086 Unbounded => len,
1087 };
1088
1089 if !(start <= end) {
::core::panicking::panic("assertion failed: start <= end")
};assert!(start <= end);
1090 if !(end <= len) { ::core::panicking::panic("assertion failed: end <= len") };assert!(end <= len);
1091
1092 unsafe {
1093 self.set_len(start);
1094
1095 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1096
1097 Drain {
1098 tail_start: end,
1099 tail_len: len - end,
1100 iter: range_slice.iter(),
1101 vec: NonNull::new_unchecked(self as *mut _),
1104 }
1105 }
1106 }
1107
1108 #[cfg(feature = "drain_filter")]
1109 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1166 where
1167 F: FnMut(&mut A::Item) -> bool,
1168 {
1169 let old_len = self.len();
1170
1171 unsafe {
1173 self.set_len(0);
1174 }
1175
1176 DrainFilter {
1177 vec: self,
1178 idx: 0,
1179 del: 0,
1180 old_len,
1181 pred: filter,
1182 panic_flag: false,
1183 }
1184 }
1185
1186 #[inline]
1188 pub fn push(&mut self, value: A::Item) {
1189 unsafe {
1190 let (mut ptr, mut len, cap) = self.triple_mut();
1191 if *len == cap {
1192 self.reserve_one_unchecked();
1193 let (heap_ptr, heap_len) = self.data.heap_mut();
1194 ptr = heap_ptr;
1195 len = heap_len;
1196 }
1197 ptr::write(ptr.as_ptr().add(*len), value);
1198 *len += 1;
1199 }
1200 }
1201
1202 #[inline]
1205 pub fn pop(&mut self) -> Option<A::Item> {
1206 unsafe {
1207 let (ptr, len_ptr, _) = self.triple_mut();
1208 let ptr: *const _ = ptr.as_ptr();
1209 if *len_ptr == 0 {
1210 return None;
1211 }
1212 let last_index = *len_ptr - 1;
1213 *len_ptr = last_index;
1214 Some(ptr::read(ptr.add(last_index)))
1215 }
1216 }
1217
1218 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1231 where
1232 B: Array<Item = A::Item>,
1233 {
1234 self.extend(other.drain(..))
1235 }
1236
1237 pub fn grow(&mut self, new_cap: usize) {
1242 infallible(self.try_grow(new_cap))
1243 }
1244
1245 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1249 unsafe {
1250 let unspilled = !self.spilled();
1251 let (ptr, &mut len, cap) = self.triple_mut();
1252 if !(new_cap >= len) {
::core::panicking::panic("assertion failed: new_cap >= len")
};assert!(new_cap >= len);
1253 if new_cap <= Self::inline_capacity() {
1254 if unspilled {
1255 return Ok(());
1256 }
1257 self.data = SmallVecData::empty();
1258 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1259 self.capacity = len;
1260 deallocate(ptr, cap);
1261 } else if new_cap != cap {
1262 let layout = layout_array::<A::Item>(new_cap)?;
1263 if true {
if !(layout.size() > 0) {
::core::panicking::panic("assertion failed: layout.size() > 0")
};
};debug_assert!(layout.size() > 0);
1264 let new_alloc;
1265 if unspilled {
1266 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1267 .ok_or(CollectionAllocErr::AllocErr { layout })?
1268 .cast();
1269 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1270 } else {
1271 let old_layout = layout_array::<A::Item>(cap)?;
1274
1275 let new_ptr =
1276 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1277 new_alloc = NonNull::new(new_ptr)
1278 .ok_or(CollectionAllocErr::AllocErr { layout })?
1279 .cast();
1280 }
1281 self.data = SmallVecData::from_heap(new_alloc, len);
1282 self.capacity = new_cap;
1283 }
1284 Ok(())
1285 }
1286 }
1287
1288 #[inline]
1294 pub fn reserve(&mut self, additional: usize) {
1295 infallible(self.try_reserve(additional))
1296 }
1297
1298 #[cold]
1301 fn reserve_one_unchecked(&mut self) {
1302 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());
1303 let new_cap = self
1304 .len()
1305 .checked_add(1)
1306 .and_then(usize::checked_next_power_of_two)
1307 .expect("capacity overflow");
1308 infallible(self.try_grow(new_cap))
1309 }
1310
1311 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1315 let (_, &mut len, cap) = self.triple_mut();
1318 if cap - len >= additional {
1319 return Ok(());
1320 }
1321 let new_cap = len
1322 .checked_add(additional)
1323 .and_then(usize::checked_next_power_of_two)
1324 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1325 self.try_grow(new_cap)
1326 }
1327
1328 pub fn reserve_exact(&mut self, additional: usize) {
1333 infallible(self.try_reserve_exact(additional))
1334 }
1335
1336 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1339 let (_, &mut len, cap) = self.triple_mut();
1340 if cap - len >= additional {
1341 return Ok(());
1342 }
1343 let new_cap = len
1344 .checked_add(additional)
1345 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1346 self.try_grow(new_cap)
1347 }
1348
1349 pub fn shrink_to_fit(&mut self) {
1354 if !self.spilled() {
1355 return;
1356 }
1357 let len = self.len();
1358 if self.inline_size() >= len {
1359 unsafe {
1360 let (ptr, len) = self.data.heap();
1361 self.data = SmallVecData::empty();
1362 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1363 deallocate(ptr.0, self.capacity);
1364 self.capacity = len;
1365 }
1366 } else if self.capacity() > len {
1367 self.grow(len);
1368 }
1369 }
1370
1371 pub fn truncate(&mut self, len: usize) {
1380 unsafe {
1381 let (ptr, len_ptr, _) = self.triple_mut();
1382 let ptr = ptr.as_ptr();
1383 while len < *len_ptr {
1384 let last_index = *len_ptr - 1;
1385 *len_ptr = last_index;
1386 ptr::drop_in_place(ptr.add(last_index));
1387 }
1388 }
1389 }
1390
1391 pub fn as_slice(&self) -> &[A::Item] {
1395 self
1396 }
1397
1398 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1402 self
1403 }
1404
1405 #[inline]
1412 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1413 let len = self.len();
1414 self.swap(len - 1, index);
1415 self.pop()
1416 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1417 }
1418
1419 #[inline]
1421 pub fn clear(&mut self) {
1422 self.truncate(0);
1423 }
1424
1425 pub fn remove(&mut self, index: usize) -> A::Item {
1430 unsafe {
1431 let (ptr, len_ptr, _) = self.triple_mut();
1432 let len = *len_ptr;
1433 if !(index < len) {
::core::panicking::panic("assertion failed: index < len")
};assert!(index < len);
1434 *len_ptr = len - 1;
1435 let ptr = ptr.as_ptr().add(index);
1436 let item = ptr::read(ptr);
1437 ptr::copy(ptr.add(1), ptr, len - index - 1);
1438 item
1439 }
1440 }
1441
1442 pub fn insert(&mut self, index: usize, element: A::Item) {
1447 unsafe {
1448 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1449 if *len_ptr == cap {
1450 self.reserve_one_unchecked();
1451 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1452 ptr = heap_ptr;
1453 len_ptr = heap_len_ptr;
1454 }
1455 let mut ptr = ptr.as_ptr();
1456 let len = *len_ptr;
1457 if index > len {
1458 ::core::panicking::panic("index exceeds length");panic!("index exceeds length");
1459 }
1460 ptr = ptr.add(index);
1462 if index < len {
1463 ptr::copy(ptr, ptr.add(1), len - index);
1465 }
1466 *len_ptr = len + 1;
1467 ptr::write(ptr, element);
1468 }
1469 }
1470
1471 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1474 let mut iter = iterable.into_iter();
1475 if index == self.len() {
1476 return self.extend(iter);
1477 }
1478
1479 let (lower_size_bound, _) = iter.size_hint();
1480 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); 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;
1485 let old_len = self.len();
1486 if !(index <= old_len) {
::core::panicking::panic("assertion failed: index <= old_len")
};assert!(index <= old_len);
1487
1488 unsafe {
1489 self.reserve(lower_size_bound);
1491 let start = self.as_mut_ptr();
1492 let ptr = start.add(index);
1493
1494 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1496
1497 self.set_len(0);
1500 let mut guard = DropOnPanic {
1501 start,
1502 skip: index..(index + lower_size_bound),
1503 len: old_len + lower_size_bound,
1504 };
1505
1506 let start = self.as_mut_ptr();
1509 let ptr = start.add(index);
1510
1511 while num_added < lower_size_bound {
1512 let element = match iter.next() {
1513 Some(x) => x,
1514 None => break,
1515 };
1516 let cur = ptr.add(num_added);
1517 ptr::write(cur, element);
1518 guard.skip.start += 1;
1519 num_added += 1;
1520 }
1521
1522 if num_added < lower_size_bound {
1523 ptr::copy(
1526 ptr.add(lower_size_bound),
1527 ptr.add(num_added),
1528 old_len - index,
1529 );
1530 }
1531 self.set_len(old_len + num_added);
1534 mem::forget(guard);
1535 }
1536
1537 for element in iter {
1539 self.insert(index + num_added, element);
1540 num_added += 1;
1541 }
1542
1543 struct DropOnPanic<T> {
1544 start: *mut T,
1545 skip: Range<usize>, len: usize,
1547 }
1548
1549 impl<T> Drop for DropOnPanic<T> {
1550 fn drop(&mut self) {
1551 for i in 0..self.len {
1552 if !self.skip.contains(&i) {
1553 unsafe {
1554 ptr::drop_in_place(self.start.add(i));
1555 }
1556 }
1557 }
1558 }
1559 }
1560 }
1561
1562 pub fn into_vec(mut self) -> Vec<A::Item> {
1565 if self.spilled() {
1566 unsafe {
1567 let (ptr, &mut len) = self.data.heap_mut();
1568 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1569 mem::forget(self);
1570 v
1571 }
1572 } else {
1573 self.into_iter().collect()
1574 }
1575 }
1576
1577 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1582 self.into_vec().into_boxed_slice()
1583 }
1584
1585 pub fn into_inner(self) -> Result<A, Self> {
1592 if self.spilled() || self.len() != A::size() {
1593 Err(self)
1595 } else {
1596 unsafe {
1597 let data = ptr::read(&self.data);
1598 mem::forget(self);
1599 Ok(data.into_inline().assume_init())
1600 }
1601 }
1602 }
1603
1604 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1610 let mut del = 0;
1611 let len = self.len();
1612 for i in 0..len {
1613 if !f(&mut self[i]) {
1614 del += 1;
1615 } else if del > 0 {
1616 self.swap(i - del, i);
1617 }
1618 }
1619 self.truncate(len - del);
1620 }
1621
1622 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1628 self.retain(f)
1629 }
1630
1631 pub fn dedup(&mut self)
1633 where
1634 A::Item: PartialEq<A::Item>,
1635 {
1636 self.dedup_by(|a, b| a == b);
1637 }
1638
1639 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1642 where
1643 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1644 {
1645 let len = self.len();
1648 if len <= 1 {
1649 return;
1650 }
1651
1652 let ptr = self.as_mut_ptr();
1653 let mut w: usize = 1;
1654
1655 unsafe {
1656 for r in 1..len {
1657 let p_r = ptr.add(r);
1658 let p_wm1 = ptr.add(w - 1);
1659 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1660 if r != w {
1661 let p_w = p_wm1.add(1);
1662 mem::swap(&mut *p_r, &mut *p_w);
1663 }
1664 w += 1;
1665 }
1666 }
1667 }
1668
1669 self.truncate(w);
1670 }
1671
1672 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1674 where
1675 F: FnMut(&mut A::Item) -> K,
1676 K: PartialEq<K>,
1677 {
1678 self.dedup_by(|a, b| key(a) == key(b));
1679 }
1680
1681 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1712 where
1713 F: FnMut() -> A::Item,
1714 {
1715 let old_len = self.len();
1716 if old_len < new_len {
1717 let mut f = f;
1718 let additional = new_len - old_len;
1719 self.reserve(additional);
1720 for _ in 0..additional {
1721 self.push(f());
1722 }
1723 } else if old_len > new_len {
1724 self.truncate(new_len);
1725 }
1726 }
1727
1728 #[inline]
1796 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1797 let ptr = unsafe {
1800 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.");
1801 NonNull::new_unchecked(ptr)
1802 };
1803 if !(capacity > Self::inline_capacity()) {
::core::panicking::panic("assertion failed: capacity > Self::inline_capacity()")
};assert!(capacity > Self::inline_capacity());
1804 SmallVec {
1805 capacity,
1806 data: SmallVecData::from_heap(ptr, length),
1807 }
1808 }
1809
1810 pub fn as_ptr(&self) -> *const A::Item {
1812 self.triple().0.as_ptr()
1816 }
1817
1818 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1820 self.triple_mut().0.as_ptr()
1824 }
1825}
1826
1827impl<A: Array> SmallVec<A>
1828where
1829 A::Item: Copy,
1830{
1831 pub fn from_slice(slice: &[A::Item]) -> Self {
1836 let len = slice.len();
1837 if len <= Self::inline_capacity() {
1838 SmallVec {
1839 capacity: len,
1840 data: SmallVecData::from_inline(unsafe {
1841 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1842 ptr::copy_nonoverlapping(
1843 slice.as_ptr(),
1844 data.as_mut_ptr() as *mut A::Item,
1845 len,
1846 );
1847 data
1848 }),
1849 }
1850 } else {
1851 let mut b = slice.to_vec();
1852 let cap = b.capacity();
1853 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1854 mem::forget(b);
1855 SmallVec {
1856 capacity: cap,
1857 data: SmallVecData::from_heap(ptr, len),
1858 }
1859 }
1860 }
1861
1862 #[inline]
1867 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1868 self.reserve(slice.len());
1869
1870 let len = self.len();
1871 if !(index <= len) {
::core::panicking::panic("assertion failed: index <= len")
};assert!(index <= len);
1872
1873 unsafe {
1874 let slice_ptr = slice.as_ptr();
1875 let ptr = self.as_mut_ptr().add(index);
1876 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1877 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1878 self.set_len(len + slice.len());
1879 }
1880 }
1881
1882 #[inline]
1886 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1887 let len = self.len();
1888 self.insert_from_slice(len, slice);
1889 }
1890}
1891
1892impl<A: Array> SmallVec<A>
1893where
1894 A::Item: Clone,
1895{
1896 pub fn resize(&mut self, len: usize, value: A::Item) {
1903 let old_len = self.len();
1904
1905 if len > old_len {
1906 self.extend(repeat(value).take(len - old_len));
1907 } else {
1908 self.truncate(len);
1909 }
1910 }
1911
1912 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1920 if n > Self::inline_capacity() {
1921 ::alloc::vec::from_elem(elem, n)vec![elem; n].into()
1922 } else {
1923 let mut v = SmallVec::<A>::new();
1924 unsafe {
1925 let (ptr, len_ptr, _) = v.triple_mut();
1926 let ptr = ptr.as_ptr();
1927 let mut local_len = SetLenOnDrop::new(len_ptr);
1928
1929 for i in 0..n {
1930 ::core::ptr::write(ptr.add(i), elem.clone());
1931 local_len.increment_len(1);
1932 }
1933 }
1934 v
1935 }
1936 }
1937}
1938
1939impl<A: Array> ops::Deref for SmallVec<A> {
1940 type Target = [A::Item];
1941 #[inline]
1942 fn deref(&self) -> &[A::Item] {
1943 unsafe {
1944 let (ptr, len, _) = self.triple();
1945 slice::from_raw_parts(ptr.as_ptr(), len)
1946 }
1947 }
1948}
1949
1950impl<A: Array> ops::DerefMut for SmallVec<A> {
1951 #[inline]
1952 fn deref_mut(&mut self) -> &mut [A::Item] {
1953 unsafe {
1954 let (ptr, &mut len, _) = self.triple_mut();
1955 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1956 }
1957 }
1958}
1959
1960impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1961 #[inline]
1962 fn as_ref(&self) -> &[A::Item] {
1963 self
1964 }
1965}
1966
1967impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1968 #[inline]
1969 fn as_mut(&mut self) -> &mut [A::Item] {
1970 self
1971 }
1972}
1973
1974impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1975 #[inline]
1976 fn borrow(&self) -> &[A::Item] {
1977 self
1978 }
1979}
1980
1981impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1982 #[inline]
1983 fn borrow_mut(&mut self) -> &mut [A::Item] {
1984 self
1985 }
1986}
1987
1988#[cfg(feature = "write")]
1989#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1990impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1991 #[inline]
1992 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1993 self.extend_from_slice(buf);
1994 Ok(buf.len())
1995 }
1996
1997 #[inline]
1998 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1999 self.extend_from_slice(buf);
2000 Ok(())
2001 }
2002
2003 #[inline]
2004 fn flush(&mut self) -> io::Result<()> {
2005 Ok(())
2006 }
2007}
2008
2009#[cfg(feature = "serde")]
2010#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2011impl<A: Array> Serialize for SmallVec<A>
2012where
2013 A::Item: Serialize,
2014{
2015 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2016 let mut state = serializer.serialize_seq(Some(self.len()))?;
2017 for item in self {
2018 state.serialize_element(&item)?;
2019 }
2020 state.end()
2021 }
2022}
2023
2024#[cfg(feature = "serde")]
2025#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2026impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2027where
2028 A::Item: Deserialize<'de>,
2029{
2030 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2031 deserializer.deserialize_seq(SmallVecVisitor {
2032 phantom: PhantomData,
2033 })
2034 }
2035}
2036
2037#[cfg(feature = "serde")]
2038struct SmallVecVisitor<A> {
2039 phantom: PhantomData<A>,
2040}
2041
2042#[cfg(feature = "serde")]
2043impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2044where
2045 A::Item: Deserialize<'de>,
2046{
2047 type Value = SmallVec<A>;
2048
2049 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 formatter.write_str("a sequence")
2051 }
2052
2053 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2054 where
2055 B: SeqAccess<'de>,
2056 {
2057 use serde::de::Error;
2058 let len = seq.size_hint().unwrap_or(0);
2059 let mut values = SmallVec::new();
2060 values.try_reserve(len).map_err(B::Error::custom)?;
2061
2062 while let Some(value) = seq.next_element()? {
2063 values.push(value);
2064 }
2065
2066 Ok(values)
2067 }
2068}
2069
2070#[cfg(feature = "malloc_size_of")]
2071impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2072 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2073 if self.spilled() {
2074 unsafe { ops.malloc_size_of(self.as_ptr()) }
2075 } else {
2076 0
2077 }
2078 }
2079}
2080
2081#[cfg(feature = "malloc_size_of")]
2082impl<A> MallocSizeOf for SmallVec<A>
2083where
2084 A: Array,
2085 A::Item: MallocSizeOf,
2086{
2087 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2088 let mut n = self.shallow_size_of(ops);
2089 for elem in self.iter() {
2090 n += elem.size_of(ops);
2091 }
2092 n
2093 }
2094}
2095
2096#[cfg(feature = "specialization")]
2097trait SpecFrom<A: Array, S> {
2098 fn spec_from(slice: S) -> SmallVec<A>;
2099}
2100
2101#[cfg(feature = "specialization")]
2102mod specialization;
2103
2104#[cfg(feature = "arbitrary")]
2105mod arbitrary;
2106
2107#[cfg(feature = "specialization")]
2108impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2109where
2110 A::Item: Copy,
2111{
2112 #[inline]
2113 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2114 SmallVec::from_slice(slice)
2115 }
2116}
2117
2118impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2119where
2120 A::Item: Clone,
2121{
2122 #[cfg(not(feature = "specialization"))]
2123 #[inline]
2124 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2125 slice.iter().cloned().collect()
2126 }
2127
2128 #[cfg(feature = "specialization")]
2129 #[inline]
2130 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2131 SmallVec::spec_from(slice)
2132 }
2133}
2134
2135impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2136 #[inline]
2137 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2138 SmallVec::from_vec(vec)
2139 }
2140}
2141
2142impl<A: Array> From<A> for SmallVec<A> {
2143 #[inline]
2144 fn from(array: A) -> SmallVec<A> {
2145 SmallVec::from_buf(array)
2146 }
2147}
2148
2149impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2150 type Output = I::Output;
2151
2152 fn index(&self, index: I) -> &I::Output {
2153 &(**self)[index]
2154 }
2155}
2156
2157impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2158 fn index_mut(&mut self, index: I) -> &mut I::Output {
2159 &mut (&mut **self)[index]
2160 }
2161}
2162
2163#[allow(deprecated)]
2164impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2165where
2166 A::Item: Copy,
2167{
2168 fn extend_from_slice(&mut self, other: &[A::Item]) {
2169 SmallVec::extend_from_slice(self, other)
2170 }
2171}
2172
2173impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2174 #[inline]
2175 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2176 let mut v = SmallVec::new();
2177 v.extend(iterable);
2178 v
2179 }
2180}
2181
2182impl<A: Array> Extend<A::Item> for SmallVec<A> {
2183 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2184 let mut iter = iterable.into_iter();
2185 let (lower_size_bound, _) = iter.size_hint();
2186 self.reserve(lower_size_bound);
2187
2188 unsafe {
2189 let (ptr, len_ptr, cap) = self.triple_mut();
2190 let ptr = ptr.as_ptr();
2191 let mut len = SetLenOnDrop::new(len_ptr);
2192 while len.get() < cap {
2193 if let Some(out) = iter.next() {
2194 ptr::write(ptr.add(len.get()), out);
2195 len.increment_len(1);
2196 } else {
2197 return;
2198 }
2199 }
2200 }
2201
2202 for elem in iter {
2203 self.push(elem);
2204 }
2205 }
2206}
2207
2208impl<A: Array> fmt::Debug for SmallVec<A>
2209where
2210 A::Item: fmt::Debug,
2211{
2212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2213 f.debug_list().entries(self.iter()).finish()
2214 }
2215}
2216
2217impl<A: Array> Default for SmallVec<A> {
2218 #[inline]
2219 fn default() -> SmallVec<A> {
2220 SmallVec::new()
2221 }
2222}
2223
2224#[cfg(feature = "may_dangle")]
2225unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2226 fn drop(&mut self) {
2227 unsafe {
2228 if self.spilled() {
2229 let (ptr, &mut len) = self.data.heap_mut();
2230 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2231 } else {
2232 ptr::drop_in_place(&mut self[..]);
2233 }
2234 }
2235 }
2236}
2237
2238#[cfg(not(feature = "may_dangle"))]
2239impl<A: Array> Drop for SmallVec<A> {
2240 fn drop(&mut self) {
2241 unsafe {
2242 if self.spilled() {
2243 let (ptr, &mut len) = self.data.heap_mut();
2244 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2245 } else {
2246 ptr::drop_in_place(&mut self[..]);
2247 }
2248 }
2249 }
2250}
2251
2252impl<A: Array> Clone for SmallVec<A>
2253where
2254 A::Item: Clone,
2255{
2256 #[inline]
2257 fn clone(&self) -> SmallVec<A> {
2258 SmallVec::from(self.as_slice())
2259 }
2260
2261 fn clone_from(&mut self, source: &Self) {
2262 self.truncate(source.len());
2266
2267 let (init, tail) = source.split_at(self.len());
2270
2271 self.clone_from_slice(init);
2273 self.extend(tail.iter().cloned());
2274 }
2275}
2276
2277impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2278where
2279 A::Item: PartialEq<B::Item>,
2280{
2281 #[inline]
2282 fn eq(&self, other: &SmallVec<B>) -> bool {
2283 self[..] == other[..]
2284 }
2285}
2286
2287impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2288
2289impl<A: Array> PartialOrd for SmallVec<A>
2290where
2291 A::Item: PartialOrd,
2292{
2293 #[inline]
2294 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2295 PartialOrd::partial_cmp(&**self, &**other)
2296 }
2297}
2298
2299impl<A: Array> Ord for SmallVec<A>
2300where
2301 A::Item: Ord,
2302{
2303 #[inline]
2304 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2305 Ord::cmp(&**self, &**other)
2306 }
2307}
2308
2309impl<A: Array> Hash for SmallVec<A>
2310where
2311 A::Item: Hash,
2312{
2313 fn hash<H: Hasher>(&self, state: &mut H) {
2314 (**self).hash(state)
2315 }
2316}
2317
2318unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2319
2320pub struct IntoIter<A: Array> {
2326 data: SmallVec<A>,
2327 current: usize,
2328 end: usize,
2329}
2330
2331impl<A: Array> fmt::Debug for IntoIter<A>
2332where
2333 A::Item: fmt::Debug,
2334{
2335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2336 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2337 }
2338}
2339
2340impl<A: Array + Clone> Clone for IntoIter<A>
2341where
2342 A::Item: Clone,
2343{
2344 fn clone(&self) -> IntoIter<A> {
2345 SmallVec::from(self.as_slice()).into_iter()
2346 }
2347}
2348
2349impl<A: Array> Drop for IntoIter<A> {
2350 fn drop(&mut self) {
2351 for _ in self {}
2352 }
2353}
2354
2355impl<A: Array> Iterator for IntoIter<A> {
2356 type Item = A::Item;
2357
2358 #[inline]
2359 fn next(&mut self) -> Option<A::Item> {
2360 if self.current == self.end {
2361 None
2362 } else {
2363 unsafe {
2364 let current = self.current;
2365 self.current += 1;
2366 Some(ptr::read(self.data.as_ptr().add(current)))
2367 }
2368 }
2369 }
2370
2371 #[inline]
2372 fn size_hint(&self) -> (usize, Option<usize>) {
2373 let size = self.end - self.current;
2374 (size, Some(size))
2375 }
2376}
2377
2378impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2379 #[inline]
2380 fn next_back(&mut self) -> Option<A::Item> {
2381 if self.current == self.end {
2382 None
2383 } else {
2384 unsafe {
2385 self.end -= 1;
2386 Some(ptr::read(self.data.as_ptr().add(self.end)))
2387 }
2388 }
2389 }
2390}
2391
2392impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2393impl<A: Array> FusedIterator for IntoIter<A> {}
2394
2395impl<A: Array> IntoIter<A> {
2396 pub fn as_slice(&self) -> &[A::Item] {
2398 let len = self.end - self.current;
2399 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2400 }
2401
2402 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2404 let len = self.end - self.current;
2405 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2406 }
2407}
2408
2409impl<A: Array> IntoIterator for SmallVec<A> {
2410 type IntoIter = IntoIter<A>;
2411 type Item = A::Item;
2412 fn into_iter(mut self) -> Self::IntoIter {
2413 unsafe {
2414 let len = self.len();
2417 self.set_len(0);
2418 IntoIter {
2419 data: self,
2420 current: 0,
2421 end: len,
2422 }
2423 }
2424 }
2425}
2426
2427impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2428 type IntoIter = slice::Iter<'a, A::Item>;
2429 type Item = &'a A::Item;
2430 fn into_iter(self) -> Self::IntoIter {
2431 self.iter()
2432 }
2433}
2434
2435impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2436 type IntoIter = slice::IterMut<'a, A::Item>;
2437 type Item = &'a mut A::Item;
2438 fn into_iter(self) -> Self::IntoIter {
2439 self.iter_mut()
2440 }
2441}
2442
2443pub unsafe trait Array {
2445 type Item;
2447 fn size() -> usize;
2449}
2450
2451struct SetLenOnDrop<'a> {
2455 len: &'a mut usize,
2456 local_len: usize,
2457}
2458
2459impl<'a> SetLenOnDrop<'a> {
2460 #[inline]
2461 fn new(len: &'a mut usize) -> Self {
2462 SetLenOnDrop {
2463 local_len: *len,
2464 len,
2465 }
2466 }
2467
2468 #[inline]
2469 fn get(&self) -> usize {
2470 self.local_len
2471 }
2472
2473 #[inline]
2474 fn increment_len(&mut self, increment: usize) {
2475 self.local_len += increment;
2476 }
2477}
2478
2479impl<'a> Drop for SetLenOnDrop<'a> {
2480 #[inline]
2481 fn drop(&mut self) {
2482 *self.len = self.local_len;
2483 }
2484}
2485
2486#[cfg(feature = "const_new")]
2487impl<T, const N: usize> SmallVec<[T; N]> {
2488 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2493 #[inline]
2494 pub const fn new_const() -> Self {
2495 SmallVec {
2496 capacity: 0,
2497 data: SmallVecData::from_const(MaybeUninit::uninit()),
2498 }
2499 }
2500
2501 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2508 #[inline]
2509 pub const fn from_const(items: [T; N]) -> Self {
2510 SmallVec {
2511 capacity: N,
2512 data: SmallVecData::from_const(MaybeUninit::new(items)),
2513 }
2514 }
2515
2516 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2524 #[inline]
2525 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2526 SmallVec {
2527 capacity: len,
2528 data: SmallVecData::from_const(MaybeUninit::new(items)),
2529 }
2530 }
2531}
2532
2533#[cfg(feature = "const_generics")]
2534#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2535unsafe impl<T, const N: usize> Array for [T; N] {
2536 type Item = T;
2537 #[inline]
2538 fn size() -> usize {
2539 N
2540 }
2541}
2542
2543#[cfg(not(feature = "const_generics"))]
2544macro_rules! impl_array(
2545 ($($size:expr),+) => {
2546 $(
2547 unsafe impl<T> Array for [T; $size] {
2548 type Item = T;
2549 #[inline]
2550 fn size() -> usize { $size }
2551 }
2552 )+
2553 }
2554);
2555
2556#[cfg(not(feature = "const_generics"))]
2557impl_array!(
2558 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,
2559 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2560 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2561);
2562
2563pub trait ToSmallVec<A: Array> {
2565 fn to_smallvec(&self) -> SmallVec<A>;
2567}
2568
2569impl<A: Array> ToSmallVec<A> for [A::Item]
2570where
2571 A::Item: Copy,
2572{
2573 #[inline]
2574 fn to_smallvec(&self) -> SmallVec<A> {
2575 SmallVec::from_slice(self)
2576 }
2577}
2578
2579#[repr(transparent)]
2581struct ConstNonNull<T>(NonNull<T>);
2582
2583impl<T> ConstNonNull<T> {
2584 #[inline]
2585 fn new(ptr: *const T) -> Option<Self> {
2586 NonNull::new(ptr as *mut T).map(Self)
2587 }
2588 #[inline]
2589 fn as_ptr(self) -> *const T {
2590 self.0.as_ptr()
2591 }
2592}
2593
2594impl<T> Clone for ConstNonNull<T> {
2595 #[inline]
2596 fn clone(&self) -> Self {
2597 *self
2598 }
2599}
2600
2601impl<T> Copy for ConstNonNull<T> {}
2602
2603#[cfg(feature = "impl_bincode")]
2604use bincode::{
2605 de::{read::Reader, BorrowDecoder, Decode, Decoder},
2606 enc::{write::Writer, Encode, Encoder},
2607 error::{DecodeError, EncodeError},
2608 BorrowDecode,
2609};
2610
2611#[cfg(feature = "impl_bincode")]
2612impl<A, Context> Decode<Context> for SmallVec<A>
2613where
2614 A: Array,
2615 A::Item: Decode<Context>,
2616{
2617 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2618 use core::convert::TryInto;
2619 let len = u64::decode(decoder)?;
2620 let len = len
2621 .try_into()
2622 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2623 decoder.claim_container_read::<A::Item>(len)?;
2624
2625 let mut vec = SmallVec::with_capacity(len);
2626 if unty::type_equal::<A::Item, u8>() {
2627 let ptr = vec.as_mut_ptr();
2631 unsafe {
2634 core::ptr::write_bytes(ptr, 0, len);
2635 vec.set_len(len);
2636 }
2637 let slice = vec.as_mut_slice();
2639 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2641 decoder.reader().read(slice)?;
2642 } else {
2643 for _ in 0..len {
2644 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2645 vec.push(A::Item::decode(decoder)?);
2646 }
2647 }
2648 Ok(vec)
2649 }
2650}
2651
2652#[cfg(feature = "impl_bincode")]
2653impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2654where
2655 A: Array,
2656 A::Item: BorrowDecode<'de, Context>,
2657{
2658 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2659 decoder: &mut D,
2660 ) -> Result<Self, DecodeError> {
2661 use core::convert::TryInto;
2662 let len = u64::decode(decoder)?;
2663 let len = len
2664 .try_into()
2665 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2666 decoder.claim_container_read::<A::Item>(len)?;
2667
2668 let mut vec = SmallVec::with_capacity(len);
2669 if unty::type_equal::<A::Item, u8>() {
2670 let ptr = vec.as_mut_ptr();
2674 unsafe {
2677 core::ptr::write_bytes(ptr, 0, len);
2678 vec.set_len(len);
2679 }
2680 let slice = vec.as_mut_slice();
2682 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2684 decoder.reader().read(slice)?;
2685 } else {
2686 for _ in 0..len {
2687 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2688 vec.push(A::Item::borrow_decode(decoder)?);
2689 }
2690 }
2691 Ok(vec)
2692 }
2693}
2694
2695#[cfg(feature = "impl_bincode")]
2696impl<A> Encode for SmallVec<A>
2697where
2698 A: Array,
2699 A::Item: Encode,
2700{
2701 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2702 (self.len() as u64).encode(encoder)?;
2703 if unty::type_equal::<A::Item, u8>() {
2704 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2706 encoder.writer().write(slice)?;
2707 } else {
2708 for item in self.iter() {
2709 item.encode(encoder)?;
2710 }
2711 }
2712 Ok(())
2713 }
2714}