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>() != 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]
655    unsafe fn into_inline(self) -> MaybeUninit<A> {
656        core::mem::ManuallyDrop::into_inner(self.inline)
657    }
658    #[inline]
659    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
660        (ConstNonNull(self.heap.0), self.heap.1)
661    }
662    #[inline]
663    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
664        let h = &mut self.heap;
665        (h.0, &mut h.1)
666    }
667    #[inline]
668    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
669        SmallVecData { heap: (ptr, len) }
670    }
671}
672
673#[cfg(not(feature = "union"))]
674enum SmallVecData<A: Array> {
675    Inline(MaybeUninit<A>),
676    Heap {
678        ptr: NonNull<A::Item>,
683        len: usize,
684    },
685}
686
687#[cfg(all(not(feature = "union"), feature = "const_new"))]
688impl<T, const N: usize> SmallVecData<[T; N]> {
689    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
690    #[inline]
691    const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
692        SmallVecData::Inline(inline)
693    }
694}
695
696#[cfg(not(feature = "union"))]
697impl<A: Array> SmallVecData<A> {
698    #[inline]
699    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700        match self {
701            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702            _ => debug_unreachable!(),
703        }
704    }
705    #[inline]
706    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707        match self {
708            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709            _ => debug_unreachable!(),
710        }
711    }
712    #[inline]
713    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714        SmallVecData::Inline(inline)
715    }
716    #[inline]
717    unsafe fn into_inline(self) -> MaybeUninit<A> {
718        match self {
719            SmallVecData::Inline(a) => a,
720            _ => debug_unreachable!(),
721        }
722    }
723    #[inline]
724    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725        match self {
726            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727            _ => debug_unreachable!(),
728        }
729    }
730    #[inline]
731    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732        match self {
733            SmallVecData::Heap { ptr, len } => (*ptr, len),
734            _ => debug_unreachable!(),
735        }
736    }
737    #[inline]
738    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739        SmallVecData::Heap { ptr, len }
740    }
741}
742
743unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
744unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
745
746pub struct SmallVec<A: Array> {
773    capacity: usize,
777    data: SmallVecData<A>,
778}
779
780impl<A: Array> SmallVec<A> {
781    #[inline]
783    pub fn new() -> SmallVec<A> {
784        assert!(
787            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789        );
790        SmallVec {
791            capacity: 0,
792            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793        }
794    }
795
796    #[inline]
810    pub fn with_capacity(n: usize) -> Self {
811        let mut v = SmallVec::new();
812        v.reserve_exact(n);
813        v
814    }
815
816    #[inline]
829    pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
830        if vec.capacity() <= Self::inline_capacity() {
831            unsafe {
834                let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit());
835                let len = vec.len();
836                vec.set_len(0);
837                ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
838
839                SmallVec {
840                    capacity: len,
841                    data,
842                }
843            }
844        } else {
845            let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
846            mem::forget(vec);
847            let ptr = NonNull::new(ptr)
848                .expect("Cannot be null by `Vec` invariant");
850
851            SmallVec {
852                capacity: cap,
853                data: SmallVecData::from_heap(ptr, len),
854            }
855        }
856    }
857
858    #[inline]
870    pub fn from_buf(buf: A) -> SmallVec<A> {
871        SmallVec {
872            capacity: A::size(),
873            data: SmallVecData::from_inline(MaybeUninit::new(buf)),
874        }
875    }
876
877    #[inline]
890    pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
891        assert!(len <= A::size());
892        unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
893    }
894
895    #[inline]
911    pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
912        SmallVec {
913            capacity: len,
914            data: SmallVecData::from_inline(buf),
915        }
916    }
917
918    pub unsafe fn set_len(&mut self, new_len: usize) {
924        let (_, len_ptr, _) = self.triple_mut();
925        *len_ptr = new_len;
926    }
927
928    #[inline]
930    fn inline_capacity() -> usize {
931        if mem::size_of::<A::Item>() > 0 {
932            A::size()
933        } else {
934            core::usize::MAX
945        }
946    }
947
948    #[inline]
950    pub fn inline_size(&self) -> usize {
951        Self::inline_capacity()
952    }
953
954    #[inline]
956    pub fn len(&self) -> usize {
957        self.triple().1
958    }
959
960    #[inline]
962    pub fn is_empty(&self) -> bool {
963        self.len() == 0
964    }
965
966    #[inline]
968    pub fn capacity(&self) -> usize {
969        self.triple().2
970    }
971
972    #[inline]
975    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976        unsafe {
977            if self.spilled() {
978                let (ptr, len) = self.data.heap();
979                (ptr, len, self.capacity)
980            } else {
981                (self.data.inline(), self.capacity, Self::inline_capacity())
982            }
983        }
984    }
985
986    #[inline]
988    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989        unsafe {
990            if self.spilled() {
991                let (ptr, len_ptr) = self.data.heap_mut();
992                (ptr, len_ptr, self.capacity)
993            } else {
994                (
995                    self.data.inline_mut(),
996                    &mut self.capacity,
997                    Self::inline_capacity(),
998                )
999            }
1000        }
1001    }
1002
1003    #[inline]
1005    pub fn spilled(&self) -> bool {
1006        self.capacity > Self::inline_capacity()
1007    }
1008
1009    pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1023    where
1024        R: RangeBounds<usize>,
1025    {
1026        use core::ops::Bound::*;
1027
1028        let len = self.len();
1029        let start = match range.start_bound() {
1030            Included(&n) => n,
1031            Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1032            Unbounded => 0,
1033        };
1034        let end = match range.end_bound() {
1035            Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1036            Excluded(&n) => n,
1037            Unbounded => len,
1038        };
1039
1040        assert!(start <= end);
1041        assert!(end <= len);
1042
1043        unsafe {
1044            self.set_len(start);
1045
1046            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1047
1048            Drain {
1049                tail_start: end,
1050                tail_len: len - end,
1051                iter: range_slice.iter(),
1052                vec: NonNull::new_unchecked(self as *mut _),
1054            }
1055        }
1056    }
1057
1058    #[cfg(feature = "drain_filter")]
1059    pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F,>
1103    where
1104        F: FnMut(&mut A::Item) -> bool,
1105    {
1106        let old_len = self.len();
1107
1108        unsafe {
1110            self.set_len(0);
1111        }
1112
1113        DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
1114    }
1115
1116    #[inline]
1118    pub fn push(&mut self, value: A::Item) {
1119        unsafe {
1120            let (mut ptr, mut len, cap) = self.triple_mut();
1121            if *len == cap {
1122                self.reserve_one_unchecked();
1123                let (heap_ptr, heap_len) = self.data.heap_mut();
1124                ptr = heap_ptr;
1125                len = heap_len;
1126            }
1127            ptr::write(ptr.as_ptr().add(*len), value);
1128            *len += 1;
1129        }
1130    }
1131
1132    #[inline]
1134    pub fn pop(&mut self) -> Option<A::Item> {
1135        unsafe {
1136            let (ptr, len_ptr, _) = self.triple_mut();
1137            let ptr: *const _ = ptr.as_ptr();
1138            if *len_ptr == 0 {
1139                return None;
1140            }
1141            let last_index = *len_ptr - 1;
1142            *len_ptr = last_index;
1143            Some(ptr::read(ptr.add(last_index)))
1144        }
1145    }
1146
1147    pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1160    where
1161        B: Array<Item = A::Item>,
1162    {
1163        self.extend(other.drain(..))
1164    }
1165
1166    pub fn grow(&mut self, new_cap: usize) {
1171        infallible(self.try_grow(new_cap))
1172    }
1173
1174    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178        unsafe {
1179            let unspilled = !self.spilled();
1180            let (ptr, &mut len, cap) = self.triple_mut();
1181            assert!(new_cap >= len);
1182            if new_cap <= Self::inline_capacity() {
1183                if unspilled {
1184                    return Ok(());
1185                }
1186                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188                self.capacity = len;
1189                deallocate(ptr, cap);
1190            } else if new_cap != cap {
1191                let layout = layout_array::<A::Item>(new_cap)?;
1192                debug_assert!(layout.size() > 0);
1193                let new_alloc;
1194                if unspilled {
1195                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197                        .cast();
1198                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199                } else {
1200                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204                    let new_ptr =
1205                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206                    new_alloc = NonNull::new(new_ptr)
1207                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208                        .cast();
1209                }
1210                self.data = SmallVecData::from_heap(new_alloc, len);
1211                self.capacity = new_cap;
1212            }
1213            Ok(())
1214        }
1215    }
1216
1217    #[inline]
1223    pub fn reserve(&mut self, additional: usize) {
1224        infallible(self.try_reserve(additional))
1225    }
1226
1227    #[cold]
1229    fn reserve_one_unchecked(&mut self) {
1230        debug_assert_eq!(self.len(), self.capacity());
1231        let new_cap = self.len()
1232            .checked_add(1)
1233            .and_then(usize::checked_next_power_of_two)
1234            .expect("capacity overflow");
1235        infallible(self.try_grow(new_cap))
1236    }
1237
1238    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1242        let (_, &mut len, cap) = self.triple_mut();
1245        if cap - len >= additional {
1246            return Ok(());
1247        }
1248        let new_cap = len
1249            .checked_add(additional)
1250            .and_then(usize::checked_next_power_of_two)
1251            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1252        self.try_grow(new_cap)
1253    }
1254
1255    pub fn reserve_exact(&mut self, additional: usize) {
1259        infallible(self.try_reserve_exact(additional))
1260    }
1261
1262    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1264        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            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1271        self.try_grow(new_cap)
1272    }
1273
1274    pub fn shrink_to_fit(&mut self) {
1279        if !self.spilled() {
1280            return;
1281        }
1282        let len = self.len();
1283        if self.inline_size() >= len {
1284            unsafe {
1285                let (ptr, len) = self.data.heap();
1286                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1287                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1288                deallocate(ptr.0, self.capacity);
1289                self.capacity = len;
1290            }
1291        } else if self.capacity() > len {
1292            self.grow(len);
1293        }
1294    }
1295
1296    pub fn truncate(&mut self, len: usize) {
1304        unsafe {
1305            let (ptr, len_ptr, _) = self.triple_mut();
1306            let ptr = ptr.as_ptr();
1307            while len < *len_ptr {
1308                let last_index = *len_ptr - 1;
1309                *len_ptr = last_index;
1310                ptr::drop_in_place(ptr.add(last_index));
1311            }
1312        }
1313    }
1314
1315    pub fn as_slice(&self) -> &[A::Item] {
1319        self
1320    }
1321
1322    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1326        self
1327    }
1328
1329    #[inline]
1335    pub fn swap_remove(&mut self, index: usize) -> A::Item {
1336        let len = self.len();
1337        self.swap(len - 1, index);
1338        self.pop()
1339            .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1340    }
1341
1342    #[inline]
1344    pub fn clear(&mut self) {
1345        self.truncate(0);
1346    }
1347
1348    pub fn remove(&mut self, index: usize) -> A::Item {
1353        unsafe {
1354            let (ptr, len_ptr, _) = self.triple_mut();
1355            let len = *len_ptr;
1356            assert!(index < len);
1357            *len_ptr = len - 1;
1358            let ptr = ptr.as_ptr().add(index);
1359            let item = ptr::read(ptr);
1360            ptr::copy(ptr.add(1), ptr, len - index - 1);
1361            item
1362        }
1363    }
1364
1365    pub fn insert(&mut self, index: usize, element: A::Item) {
1369        unsafe {
1370            let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1371            if *len_ptr == cap {
1372                self.reserve_one_unchecked();
1373                let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1374                ptr = heap_ptr;
1375                len_ptr = heap_len_ptr;
1376            }
1377            let mut ptr = ptr.as_ptr();
1378            let len = *len_ptr;
1379            if index > len {
1380                panic!("index exceeds length");
1381            }
1382            ptr = ptr.add(index);
1384            if index < len {
1385                ptr::copy(ptr, ptr.add(1), len - index);
1387            }
1388            *len_ptr = len + 1;
1389            ptr::write(ptr, element);
1390        }
1391    }
1392
1393    pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1396        let mut iter = iterable.into_iter();
1397        if index == self.len() {
1398            return self.extend(iter);
1399        }
1400
1401        let (lower_size_bound, _) = iter.size_hint();
1402        assert!(lower_size_bound <= core::isize::MAX as usize); assert!(index + lower_size_bound >= index); let mut num_added = 0;
1406        let old_len = self.len();
1407        assert!(index <= old_len);
1408
1409        unsafe {
1410            self.reserve(lower_size_bound);
1412            let start = self.as_mut_ptr();
1413            let ptr = start.add(index);
1414
1415            ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1417
1418            self.set_len(0);
1420            let mut guard = DropOnPanic {
1421                start,
1422                skip: index..(index + lower_size_bound),
1423                len: old_len + lower_size_bound,
1424            };
1425
1426            let start = self.as_mut_ptr();
1428            let ptr = start.add(index);
1429
1430            while num_added < lower_size_bound {
1431                let element = match iter.next() {
1432                    Some(x) => x,
1433                    None => break,
1434                };
1435                let cur = ptr.add(num_added);
1436                ptr::write(cur, element);
1437                guard.skip.start += 1;
1438                num_added += 1;
1439            }
1440
1441            if num_added < lower_size_bound {
1442                ptr::copy(
1444                    ptr.add(lower_size_bound),
1445                    ptr.add(num_added),
1446                    old_len - index,
1447                );
1448            }
1449            self.set_len(old_len + num_added);
1451            mem::forget(guard);
1452        }
1453
1454        for element in iter {
1456            self.insert(index + num_added, element);
1457            num_added += 1;
1458        }
1459
1460        struct DropOnPanic<T> {
1461            start: *mut T,
1462            skip: Range<usize>, len: usize,
1464        }
1465
1466        impl<T> Drop for DropOnPanic<T> {
1467            fn drop(&mut self) {
1468                for i in 0..self.len {
1469                    if !self.skip.contains(&i) {
1470                        unsafe {
1471                            ptr::drop_in_place(self.start.add(i));
1472                        }
1473                    }
1474                }
1475            }
1476        }
1477    }
1478
1479    pub fn into_vec(mut self) -> Vec<A::Item> {
1482        if self.spilled() {
1483            unsafe {
1484                let (ptr, &mut len) = self.data.heap_mut();
1485                let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1486                mem::forget(self);
1487                v
1488            }
1489        } else {
1490            self.into_iter().collect()
1491        }
1492    }
1493
1494    pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1499        self.into_vec().into_boxed_slice()
1500    }
1501
1502    pub fn into_inner(self) -> Result<A, Self> {
1507        if self.spilled() || self.len() != A::size() {
1508            Err(self)
1510        } else {
1511            unsafe {
1512                let data = ptr::read(&self.data);
1513                mem::forget(self);
1514                Ok(data.into_inline().assume_init())
1515            }
1516        }
1517    }
1518
1519    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1525        let mut del = 0;
1526        let len = self.len();
1527        for i in 0..len {
1528            if !f(&mut self[i]) {
1529                del += 1;
1530            } else if del > 0 {
1531                self.swap(i - del, i);
1532            }
1533        }
1534        self.truncate(len - del);
1535    }
1536
1537    pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1543        self.retain(f)
1544    }
1545
1546    pub fn dedup(&mut self)
1548    where
1549        A::Item: PartialEq<A::Item>,
1550    {
1551        self.dedup_by(|a, b| a == b);
1552    }
1553
1554    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1556    where
1557        F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1558    {
1559        let len = self.len();
1562        if len <= 1 {
1563            return;
1564        }
1565
1566        let ptr = self.as_mut_ptr();
1567        let mut w: usize = 1;
1568
1569        unsafe {
1570            for r in 1..len {
1571                let p_r = ptr.add(r);
1572                let p_wm1 = ptr.add(w - 1);
1573                if !same_bucket(&mut *p_r, &mut *p_wm1) {
1574                    if r != w {
1575                        let p_w = p_wm1.add(1);
1576                        mem::swap(&mut *p_r, &mut *p_w);
1577                    }
1578                    w += 1;
1579                }
1580            }
1581        }
1582
1583        self.truncate(w);
1584    }
1585
1586    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1588    where
1589        F: FnMut(&mut A::Item) -> K,
1590        K: PartialEq<K>,
1591    {
1592        self.dedup_by(|a, b| key(a) == key(b));
1593    }
1594
1595    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1621    where
1622        F: FnMut() -> A::Item,
1623    {
1624        let old_len = self.len();
1625        if old_len < new_len {
1626            let mut f = f;
1627            let additional = new_len - old_len;
1628            self.reserve(additional);
1629            for _ in 0..additional {
1630                self.push(f());
1631            }
1632        } else if old_len > new_len {
1633            self.truncate(new_len);
1634        }
1635    }
1636
1637    #[inline]
1705    pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1706        let ptr = unsafe {
1709            debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1710            NonNull::new_unchecked(ptr)
1711        };
1712        assert!(capacity > Self::inline_capacity());
1713        SmallVec {
1714            capacity,
1715            data: SmallVecData::from_heap(ptr, length),
1716        }
1717    }
1718
1719    pub fn as_ptr(&self) -> *const A::Item {
1721        self.triple().0.as_ptr()
1725    }
1726
1727    pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1729        self.triple_mut().0.as_ptr()
1733    }
1734}
1735
1736impl<A: Array> SmallVec<A>
1737where
1738    A::Item: Copy,
1739{
1740    pub fn from_slice(slice: &[A::Item]) -> Self {
1744        let len = slice.len();
1745        if len <= Self::inline_capacity() {
1746            SmallVec {
1747                capacity: len,
1748                data: SmallVecData::from_inline(unsafe {
1749                    let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1750                    ptr::copy_nonoverlapping(
1751                        slice.as_ptr(),
1752                        data.as_mut_ptr() as *mut A::Item,
1753                        len,
1754                    );
1755                    data
1756                }),
1757            }
1758        } else {
1759            let mut b = slice.to_vec();
1760            let cap = b.capacity();
1761            let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1762            mem::forget(b);
1763            SmallVec {
1764                capacity: cap,
1765                data: SmallVecData::from_heap(ptr, len),
1766            }
1767        }
1768    }
1769
1770    #[inline]
1775    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1776        self.reserve(slice.len());
1777
1778        let len = self.len();
1779        assert!(index <= len);
1780
1781        unsafe {
1782            let slice_ptr = slice.as_ptr();
1783            let ptr = self.as_mut_ptr().add(index);
1784            ptr::copy(ptr, ptr.add(slice.len()), len - index);
1785            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1786            self.set_len(len + slice.len());
1787        }
1788    }
1789
1790    #[inline]
1794    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1795        let len = self.len();
1796        self.insert_from_slice(len, slice);
1797    }
1798}
1799
1800impl<A: Array> SmallVec<A>
1801where
1802    A::Item: Clone,
1803{
1804    pub fn resize(&mut self, len: usize, value: A::Item) {
1811        let old_len = self.len();
1812
1813        if len > old_len {
1814            self.extend(repeat(value).take(len - old_len));
1815        } else {
1816            self.truncate(len);
1817        }
1818    }
1819
1820    pub fn from_elem(elem: A::Item, n: usize) -> Self {
1828        if n > Self::inline_capacity() {
1829            vec![elem; n].into()
1830        } else {
1831            let mut v = SmallVec::<A>::new();
1832            unsafe {
1833                let (ptr, len_ptr, _) = v.triple_mut();
1834                let ptr = ptr.as_ptr();
1835                let mut local_len = SetLenOnDrop::new(len_ptr);
1836
1837                for i in 0..n {
1838                    ::core::ptr::write(ptr.add(i), elem.clone());
1839                    local_len.increment_len(1);
1840                }
1841            }
1842            v
1843        }
1844    }
1845}
1846
1847impl<A: Array> ops::Deref for SmallVec<A> {
1848    type Target = [A::Item];
1849    #[inline]
1850    fn deref(&self) -> &[A::Item] {
1851        unsafe {
1852            let (ptr, len, _) = self.triple();
1853            slice::from_raw_parts(ptr.as_ptr(), len)
1854        }
1855    }
1856}
1857
1858impl<A: Array> ops::DerefMut for SmallVec<A> {
1859    #[inline]
1860    fn deref_mut(&mut self) -> &mut [A::Item] {
1861        unsafe {
1862            let (ptr, &mut len, _) = self.triple_mut();
1863            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864        }
1865    }
1866}
1867
1868impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1869    #[inline]
1870    fn as_ref(&self) -> &[A::Item] {
1871        self
1872    }
1873}
1874
1875impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1876    #[inline]
1877    fn as_mut(&mut self) -> &mut [A::Item] {
1878        self
1879    }
1880}
1881
1882impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1883    #[inline]
1884    fn borrow(&self) -> &[A::Item] {
1885        self
1886    }
1887}
1888
1889impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1890    #[inline]
1891    fn borrow_mut(&mut self) -> &mut [A::Item] {
1892        self
1893    }
1894}
1895
1896#[cfg(feature = "write")]
1897#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1898impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1899    #[inline]
1900    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1901        self.extend_from_slice(buf);
1902        Ok(buf.len())
1903    }
1904
1905    #[inline]
1906    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1907        self.extend_from_slice(buf);
1908        Ok(())
1909    }
1910
1911    #[inline]
1912    fn flush(&mut self) -> io::Result<()> {
1913        Ok(())
1914    }
1915}
1916
1917#[cfg(feature = "serde")]
1918#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1919impl<A: Array> Serialize for SmallVec<A>
1920where
1921    A::Item: Serialize,
1922{
1923    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1924        let mut state = serializer.serialize_seq(Some(self.len()))?;
1925        for item in self {
1926            state.serialize_element(&item)?;
1927        }
1928        state.end()
1929    }
1930}
1931
1932#[cfg(feature = "serde")]
1933#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1934impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
1935where
1936    A::Item: Deserialize<'de>,
1937{
1938    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1939        deserializer.deserialize_seq(SmallVecVisitor {
1940            phantom: PhantomData,
1941        })
1942    }
1943}
1944
1945#[cfg(feature = "serde")]
1946struct SmallVecVisitor<A> {
1947    phantom: PhantomData<A>,
1948}
1949
1950#[cfg(feature = "serde")]
1951impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1952where
1953    A::Item: Deserialize<'de>,
1954{
1955    type Value = SmallVec<A>;
1956
1957    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1958        formatter.write_str("a sequence")
1959    }
1960
1961    fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1962    where
1963        B: SeqAccess<'de>,
1964    {
1965        use serde::de::Error;
1966        let len = seq.size_hint().unwrap_or(0);
1967        let mut values = SmallVec::new();
1968        values.try_reserve(len).map_err(B::Error::custom)?;
1969
1970        while let Some(value) = seq.next_element()? {
1971            values.push(value);
1972        }
1973
1974        Ok(values)
1975    }
1976}
1977
1978#[cfg(feature = "malloc_size_of")]
1979impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
1980    fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
1981        if self.spilled() {
1982            unsafe { ops.malloc_size_of(self.as_ptr()) }
1983        } else {
1984            0
1985        }
1986    }
1987}
1988
1989#[cfg(feature = "malloc_size_of")]
1990impl<A> MallocSizeOf for SmallVec<A>
1991where
1992    A: Array,
1993    A::Item: MallocSizeOf,
1994{
1995    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
1996        let mut n = self.shallow_size_of(ops);
1997        for elem in self.iter() {
1998            n += elem.size_of(ops);
1999        }
2000        n
2001    }
2002}
2003
2004#[cfg(feature = "specialization")]
2005trait SpecFrom<A: Array, S> {
2006    fn spec_from(slice: S) -> SmallVec<A>;
2007}
2008
2009#[cfg(feature = "specialization")]
2010mod specialization;
2011
2012#[cfg(feature = "arbitrary")]
2013mod arbitrary;
2014
2015#[cfg(feature = "specialization")]
2016impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2017where
2018    A::Item: Copy,
2019{
2020    #[inline]
2021    fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2022        SmallVec::from_slice(slice)
2023    }
2024}
2025
2026impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2027where
2028    A::Item: Clone,
2029{
2030    #[cfg(not(feature = "specialization"))]
2031    #[inline]
2032    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2033        slice.iter().cloned().collect()
2034    }
2035
2036    #[cfg(feature = "specialization")]
2037    #[inline]
2038    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2039        SmallVec::spec_from(slice)
2040    }
2041}
2042
2043impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2044    #[inline]
2045    fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2046        SmallVec::from_vec(vec)
2047    }
2048}
2049
2050impl<A: Array> From<A> for SmallVec<A> {
2051    #[inline]
2052    fn from(array: A) -> SmallVec<A> {
2053        SmallVec::from_buf(array)
2054    }
2055}
2056
2057impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2058    type Output = I::Output;
2059
2060    fn index(&self, index: I) -> &I::Output {
2061        &(**self)[index]
2062    }
2063}
2064
2065impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2066    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067        &mut (&mut **self)[index]
2068    }
2069}
2070
2071#[allow(deprecated)]
2072impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2073where
2074    A::Item: Copy,
2075{
2076    fn extend_from_slice(&mut self, other: &[A::Item]) {
2077        SmallVec::extend_from_slice(self, other)
2078    }
2079}
2080
2081impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2082    #[inline]
2083    fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2084        let mut v = SmallVec::new();
2085        v.extend(iterable);
2086        v
2087    }
2088}
2089
2090impl<A: Array> Extend<A::Item> for SmallVec<A> {
2091    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092        let mut iter = iterable.into_iter();
2093        let (lower_size_bound, _) = iter.size_hint();
2094        self.reserve(lower_size_bound);
2095
2096        unsafe {
2097            let (ptr, len_ptr, cap) = self.triple_mut();
2098            let ptr = ptr.as_ptr();
2099            let mut len = SetLenOnDrop::new(len_ptr);
2100            while len.get() < cap {
2101                if let Some(out) = iter.next() {
2102                    ptr::write(ptr.add(len.get()), out);
2103                    len.increment_len(1);
2104                } else {
2105                    return;
2106                }
2107            }
2108        }
2109
2110        for elem in iter {
2111            self.push(elem);
2112        }
2113    }
2114}
2115
2116impl<A: Array> fmt::Debug for SmallVec<A>
2117where
2118    A::Item: fmt::Debug,
2119{
2120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2121        f.debug_list().entries(self.iter()).finish()
2122    }
2123}
2124
2125impl<A: Array> Default for SmallVec<A> {
2126    #[inline]
2127    fn default() -> SmallVec<A> {
2128        SmallVec::new()
2129    }
2130}
2131
2132#[cfg(feature = "may_dangle")]
2133unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2134    fn drop(&mut self) {
2135        unsafe {
2136            if self.spilled() {
2137                let (ptr, &mut len) = self.data.heap_mut();
2138                Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2139            } else {
2140                ptr::drop_in_place(&mut self[..]);
2141            }
2142        }
2143    }
2144}
2145
2146#[cfg(not(feature = "may_dangle"))]
2147impl<A: Array> Drop for SmallVec<A> {
2148    fn drop(&mut self) {
2149        unsafe {
2150            if self.spilled() {
2151                let (ptr, &mut len) = self.data.heap_mut();
2152                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153            } else {
2154                ptr::drop_in_place(&mut self[..]);
2155            }
2156        }
2157    }
2158}
2159
2160impl<A: Array> Clone for SmallVec<A>
2161where
2162    A::Item: Clone,
2163{
2164    #[inline]
2165    fn clone(&self) -> SmallVec<A> {
2166        SmallVec::from(self.as_slice())
2167    }
2168
2169    fn clone_from(&mut self, source: &Self) {
2170        self.truncate(source.len());
2174
2175        let (init, tail) = source.split_at(self.len());
2178
2179        self.clone_from_slice(init);
2181        self.extend(tail.iter().cloned());
2182    }
2183}
2184
2185impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2186where
2187    A::Item: PartialEq<B::Item>,
2188{
2189    #[inline]
2190    fn eq(&self, other: &SmallVec<B>) -> bool {
2191        self[..] == other[..]
2192    }
2193}
2194
2195impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2196
2197impl<A: Array> PartialOrd for SmallVec<A>
2198where
2199    A::Item: PartialOrd,
2200{
2201    #[inline]
2202    fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2203        PartialOrd::partial_cmp(&**self, &**other)
2204    }
2205}
2206
2207impl<A: Array> Ord for SmallVec<A>
2208where
2209    A::Item: Ord,
2210{
2211    #[inline]
2212    fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2213        Ord::cmp(&**self, &**other)
2214    }
2215}
2216
2217impl<A: Array> Hash for SmallVec<A>
2218where
2219    A::Item: Hash,
2220{
2221    fn hash<H: Hasher>(&self, state: &mut H) {
2222        (**self).hash(state)
2223    }
2224}
2225
2226unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2227
2228pub struct IntoIter<A: Array> {
2234    data: SmallVec<A>,
2235    current: usize,
2236    end: usize,
2237}
2238
2239impl<A: Array> fmt::Debug for IntoIter<A>
2240where
2241    A::Item: fmt::Debug,
2242{
2243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2244        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2245    }
2246}
2247
2248impl<A: Array + Clone> Clone for IntoIter<A>
2249where
2250    A::Item: Clone,
2251{
2252    fn clone(&self) -> IntoIter<A> {
2253        SmallVec::from(self.as_slice()).into_iter()
2254    }
2255}
2256
2257impl<A: Array> Drop for IntoIter<A> {
2258    fn drop(&mut self) {
2259        for _ in self {}
2260    }
2261}
2262
2263impl<A: Array> Iterator for IntoIter<A> {
2264    type Item = A::Item;
2265
2266    #[inline]
2267    fn next(&mut self) -> Option<A::Item> {
2268        if self.current == self.end {
2269            None
2270        } else {
2271            unsafe {
2272                let current = self.current;
2273                self.current += 1;
2274                Some(ptr::read(self.data.as_ptr().add(current)))
2275            }
2276        }
2277    }
2278
2279    #[inline]
2280    fn size_hint(&self) -> (usize, Option<usize>) {
2281        let size = self.end - self.current;
2282        (size, Some(size))
2283    }
2284}
2285
2286impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2287    #[inline]
2288    fn next_back(&mut self) -> Option<A::Item> {
2289        if self.current == self.end {
2290            None
2291        } else {
2292            unsafe {
2293                self.end -= 1;
2294                Some(ptr::read(self.data.as_ptr().add(self.end)))
2295            }
2296        }
2297    }
2298}
2299
2300impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2301impl<A: Array> FusedIterator for IntoIter<A> {}
2302
2303impl<A: Array> IntoIter<A> {
2304    pub fn as_slice(&self) -> &[A::Item] {
2306        let len = self.end - self.current;
2307        unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2308    }
2309
2310    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2312        let len = self.end - self.current;
2313        unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2314    }
2315}
2316
2317impl<A: Array> IntoIterator for SmallVec<A> {
2318    type IntoIter = IntoIter<A>;
2319    type Item = A::Item;
2320    fn into_iter(mut self) -> Self::IntoIter {
2321        unsafe {
2322            let len = self.len();
2324            self.set_len(0);
2325            IntoIter {
2326                data: self,
2327                current: 0,
2328                end: len,
2329            }
2330        }
2331    }
2332}
2333
2334impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2335    type IntoIter = slice::Iter<'a, A::Item>;
2336    type Item = &'a A::Item;
2337    fn into_iter(self) -> Self::IntoIter {
2338        self.iter()
2339    }
2340}
2341
2342impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2343    type IntoIter = slice::IterMut<'a, A::Item>;
2344    type Item = &'a mut A::Item;
2345    fn into_iter(self) -> Self::IntoIter {
2346        self.iter_mut()
2347    }
2348}
2349
2350pub unsafe trait Array {
2352    type Item;
2354    fn size() -> usize;
2356}
2357
2358struct SetLenOnDrop<'a> {
2362    len: &'a mut usize,
2363    local_len: usize,
2364}
2365
2366impl<'a> SetLenOnDrop<'a> {
2367    #[inline]
2368    fn new(len: &'a mut usize) -> Self {
2369        SetLenOnDrop {
2370            local_len: *len,
2371            len,
2372        }
2373    }
2374
2375    #[inline]
2376    fn get(&self) -> usize {
2377        self.local_len
2378    }
2379
2380    #[inline]
2381    fn increment_len(&mut self, increment: usize) {
2382        self.local_len += increment;
2383    }
2384}
2385
2386impl<'a> Drop for SetLenOnDrop<'a> {
2387    #[inline]
2388    fn drop(&mut self) {
2389        *self.len = self.local_len;
2390    }
2391}
2392
2393#[cfg(feature = "const_new")]
2394impl<T, const N: usize> SmallVec<[T; N]> {
2395    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2399    #[inline]
2400    pub const fn new_const() -> Self {
2401        SmallVec {
2402            capacity: 0,
2403            data: SmallVecData::from_const(MaybeUninit::uninit()),
2404        }
2405    }
2406
2407    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2411    #[inline]
2412    pub const fn from_const(items: [T; N]) -> Self {
2413        SmallVec {
2414            capacity: N,
2415            data: SmallVecData::from_const(MaybeUninit::new(items)),
2416        }
2417    }
2418
2419    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2425    #[inline]
2426    pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2427        SmallVec {
2428            capacity: len,
2429            data: SmallVecData::from_const(MaybeUninit::new(items)),
2430        }
2431    }
2432}
2433
2434#[cfg(feature = "const_generics")]
2435#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2436unsafe impl<T, const N: usize> Array for [T; N] {
2437    type Item = T;
2438    #[inline]
2439    fn size() -> usize {
2440        N
2441    }
2442}
2443
2444#[cfg(not(feature = "const_generics"))]
2445macro_rules! impl_array(
2446    ($($size:expr),+) => {
2447        $(
2448            unsafe impl<T> Array for [T; $size] {
2449                type Item = T;
2450                #[inline]
2451                fn size() -> usize { $size }
2452            }
2453        )+
2454    }
2455);
2456
2457#[cfg(not(feature = "const_generics"))]
2458impl_array!(
2459    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,
2460    26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2461    0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2462);
2463
2464pub trait ToSmallVec<A: Array> {
2466    fn to_smallvec(&self) -> SmallVec<A>;
2468}
2469
2470impl<A: Array> ToSmallVec<A> for [A::Item]
2471where
2472    A::Item: Copy,
2473{
2474    #[inline]
2475    fn to_smallvec(&self) -> SmallVec<A> {
2476        SmallVec::from_slice(self)
2477    }
2478}
2479
2480#[repr(transparent)]
2482struct ConstNonNull<T>(NonNull<T>);
2483
2484impl<T> ConstNonNull<T> {
2485    #[inline]
2486    fn new(ptr: *const T) -> Option<Self> {
2487        NonNull::new(ptr as *mut T).map(Self)
2488    }
2489    #[inline]
2490    fn as_ptr(self) -> *const T {
2491        self.0.as_ptr()
2492    }
2493}
2494
2495impl<T> Clone for ConstNonNull<T> {
2496    #[inline]
2497    fn clone(&self) -> Self {
2498        *self
2499    }
2500}
2501
2502impl<T> Copy for ConstNonNull<T> {}
2503
2504#[cfg(feature = "impl_bincode")]
2505use bincode::{
2506    de::{BorrowDecoder, Decode, Decoder, read::Reader},
2507    enc::{Encode, Encoder, write::Writer},
2508    error::{DecodeError, EncodeError},
2509    BorrowDecode,
2510};
2511
2512#[cfg(feature = "impl_bincode")]
2513impl<A, Context> Decode<Context> for SmallVec<A>
2514where
2515    A: Array,
2516    A::Item: Decode<Context>,
2517{
2518    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2519        use core::convert::TryInto;
2520        let len = u64::decode(decoder)?;
2521        let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2522        decoder.claim_container_read::<A::Item>(len)?;
2523
2524        let mut vec = SmallVec::with_capacity(len);
2525        if unty::type_equal::<A::Item, u8>() {
2526            let ptr = vec.as_mut_ptr();
2529            unsafe {
2531                core::ptr::write_bytes(ptr, 0, len);
2532                vec.set_len(len);
2533            }
2534            let slice = vec.as_mut_slice();
2536            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2538            decoder.reader().read(slice)?;
2539        } else {
2540            for _ in 0..len {
2541                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2542                vec.push(A::Item::decode(decoder)?);
2543            }
2544        }
2545        Ok(vec)
2546    }
2547}
2548
2549#[cfg(feature = "impl_bincode")]
2550impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2551where
2552    A: Array,
2553    A::Item: BorrowDecode<'de, Context>,
2554{
2555    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2556        use core::convert::TryInto;
2557        let len = u64::decode(decoder)?;
2558        let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2559        decoder.claim_container_read::<A::Item>(len)?;
2560
2561        let mut vec = SmallVec::with_capacity(len);
2562        if unty::type_equal::<A::Item, u8>() {
2563            let ptr = vec.as_mut_ptr();
2566            unsafe {
2568                core::ptr::write_bytes(ptr, 0, len);
2569                vec.set_len(len);
2570            }
2571            let slice = vec.as_mut_slice();
2573            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2575            decoder.reader().read(slice)?;
2576        } else {
2577            for _ in 0..len {
2578                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2579                vec.push(A::Item::borrow_decode(decoder)?);
2580            }
2581        }
2582        Ok(vec)
2583    }
2584}
2585
2586#[cfg(feature = "impl_bincode")]
2587impl<A> Encode for SmallVec<A>
2588where
2589    A: Array,
2590    A::Item: Encode,
2591{
2592    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2593        (self.len() as u64).encode(encoder)?;
2594        if unty::type_equal::<A::Item, u8>() {
2595            let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2597            encoder.writer().write(slice)?;
2598        } else {
2599            for item in self.iter() {
2600                item.encode(encoder)?;
2601            }
2602        }
2603        Ok(())
2604    }
2605}