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 = "malloc_size_of")]
130use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
131
132#[cfg(feature = "serde")]
133use serde::{
134 de::{Deserialize, Deserializer, SeqAccess, Visitor},
135 ser::{Serialize, SerializeSeq, Serializer},
136};
137
138#[cfg(feature = "serde")]
139use core::marker::PhantomData;
140
141#[cfg(feature = "write")]
142use std::io;
143
144#[cfg(feature = "drain_keep_rest")]
145use core::mem::ManuallyDrop;
146
147#[macro_export]
184macro_rules! smallvec {
185 (@one $x:expr) => (1usize);
187 () => (
188 $crate::SmallVec::new()
189 );
190 ($elem:expr; $n:expr) => ({
191 $crate::SmallVec::from_elem($elem, $n)
192 });
193 ($($x:expr),+$(,)?) => ({
194 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
195 let mut vec = $crate::SmallVec::new();
196 if count <= vec.inline_size() {
197 $(vec.push($x);)*
198 vec
199 } else {
200 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
201 }
202 });
203}
204
205#[cfg(feature = "const_new")]
235#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
236#[macro_export]
237macro_rules! smallvec_inline {
238 (@one $x:expr) => (1usize);
240 ($elem:expr; $n:expr) => ({
241 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
242 });
243 ($($x:expr),+ $(,)?) => ({
244 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
245 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
246 });
247}
248
249#[cfg(not(feature = "union"))]
251macro_rules! debug_unreachable {
252 () => {
253 debug_unreachable!("entered unreachable code")
254 };
255 ($e:expr) => {
256 if cfg!(debug_assertions) {
257 panic!($e);
258 } else {
259 unreachable_unchecked();
260 }
261 };
262}
263
264#[doc(hidden)]
284#[deprecated]
285pub trait ExtendFromSlice<T> {
286 fn extend_from_slice(&mut self, other: &[T]);
288}
289
290#[allow(deprecated)]
291impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
292 fn extend_from_slice(&mut self, other: &[T]) {
293 Vec::extend_from_slice(self, other)
294 }
295}
296
297#[derive(Debug)]
299pub enum CollectionAllocErr {
300 CapacityOverflow,
302 AllocErr {
304 layout: Layout,
306 },
307}
308
309impl fmt::Display for CollectionAllocErr {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 write!(f, "Allocation error: {:?}", self)
312 }
313}
314
315#[allow(deprecated)]
316impl From<LayoutErr> for CollectionAllocErr {
317 fn from(_: LayoutErr) -> Self {
318 CollectionAllocErr::CapacityOverflow
319 }
320}
321
322fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
323 match result {
324 Ok(x) => x,
325 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
326 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
327 }
328}
329
330fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333 let size = mem::size_of::<T>()
334 .checked_mul(n)
335 .ok_or(CollectionAllocErr::CapacityOverflow)?;
336 let align = mem::align_of::<T>();
337 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338}
339
340unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
341 let layout = layout_array::<T>(capacity).unwrap();
343 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
344}
345
346pub struct Drain<'a, T: 'a + Array> {
352 tail_start: usize,
353 tail_len: usize,
354 iter: slice::Iter<'a, T::Item>,
355 vec: NonNull<SmallVec<T>>,
356}
357
358impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
359where
360 T::Item: fmt::Debug,
361{
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
364 }
365}
366
367unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
368unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
369
370impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
371 type Item = T::Item;
372
373 #[inline]
374 fn next(&mut self) -> Option<T::Item> {
375 self.iter
376 .next()
377 .map(|reference| unsafe { ptr::read(reference) })
378 }
379
380 #[inline]
381 fn size_hint(&self) -> (usize, Option<usize>) {
382 self.iter.size_hint()
383 }
384}
385
386impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
387 #[inline]
388 fn next_back(&mut self) -> Option<T::Item> {
389 self.iter
390 .next_back()
391 .map(|reference| unsafe { ptr::read(reference) })
392 }
393}
394
395impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
396 #[inline]
397 fn len(&self) -> usize {
398 self.iter.len()
399 }
400}
401
402impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
403
404impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
405 fn drop(&mut self) {
406 self.for_each(drop);
407
408 if self.tail_len > 0 {
409 unsafe {
410 let source_vec = self.vec.as_mut();
411
412 let start = source_vec.len();
414 let tail = self.tail_start;
415 if tail != start {
416 let ptr = source_vec.as_mut_ptr();
419 let src = ptr.add(tail);
420 let dst = ptr.add(start);
421 ptr::copy(src, dst, self.tail_len);
422 }
423 source_vec.set_len(start + self.tail_len);
424 }
425 }
426 }
427}
428
429#[cfg(feature = "drain_filter")]
430pub struct DrainFilter<'a, T, F>
436where
437 F: FnMut(&mut T::Item) -> bool,
438 T: Array,
439{
440 vec: &'a mut SmallVec<T>,
441 idx: usize,
443 del: usize,
445 old_len: usize,
447 pred: F,
449 panic_flag: bool,
455}
456
457#[cfg(feature = "drain_filter")]
458impl <T, F> fmt::Debug for DrainFilter<'_, T, F>
459where
460 F: FnMut(&mut T::Item) -> bool,
461 T: Array,
462 T::Item: fmt::Debug,
463{
464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 f.debug_tuple("DrainFilter").field(&self.vec.as_slice()).finish()
466 }
467}
468
469#[cfg(feature = "drain_filter")]
470impl <T, F> Iterator for DrainFilter<'_, T, F>
471where
472 F: FnMut(&mut T::Item) -> bool,
473 T: Array,
474{
475 type Item = T::Item;
476
477 fn next(&mut self) -> Option<T::Item>
478 {
479 unsafe {
480 while self.idx < self.old_len {
481 let i = self.idx;
482 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
483 self.panic_flag = true;
484 let drained = (self.pred)(&mut v[i]);
485 self.panic_flag = false;
486 self.idx += 1;
490 if drained {
491 self.del += 1;
492 return Some(ptr::read(&v[i]));
493 } else if self.del > 0 {
494 let del = self.del;
495 let src: *const Self::Item = &v[i];
496 let dst: *mut Self::Item = &mut v[i - del];
497 ptr::copy_nonoverlapping(src, dst, 1);
498 }
499 }
500 None
501 }
502 }
503
504 fn size_hint(&self) -> (usize, Option<usize>) {
505 (0, Some(self.old_len - self.idx))
506 }
507}
508
509#[cfg(feature = "drain_filter")]
510impl <T, F> Drop for DrainFilter<'_, T, F>
511where
512 F: FnMut(&mut T::Item) -> bool,
513 T: Array,
514{
515 fn drop(&mut self) {
516 struct BackshiftOnDrop<'a, 'b, T, F>
517 where
518 F: FnMut(&mut T::Item) -> bool,
519 T: Array
520 {
521 drain: &'b mut DrainFilter<'a, T, F>,
522 }
523
524 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
525 where
526 F: FnMut(&mut T::Item) -> bool,
527 T: Array
528 {
529 fn drop(&mut self) {
530 unsafe {
531 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
532 let ptr = self.drain.vec.as_mut_ptr();
539 let src = ptr.add(self.drain.idx);
540 let dst = src.sub(self.drain.del);
541 let tail_len = self.drain.old_len - self.drain.idx;
542 src.copy_to(dst, tail_len);
543 }
544 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
545 }
546 }
547 }
548
549 let backshift = BackshiftOnDrop { drain: self };
550
551 if !backshift.drain.panic_flag {
555 backshift.drain.for_each(drop);
556 }
557 }
558}
559
560#[cfg(feature = "drain_keep_rest")]
561impl <T, F> DrainFilter<'_, T, F>
562where
563 F: FnMut(&mut T::Item) -> bool,
564 T: Array
565{
566 pub fn keep_rest(self)
586 {
587 let mut this = ManuallyDrop::new(self);
602
603 unsafe {
604 let needs_move = mem::size_of::<T::Item>() != 0;
606
607 if needs_move && this.idx < this.old_len && this.del > 0 {
608 let ptr = this.vec.as_mut_ptr();
609 let src = ptr.add(this.idx);
610 let dst = src.sub(this.del);
611 let tail_len = this.old_len - this.idx;
612 src.copy_to(dst, tail_len);
613 }
614
615 let new_len = this.old_len - this.del;
616 this.vec.set_len(new_len);
617 }
618 }
619}
620
621#[cfg(feature = "union")]
622union SmallVecData<A: Array> {
623 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
624 heap: (NonNull<A::Item>, usize),
625}
626
627#[cfg(all(feature = "union", feature = "const_new"))]
628impl<T, const N: usize> SmallVecData<[T; N]> {
629 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
630 #[inline]
631 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
632 SmallVecData {
633 inline: core::mem::ManuallyDrop::new(inline),
634 }
635 }
636}
637
638#[cfg(feature = "union")]
639impl<A: Array> SmallVecData<A> {
640 #[inline]
641 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
642 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
643 }
644 #[inline]
645 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
646 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
647 }
648 #[inline]
649 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
650 SmallVecData {
651 inline: core::mem::ManuallyDrop::new(inline),
652 }
653 }
654 #[inline]
662 fn empty() -> SmallVecData<A> {
663 SmallVecData { inline: unsafe { MaybeUninit::uninit().assume_init() } }
666 }
667 #[inline]
668 unsafe fn into_inline(self) -> MaybeUninit<A> {
669 core::mem::ManuallyDrop::into_inner(self.inline)
670 }
671 #[inline]
672 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
673 (ConstNonNull(self.heap.0), self.heap.1)
674 }
675 #[inline]
676 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
677 let h = &mut self.heap;
678 (h.0, &mut h.1)
679 }
680 #[inline]
681 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
682 SmallVecData { heap: (ptr, len) }
683 }
684}
685
686#[cfg(not(feature = "union"))]
687enum SmallVecData<A: Array> {
688 Inline(MaybeUninit<A>),
689 Heap {
691 ptr: NonNull<A::Item>,
696 len: usize,
697 },
698}
699
700#[cfg(all(not(feature = "union"), feature = "const_new"))]
701impl<T, const N: usize> SmallVecData<[T; N]> {
702 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
703 #[inline]
704 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
705 SmallVecData::Inline(inline)
706 }
707}
708
709#[cfg(not(feature = "union"))]
710impl<A: Array> SmallVecData<A> {
711 #[inline]
712 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
713 match self {
714 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
715 _ => debug_unreachable!(),
716 }
717 }
718 #[inline]
719 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
720 match self {
721 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
722 _ => debug_unreachable!(),
723 }
724 }
725 #[inline]
726 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
727 SmallVecData::Inline(inline)
728 }
729 #[inline]
731 fn empty() -> SmallVecData<A> {
732 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
735 }
736 #[inline]
737 unsafe fn into_inline(self) -> MaybeUninit<A> {
738 match self {
739 SmallVecData::Inline(a) => a,
740 _ => debug_unreachable!(),
741 }
742 }
743 #[inline]
744 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
745 match self {
746 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
747 _ => debug_unreachable!(),
748 }
749 }
750 #[inline]
751 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
752 match self {
753 SmallVecData::Heap { ptr, len } => (*ptr, len),
754 _ => debug_unreachable!(),
755 }
756 }
757 #[inline]
758 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
759 SmallVecData::Heap { ptr, len }
760 }
761}
762
763unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
764unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
765
766pub struct SmallVec<A: Array> {
793 capacity: usize,
797 data: SmallVecData<A>,
798}
799
800impl<A: Array> SmallVec<A> {
801 #[inline]
803 pub fn new() -> SmallVec<A> {
804 assert!(
807 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
808 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
809 );
810 SmallVec {
811 capacity: 0,
812 data: SmallVecData::empty(),
813 }
814 }
815
816 #[inline]
830 pub fn with_capacity(n: usize) -> Self {
831 let mut v = SmallVec::new();
832 v.reserve_exact(n);
833 v
834 }
835
836 #[inline]
849 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
850 if vec.capacity() <= Self::inline_capacity() {
851 unsafe {
854 let mut data = SmallVecData::<A>::empty();
855 let len = vec.len();
856 vec.set_len(0);
857 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
858
859 SmallVec {
860 capacity: len,
861 data,
862 }
863 }
864 } else {
865 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
866 mem::forget(vec);
867 let ptr = NonNull::new(ptr)
868 .expect("Cannot be null by `Vec` invariant");
870
871 SmallVec {
872 capacity: cap,
873 data: SmallVecData::from_heap(ptr, len),
874 }
875 }
876 }
877
878 #[inline]
890 pub fn from_buf(buf: A) -> SmallVec<A> {
891 SmallVec {
892 capacity: A::size(),
893 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
894 }
895 }
896
897 #[inline]
910 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
911 assert!(len <= A::size());
912 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
913 }
914
915 #[inline]
931 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
932 SmallVec {
933 capacity: len,
934 data: SmallVecData::from_inline(buf),
935 }
936 }
937
938 pub unsafe fn set_len(&mut self, new_len: usize) {
944 let (_, len_ptr, _) = self.triple_mut();
945 *len_ptr = new_len;
946 }
947
948 #[inline]
950 fn inline_capacity() -> usize {
951 if mem::size_of::<A::Item>() > 0 {
952 A::size()
953 } else {
954 core::usize::MAX
965 }
966 }
967
968 #[inline]
970 pub fn inline_size(&self) -> usize {
971 Self::inline_capacity()
972 }
973
974 #[inline]
976 pub fn len(&self) -> usize {
977 self.triple().1
978 }
979
980 #[inline]
982 pub fn is_empty(&self) -> bool {
983 self.len() == 0
984 }
985
986 #[inline]
988 pub fn capacity(&self) -> usize {
989 self.triple().2
990 }
991
992 #[inline]
995 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
996 unsafe {
997 if self.spilled() {
998 let (ptr, len) = self.data.heap();
999 (ptr, len, self.capacity)
1000 } else {
1001 (self.data.inline(), self.capacity, Self::inline_capacity())
1002 }
1003 }
1004 }
1005
1006 #[inline]
1008 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1009 unsafe {
1010 if self.spilled() {
1011 let (ptr, len_ptr) = self.data.heap_mut();
1012 (ptr, len_ptr, self.capacity)
1013 } else {
1014 (
1015 self.data.inline_mut(),
1016 &mut self.capacity,
1017 Self::inline_capacity(),
1018 )
1019 }
1020 }
1021 }
1022
1023 #[inline]
1025 pub fn spilled(&self) -> bool {
1026 self.capacity > Self::inline_capacity()
1027 }
1028
1029 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1043 where
1044 R: RangeBounds<usize>,
1045 {
1046 use core::ops::Bound::*;
1047
1048 let len = self.len();
1049 let start = match range.start_bound() {
1050 Included(&n) => n,
1051 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1052 Unbounded => 0,
1053 };
1054 let end = match range.end_bound() {
1055 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1056 Excluded(&n) => n,
1057 Unbounded => len,
1058 };
1059
1060 assert!(start <= end);
1061 assert!(end <= len);
1062
1063 unsafe {
1064 self.set_len(start);
1065
1066 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1067
1068 Drain {
1069 tail_start: end,
1070 tail_len: len - end,
1071 iter: range_slice.iter(),
1072 vec: NonNull::new_unchecked(self as *mut _),
1074 }
1075 }
1076 }
1077
1078 #[cfg(feature = "drain_filter")]
1079 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F,>
1123 where
1124 F: FnMut(&mut A::Item) -> bool,
1125 {
1126 let old_len = self.len();
1127
1128 unsafe {
1130 self.set_len(0);
1131 }
1132
1133 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
1134 }
1135
1136 #[inline]
1138 pub fn push(&mut self, value: A::Item) {
1139 unsafe {
1140 let (mut ptr, mut len, cap) = self.triple_mut();
1141 if *len == cap {
1142 self.reserve_one_unchecked();
1143 let (heap_ptr, heap_len) = self.data.heap_mut();
1144 ptr = heap_ptr;
1145 len = heap_len;
1146 }
1147 ptr::write(ptr.as_ptr().add(*len), value);
1148 *len += 1;
1149 }
1150 }
1151
1152 #[inline]
1154 pub fn pop(&mut self) -> Option<A::Item> {
1155 unsafe {
1156 let (ptr, len_ptr, _) = self.triple_mut();
1157 let ptr: *const _ = ptr.as_ptr();
1158 if *len_ptr == 0 {
1159 return None;
1160 }
1161 let last_index = *len_ptr - 1;
1162 *len_ptr = last_index;
1163 Some(ptr::read(ptr.add(last_index)))
1164 }
1165 }
1166
1167 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1180 where
1181 B: Array<Item = A::Item>,
1182 {
1183 self.extend(other.drain(..))
1184 }
1185
1186 pub fn grow(&mut self, new_cap: usize) {
1191 infallible(self.try_grow(new_cap))
1192 }
1193
1194 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1198 unsafe {
1199 let unspilled = !self.spilled();
1200 let (ptr, &mut len, cap) = self.triple_mut();
1201 assert!(new_cap >= len);
1202 if new_cap <= Self::inline_capacity() {
1203 if unspilled {
1204 return Ok(());
1205 }
1206 self.data = SmallVecData::empty();
1207 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1208 self.capacity = len;
1209 deallocate(ptr, cap);
1210 } else if new_cap != cap {
1211 let layout = layout_array::<A::Item>(new_cap)?;
1212 debug_assert!(layout.size() > 0);
1213 let new_alloc;
1214 if unspilled {
1215 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1216 .ok_or(CollectionAllocErr::AllocErr { layout })?
1217 .cast();
1218 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1219 } else {
1220 let old_layout = layout_array::<A::Item>(cap)?;
1223
1224 let new_ptr =
1225 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1226 new_alloc = NonNull::new(new_ptr)
1227 .ok_or(CollectionAllocErr::AllocErr { layout })?
1228 .cast();
1229 }
1230 self.data = SmallVecData::from_heap(new_alloc, len);
1231 self.capacity = new_cap;
1232 }
1233 Ok(())
1234 }
1235 }
1236
1237 #[inline]
1243 pub fn reserve(&mut self, additional: usize) {
1244 infallible(self.try_reserve(additional))
1245 }
1246
1247 #[cold]
1249 fn reserve_one_unchecked(&mut self) {
1250 debug_assert_eq!(self.len(), self.capacity());
1251 let new_cap = self.len()
1252 .checked_add(1)
1253 .and_then(usize::checked_next_power_of_two)
1254 .expect("capacity overflow");
1255 infallible(self.try_grow(new_cap))
1256 }
1257
1258 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1262 let (_, &mut len, cap) = self.triple_mut();
1265 if cap - len >= additional {
1266 return Ok(());
1267 }
1268 let new_cap = len
1269 .checked_add(additional)
1270 .and_then(usize::checked_next_power_of_two)
1271 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1272 self.try_grow(new_cap)
1273 }
1274
1275 pub fn reserve_exact(&mut self, additional: usize) {
1279 infallible(self.try_reserve_exact(additional))
1280 }
1281
1282 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1284 let (_, &mut len, cap) = self.triple_mut();
1285 if cap - len >= additional {
1286 return Ok(());
1287 }
1288 let new_cap = len
1289 .checked_add(additional)
1290 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1291 self.try_grow(new_cap)
1292 }
1293
1294 pub fn shrink_to_fit(&mut self) {
1299 if !self.spilled() {
1300 return;
1301 }
1302 let len = self.len();
1303 if self.inline_size() >= len {
1304 unsafe {
1305 let (ptr, len) = self.data.heap();
1306 self.data = SmallVecData::empty();
1307 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1308 deallocate(ptr.0, self.capacity);
1309 self.capacity = len;
1310 }
1311 } else if self.capacity() > len {
1312 self.grow(len);
1313 }
1314 }
1315
1316 pub fn truncate(&mut self, len: usize) {
1324 unsafe {
1325 let (ptr, len_ptr, _) = self.triple_mut();
1326 let ptr = ptr.as_ptr();
1327 while len < *len_ptr {
1328 let last_index = *len_ptr - 1;
1329 *len_ptr = last_index;
1330 ptr::drop_in_place(ptr.add(last_index));
1331 }
1332 }
1333 }
1334
1335 pub fn as_slice(&self) -> &[A::Item] {
1339 self
1340 }
1341
1342 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1346 self
1347 }
1348
1349 #[inline]
1355 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1356 let len = self.len();
1357 self.swap(len - 1, index);
1358 self.pop()
1359 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1360 }
1361
1362 #[inline]
1364 pub fn clear(&mut self) {
1365 self.truncate(0);
1366 }
1367
1368 pub fn remove(&mut self, index: usize) -> A::Item {
1373 unsafe {
1374 let (ptr, len_ptr, _) = self.triple_mut();
1375 let len = *len_ptr;
1376 assert!(index < len);
1377 *len_ptr = len - 1;
1378 let ptr = ptr.as_ptr().add(index);
1379 let item = ptr::read(ptr);
1380 ptr::copy(ptr.add(1), ptr, len - index - 1);
1381 item
1382 }
1383 }
1384
1385 pub fn insert(&mut self, index: usize, element: A::Item) {
1389 unsafe {
1390 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1391 if *len_ptr == cap {
1392 self.reserve_one_unchecked();
1393 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1394 ptr = heap_ptr;
1395 len_ptr = heap_len_ptr;
1396 }
1397 let mut ptr = ptr.as_ptr();
1398 let len = *len_ptr;
1399 if index > len {
1400 panic!("index exceeds length");
1401 }
1402 ptr = ptr.add(index);
1404 if index < len {
1405 ptr::copy(ptr, ptr.add(1), len - index);
1407 }
1408 *len_ptr = len + 1;
1409 ptr::write(ptr, element);
1410 }
1411 }
1412
1413 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1416 let mut iter = iterable.into_iter();
1417 if index == self.len() {
1418 return self.extend(iter);
1419 }
1420
1421 let (lower_size_bound, _) = iter.size_hint();
1422 assert!(lower_size_bound <= core::isize::MAX as usize); assert!(index + lower_size_bound >= index); let mut num_added = 0;
1426 let old_len = self.len();
1427 assert!(index <= old_len);
1428
1429 unsafe {
1430 self.reserve(lower_size_bound);
1432 let start = self.as_mut_ptr();
1433 let ptr = start.add(index);
1434
1435 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1437
1438 self.set_len(0);
1440 let mut guard = DropOnPanic {
1441 start,
1442 skip: index..(index + lower_size_bound),
1443 len: old_len + lower_size_bound,
1444 };
1445
1446 let start = self.as_mut_ptr();
1448 let ptr = start.add(index);
1449
1450 while num_added < lower_size_bound {
1451 let element = match iter.next() {
1452 Some(x) => x,
1453 None => break,
1454 };
1455 let cur = ptr.add(num_added);
1456 ptr::write(cur, element);
1457 guard.skip.start += 1;
1458 num_added += 1;
1459 }
1460
1461 if num_added < lower_size_bound {
1462 ptr::copy(
1464 ptr.add(lower_size_bound),
1465 ptr.add(num_added),
1466 old_len - index,
1467 );
1468 }
1469 self.set_len(old_len + num_added);
1471 mem::forget(guard);
1472 }
1473
1474 for element in iter {
1476 self.insert(index + num_added, element);
1477 num_added += 1;
1478 }
1479
1480 struct DropOnPanic<T> {
1481 start: *mut T,
1482 skip: Range<usize>, len: usize,
1484 }
1485
1486 impl<T> Drop for DropOnPanic<T> {
1487 fn drop(&mut self) {
1488 for i in 0..self.len {
1489 if !self.skip.contains(&i) {
1490 unsafe {
1491 ptr::drop_in_place(self.start.add(i));
1492 }
1493 }
1494 }
1495 }
1496 }
1497 }
1498
1499 pub fn into_vec(mut self) -> Vec<A::Item> {
1502 if self.spilled() {
1503 unsafe {
1504 let (ptr, &mut len) = self.data.heap_mut();
1505 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1506 mem::forget(self);
1507 v
1508 }
1509 } else {
1510 self.into_iter().collect()
1511 }
1512 }
1513
1514 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1519 self.into_vec().into_boxed_slice()
1520 }
1521
1522 pub fn into_inner(self) -> Result<A, Self> {
1527 if self.spilled() || self.len() != A::size() {
1528 Err(self)
1530 } else {
1531 unsafe {
1532 let data = ptr::read(&self.data);
1533 mem::forget(self);
1534 Ok(data.into_inline().assume_init())
1535 }
1536 }
1537 }
1538
1539 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1545 let mut del = 0;
1546 let len = self.len();
1547 for i in 0..len {
1548 if !f(&mut self[i]) {
1549 del += 1;
1550 } else if del > 0 {
1551 self.swap(i - del, i);
1552 }
1553 }
1554 self.truncate(len - del);
1555 }
1556
1557 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1563 self.retain(f)
1564 }
1565
1566 pub fn dedup(&mut self)
1568 where
1569 A::Item: PartialEq<A::Item>,
1570 {
1571 self.dedup_by(|a, b| a == b);
1572 }
1573
1574 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1576 where
1577 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1578 {
1579 let len = self.len();
1582 if len <= 1 {
1583 return;
1584 }
1585
1586 let ptr = self.as_mut_ptr();
1587 let mut w: usize = 1;
1588
1589 unsafe {
1590 for r in 1..len {
1591 let p_r = ptr.add(r);
1592 let p_wm1 = ptr.add(w - 1);
1593 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1594 if r != w {
1595 let p_w = p_wm1.add(1);
1596 mem::swap(&mut *p_r, &mut *p_w);
1597 }
1598 w += 1;
1599 }
1600 }
1601 }
1602
1603 self.truncate(w);
1604 }
1605
1606 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1608 where
1609 F: FnMut(&mut A::Item) -> K,
1610 K: PartialEq<K>,
1611 {
1612 self.dedup_by(|a, b| key(a) == key(b));
1613 }
1614
1615 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1641 where
1642 F: FnMut() -> A::Item,
1643 {
1644 let old_len = self.len();
1645 if old_len < new_len {
1646 let mut f = f;
1647 let additional = new_len - old_len;
1648 self.reserve(additional);
1649 for _ in 0..additional {
1650 self.push(f());
1651 }
1652 } else if old_len > new_len {
1653 self.truncate(new_len);
1654 }
1655 }
1656
1657 #[inline]
1725 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1726 let ptr = unsafe {
1729 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1730 NonNull::new_unchecked(ptr)
1731 };
1732 assert!(capacity > Self::inline_capacity());
1733 SmallVec {
1734 capacity,
1735 data: SmallVecData::from_heap(ptr, length),
1736 }
1737 }
1738
1739 pub fn as_ptr(&self) -> *const A::Item {
1741 self.triple().0.as_ptr()
1745 }
1746
1747 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1749 self.triple_mut().0.as_ptr()
1753 }
1754}
1755
1756impl<A: Array> SmallVec<A>
1757where
1758 A::Item: Copy,
1759{
1760 pub fn from_slice(slice: &[A::Item]) -> Self {
1764 let len = slice.len();
1765 if len <= Self::inline_capacity() {
1766 SmallVec {
1767 capacity: len,
1768 data: SmallVecData::from_inline(unsafe {
1769 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1770 ptr::copy_nonoverlapping(
1771 slice.as_ptr(),
1772 data.as_mut_ptr() as *mut A::Item,
1773 len,
1774 );
1775 data
1776 }),
1777 }
1778 } else {
1779 let mut b = slice.to_vec();
1780 let cap = b.capacity();
1781 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1782 mem::forget(b);
1783 SmallVec {
1784 capacity: cap,
1785 data: SmallVecData::from_heap(ptr, len),
1786 }
1787 }
1788 }
1789
1790 #[inline]
1795 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1796 self.reserve(slice.len());
1797
1798 let len = self.len();
1799 assert!(index <= len);
1800
1801 unsafe {
1802 let slice_ptr = slice.as_ptr();
1803 let ptr = self.as_mut_ptr().add(index);
1804 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1805 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1806 self.set_len(len + slice.len());
1807 }
1808 }
1809
1810 #[inline]
1814 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1815 let len = self.len();
1816 self.insert_from_slice(len, slice);
1817 }
1818}
1819
1820impl<A: Array> SmallVec<A>
1821where
1822 A::Item: Clone,
1823{
1824 pub fn resize(&mut self, len: usize, value: A::Item) {
1831 let old_len = self.len();
1832
1833 if len > old_len {
1834 self.extend(repeat(value).take(len - old_len));
1835 } else {
1836 self.truncate(len);
1837 }
1838 }
1839
1840 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1848 if n > Self::inline_capacity() {
1849 vec![elem; n].into()
1850 } else {
1851 let mut v = SmallVec::<A>::new();
1852 unsafe {
1853 let (ptr, len_ptr, _) = v.triple_mut();
1854 let ptr = ptr.as_ptr();
1855 let mut local_len = SetLenOnDrop::new(len_ptr);
1856
1857 for i in 0..n {
1858 ::core::ptr::write(ptr.add(i), elem.clone());
1859 local_len.increment_len(1);
1860 }
1861 }
1862 v
1863 }
1864 }
1865}
1866
1867impl<A: Array> ops::Deref for SmallVec<A> {
1868 type Target = [A::Item];
1869 #[inline]
1870 fn deref(&self) -> &[A::Item] {
1871 unsafe {
1872 let (ptr, len, _) = self.triple();
1873 slice::from_raw_parts(ptr.as_ptr(), len)
1874 }
1875 }
1876}
1877
1878impl<A: Array> ops::DerefMut for SmallVec<A> {
1879 #[inline]
1880 fn deref_mut(&mut self) -> &mut [A::Item] {
1881 unsafe {
1882 let (ptr, &mut len, _) = self.triple_mut();
1883 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1884 }
1885 }
1886}
1887
1888impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1889 #[inline]
1890 fn as_ref(&self) -> &[A::Item] {
1891 self
1892 }
1893}
1894
1895impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1896 #[inline]
1897 fn as_mut(&mut self) -> &mut [A::Item] {
1898 self
1899 }
1900}
1901
1902impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1903 #[inline]
1904 fn borrow(&self) -> &[A::Item] {
1905 self
1906 }
1907}
1908
1909impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1910 #[inline]
1911 fn borrow_mut(&mut self) -> &mut [A::Item] {
1912 self
1913 }
1914}
1915
1916#[cfg(feature = "write")]
1917#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1918impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1919 #[inline]
1920 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1921 self.extend_from_slice(buf);
1922 Ok(buf.len())
1923 }
1924
1925 #[inline]
1926 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1927 self.extend_from_slice(buf);
1928 Ok(())
1929 }
1930
1931 #[inline]
1932 fn flush(&mut self) -> io::Result<()> {
1933 Ok(())
1934 }
1935}
1936
1937#[cfg(feature = "serde")]
1938#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1939impl<A: Array> Serialize for SmallVec<A>
1940where
1941 A::Item: Serialize,
1942{
1943 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1944 let mut state = serializer.serialize_seq(Some(self.len()))?;
1945 for item in self {
1946 state.serialize_element(&item)?;
1947 }
1948 state.end()
1949 }
1950}
1951
1952#[cfg(feature = "serde")]
1953#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1954impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
1955where
1956 A::Item: Deserialize<'de>,
1957{
1958 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1959 deserializer.deserialize_seq(SmallVecVisitor {
1960 phantom: PhantomData,
1961 })
1962 }
1963}
1964
1965#[cfg(feature = "serde")]
1966struct SmallVecVisitor<A> {
1967 phantom: PhantomData<A>,
1968}
1969
1970#[cfg(feature = "serde")]
1971impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1972where
1973 A::Item: Deserialize<'de>,
1974{
1975 type Value = SmallVec<A>;
1976
1977 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1978 formatter.write_str("a sequence")
1979 }
1980
1981 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1982 where
1983 B: SeqAccess<'de>,
1984 {
1985 use serde::de::Error;
1986 let len = seq.size_hint().unwrap_or(0);
1987 let mut values = SmallVec::new();
1988 values.try_reserve(len).map_err(B::Error::custom)?;
1989
1990 while let Some(value) = seq.next_element()? {
1991 values.push(value);
1992 }
1993
1994 Ok(values)
1995 }
1996}
1997
1998#[cfg(feature = "malloc_size_of")]
1999impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2000 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2001 if self.spilled() {
2002 unsafe { ops.malloc_size_of(self.as_ptr()) }
2003 } else {
2004 0
2005 }
2006 }
2007}
2008
2009#[cfg(feature = "malloc_size_of")]
2010impl<A> MallocSizeOf for SmallVec<A>
2011where
2012 A: Array,
2013 A::Item: MallocSizeOf,
2014{
2015 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2016 let mut n = self.shallow_size_of(ops);
2017 for elem in self.iter() {
2018 n += elem.size_of(ops);
2019 }
2020 n
2021 }
2022}
2023
2024#[cfg(feature = "specialization")]
2025trait SpecFrom<A: Array, S> {
2026 fn spec_from(slice: S) -> SmallVec<A>;
2027}
2028
2029#[cfg(feature = "specialization")]
2030mod specialization;
2031
2032#[cfg(feature = "arbitrary")]
2033mod arbitrary;
2034
2035#[cfg(feature = "specialization")]
2036impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2037where
2038 A::Item: Copy,
2039{
2040 #[inline]
2041 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2042 SmallVec::from_slice(slice)
2043 }
2044}
2045
2046impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2047where
2048 A::Item: Clone,
2049{
2050 #[cfg(not(feature = "specialization"))]
2051 #[inline]
2052 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2053 slice.iter().cloned().collect()
2054 }
2055
2056 #[cfg(feature = "specialization")]
2057 #[inline]
2058 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2059 SmallVec::spec_from(slice)
2060 }
2061}
2062
2063impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2064 #[inline]
2065 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2066 SmallVec::from_vec(vec)
2067 }
2068}
2069
2070impl<A: Array> From<A> for SmallVec<A> {
2071 #[inline]
2072 fn from(array: A) -> SmallVec<A> {
2073 SmallVec::from_buf(array)
2074 }
2075}
2076
2077impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2078 type Output = I::Output;
2079
2080 fn index(&self, index: I) -> &I::Output {
2081 &(**self)[index]
2082 }
2083}
2084
2085impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2086 fn index_mut(&mut self, index: I) -> &mut I::Output {
2087 &mut (&mut **self)[index]
2088 }
2089}
2090
2091#[allow(deprecated)]
2092impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2093where
2094 A::Item: Copy,
2095{
2096 fn extend_from_slice(&mut self, other: &[A::Item]) {
2097 SmallVec::extend_from_slice(self, other)
2098 }
2099}
2100
2101impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2102 #[inline]
2103 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2104 let mut v = SmallVec::new();
2105 v.extend(iterable);
2106 v
2107 }
2108}
2109
2110impl<A: Array> Extend<A::Item> for SmallVec<A> {
2111 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2112 let mut iter = iterable.into_iter();
2113 let (lower_size_bound, _) = iter.size_hint();
2114 self.reserve(lower_size_bound);
2115
2116 unsafe {
2117 let (ptr, len_ptr, cap) = self.triple_mut();
2118 let ptr = ptr.as_ptr();
2119 let mut len = SetLenOnDrop::new(len_ptr);
2120 while len.get() < cap {
2121 if let Some(out) = iter.next() {
2122 ptr::write(ptr.add(len.get()), out);
2123 len.increment_len(1);
2124 } else {
2125 return;
2126 }
2127 }
2128 }
2129
2130 for elem in iter {
2131 self.push(elem);
2132 }
2133 }
2134}
2135
2136impl<A: Array> fmt::Debug for SmallVec<A>
2137where
2138 A::Item: fmt::Debug,
2139{
2140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2141 f.debug_list().entries(self.iter()).finish()
2142 }
2143}
2144
2145impl<A: Array> Default for SmallVec<A> {
2146 #[inline]
2147 fn default() -> SmallVec<A> {
2148 SmallVec::new()
2149 }
2150}
2151
2152#[cfg(feature = "may_dangle")]
2153unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2154 fn drop(&mut self) {
2155 unsafe {
2156 if self.spilled() {
2157 let (ptr, &mut len) = self.data.heap_mut();
2158 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2159 } else {
2160 ptr::drop_in_place(&mut self[..]);
2161 }
2162 }
2163 }
2164}
2165
2166#[cfg(not(feature = "may_dangle"))]
2167impl<A: Array> Drop for SmallVec<A> {
2168 fn drop(&mut self) {
2169 unsafe {
2170 if self.spilled() {
2171 let (ptr, &mut len) = self.data.heap_mut();
2172 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2173 } else {
2174 ptr::drop_in_place(&mut self[..]);
2175 }
2176 }
2177 }
2178}
2179
2180impl<A: Array> Clone for SmallVec<A>
2181where
2182 A::Item: Clone,
2183{
2184 #[inline]
2185 fn clone(&self) -> SmallVec<A> {
2186 SmallVec::from(self.as_slice())
2187 }
2188
2189 fn clone_from(&mut self, source: &Self) {
2190 self.truncate(source.len());
2194
2195 let (init, tail) = source.split_at(self.len());
2198
2199 self.clone_from_slice(init);
2201 self.extend(tail.iter().cloned());
2202 }
2203}
2204
2205impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2206where
2207 A::Item: PartialEq<B::Item>,
2208{
2209 #[inline]
2210 fn eq(&self, other: &SmallVec<B>) -> bool {
2211 self[..] == other[..]
2212 }
2213}
2214
2215impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2216
2217impl<A: Array> PartialOrd for SmallVec<A>
2218where
2219 A::Item: PartialOrd,
2220{
2221 #[inline]
2222 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2223 PartialOrd::partial_cmp(&**self, &**other)
2224 }
2225}
2226
2227impl<A: Array> Ord for SmallVec<A>
2228where
2229 A::Item: Ord,
2230{
2231 #[inline]
2232 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2233 Ord::cmp(&**self, &**other)
2234 }
2235}
2236
2237impl<A: Array> Hash for SmallVec<A>
2238where
2239 A::Item: Hash,
2240{
2241 fn hash<H: Hasher>(&self, state: &mut H) {
2242 (**self).hash(state)
2243 }
2244}
2245
2246unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2247
2248pub struct IntoIter<A: Array> {
2254 data: SmallVec<A>,
2255 current: usize,
2256 end: usize,
2257}
2258
2259impl<A: Array> fmt::Debug for IntoIter<A>
2260where
2261 A::Item: fmt::Debug,
2262{
2263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2264 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2265 }
2266}
2267
2268impl<A: Array + Clone> Clone for IntoIter<A>
2269where
2270 A::Item: Clone,
2271{
2272 fn clone(&self) -> IntoIter<A> {
2273 SmallVec::from(self.as_slice()).into_iter()
2274 }
2275}
2276
2277impl<A: Array> Drop for IntoIter<A> {
2278 fn drop(&mut self) {
2279 for _ in self {}
2280 }
2281}
2282
2283impl<A: Array> Iterator for IntoIter<A> {
2284 type Item = A::Item;
2285
2286 #[inline]
2287 fn next(&mut self) -> Option<A::Item> {
2288 if self.current == self.end {
2289 None
2290 } else {
2291 unsafe {
2292 let current = self.current;
2293 self.current += 1;
2294 Some(ptr::read(self.data.as_ptr().add(current)))
2295 }
2296 }
2297 }
2298
2299 #[inline]
2300 fn size_hint(&self) -> (usize, Option<usize>) {
2301 let size = self.end - self.current;
2302 (size, Some(size))
2303 }
2304}
2305
2306impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2307 #[inline]
2308 fn next_back(&mut self) -> Option<A::Item> {
2309 if self.current == self.end {
2310 None
2311 } else {
2312 unsafe {
2313 self.end -= 1;
2314 Some(ptr::read(self.data.as_ptr().add(self.end)))
2315 }
2316 }
2317 }
2318}
2319
2320impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2321impl<A: Array> FusedIterator for IntoIter<A> {}
2322
2323impl<A: Array> IntoIter<A> {
2324 pub fn as_slice(&self) -> &[A::Item] {
2326 let len = self.end - self.current;
2327 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2328 }
2329
2330 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2332 let len = self.end - self.current;
2333 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2334 }
2335}
2336
2337impl<A: Array> IntoIterator for SmallVec<A> {
2338 type IntoIter = IntoIter<A>;
2339 type Item = A::Item;
2340 fn into_iter(mut self) -> Self::IntoIter {
2341 unsafe {
2342 let len = self.len();
2344 self.set_len(0);
2345 IntoIter {
2346 data: self,
2347 current: 0,
2348 end: len,
2349 }
2350 }
2351 }
2352}
2353
2354impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2355 type IntoIter = slice::Iter<'a, A::Item>;
2356 type Item = &'a A::Item;
2357 fn into_iter(self) -> Self::IntoIter {
2358 self.iter()
2359 }
2360}
2361
2362impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2363 type IntoIter = slice::IterMut<'a, A::Item>;
2364 type Item = &'a mut A::Item;
2365 fn into_iter(self) -> Self::IntoIter {
2366 self.iter_mut()
2367 }
2368}
2369
2370pub unsafe trait Array {
2372 type Item;
2374 fn size() -> usize;
2376}
2377
2378struct SetLenOnDrop<'a> {
2382 len: &'a mut usize,
2383 local_len: usize,
2384}
2385
2386impl<'a> SetLenOnDrop<'a> {
2387 #[inline]
2388 fn new(len: &'a mut usize) -> Self {
2389 SetLenOnDrop {
2390 local_len: *len,
2391 len,
2392 }
2393 }
2394
2395 #[inline]
2396 fn get(&self) -> usize {
2397 self.local_len
2398 }
2399
2400 #[inline]
2401 fn increment_len(&mut self, increment: usize) {
2402 self.local_len += increment;
2403 }
2404}
2405
2406impl<'a> Drop for SetLenOnDrop<'a> {
2407 #[inline]
2408 fn drop(&mut self) {
2409 *self.len = self.local_len;
2410 }
2411}
2412
2413#[cfg(feature = "const_new")]
2414impl<T, const N: usize> SmallVec<[T; N]> {
2415 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2419 #[inline]
2420 pub const fn new_const() -> Self {
2421 SmallVec {
2422 capacity: 0,
2423 data: SmallVecData::from_const(MaybeUninit::uninit()),
2424 }
2425 }
2426
2427 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2431 #[inline]
2432 pub const fn from_const(items: [T; N]) -> Self {
2433 SmallVec {
2434 capacity: N,
2435 data: SmallVecData::from_const(MaybeUninit::new(items)),
2436 }
2437 }
2438
2439 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2445 #[inline]
2446 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2447 SmallVec {
2448 capacity: len,
2449 data: SmallVecData::from_const(MaybeUninit::new(items)),
2450 }
2451 }
2452}
2453
2454#[cfg(feature = "const_generics")]
2455#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2456unsafe impl<T, const N: usize> Array for [T; N] {
2457 type Item = T;
2458 #[inline]
2459 fn size() -> usize {
2460 N
2461 }
2462}
2463
2464#[cfg(not(feature = "const_generics"))]
2465macro_rules! impl_array(
2466 ($($size:expr),+) => {
2467 $(
2468 unsafe impl<T> Array for [T; $size] {
2469 type Item = T;
2470 #[inline]
2471 fn size() -> usize { $size }
2472 }
2473 )+
2474 }
2475);
2476
2477#[cfg(not(feature = "const_generics"))]
2478impl_array!(
2479 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,
2480 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2481 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2482);
2483
2484pub trait ToSmallVec<A: Array> {
2486 fn to_smallvec(&self) -> SmallVec<A>;
2488}
2489
2490impl<A: Array> ToSmallVec<A> for [A::Item]
2491where
2492 A::Item: Copy,
2493{
2494 #[inline]
2495 fn to_smallvec(&self) -> SmallVec<A> {
2496 SmallVec::from_slice(self)
2497 }
2498}
2499
2500#[repr(transparent)]
2502struct ConstNonNull<T>(NonNull<T>);
2503
2504impl<T> ConstNonNull<T> {
2505 #[inline]
2506 fn new(ptr: *const T) -> Option<Self> {
2507 NonNull::new(ptr as *mut T).map(Self)
2508 }
2509 #[inline]
2510 fn as_ptr(self) -> *const T {
2511 self.0.as_ptr()
2512 }
2513}
2514
2515impl<T> Clone for ConstNonNull<T> {
2516 #[inline]
2517 fn clone(&self) -> Self {
2518 *self
2519 }
2520}
2521
2522impl<T> Copy for ConstNonNull<T> {}
2523
2524#[cfg(feature = "impl_bincode")]
2525use bincode::{
2526 de::{BorrowDecoder, Decode, Decoder, read::Reader},
2527 enc::{Encode, Encoder, write::Writer},
2528 error::{DecodeError, EncodeError},
2529 BorrowDecode,
2530};
2531
2532#[cfg(feature = "impl_bincode")]
2533impl<A, Context> Decode<Context> for SmallVec<A>
2534where
2535 A: Array,
2536 A::Item: Decode<Context>,
2537{
2538 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2539 use core::convert::TryInto;
2540 let len = u64::decode(decoder)?;
2541 let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2542 decoder.claim_container_read::<A::Item>(len)?;
2543
2544 let mut vec = SmallVec::with_capacity(len);
2545 if unty::type_equal::<A::Item, u8>() {
2546 let ptr = vec.as_mut_ptr();
2549 unsafe {
2551 core::ptr::write_bytes(ptr, 0, len);
2552 vec.set_len(len);
2553 }
2554 let slice = vec.as_mut_slice();
2556 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2558 decoder.reader().read(slice)?;
2559 } else {
2560 for _ in 0..len {
2561 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2562 vec.push(A::Item::decode(decoder)?);
2563 }
2564 }
2565 Ok(vec)
2566 }
2567}
2568
2569#[cfg(feature = "impl_bincode")]
2570impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2571where
2572 A: Array,
2573 A::Item: BorrowDecode<'de, Context>,
2574{
2575 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2576 use core::convert::TryInto;
2577 let len = u64::decode(decoder)?;
2578 let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2579 decoder.claim_container_read::<A::Item>(len)?;
2580
2581 let mut vec = SmallVec::with_capacity(len);
2582 if unty::type_equal::<A::Item, u8>() {
2583 let ptr = vec.as_mut_ptr();
2586 unsafe {
2588 core::ptr::write_bytes(ptr, 0, len);
2589 vec.set_len(len);
2590 }
2591 let slice = vec.as_mut_slice();
2593 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2595 decoder.reader().read(slice)?;
2596 } else {
2597 for _ in 0..len {
2598 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2599 vec.push(A::Item::borrow_decode(decoder)?);
2600 }
2601 }
2602 Ok(vec)
2603 }
2604}
2605
2606#[cfg(feature = "impl_bincode")]
2607impl<A> Encode for SmallVec<A>
2608where
2609 A: Array,
2610 A::Item: Encode,
2611{
2612 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2613 (self.len() as u64).encode(encoder)?;
2614 if unty::type_equal::<A::Item, u8>() {
2615 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2617 encoder.writer().write(slice)?;
2618 } else {
2619 for item in self.iter() {
2620 item.encode(encoder)?;
2621 }
2622 }
2623 Ok(())
2624 }
2625}