1#![no_std]
93#![cfg_attr(docsrs, feature(doc_cfg))]
94#![cfg_attr(feature = "specialization", allow(incomplete_features))]
95#![cfg_attr(feature = "specialization", feature(specialization))]
96#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
97#![cfg_attr(
98 feature = "debugger_visualizer",
99 feature(debugger_visualizer),
100 debugger_visualizer(natvis_file = "../debug_metadata/smallvec.natvis")
101)]
102#![deny(missing_docs)]
103
104#[doc(hidden)]
105pub extern crate alloc;
106
107#[cfg(any(test, feature = "write"))]
108extern crate std;
109
110#[cfg(test)]
111mod tests;
112
113#[allow(deprecated)]
114use alloc::alloc::{Layout, LayoutErr};
115use alloc::boxed::Box;
116use alloc::{vec, vec::Vec};
117use core::borrow::{Borrow, BorrowMut};
118use core::cmp;
119use core::fmt;
120use core::hash::{Hash, Hasher};
121use core::hint::unreachable_unchecked;
122use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator};
123use core::mem;
124use core::mem::MaybeUninit;
125use core::ops::{self, Range, RangeBounds};
126use core::ptr::{self, NonNull};
127use core::slice::{self, SliceIndex};
128
129#[cfg(feature = "serde")]
130use serde::{
131 de::{Deserialize, Deserializer, SeqAccess, Visitor},
132 ser::{Serialize, SerializeSeq, Serializer},
133};
134
135#[cfg(feature = "serde")]
136use core::marker::PhantomData;
137
138#[cfg(feature = "write")]
139use std::io;
140
141#[cfg(feature = "drain_keep_rest")]
142use core::mem::ManuallyDrop;
143
144#[macro_export]
182macro_rules! smallvec {
183 (@one $x:expr) => (1usize);
185 ($elem:expr; $n:expr) => ({
186 $crate::SmallVec::from_elem($elem, $n)
187 });
188 ($($x:expr),*$(,)*) => ({
189 let count = 0usize $(+ $crate::smallvec!(@one $x))*;
190 #[allow(unused_mut)]
191 let mut vec = $crate::SmallVec::new();
192 if count <= vec.inline_size() {
193 $(vec.push($x);)*
194 vec
195 } else {
196 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)*])
197 }
198 });
199}
200
201#[cfg(feature = "const_new")]
231#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
232#[macro_export]
233macro_rules! smallvec_inline {
234 (@one $x:expr) => (1usize);
236 ($elem:expr; $n:expr) => ({
237 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
238 });
239 ($($x:expr),+ $(,)?) => ({
240 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
241 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
242 });
243}
244
245#[cfg(not(feature = "union"))]
247macro_rules! debug_unreachable {
248 () => {
249 debug_unreachable!("entered unreachable code")
250 };
251 ($e:expr) => {
252 if cfg!(debug_assertions) {
253 panic!($e);
254 } else {
255 unreachable_unchecked();
256 }
257 };
258}
259
260#[doc(hidden)]
280#[deprecated]
281pub trait ExtendFromSlice<T> {
282 fn extend_from_slice(&mut self, other: &[T]);
284}
285
286#[allow(deprecated)]
287impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
288 fn extend_from_slice(&mut self, other: &[T]) {
289 Vec::extend_from_slice(self, other)
290 }
291}
292
293#[derive(Debug)]
295pub enum CollectionAllocErr {
296 CapacityOverflow,
298 AllocErr {
300 layout: Layout,
302 },
303}
304
305impl fmt::Display for CollectionAllocErr {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 write!(f, "Allocation error: {:?}", self)
308 }
309}
310
311#[allow(deprecated)]
312impl From<LayoutErr> for CollectionAllocErr {
313 fn from(_: LayoutErr) -> Self {
314 CollectionAllocErr::CapacityOverflow
315 }
316}
317
318fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
319 match result {
320 Ok(x) => x,
321 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
322 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
323 }
324}
325
326fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
329 let size = mem::size_of::<T>()
330 .checked_mul(n)
331 .ok_or(CollectionAllocErr::CapacityOverflow)?;
332 let align = mem::align_of::<T>();
333 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
334}
335
336unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
337 let layout = layout_array::<T>(capacity).unwrap();
339 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
340}
341
342pub struct Drain<'a, T: 'a + Array> {
348 tail_start: usize,
349 tail_len: usize,
350 iter: slice::Iter<'a, T::Item>,
351 vec: NonNull<SmallVec<T>>,
352}
353
354impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
355where
356 T::Item: fmt::Debug,
357{
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
360 }
361}
362
363unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
364unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
365
366impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
367 type Item = T::Item;
368
369 #[inline]
370 fn next(&mut self) -> Option<T::Item> {
371 self.iter
372 .next()
373 .map(|reference| unsafe { ptr::read(reference) })
374 }
375
376 #[inline]
377 fn size_hint(&self) -> (usize, Option<usize>) {
378 self.iter.size_hint()
379 }
380}
381
382impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
383 #[inline]
384 fn next_back(&mut self) -> Option<T::Item> {
385 self.iter
386 .next_back()
387 .map(|reference| unsafe { ptr::read(reference) })
388 }
389}
390
391impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
392 #[inline]
393 fn len(&self) -> usize {
394 self.iter.len()
395 }
396}
397
398impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
399
400impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
401 fn drop(&mut self) {
402 self.for_each(drop);
403
404 if self.tail_len > 0 {
405 unsafe {
406 let source_vec = self.vec.as_mut();
407
408 let start = source_vec.len();
410 let tail = self.tail_start;
411 if tail != start {
412 let ptr = source_vec.as_mut_ptr();
415 let src = ptr.add(tail);
416 let dst = ptr.add(start);
417 ptr::copy(src, dst, self.tail_len);
418 }
419 source_vec.set_len(start + self.tail_len);
420 }
421 }
422 }
423}
424
425#[cfg(feature = "drain_filter")]
426pub struct DrainFilter<'a, T, F>
432where
433 F: FnMut(&mut T::Item) -> bool,
434 T: Array,
435{
436 vec: &'a mut SmallVec<T>,
437 idx: usize,
439 del: usize,
441 old_len: usize,
443 pred: F,
445 panic_flag: bool,
451}
452
453#[cfg(feature = "drain_filter")]
454impl <T, F> fmt::Debug for DrainFilter<'_, T, F>
455where
456 F: FnMut(&mut T::Item) -> bool,
457 T: Array,
458 T::Item: fmt::Debug,
459{
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 f.debug_tuple("DrainFilter").field(&self.vec.as_slice()).finish()
462 }
463}
464
465#[cfg(feature = "drain_filter")]
466impl <T, F> Iterator for DrainFilter<'_, T, F>
467where
468 F: FnMut(&mut T::Item) -> bool,
469 T: Array,
470{
471 type Item = T::Item;
472
473 fn next(&mut self) -> Option<T::Item>
474 {
475 unsafe {
476 while self.idx < self.old_len {
477 let i = self.idx;
478 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
479 self.panic_flag = true;
480 let drained = (self.pred)(&mut v[i]);
481 self.panic_flag = false;
482 self.idx += 1;
486 if drained {
487 self.del += 1;
488 return Some(ptr::read(&v[i]));
489 } else if self.del > 0 {
490 let del = self.del;
491 let src: *const Self::Item = &v[i];
492 let dst: *mut Self::Item = &mut v[i - del];
493 ptr::copy_nonoverlapping(src, dst, 1);
494 }
495 }
496 None
497 }
498 }
499
500 fn size_hint(&self) -> (usize, Option<usize>) {
501 (0, Some(self.old_len - self.idx))
502 }
503}
504
505#[cfg(feature = "drain_filter")]
506impl <T, F> Drop for DrainFilter<'_, T, F>
507where
508 F: FnMut(&mut T::Item) -> bool,
509 T: Array,
510{
511 fn drop(&mut self) {
512 struct BackshiftOnDrop<'a, 'b, T, F>
513 where
514 F: FnMut(&mut T::Item) -> bool,
515 T: Array
516 {
517 drain: &'b mut DrainFilter<'a, T, F>,
518 }
519
520 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
521 where
522 F: FnMut(&mut T::Item) -> bool,
523 T: Array
524 {
525 fn drop(&mut self) {
526 unsafe {
527 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
528 let ptr = self.drain.vec.as_mut_ptr();
535 let src = ptr.add(self.drain.idx);
536 let dst = src.sub(self.drain.del);
537 let tail_len = self.drain.old_len - self.drain.idx;
538 src.copy_to(dst, tail_len);
539 }
540 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
541 }
542 }
543 }
544
545 let backshift = BackshiftOnDrop { drain: self };
546
547 if !backshift.drain.panic_flag {
551 backshift.drain.for_each(drop);
552 }
553 }
554}
555
556#[cfg(feature = "drain_keep_rest")]
557impl <T, F> DrainFilter<'_, T, F>
558where
559 F: FnMut(&mut T::Item) -> bool,
560 T: Array
561{
562 pub fn keep_rest(self)
582 {
583 let mut this = ManuallyDrop::new(self);
598
599 unsafe {
600 let needs_move = mem::size_of::<T>() != 0;
602
603 if needs_move && this.idx < this.old_len && this.del > 0 {
604 let ptr = this.vec.as_mut_ptr();
605 let src = ptr.add(this.idx);
606 let dst = src.sub(this.del);
607 let tail_len = this.old_len - this.idx;
608 src.copy_to(dst, tail_len);
609 }
610
611 let new_len = this.old_len - this.del;
612 this.vec.set_len(new_len);
613 }
614 }
615}
616
617#[cfg(feature = "union")]
618union SmallVecData<A: Array> {
619 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
620 heap: (NonNull<A::Item>, usize),
621}
622
623#[cfg(all(feature = "union", feature = "const_new"))]
624impl<T, const N: usize> SmallVecData<[T; N]> {
625 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
626 #[inline]
627 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
628 SmallVecData {
629 inline: core::mem::ManuallyDrop::new(inline),
630 }
631 }
632}
633
634#[cfg(feature = "union")]
635impl<A: Array> SmallVecData<A> {
636 #[inline]
637 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
638 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
639 }
640 #[inline]
641 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
642 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
643 }
644 #[inline]
645 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
646 SmallVecData {
647 inline: core::mem::ManuallyDrop::new(inline),
648 }
649 }
650 #[inline]
651 unsafe fn into_inline(self) -> MaybeUninit<A> {
652 core::mem::ManuallyDrop::into_inner(self.inline)
653 }
654 #[inline]
655 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
656 (ConstNonNull(self.heap.0), self.heap.1)
657 }
658 #[inline]
659 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
660 let h = &mut self.heap;
661 (h.0, &mut h.1)
662 }
663 #[inline]
664 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
665 SmallVecData { heap: (ptr, len) }
666 }
667}
668
669#[cfg(not(feature = "union"))]
670enum SmallVecData<A: Array> {
671 Inline(MaybeUninit<A>),
672 Heap {
674 ptr: NonNull<A::Item>,
679 len: usize,
680 },
681}
682
683#[cfg(all(not(feature = "union"), feature = "const_new"))]
684impl<T, const N: usize> SmallVecData<[T; N]> {
685 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
686 #[inline]
687 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
688 SmallVecData::Inline(inline)
689 }
690}
691
692#[cfg(not(feature = "union"))]
693impl<A: Array> SmallVecData<A> {
694 #[inline]
695 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
696 match self {
697 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
698 _ => debug_unreachable!(),
699 }
700 }
701 #[inline]
702 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
703 match self {
704 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
705 _ => debug_unreachable!(),
706 }
707 }
708 #[inline]
709 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
710 SmallVecData::Inline(inline)
711 }
712 #[inline]
713 unsafe fn into_inline(self) -> MaybeUninit<A> {
714 match self {
715 SmallVecData::Inline(a) => a,
716 _ => debug_unreachable!(),
717 }
718 }
719 #[inline]
720 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
721 match self {
722 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
723 _ => debug_unreachable!(),
724 }
725 }
726 #[inline]
727 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
728 match self {
729 SmallVecData::Heap { ptr, len } => (*ptr, len),
730 _ => debug_unreachable!(),
731 }
732 }
733 #[inline]
734 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
735 SmallVecData::Heap { ptr, len }
736 }
737}
738
739unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
740unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
741
742pub struct SmallVec<A: Array> {
769 capacity: usize,
773 data: SmallVecData<A>,
774}
775
776impl<A: Array> SmallVec<A> {
777 #[inline]
779 pub fn new() -> SmallVec<A> {
780 assert!(
783 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
784 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
785 );
786 SmallVec {
787 capacity: 0,
788 data: SmallVecData::from_inline(MaybeUninit::uninit()),
789 }
790 }
791
792 #[inline]
806 pub fn with_capacity(n: usize) -> Self {
807 let mut v = SmallVec::new();
808 v.reserve_exact(n);
809 v
810 }
811
812 #[inline]
825 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
826 if vec.capacity() <= Self::inline_capacity() {
827 unsafe {
830 let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit());
831 let len = vec.len();
832 vec.set_len(0);
833 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
834
835 SmallVec {
836 capacity: len,
837 data,
838 }
839 }
840 } else {
841 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
842 mem::forget(vec);
843 let ptr = NonNull::new(ptr)
844 .expect("Cannot be null by `Vec` invariant");
846
847 SmallVec {
848 capacity: cap,
849 data: SmallVecData::from_heap(ptr, len),
850 }
851 }
852 }
853
854 #[inline]
866 pub fn from_buf(buf: A) -> SmallVec<A> {
867 SmallVec {
868 capacity: A::size(),
869 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
870 }
871 }
872
873 #[inline]
886 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
887 assert!(len <= A::size());
888 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
889 }
890
891 #[inline]
907 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
908 SmallVec {
909 capacity: len,
910 data: SmallVecData::from_inline(buf),
911 }
912 }
913
914 pub unsafe fn set_len(&mut self, new_len: usize) {
920 let (_, len_ptr, _) = self.triple_mut();
921 *len_ptr = new_len;
922 }
923
924 #[inline]
926 fn inline_capacity() -> usize {
927 if mem::size_of::<A::Item>() > 0 {
928 A::size()
929 } else {
930 core::usize::MAX
941 }
942 }
943
944 #[inline]
946 pub fn inline_size(&self) -> usize {
947 Self::inline_capacity()
948 }
949
950 #[inline]
952 pub fn len(&self) -> usize {
953 self.triple().1
954 }
955
956 #[inline]
958 pub fn is_empty(&self) -> bool {
959 self.len() == 0
960 }
961
962 #[inline]
964 pub fn capacity(&self) -> usize {
965 self.triple().2
966 }
967
968 #[inline]
971 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
972 unsafe {
973 if self.spilled() {
974 let (ptr, len) = self.data.heap();
975 (ptr, len, self.capacity)
976 } else {
977 (self.data.inline(), self.capacity, Self::inline_capacity())
978 }
979 }
980 }
981
982 #[inline]
984 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
985 unsafe {
986 if self.spilled() {
987 let (ptr, len_ptr) = self.data.heap_mut();
988 (ptr, len_ptr, self.capacity)
989 } else {
990 (
991 self.data.inline_mut(),
992 &mut self.capacity,
993 Self::inline_capacity(),
994 )
995 }
996 }
997 }
998
999 #[inline]
1001 pub fn spilled(&self) -> bool {
1002 self.capacity > Self::inline_capacity()
1003 }
1004
1005 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1019 where
1020 R: RangeBounds<usize>,
1021 {
1022 use core::ops::Bound::*;
1023
1024 let len = self.len();
1025 let start = match range.start_bound() {
1026 Included(&n) => n,
1027 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1028 Unbounded => 0,
1029 };
1030 let end = match range.end_bound() {
1031 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1032 Excluded(&n) => n,
1033 Unbounded => len,
1034 };
1035
1036 assert!(start <= end);
1037 assert!(end <= len);
1038
1039 unsafe {
1040 self.set_len(start);
1041
1042 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1043
1044 Drain {
1045 tail_start: end,
1046 tail_len: len - end,
1047 iter: range_slice.iter(),
1048 vec: NonNull::new_unchecked(self as *mut _),
1050 }
1051 }
1052 }
1053
1054 #[cfg(feature = "drain_filter")]
1055 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F,>
1099 where
1100 F: FnMut(&mut A::Item) -> bool,
1101 {
1102 let old_len = self.len();
1103
1104 unsafe {
1106 self.set_len(0);
1107 }
1108
1109 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
1110 }
1111
1112 #[inline]
1114 pub fn push(&mut self, value: A::Item) {
1115 unsafe {
1116 let (mut ptr, mut len, cap) = self.triple_mut();
1117 if *len == cap {
1118 self.reserve_one_unchecked();
1119 let (heap_ptr, heap_len) = self.data.heap_mut();
1120 ptr = heap_ptr;
1121 len = heap_len;
1122 }
1123 ptr::write(ptr.as_ptr().add(*len), value);
1124 *len += 1;
1125 }
1126 }
1127
1128 #[inline]
1130 pub fn pop(&mut self) -> Option<A::Item> {
1131 unsafe {
1132 let (ptr, len_ptr, _) = self.triple_mut();
1133 let ptr: *const _ = ptr.as_ptr();
1134 if *len_ptr == 0 {
1135 return None;
1136 }
1137 let last_index = *len_ptr - 1;
1138 *len_ptr = last_index;
1139 Some(ptr::read(ptr.add(last_index)))
1140 }
1141 }
1142
1143 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1156 where
1157 B: Array<Item = A::Item>,
1158 {
1159 self.extend(other.drain(..))
1160 }
1161
1162 pub fn grow(&mut self, new_cap: usize) {
1167 infallible(self.try_grow(new_cap))
1168 }
1169
1170 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1174 unsafe {
1175 let unspilled = !self.spilled();
1176 let (ptr, &mut len, cap) = self.triple_mut();
1177 assert!(new_cap >= len);
1178 if new_cap <= Self::inline_capacity() {
1179 if unspilled {
1180 return Ok(());
1181 }
1182 self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1183 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1184 self.capacity = len;
1185 deallocate(ptr, cap);
1186 } else if new_cap != cap {
1187 let layout = layout_array::<A::Item>(new_cap)?;
1188 debug_assert!(layout.size() > 0);
1189 let new_alloc;
1190 if unspilled {
1191 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1192 .ok_or(CollectionAllocErr::AllocErr { layout })?
1193 .cast();
1194 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1195 } else {
1196 let old_layout = layout_array::<A::Item>(cap)?;
1199
1200 let new_ptr =
1201 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1202 new_alloc = NonNull::new(new_ptr)
1203 .ok_or(CollectionAllocErr::AllocErr { layout })?
1204 .cast();
1205 }
1206 self.data = SmallVecData::from_heap(new_alloc, len);
1207 self.capacity = new_cap;
1208 }
1209 Ok(())
1210 }
1211 }
1212
1213 #[inline]
1219 pub fn reserve(&mut self, additional: usize) {
1220 infallible(self.try_reserve(additional))
1221 }
1222
1223 #[cold]
1225 fn reserve_one_unchecked(&mut self) {
1226 debug_assert_eq!(self.len(), self.capacity());
1227 let new_cap = self.len()
1228 .checked_add(1)
1229 .and_then(usize::checked_next_power_of_two)
1230 .expect("capacity overflow");
1231 infallible(self.try_grow(new_cap))
1232 }
1233
1234 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1238 let (_, &mut len, cap) = self.triple_mut();
1241 if cap - len >= additional {
1242 return Ok(());
1243 }
1244 let new_cap = len
1245 .checked_add(additional)
1246 .and_then(usize::checked_next_power_of_two)
1247 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1248 self.try_grow(new_cap)
1249 }
1250
1251 pub fn reserve_exact(&mut self, additional: usize) {
1255 infallible(self.try_reserve_exact(additional))
1256 }
1257
1258 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1260 let (_, &mut len, cap) = self.triple_mut();
1261 if cap - len >= additional {
1262 return Ok(());
1263 }
1264 let new_cap = len
1265 .checked_add(additional)
1266 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1267 self.try_grow(new_cap)
1268 }
1269
1270 pub fn shrink_to_fit(&mut self) {
1275 if !self.spilled() {
1276 return;
1277 }
1278 let len = self.len();
1279 if self.inline_size() >= len {
1280 unsafe {
1281 let (ptr, len) = self.data.heap();
1282 self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1283 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1284 deallocate(ptr.0, self.capacity);
1285 self.capacity = len;
1286 }
1287 } else if self.capacity() > len {
1288 self.grow(len);
1289 }
1290 }
1291
1292 pub fn truncate(&mut self, len: usize) {
1300 unsafe {
1301 let (ptr, len_ptr, _) = self.triple_mut();
1302 let ptr = ptr.as_ptr();
1303 while len < *len_ptr {
1304 let last_index = *len_ptr - 1;
1305 *len_ptr = last_index;
1306 ptr::drop_in_place(ptr.add(last_index));
1307 }
1308 }
1309 }
1310
1311 pub fn as_slice(&self) -> &[A::Item] {
1315 self
1316 }
1317
1318 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1322 self
1323 }
1324
1325 #[inline]
1331 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1332 let len = self.len();
1333 self.swap(len - 1, index);
1334 self.pop()
1335 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1336 }
1337
1338 #[inline]
1340 pub fn clear(&mut self) {
1341 self.truncate(0);
1342 }
1343
1344 pub fn remove(&mut self, index: usize) -> A::Item {
1349 unsafe {
1350 let (ptr, len_ptr, _) = self.triple_mut();
1351 let len = *len_ptr;
1352 assert!(index < len);
1353 *len_ptr = len - 1;
1354 let ptr = ptr.as_ptr().add(index);
1355 let item = ptr::read(ptr);
1356 ptr::copy(ptr.add(1), ptr, len - index - 1);
1357 item
1358 }
1359 }
1360
1361 pub fn insert(&mut self, index: usize, element: A::Item) {
1365 unsafe {
1366 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1367 if *len_ptr == cap {
1368 self.reserve_one_unchecked();
1369 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1370 ptr = heap_ptr;
1371 len_ptr = heap_len_ptr;
1372 }
1373 let mut ptr = ptr.as_ptr();
1374 let len = *len_ptr;
1375 ptr = ptr.add(index);
1376 if index < len {
1377 ptr::copy(ptr, ptr.add(1), len - index);
1378 } else if index == len {
1379 } else {
1381 panic!("index exceeds length");
1382 }
1383 *len_ptr = len + 1;
1384 ptr::write(ptr, element);
1385 }
1386 }
1387
1388 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1391 let mut iter = iterable.into_iter();
1392 if index == self.len() {
1393 return self.extend(iter);
1394 }
1395
1396 let (lower_size_bound, _) = iter.size_hint();
1397 assert!(lower_size_bound <= core::isize::MAX as usize); assert!(index + lower_size_bound >= index); let mut num_added = 0;
1401 let old_len = self.len();
1402 assert!(index <= old_len);
1403
1404 unsafe {
1405 self.reserve(lower_size_bound);
1407 let start = self.as_mut_ptr();
1408 let ptr = start.add(index);
1409
1410 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1412
1413 self.set_len(0);
1415 let mut guard = DropOnPanic {
1416 start,
1417 skip: index..(index + lower_size_bound),
1418 len: old_len + lower_size_bound,
1419 };
1420
1421 let start = self.as_mut_ptr();
1423 let ptr = start.add(index);
1424
1425 while num_added < lower_size_bound {
1426 let element = match iter.next() {
1427 Some(x) => x,
1428 None => break,
1429 };
1430 let cur = ptr.add(num_added);
1431 ptr::write(cur, element);
1432 guard.skip.start += 1;
1433 num_added += 1;
1434 }
1435
1436 if num_added < lower_size_bound {
1437 ptr::copy(
1439 ptr.add(lower_size_bound),
1440 ptr.add(num_added),
1441 old_len - index,
1442 );
1443 }
1444 self.set_len(old_len + num_added);
1446 mem::forget(guard);
1447 }
1448
1449 for element in iter {
1451 self.insert(index + num_added, element);
1452 num_added += 1;
1453 }
1454
1455 struct DropOnPanic<T> {
1456 start: *mut T,
1457 skip: Range<usize>, len: usize,
1459 }
1460
1461 impl<T> Drop for DropOnPanic<T> {
1462 fn drop(&mut self) {
1463 for i in 0..self.len {
1464 if !self.skip.contains(&i) {
1465 unsafe {
1466 ptr::drop_in_place(self.start.add(i));
1467 }
1468 }
1469 }
1470 }
1471 }
1472 }
1473
1474 pub fn into_vec(mut self) -> Vec<A::Item> {
1477 if self.spilled() {
1478 unsafe {
1479 let (ptr, &mut len) = self.data.heap_mut();
1480 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1481 mem::forget(self);
1482 v
1483 }
1484 } else {
1485 self.into_iter().collect()
1486 }
1487 }
1488
1489 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1494 self.into_vec().into_boxed_slice()
1495 }
1496
1497 pub fn into_inner(self) -> Result<A, Self> {
1502 if self.spilled() || self.len() != A::size() {
1503 Err(self)
1505 } else {
1506 unsafe {
1507 let data = ptr::read(&self.data);
1508 mem::forget(self);
1509 Ok(data.into_inline().assume_init())
1510 }
1511 }
1512 }
1513
1514 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1520 let mut del = 0;
1521 let len = self.len();
1522 for i in 0..len {
1523 if !f(&mut self[i]) {
1524 del += 1;
1525 } else if del > 0 {
1526 self.swap(i - del, i);
1527 }
1528 }
1529 self.truncate(len - del);
1530 }
1531
1532 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1538 self.retain(f)
1539 }
1540
1541 pub fn dedup(&mut self)
1543 where
1544 A::Item: PartialEq<A::Item>,
1545 {
1546 self.dedup_by(|a, b| a == b);
1547 }
1548
1549 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1551 where
1552 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1553 {
1554 let len = self.len();
1557 if len <= 1 {
1558 return;
1559 }
1560
1561 let ptr = self.as_mut_ptr();
1562 let mut w: usize = 1;
1563
1564 unsafe {
1565 for r in 1..len {
1566 let p_r = ptr.add(r);
1567 let p_wm1 = ptr.add(w - 1);
1568 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1569 if r != w {
1570 let p_w = p_wm1.add(1);
1571 mem::swap(&mut *p_r, &mut *p_w);
1572 }
1573 w += 1;
1574 }
1575 }
1576 }
1577
1578 self.truncate(w);
1579 }
1580
1581 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1583 where
1584 F: FnMut(&mut A::Item) -> K,
1585 K: PartialEq<K>,
1586 {
1587 self.dedup_by(|a, b| key(a) == key(b));
1588 }
1589
1590 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1616 where
1617 F: FnMut() -> A::Item,
1618 {
1619 let old_len = self.len();
1620 if old_len < new_len {
1621 let mut f = f;
1622 let additional = new_len - old_len;
1623 self.reserve(additional);
1624 for _ in 0..additional {
1625 self.push(f());
1626 }
1627 } else if old_len > new_len {
1628 self.truncate(new_len);
1629 }
1630 }
1631
1632 #[inline]
1700 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1701 let ptr = unsafe {
1704 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1705 NonNull::new_unchecked(ptr)
1706 };
1707 assert!(capacity > Self::inline_capacity());
1708 SmallVec {
1709 capacity,
1710 data: SmallVecData::from_heap(ptr, length),
1711 }
1712 }
1713
1714 pub fn as_ptr(&self) -> *const A::Item {
1716 self.triple().0.as_ptr()
1720 }
1721
1722 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1724 self.triple_mut().0.as_ptr()
1728 }
1729}
1730
1731impl<A: Array> SmallVec<A>
1732where
1733 A::Item: Copy,
1734{
1735 pub fn from_slice(slice: &[A::Item]) -> Self {
1739 let len = slice.len();
1740 if len <= Self::inline_capacity() {
1741 SmallVec {
1742 capacity: len,
1743 data: SmallVecData::from_inline(unsafe {
1744 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1745 ptr::copy_nonoverlapping(
1746 slice.as_ptr(),
1747 data.as_mut_ptr() as *mut A::Item,
1748 len,
1749 );
1750 data
1751 }),
1752 }
1753 } else {
1754 let mut b = slice.to_vec();
1755 let cap = b.capacity();
1756 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1757 mem::forget(b);
1758 SmallVec {
1759 capacity: cap,
1760 data: SmallVecData::from_heap(ptr, len),
1761 }
1762 }
1763 }
1764
1765 #[inline]
1770 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1771 self.reserve(slice.len());
1772
1773 let len = self.len();
1774 assert!(index <= len);
1775
1776 unsafe {
1777 let slice_ptr = slice.as_ptr();
1778 let ptr = self.as_mut_ptr().add(index);
1779 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1780 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1781 self.set_len(len + slice.len());
1782 }
1783 }
1784
1785 #[inline]
1789 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1790 let len = self.len();
1791 self.insert_from_slice(len, slice);
1792 }
1793}
1794
1795impl<A: Array> SmallVec<A>
1796where
1797 A::Item: Clone,
1798{
1799 pub fn resize(&mut self, len: usize, value: A::Item) {
1806 let old_len = self.len();
1807
1808 if len > old_len {
1809 self.extend(repeat(value).take(len - old_len));
1810 } else {
1811 self.truncate(len);
1812 }
1813 }
1814
1815 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1823 if n > Self::inline_capacity() {
1824 vec![elem; n].into()
1825 } else {
1826 let mut v = SmallVec::<A>::new();
1827 unsafe {
1828 let (ptr, len_ptr, _) = v.triple_mut();
1829 let ptr = ptr.as_ptr();
1830 let mut local_len = SetLenOnDrop::new(len_ptr);
1831
1832 for i in 0..n {
1833 ::core::ptr::write(ptr.add(i), elem.clone());
1834 local_len.increment_len(1);
1835 }
1836 }
1837 v
1838 }
1839 }
1840}
1841
1842impl<A: Array> ops::Deref for SmallVec<A> {
1843 type Target = [A::Item];
1844 #[inline]
1845 fn deref(&self) -> &[A::Item] {
1846 unsafe {
1847 let (ptr, len, _) = self.triple();
1848 slice::from_raw_parts(ptr.as_ptr(), len)
1849 }
1850 }
1851}
1852
1853impl<A: Array> ops::DerefMut for SmallVec<A> {
1854 #[inline]
1855 fn deref_mut(&mut self) -> &mut [A::Item] {
1856 unsafe {
1857 let (ptr, &mut len, _) = self.triple_mut();
1858 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1859 }
1860 }
1861}
1862
1863impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1864 #[inline]
1865 fn as_ref(&self) -> &[A::Item] {
1866 self
1867 }
1868}
1869
1870impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1871 #[inline]
1872 fn as_mut(&mut self) -> &mut [A::Item] {
1873 self
1874 }
1875}
1876
1877impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1878 #[inline]
1879 fn borrow(&self) -> &[A::Item] {
1880 self
1881 }
1882}
1883
1884impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1885 #[inline]
1886 fn borrow_mut(&mut self) -> &mut [A::Item] {
1887 self
1888 }
1889}
1890
1891#[cfg(feature = "write")]
1892#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1893impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1894 #[inline]
1895 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1896 self.extend_from_slice(buf);
1897 Ok(buf.len())
1898 }
1899
1900 #[inline]
1901 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1902 self.extend_from_slice(buf);
1903 Ok(())
1904 }
1905
1906 #[inline]
1907 fn flush(&mut self) -> io::Result<()> {
1908 Ok(())
1909 }
1910}
1911
1912#[cfg(feature = "serde")]
1913#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1914impl<A: Array> Serialize for SmallVec<A>
1915where
1916 A::Item: Serialize,
1917{
1918 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1919 let mut state = serializer.serialize_seq(Some(self.len()))?;
1920 for item in self {
1921 state.serialize_element(&item)?;
1922 }
1923 state.end()
1924 }
1925}
1926
1927#[cfg(feature = "serde")]
1928#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1929impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
1930where
1931 A::Item: Deserialize<'de>,
1932{
1933 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1934 deserializer.deserialize_seq(SmallVecVisitor {
1935 phantom: PhantomData,
1936 })
1937 }
1938}
1939
1940#[cfg(feature = "serde")]
1941struct SmallVecVisitor<A> {
1942 phantom: PhantomData<A>,
1943}
1944
1945#[cfg(feature = "serde")]
1946impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1947where
1948 A::Item: Deserialize<'de>,
1949{
1950 type Value = SmallVec<A>;
1951
1952 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1953 formatter.write_str("a sequence")
1954 }
1955
1956 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1957 where
1958 B: SeqAccess<'de>,
1959 {
1960 use serde::de::Error;
1961 let len = seq.size_hint().unwrap_or(0);
1962 let mut values = SmallVec::new();
1963 values.try_reserve(len).map_err(B::Error::custom)?;
1964
1965 while let Some(value) = seq.next_element()? {
1966 values.push(value);
1967 }
1968
1969 Ok(values)
1970 }
1971}
1972
1973#[cfg(feature = "specialization")]
1974trait SpecFrom<A: Array, S> {
1975 fn spec_from(slice: S) -> SmallVec<A>;
1976}
1977
1978#[cfg(feature = "specialization")]
1979mod specialization;
1980
1981#[cfg(feature = "arbitrary")]
1982mod arbitrary;
1983
1984#[cfg(feature = "specialization")]
1985impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
1986where
1987 A::Item: Copy,
1988{
1989 #[inline]
1990 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
1991 SmallVec::from_slice(slice)
1992 }
1993}
1994
1995impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
1996where
1997 A::Item: Clone,
1998{
1999 #[cfg(not(feature = "specialization"))]
2000 #[inline]
2001 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2002 slice.iter().cloned().collect()
2003 }
2004
2005 #[cfg(feature = "specialization")]
2006 #[inline]
2007 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2008 SmallVec::spec_from(slice)
2009 }
2010}
2011
2012impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2013 #[inline]
2014 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2015 SmallVec::from_vec(vec)
2016 }
2017}
2018
2019impl<A: Array> From<A> for SmallVec<A> {
2020 #[inline]
2021 fn from(array: A) -> SmallVec<A> {
2022 SmallVec::from_buf(array)
2023 }
2024}
2025
2026impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2027 type Output = I::Output;
2028
2029 fn index(&self, index: I) -> &I::Output {
2030 &(**self)[index]
2031 }
2032}
2033
2034impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2035 fn index_mut(&mut self, index: I) -> &mut I::Output {
2036 &mut (&mut **self)[index]
2037 }
2038}
2039
2040#[allow(deprecated)]
2041impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2042where
2043 A::Item: Copy,
2044{
2045 fn extend_from_slice(&mut self, other: &[A::Item]) {
2046 SmallVec::extend_from_slice(self, other)
2047 }
2048}
2049
2050impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2051 #[inline]
2052 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2053 let mut v = SmallVec::new();
2054 v.extend(iterable);
2055 v
2056 }
2057}
2058
2059impl<A: Array> Extend<A::Item> for SmallVec<A> {
2060 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2061 let mut iter = iterable.into_iter();
2062 let (lower_size_bound, _) = iter.size_hint();
2063 self.reserve(lower_size_bound);
2064
2065 unsafe {
2066 let (ptr, len_ptr, cap) = self.triple_mut();
2067 let ptr = ptr.as_ptr();
2068 let mut len = SetLenOnDrop::new(len_ptr);
2069 while len.get() < cap {
2070 if let Some(out) = iter.next() {
2071 ptr::write(ptr.add(len.get()), out);
2072 len.increment_len(1);
2073 } else {
2074 return;
2075 }
2076 }
2077 }
2078
2079 for elem in iter {
2080 self.push(elem);
2081 }
2082 }
2083}
2084
2085impl<A: Array> fmt::Debug for SmallVec<A>
2086where
2087 A::Item: fmt::Debug,
2088{
2089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2090 f.debug_list().entries(self.iter()).finish()
2091 }
2092}
2093
2094impl<A: Array> Default for SmallVec<A> {
2095 #[inline]
2096 fn default() -> SmallVec<A> {
2097 SmallVec::new()
2098 }
2099}
2100
2101#[cfg(feature = "may_dangle")]
2102unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2103 fn drop(&mut self) {
2104 unsafe {
2105 if self.spilled() {
2106 let (ptr, &mut len) = self.data.heap_mut();
2107 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2108 } else {
2109 ptr::drop_in_place(&mut self[..]);
2110 }
2111 }
2112 }
2113}
2114
2115#[cfg(not(feature = "may_dangle"))]
2116impl<A: Array> Drop for SmallVec<A> {
2117 fn drop(&mut self) {
2118 unsafe {
2119 if self.spilled() {
2120 let (ptr, &mut len) = self.data.heap_mut();
2121 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2122 } else {
2123 ptr::drop_in_place(&mut self[..]);
2124 }
2125 }
2126 }
2127}
2128
2129impl<A: Array> Clone for SmallVec<A>
2130where
2131 A::Item: Clone,
2132{
2133 #[inline]
2134 fn clone(&self) -> SmallVec<A> {
2135 SmallVec::from(self.as_slice())
2136 }
2137
2138 fn clone_from(&mut self, source: &Self) {
2139 self.truncate(source.len());
2143
2144 let (init, tail) = source.split_at(self.len());
2147
2148 self.clone_from_slice(init);
2150 self.extend(tail.iter().cloned());
2151 }
2152}
2153
2154impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2155where
2156 A::Item: PartialEq<B::Item>,
2157{
2158 #[inline]
2159 fn eq(&self, other: &SmallVec<B>) -> bool {
2160 self[..] == other[..]
2161 }
2162}
2163
2164impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2165
2166impl<A: Array> PartialOrd for SmallVec<A>
2167where
2168 A::Item: PartialOrd,
2169{
2170 #[inline]
2171 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2172 PartialOrd::partial_cmp(&**self, &**other)
2173 }
2174}
2175
2176impl<A: Array> Ord for SmallVec<A>
2177where
2178 A::Item: Ord,
2179{
2180 #[inline]
2181 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2182 Ord::cmp(&**self, &**other)
2183 }
2184}
2185
2186impl<A: Array> Hash for SmallVec<A>
2187where
2188 A::Item: Hash,
2189{
2190 fn hash<H: Hasher>(&self, state: &mut H) {
2191 (**self).hash(state)
2192 }
2193}
2194
2195unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2196
2197pub struct IntoIter<A: Array> {
2203 data: SmallVec<A>,
2204 current: usize,
2205 end: usize,
2206}
2207
2208impl<A: Array> fmt::Debug for IntoIter<A>
2209where
2210 A::Item: fmt::Debug,
2211{
2212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2213 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2214 }
2215}
2216
2217impl<A: Array + Clone> Clone for IntoIter<A>
2218where
2219 A::Item: Clone,
2220{
2221 fn clone(&self) -> IntoIter<A> {
2222 SmallVec::from(self.as_slice()).into_iter()
2223 }
2224}
2225
2226impl<A: Array> Drop for IntoIter<A> {
2227 fn drop(&mut self) {
2228 for _ in self {}
2229 }
2230}
2231
2232impl<A: Array> Iterator for IntoIter<A> {
2233 type Item = A::Item;
2234
2235 #[inline]
2236 fn next(&mut self) -> Option<A::Item> {
2237 if self.current == self.end {
2238 None
2239 } else {
2240 unsafe {
2241 let current = self.current;
2242 self.current += 1;
2243 Some(ptr::read(self.data.as_ptr().add(current)))
2244 }
2245 }
2246 }
2247
2248 #[inline]
2249 fn size_hint(&self) -> (usize, Option<usize>) {
2250 let size = self.end - self.current;
2251 (size, Some(size))
2252 }
2253}
2254
2255impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2256 #[inline]
2257 fn next_back(&mut self) -> Option<A::Item> {
2258 if self.current == self.end {
2259 None
2260 } else {
2261 unsafe {
2262 self.end -= 1;
2263 Some(ptr::read(self.data.as_ptr().add(self.end)))
2264 }
2265 }
2266 }
2267}
2268
2269impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2270impl<A: Array> FusedIterator for IntoIter<A> {}
2271
2272impl<A: Array> IntoIter<A> {
2273 pub fn as_slice(&self) -> &[A::Item] {
2275 let len = self.end - self.current;
2276 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2277 }
2278
2279 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2281 let len = self.end - self.current;
2282 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2283 }
2284}
2285
2286impl<A: Array> IntoIterator for SmallVec<A> {
2287 type IntoIter = IntoIter<A>;
2288 type Item = A::Item;
2289 fn into_iter(mut self) -> Self::IntoIter {
2290 unsafe {
2291 let len = self.len();
2293 self.set_len(0);
2294 IntoIter {
2295 data: self,
2296 current: 0,
2297 end: len,
2298 }
2299 }
2300 }
2301}
2302
2303impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2304 type IntoIter = slice::Iter<'a, A::Item>;
2305 type Item = &'a A::Item;
2306 fn into_iter(self) -> Self::IntoIter {
2307 self.iter()
2308 }
2309}
2310
2311impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2312 type IntoIter = slice::IterMut<'a, A::Item>;
2313 type Item = &'a mut A::Item;
2314 fn into_iter(self) -> Self::IntoIter {
2315 self.iter_mut()
2316 }
2317}
2318
2319pub unsafe trait Array {
2321 type Item;
2323 fn size() -> usize;
2325}
2326
2327struct SetLenOnDrop<'a> {
2331 len: &'a mut usize,
2332 local_len: usize,
2333}
2334
2335impl<'a> SetLenOnDrop<'a> {
2336 #[inline]
2337 fn new(len: &'a mut usize) -> Self {
2338 SetLenOnDrop {
2339 local_len: *len,
2340 len,
2341 }
2342 }
2343
2344 #[inline]
2345 fn get(&self) -> usize {
2346 self.local_len
2347 }
2348
2349 #[inline]
2350 fn increment_len(&mut self, increment: usize) {
2351 self.local_len += increment;
2352 }
2353}
2354
2355impl<'a> Drop for SetLenOnDrop<'a> {
2356 #[inline]
2357 fn drop(&mut self) {
2358 *self.len = self.local_len;
2359 }
2360}
2361
2362#[cfg(feature = "const_new")]
2363impl<T, const N: usize> SmallVec<[T; N]> {
2364 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2368 #[inline]
2369 pub const fn new_const() -> Self {
2370 SmallVec {
2371 capacity: 0,
2372 data: SmallVecData::from_const(MaybeUninit::uninit()),
2373 }
2374 }
2375
2376 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2380 #[inline]
2381 pub const fn from_const(items: [T; N]) -> Self {
2382 SmallVec {
2383 capacity: N,
2384 data: SmallVecData::from_const(MaybeUninit::new(items)),
2385 }
2386 }
2387
2388 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2394 #[inline]
2395 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2396 SmallVec {
2397 capacity: len,
2398 data: SmallVecData::from_const(MaybeUninit::new(items)),
2399 }
2400 }
2401}
2402
2403#[cfg(feature = "const_generics")]
2404#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2405unsafe impl<T, const N: usize> Array for [T; N] {
2406 type Item = T;
2407 #[inline]
2408 fn size() -> usize {
2409 N
2410 }
2411}
2412
2413#[cfg(not(feature = "const_generics"))]
2414macro_rules! impl_array(
2415 ($($size:expr),+) => {
2416 $(
2417 unsafe impl<T> Array for [T; $size] {
2418 type Item = T;
2419 #[inline]
2420 fn size() -> usize { $size }
2421 }
2422 )+
2423 }
2424);
2425
2426#[cfg(not(feature = "const_generics"))]
2427impl_array!(
2428 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,
2429 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2430 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2431);
2432
2433pub trait ToSmallVec<A: Array> {
2435 fn to_smallvec(&self) -> SmallVec<A>;
2437}
2438
2439impl<A: Array> ToSmallVec<A> for [A::Item]
2440where
2441 A::Item: Copy,
2442{
2443 #[inline]
2444 fn to_smallvec(&self) -> SmallVec<A> {
2445 SmallVec::from_slice(self)
2446 }
2447}
2448
2449#[repr(transparent)]
2451struct ConstNonNull<T>(NonNull<T>);
2452
2453impl<T> ConstNonNull<T> {
2454 #[inline]
2455 fn new(ptr: *const T) -> Option<Self> {
2456 NonNull::new(ptr as *mut T).map(Self)
2457 }
2458 #[inline]
2459 fn as_ptr(self) -> *const T {
2460 self.0.as_ptr()
2461 }
2462}
2463
2464impl<T> Clone for ConstNonNull<T> {
2465 #[inline]
2466 fn clone(&self) -> Self {
2467 *self
2468 }
2469}
2470
2471impl<T> Copy for ConstNonNull<T> {}