smallvec/
lib.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Small vectors in various sizes. These store a certain number of elements inline, and fall back
8//! to the heap for larger allocations.  This can be a useful optimization for improving cache
9//! locality and reducing allocator traffic for workloads that fit within the inline buffer.
10//!
11//! ## `no_std` support
12//!
13//! By default, `smallvec` does not depend on `std`.  However, the optional
14//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
15//! When this feature is enabled, `smallvec` depends on `std`.
16//!
17//! ## Optional features
18//!
19//! ### `std`
20//!
21//! When this feature is enabled, traits available from `std` are implemented:
22//!
23//! * `SmallVec<u8, _>` implements the [`std::io::Write`] trait.
24//! * [`CollectionAllocErr`] implements [`std::error::Error`].
25//!
26//! This feature is not compatible with `#![no_std]` programs.
27//!
28//! ### `serde`
29//!
30//! When this optional dependency is enabled, `SmallVec` implements the `serde::Serialize` and
31//! `serde::Deserialize` traits.
32//!
33//! ### `extract_if`
34//!
35//! **This feature is unstable.** It may change to match the unstable `extract_if` method in libstd.
36//!
37//! Enables the `extract_if` method, which produces an iterator that calls a user-provided
38//! closure to determine which elements of the vector to remove and yield from the iterator.
39//!
40//! ### `specialization`
41//!
42//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
43//!
44//! When this feature is enabled, `SmallVec::from(slice)` has improved performance for slices
45//! of `Copy` types.  (Without this feature, you can use `SmallVec::from_slice` to get optimal
46//! performance for `Copy` types.)
47//!
48//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
49//!
50//! ### `may_dangle`
51//!
52//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
53//!
54//! This feature makes the Rust compiler less strict about use of vectors that contain borrowed
55//! references. For details, see the
56//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
57//!
58//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
59
60#![no_std]
61#![cfg_attr(docsrs, feature(doc_cfg))]
62#![cfg_attr(feature = "specialization", allow(incomplete_features))]
63#![cfg_attr(feature = "specialization", feature(specialization, trusted_len))]
64#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
65
66#[doc(hidden)]
67pub extern crate alloc;
68
69#[cfg(any(test, feature = "std"))]
70extern crate std;
71
72#[cfg(test)]
73mod tests;
74
75use alloc::boxed::Box;
76use alloc::vec;
77use alloc::vec::Vec;
78
79use alloc::alloc::Layout;
80use core::borrow::Borrow;
81use core::borrow::BorrowMut;
82use core::fmt::Debug;
83use core::hash::{Hash, Hasher};
84use core::marker::PhantomData;
85use core::mem::align_of;
86use core::mem::size_of;
87use core::mem::ManuallyDrop;
88use core::mem::MaybeUninit;
89use core::ptr::addr_of;
90use core::ptr::addr_of_mut;
91use core::ptr::copy;
92use core::ptr::copy_nonoverlapping;
93use core::ptr::NonNull;
94
95#[cfg(feature = "bytes")]
96use bytes::{buf::UninitSlice, BufMut};
97#[cfg(feature = "malloc_size_of")]
98use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
99#[cfg(feature = "serde")]
100use serde_core::{
101    de::{Deserialize, Deserializer, SeqAccess, Visitor},
102    ser::{Serialize, SerializeSeq, Serializer},
103};
104#[cfg(feature = "std")]
105use std::io;
106
107/// Error type for APIs with fallible heap allocation
108#[derive(Debug)]
109pub enum CollectionAllocErr {
110    /// Overflow `usize::MAX` or other error during size computation
111    CapacityOverflow,
112    /// The allocator return an error
113    AllocErr {
114        /// The layout that was passed to the allocator
115        layout: Layout,
116    },
117}
118impl core::fmt::Display for CollectionAllocErr {
119    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        write!(f, "Allocation error: {:?}", self)
121    }
122}
123
124impl core::error::Error for CollectionAllocErr {}
125
126/// Either a stack array with `length <= N` or a heap array
127/// whose pointer and capacity are stored here.
128///
129/// We store a `NonNull<T>` instead of a `*mut T`, so that
130/// niche-optimization can be performed and the type is covariant
131/// with respect to `T`.
132#[repr(C)]
133pub union RawSmallVec<T, const N: usize> {
134    inline: ManuallyDrop<MaybeUninit<[T; N]>>,
135    heap: (NonNull<T>, usize),
136}
137
138#[inline]
139fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
140    match result {
141        Ok(x) => x,
142        Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
143        Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
144    }
145}
146
147#[inline]
148/// A local copy of [`core::slice::range`]. The latter function is unstable
149/// and thus cannot be used yet.
150fn slice_range<R>(range: R, bounds: core::ops::RangeTo<usize>) -> core::ops::Range<usize>
151where
152    R: core::ops::RangeBounds<usize>,
153{
154    let len = bounds.end;
155
156    let start = match range.start_bound() {
157        core::ops::Bound::Included(&start) => start,
158        core::ops::Bound::Excluded(start) => start
159            .checked_add(1)
160            .unwrap_or_else(|| panic!("attempted to index slice from after maximum usize")),
161        core::ops::Bound::Unbounded => 0,
162    };
163
164    let end = match range.end_bound() {
165        core::ops::Bound::Included(end) => end
166            .checked_add(1)
167            .unwrap_or_else(|| panic!("attempted to index slice up to maximum usize")),
168        core::ops::Bound::Excluded(&end) => end,
169        core::ops::Bound::Unbounded => len,
170    };
171
172    if start > end {
173        panic!("slice index starts at {start} but ends at {end}");
174    }
175    if end > len {
176        panic!("range end index {end} out of range for slice of length {len}");
177    }
178
179    core::ops::Range { start, end }
180}
181
182impl<T, const N: usize> RawSmallVec<T, N> {
183    #[inline]
184    const fn is_zst() -> bool {
185        size_of::<T>() == 0
186    }
187
188    #[inline]
189    const fn new() -> Self {
190        Self::new_inline(MaybeUninit::uninit())
191    }
192    #[inline]
193    const fn new_inline(inline: MaybeUninit<[T; N]>) -> Self {
194        Self {
195            inline: ManuallyDrop::new(inline),
196        }
197    }
198    #[inline]
199    const fn new_heap(ptr: NonNull<T>, capacity: usize) -> Self {
200        Self {
201            heap: (ptr, capacity),
202        }
203    }
204
205    #[inline]
206    const fn as_ptr_inline(&self) -> *const T {
207        // SAFETY: This is safe because we don't read the value. We only get a pointer to the data.
208        // Dereferencing the pointer is unsafe so unsafe code is required to misuse the return
209        // value.
210        (unsafe { addr_of!(self.inline) }) as *const T
211    }
212
213    #[inline]
214    const fn as_mut_ptr_inline(&mut self) -> *mut T {
215        // SAFETY: See above.
216        (unsafe { addr_of_mut!(self.inline) }) as *mut T
217    }
218
219    /// # Safety
220    ///
221    /// The vector must be on the heap
222    #[inline]
223    const unsafe fn as_ptr_heap(&self) -> *const T {
224        self.heap.0.as_ptr()
225    }
226
227    /// # Safety
228    ///
229    /// The vector must be on the heap
230    #[inline]
231    const unsafe fn as_mut_ptr_heap(&mut self) -> *mut T {
232        self.heap.0.as_ptr()
233    }
234
235    /// # Safety
236    ///
237    /// `new_capacity` must be non zero, and greater or equal to the length.
238    /// T must not be a ZST.
239    unsafe fn try_grow_raw(
240        &mut self,
241        len: TaggedLen,
242        new_capacity: usize,
243    ) -> Result<(), CollectionAllocErr> {
244        use alloc::alloc::{alloc, realloc};
245        debug_assert!(!Self::is_zst());
246        debug_assert!(new_capacity > 0);
247        debug_assert!(new_capacity >= len.value(Self::is_zst()));
248
249        let was_on_heap = len.on_heap(Self::is_zst());
250        let ptr = if was_on_heap {
251            self.as_mut_ptr_heap()
252        } else {
253            self.as_mut_ptr_inline()
254        };
255        let len = len.value(Self::is_zst());
256
257        let new_layout =
258            Layout::array::<T>(new_capacity).map_err(|_| CollectionAllocErr::CapacityOverflow)?;
259        if new_layout.size() > isize::MAX as usize {
260            return Err(CollectionAllocErr::CapacityOverflow);
261        }
262
263        let new_ptr = if len == 0 || !was_on_heap {
264            // get a fresh allocation
265            let new_ptr = alloc(new_layout) as *mut T; // `new_layout` has nonzero size.
266            let new_ptr =
267                NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })?;
268            copy_nonoverlapping(ptr, new_ptr.as_ptr(), len);
269            new_ptr
270        } else {
271            // use realloc
272
273            // this can't overflow since we already constructed an equivalent layout during
274            // the previous allocation
275            let old_layout =
276                Layout::from_size_align_unchecked(self.heap.1 * size_of::<T>(), align_of::<T>());
277
278            // SAFETY: ptr was allocated with this allocator
279            // old_layout is the same as the layout used to allocate the previous memory block
280            // new_layout.size() is greater than zero
281            // does not overflow when rounded up to alignment. since it was constructed
282            // with Layout::array
283            let new_ptr = realloc(ptr as *mut u8, old_layout, new_layout.size()) as *mut T;
284            NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })?
285        };
286        *self = Self::new_heap(new_ptr, new_capacity);
287        Ok(())
288    }
289}
290
291/// Vec guarantees that its length is always less than [`isize::MAX`] in *bytes*.
292///
293/// For a non ZST, this means that the length is less than `isize::MAX` objects, which implies we
294/// have at least one free bit we can use. We use the least significant bit for the tag. And store
295/// the length in the `usize::BITS - 1` most significant bits.
296///
297/// For a ZST, we never use the heap, so we just store the length directly.
298#[repr(transparent)]
299#[derive(Clone, Copy)]
300struct TaggedLen(usize);
301
302impl TaggedLen {
303    #[inline]
304    pub const fn new(len: usize, on_heap: bool, is_zst: bool) -> Self {
305        if is_zst {
306            debug_assert!(!on_heap);
307            TaggedLen(len)
308        } else {
309            debug_assert!(len < isize::MAX as usize);
310            TaggedLen((len << 1) | on_heap as usize)
311        }
312    }
313
314    #[inline]
315    #[must_use]
316    pub const fn on_heap(self, is_zst: bool) -> bool {
317        if is_zst {
318            false
319        } else {
320            (self.0 & 1_usize) == 1
321        }
322    }
323
324    #[inline]
325    pub const fn value(self, is_zst: bool) -> usize {
326        if is_zst {
327            self.0
328        } else {
329            self.0 >> 1
330        }
331    }
332}
333
334#[repr(C)]
335pub struct SmallVec<T, const N: usize> {
336    len: TaggedLen,
337    raw: RawSmallVec<T, N>,
338    _marker: PhantomData<T>,
339}
340
341unsafe impl<T: Send, const N: usize> Send for SmallVec<T, N> {}
342unsafe impl<T: Sync, const N: usize> Sync for SmallVec<T, N> {}
343
344impl<T, const N: usize> Default for SmallVec<T, N> {
345    #[inline]
346    fn default() -> Self {
347        Self::new()
348    }
349}
350
351/// An iterator that removes the items from a `SmallVec` and yields them by value.
352///
353/// Returned from [`SmallVec::drain`][1].
354///
355/// [1]: struct.SmallVec.html#method.drain
356pub struct Drain<'a, T: 'a, const N: usize> {
357    // `vec` points to a valid object within its lifetime.
358    // This is ensured by the fact that we're holding an iterator to its items.
359    //
360    // # Safety
361    //
362    // Members in vec[tail_start..tail_start + tail_len] are initialized
363    // even though vec has length < tail_start
364    tail_start: usize,
365    tail_len: usize,
366    iter: core::slice::Iter<'a, T>,
367    vec: core::ptr::NonNull<SmallVec<T, N>>,
368}
369
370impl<'a, T: 'a, const N: usize> Iterator for Drain<'a, T, N> {
371    type Item = T;
372
373    #[inline]
374    fn next(&mut self) -> Option<T> {
375        // SAFETY: we shrunk the length of the vector so it no longer owns these items, and we can
376        // take ownership of them.
377        self.iter
378            .next()
379            .map(|reference| unsafe { core::ptr::read(reference) })
380    }
381
382    #[inline]
383    fn size_hint(&self) -> (usize, Option<usize>) {
384        self.iter.size_hint()
385    }
386}
387
388impl<'a, T: 'a, const N: usize> DoubleEndedIterator for Drain<'a, T, N> {
389    #[inline]
390    fn next_back(&mut self) -> Option<T> {
391        // SAFETY: see above
392        self.iter
393            .next_back()
394            .map(|reference| unsafe { core::ptr::read(reference) })
395    }
396}
397
398impl<T, const N: usize> ExactSizeIterator for Drain<'_, T, N> {
399    #[inline]
400    fn len(&self) -> usize {
401        self.iter.len()
402    }
403}
404
405impl<T, const N: usize> core::iter::FusedIterator for Drain<'_, T, N> {}
406
407impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> {
408    fn drop(&mut self) {
409        /// Moves back the un-`Drain`ed elements to restore the original `Vec`.
410        struct DropGuard<'r, 'a, T, const N: usize>(&'r mut Drain<'a, T, N>);
411
412        impl<'r, 'a, T, const N: usize> Drop for DropGuard<'r, 'a, T, N> {
413            fn drop(&mut self) {
414                if self.0.tail_len > 0 {
415                    unsafe {
416                        let source_vec = self.0.vec.as_mut();
417                        // memmove back untouched tail, update to new length
418                        let start = source_vec.len();
419                        let tail = self.0.tail_start;
420                        if tail != start {
421                            let ptr = source_vec.as_mut_ptr();
422                            let src = ptr.add(tail);
423                            let dst = ptr.add(start);
424                            core::ptr::copy(src, dst, self.0.tail_len);
425                        }
426                        source_vec.set_len(start + self.0.tail_len);
427                    }
428                }
429            }
430        }
431
432        let iter = core::mem::take(&mut self.iter);
433        let drop_len = iter.len();
434
435        let mut vec = self.vec;
436
437        if SmallVec::<T, N>::is_zst() {
438            // ZSTs have no identity, so we don't need to move them around, we only need to drop the correct amount.
439            // this can be achieved by manipulating the Vec length instead of moving values out from `iter`.
440            unsafe {
441                let vec = vec.as_mut();
442                let old_len = vec.len();
443                vec.set_len(old_len + drop_len + self.tail_len);
444                vec.truncate(old_len + self.tail_len);
445            }
446
447            return;
448        }
449
450        // ensure elements are moved back into their appropriate places, even when drop_in_place panics
451        let _guard = DropGuard(self);
452
453        if drop_len == 0 {
454            return;
455        }
456
457        // as_slice() must only be called when iter.len() is > 0 because
458        // it also gets touched by vec::Splice which may turn it into a dangling pointer
459        // which would make it and the vec pointer point to different allocations which would
460        // lead to invalid pointer arithmetic below.
461        let drop_ptr = iter.as_slice().as_ptr();
462
463        unsafe {
464            // drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
465            // a pointer with mutable provenance is necessary. Therefore we must reconstruct
466            // it from the original vec but also avoid creating a &mut to the front since that could
467            // invalidate raw pointers to it which some unsafe code might rely on.
468            let vec_ptr = vec.as_mut().as_mut_ptr();
469            // May be replaced with the line below later, once this crate's MSRV is >= 1.87.
470            //let drop_offset = drop_ptr.offset_from_unsigned(vec_ptr);
471            let drop_offset = drop_ptr.offset_from(vec_ptr) as usize;
472            let to_drop = core::ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
473            core::ptr::drop_in_place(to_drop);
474        }
475    }
476}
477
478impl<T, const N: usize> Drain<'_, T, N> {
479    #[must_use]
480    pub fn as_slice(&self) -> &[T] {
481        self.iter.as_slice()
482    }
483
484    /// The range from `self.vec.len` to `self.tail_start` contains elements
485    /// that have been moved out.
486    /// Fill that range as much as possible with new elements from the `replace_with` iterator.
487    /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
488    unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
489        let vec = unsafe { self.vec.as_mut() };
490        let range_start = vec.len();
491        let range_end = self.tail_start;
492        let range_slice = unsafe {
493            core::slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
494        };
495
496        for place in range_slice {
497            if let Some(new_item) = replace_with.next() {
498                unsafe { core::ptr::write(place, new_item) };
499                vec.set_len(vec.len() + 1);
500            } else {
501                return false;
502            }
503        }
504        true
505    }
506
507    /// Makes room for inserting more elements before the tail.
508    #[track_caller]
509    unsafe fn move_tail(&mut self, additional: usize) {
510        let vec = unsafe { self.vec.as_mut() };
511        let len = self.tail_start + self.tail_len;
512
513        // Test
514        let old_len = vec.len();
515        vec.set_len(len);
516        vec.reserve(additional);
517        vec.set_len(old_len);
518
519        let new_tail_start = self.tail_start + additional;
520        unsafe {
521            let src = vec.as_ptr().add(self.tail_start);
522            let dst = vec.as_mut_ptr().add(new_tail_start);
523            core::ptr::copy(src, dst, self.tail_len);
524        }
525        self.tail_start = new_tail_start;
526    }
527}
528
529#[cfg(feature = "extract_if")]
530/// An iterator which uses a closure to determine if an element should be removed.
531///
532/// Returned from [`SmallVec::extract_if`][1].
533///
534/// [1]: struct.SmallVec.html#method.extract_if
535pub struct ExtractIf<'a, T, const N: usize, F>
536where
537    F: FnMut(&mut T) -> bool,
538{
539    vec: &'a mut SmallVec<T, N>,
540    /// The index of the item that will be inspected by the next call to `next`.
541    idx: usize,
542    /// Elements at and beyond this point will be retained. Must be equal or smaller than `old_len`.
543    end: usize,
544    /// The number of items that have been drained (removed) thus far.
545    del: usize,
546    /// The original length of `vec` prior to draining.
547    old_len: usize,
548    /// The filter test predicate.
549    pred: F,
550}
551
552#[cfg(feature = "extract_if")]
553impl<T, const N: usize, F> core::fmt::Debug for ExtractIf<'_, T, N, F>
554where
555    F: FnMut(&mut T) -> bool,
556    T: core::fmt::Debug,
557{
558    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
559        f.debug_tuple("ExtractIf")
560            .field(&self.vec.as_slice())
561            .finish()
562    }
563}
564
565#[cfg(feature = "extract_if")]
566impl<T, F, const N: usize> Iterator for ExtractIf<'_, T, N, F>
567where
568    F: FnMut(&mut T) -> bool,
569{
570    type Item = T;
571
572    fn next(&mut self) -> Option<T> {
573        unsafe {
574            while self.idx < self.end {
575                let i = self.idx;
576                let v = core::slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
577                let drained = (self.pred)(&mut v[i]);
578                // Update the index *after* the predicate is called. If the index
579                // is updated prior and the predicate panics, the element at this
580                // index would be leaked.
581                self.idx += 1;
582                if drained {
583                    self.del += 1;
584                    return Some(core::ptr::read(&v[i]));
585                } else if self.del > 0 {
586                    let del = self.del;
587                    let src: *const T = &v[i];
588                    let dst: *mut T = &mut v[i - del];
589                    core::ptr::copy_nonoverlapping(src, dst, 1);
590                }
591            }
592            None
593        }
594    }
595
596    fn size_hint(&self) -> (usize, Option<usize>) {
597        (0, Some(self.end - self.idx))
598    }
599}
600
601#[cfg(feature = "extract_if")]
602impl<T, F, const N: usize> Drop for ExtractIf<'_, T, N, F>
603where
604    F: FnMut(&mut T) -> bool,
605{
606    fn drop(&mut self) {
607        unsafe {
608            if self.idx < self.old_len && self.del > 0 {
609                // This is a pretty messed up state, and there isn't really an
610                // obviously right thing to do. We don't want to keep trying
611                // to execute `pred`, so we just backshift all the unprocessed
612                // elements and tell the vec that they still exist. The backshift
613                // is required to prevent a double-drop of the last successfully
614                // drained item prior to a panic in the predicate.
615                let ptr = self.vec.as_mut_ptr();
616                let src = ptr.add(self.idx);
617                let dst = src.sub(self.del);
618                let tail_len = self.old_len - self.idx;
619                src.copy_to(dst, tail_len);
620            }
621            self.vec.set_len(self.old_len - self.del);
622        }
623    }
624}
625
626pub struct Splice<'a, I: Iterator + 'a, const N: usize> {
627    drain: Drain<'a, I::Item, N>,
628    replace_with: I,
629}
630
631impl<'a, I, const N: usize> core::fmt::Debug for Splice<'a, I, N>
632where
633    I: Debug + Iterator + 'a,
634    <I as Iterator>::Item: Debug,
635{
636    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
637        f.debug_tuple("Splice").field(&self.drain).finish()
638    }
639}
640
641impl<I: Iterator, const N: usize> Iterator for Splice<'_, I, N> {
642    type Item = I::Item;
643
644    fn next(&mut self) -> Option<Self::Item> {
645        self.drain.next()
646    }
647
648    fn size_hint(&self) -> (usize, Option<usize>) {
649        self.drain.size_hint()
650    }
651}
652
653impl<I: Iterator, const N: usize> DoubleEndedIterator for Splice<'_, I, N> {
654    fn next_back(&mut self) -> Option<Self::Item> {
655        self.drain.next_back()
656    }
657}
658
659impl<I: Iterator, const N: usize> ExactSizeIterator for Splice<'_, I, N> {}
660
661impl<I: Iterator, const N: usize> Drop for Splice<'_, I, N> {
662    fn drop(&mut self) {
663        self.drain.by_ref().for_each(drop);
664        // At this point draining is done and the only remaining tasks are splicing
665        // and moving things into the final place.
666        // Which means we can replace the slice::Iter with pointers that won't point to deallocated
667        // memory, so that Drain::drop is still allowed to call iter.len(), otherwise it would break
668        // the ptr.sub_ptr contract.
669        self.drain.iter = [].iter();
670
671        unsafe {
672            if self.drain.tail_len == 0 {
673                self.drain.vec.as_mut().extend(self.replace_with.by_ref());
674                return;
675            }
676
677            // First fill the range left by drain().
678            if !self.drain.fill(&mut self.replace_with) {
679                return;
680            }
681
682            // There may be more elements. Use the lower bound as an estimate.
683            // FIXME: Is the upper bound a better guess? Or something else?
684            let (lower_bound, _upper_bound) = self.replace_with.size_hint();
685            if lower_bound > 0 {
686                self.drain.move_tail(lower_bound);
687                if !self.drain.fill(&mut self.replace_with) {
688                    return;
689                }
690            }
691
692            // Collect any remaining elements.
693            let mut collected = self.replace_with.by_ref().collect::<SmallVec<I::Item, N>>().into_iter();
694            // Now we have an exact count.
695            if collected.len() > 0 {
696                self.drain.move_tail(collected.len());
697                let filled = self.drain.fill(&mut collected);
698                debug_assert!(filled);
699                debug_assert_eq!(collected.len(), 0);
700            }
701        }
702        // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
703    }
704}
705
706/// An iterator that consumes a `SmallVec` and yields its items by value.
707///
708/// Returned from [`SmallVec::into_iter`][1].
709///
710/// [1]: struct.SmallVec.html#method.into_iter
711pub struct IntoIter<T, const N: usize> {
712    // # Safety
713    //
714    // `end` decides whether the data lives on the heap or not
715    //
716    // The members from begin..end are initialized
717    raw: RawSmallVec<T, N>,
718    begin: usize,
719    end: TaggedLen,
720    _marker: PhantomData<T>,
721}
722
723// SAFETY: IntoIter has unique ownership of its contents.  Sending (or sharing) an `IntoIter<T, N>`
724// is equivalent to sending (or sharing) a `SmallVec<T, N>`.
725unsafe impl<T, const N: usize> Send for IntoIter<T, N> where T: Send {}
726unsafe impl<T, const N: usize> Sync for IntoIter<T, N> where T: Sync {}
727
728impl<T, const N: usize> IntoIter<T, N> {
729    #[inline]
730    const fn is_zst() -> bool {
731        size_of::<T>() == 0
732    }
733
734    #[inline]
735    const fn as_ptr(&self) -> *const T {
736        let on_heap = self.end.on_heap(Self::is_zst());
737        if on_heap {
738            // SAFETY: vector is on the heap
739            unsafe { self.raw.as_ptr_heap() }
740        } else {
741            self.raw.as_ptr_inline()
742        }
743    }
744
745    #[inline]
746    const fn as_mut_ptr(&mut self) -> *mut T {
747        let on_heap = self.end.on_heap(Self::is_zst());
748        if on_heap {
749            // SAFETY: vector is on the heap
750            unsafe { self.raw.as_mut_ptr_heap() }
751        } else {
752            self.raw.as_mut_ptr_inline()
753        }
754    }
755
756    #[inline]
757    pub const fn as_slice(&self) -> &[T] {
758        // SAFETY: The members in self.begin..self.end.value() are all initialized
759        // So the pointer arithmetic is valid, and so is the construction of the slice
760        unsafe {
761            let ptr = self.as_ptr();
762            core::slice::from_raw_parts(
763                ptr.add(self.begin),
764                self.end.value(Self::is_zst()) - self.begin,
765            )
766        }
767    }
768
769    #[inline]
770    pub const fn as_mut_slice(&mut self) -> &mut [T] {
771        // SAFETY: see above
772        unsafe {
773            let ptr = self.as_mut_ptr();
774            core::slice::from_raw_parts_mut(
775                ptr.add(self.begin),
776                self.end.value(Self::is_zst()) - self.begin,
777            )
778        }
779    }
780}
781
782impl<T, const N: usize> Iterator for IntoIter<T, N> {
783    type Item = T;
784
785    #[inline]
786    fn next(&mut self) -> Option<Self::Item> {
787        if self.begin == self.end.value(Self::is_zst()) {
788            None
789        } else {
790            // SAFETY: see above
791            unsafe {
792                let ptr = self.as_mut_ptr();
793                let value = ptr.add(self.begin).read();
794                self.begin += 1;
795                Some(value)
796            }
797        }
798    }
799
800    #[inline]
801    fn size_hint(&self) -> (usize, Option<usize>) {
802        let size = self.end.value(Self::is_zst()) - self.begin;
803        (size, Some(size))
804    }
805}
806
807impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
808    #[inline]
809    fn next_back(&mut self) -> Option<Self::Item> {
810        let mut end = self.end.value(Self::is_zst());
811        if self.begin == end {
812            None
813        } else {
814            // SAFETY: see above
815            unsafe {
816                let ptr = self.as_mut_ptr();
817                let on_heap = self.end.on_heap(Self::is_zst());
818                end -= 1;
819                self.end = TaggedLen::new(end, on_heap, Self::is_zst());
820                let value = ptr.add(end).read();
821                Some(value)
822            }
823        }
824    }
825}
826impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {}
827impl<T, const N: usize> core::iter::FusedIterator for IntoIter<T, N> {}
828
829impl<T, const N: usize> SmallVec<T, N> {
830    #[inline]
831    pub const fn new() -> SmallVec<T, N> {
832        Self {
833            len: TaggedLen::new(0, false, Self::is_zst()),
834            raw: RawSmallVec::new(),
835            _marker: PhantomData,
836        }
837    }
838
839    #[inline]
840    pub fn with_capacity(capacity: usize) -> Self {
841        let mut this = Self::new();
842        if capacity > Self::inline_size() {
843            this.grow(capacity);
844        }
845        this
846    }
847
848    #[inline]
849    pub const fn from_buf<const S: usize>(elements: [T; S]) -> Self {
850        const { assert!(S <= N); }
851
852        // Althought we create a new buffer, since S and N are known at compile time,
853        // even with `-C opt-level=1`, it gets optimized as best as it could be. (Checked with <godbolt.org>)
854        let mut buf: MaybeUninit<[T; N]> = MaybeUninit::uninit();
855
856        // SAFETY: buf and elements do not overlap, are aligned and have space
857        // for at least S elements since S <= N.
858        // We will drop the elements only once since we do forget(elements).
859        unsafe {
860            copy_nonoverlapping(elements.as_ptr(), buf.as_mut_ptr() as *mut T, S);
861        }
862
863        // `elements` have been moved into buf and will be droped by SmallVec
864        core::mem::forget(elements);
865
866        // SAFETY: all the members in 0..S are initialized
867        Self {
868            len: TaggedLen::new(S, false, Self::is_zst()),
869            raw: RawSmallVec::new_inline(buf),
870            _marker: PhantomData,
871        }
872    }
873
874    #[inline]
875    pub fn from_buf_and_len(buf: [T; N], len: usize) -> Self {
876        assert!(len <= N);
877        // SAFETY: all the members in 0..len are initialized
878        let mut vec = Self {
879            len: TaggedLen::new(len, false, Self::is_zst()),
880            raw: RawSmallVec::new_inline(MaybeUninit::new(buf)),
881            _marker: PhantomData,
882        };
883        // Deallocate the remaining elements so no memory is leaked.
884        unsafe {
885            // SAFETY: both the input and output pointers are in range of the stack allocation
886            let remainder_ptr = vec.raw.as_mut_ptr_inline().add(len);
887            let remainder_len = N - len;
888
889            // SAFETY: the values are initialized, so dropping them here is fine.
890            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
891                remainder_ptr,
892                remainder_len,
893            ));
894        }
895
896        vec
897    }
898
899    /// Constructs a new `SmallVec` on the stack from an A without copying elements. Also sets the length. The user is responsible for ensuring that `len <= A::size()`.
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// use smallvec::SmallVec;
905    /// use std::mem::MaybeUninit;
906    ///
907    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
908    /// let small_vec = unsafe {
909    ///     SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5)
910    /// };
911    ///
912    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
913    /// ```
914    ///
915    /// # Safety
916    ///
917    /// `len <= N`, and all the elements in `buf[..len]` must be initialized
918    #[inline]
919    pub const unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<[T; N]>, len: usize) -> Self {
920        debug_assert!(len <= N);
921        Self {
922            len: TaggedLen::new(len, false, Self::is_zst()),
923            raw: RawSmallVec::new_inline(buf),
924            _marker: PhantomData,
925        }
926    }
927}
928
929impl<T, const N: usize> SmallVec<T, N> {
930    #[inline]
931    const fn is_zst() -> bool {
932        size_of::<T>() == 0
933    }
934
935    #[inline]
936    pub fn from_vec(vec: Vec<T>) -> Self {
937        if vec.capacity() == 0 {
938            return Self::new();
939        }
940
941        if Self::is_zst() {
942            // "Move" elements to stack buffer. They're ZST so we don't actually have to do
943            // anything. Just make sure they're not dropped.
944            // We don't wrap the vector in ManuallyDrop so that when it's dropped, the memory is
945            // deallocated, if it needs to be.
946            let mut vec = vec;
947            let len = vec.len();
948
949            // SAFETY: `0` is less than the vector's capacity.
950            // old_len..new_len is an empty range. So there are no uninitialized elements
951            unsafe { vec.set_len(0) };
952            Self {
953                len: TaggedLen::new(len, false, Self::is_zst()),
954                raw: RawSmallVec::new(),
955                _marker: PhantomData,
956            }
957        } else {
958            let mut vec = ManuallyDrop::new(vec);
959            let len = vec.len();
960            let cap = vec.capacity();
961            // SAFETY: vec.capacity is not `0` (checked above), so the pointer
962            // can not dangle and thus specifically cannot be null.
963            let ptr = unsafe { NonNull::new_unchecked(vec.as_mut_ptr()) };
964
965            Self {
966                len: TaggedLen::new(len, true, Self::is_zst()),
967                raw: RawSmallVec::new_heap(ptr, cap),
968                _marker: PhantomData,
969            }
970        }
971    }
972
973    /// Sets the tag to be on the heap
974    ///
975    /// # Safety
976    ///
977    /// The active union member must be the self.raw.heap
978    #[inline]
979    unsafe fn set_on_heap(&mut self) {
980        self.len = TaggedLen::new(self.len(), true, Self::is_zst());
981    }
982
983    /// Sets the tag to be inline
984    ///
985    /// # Safety
986    ///
987    /// The active union member must be the self.raw.inline
988    #[inline]
989    unsafe fn set_inline(&mut self) {
990        self.len = TaggedLen::new(self.len(), false, Self::is_zst());
991    }
992
993    /// Sets the length of a vector.
994    ///
995    /// This will explicitly set the size of the vector, without actually modifying its buffers, so
996    /// it is up to the caller to ensure that the vector is actually the specified size.
997    ///
998    /// # Safety
999    ///
1000    /// `new_len <= self.capacity()` must be true, and all the elements in the range `..self.len`
1001    /// must be initialized.
1002    #[inline]
1003    pub unsafe fn set_len(&mut self, new_len: usize) {
1004        debug_assert!(new_len <= self.capacity());
1005        let on_heap = self.len.on_heap(Self::is_zst());
1006        self.len = TaggedLen::new(new_len, on_heap, Self::is_zst());
1007    }
1008
1009    #[inline]
1010    pub const fn inline_size() -> usize {
1011        if Self::is_zst() {
1012            usize::MAX
1013        } else {
1014            N
1015        }
1016    }
1017
1018    #[inline]
1019    pub const fn len(&self) -> usize {
1020        self.len.value(Self::is_zst())
1021    }
1022
1023    #[must_use]
1024    #[inline]
1025    pub const fn is_empty(&self) -> bool {
1026        self.len() == 0
1027    }
1028
1029    #[inline]
1030    pub const fn capacity(&self) -> usize {
1031        if self.len.on_heap(Self::is_zst()) {
1032            // SAFETY: raw.heap is active
1033            unsafe { self.raw.heap.1 }
1034        } else {
1035            Self::inline_size()
1036        }
1037    }
1038
1039    #[inline]
1040    pub const fn spilled(&self) -> bool {
1041        self.len.on_heap(Self::is_zst())
1042    }
1043
1044    /// Splits the collection into two at the given index.
1045    ///
1046    /// Returns a newly allocated vector containing the elements in the range
1047    /// `[at, len)`. After the call, the original vector will be left containing
1048    /// the elements `[0, at)` with its previous capacity unchanged.
1049    ///
1050    /// - If you want to take ownership of the entire contents and capacity of
1051    ///   the vector, see [`core::mem::take`] or [`core::mem::replace`].
1052    /// - If you don't need the returned vector at all, see [`SmallVec::truncate`].
1053    /// - If you want to take ownership of an arbitrary subslice, or you don't
1054    ///   necessarily want to store the removed items in a vector, see [`SmallVec::drain`].
1055    ///
1056    /// # Panics
1057    ///
1058    /// Panics if `at > len`.
1059    ///
1060    /// # Examples
1061    ///
1062    /// ```
1063    /// let mut vec = vec![1, 2, 3];
1064    /// let vec2 = vec.split_off(1);
1065    /// assert_eq!(vec, [1]);
1066    /// assert_eq!(vec2, [2, 3]);
1067    /// ```
1068    #[inline]
1069    pub fn split_off(&mut self, at: usize) -> Self {
1070        let len = self.len();
1071        assert!(at <= len);
1072
1073        let other_len = len - at;
1074        let mut other = Self::with_capacity(other_len);
1075
1076        // Unsafely `set_len` and copy items to `other`.
1077        unsafe {
1078            self.set_len(at);
1079            other.set_len(other_len);
1080
1081            core::ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other_len);
1082        }
1083        other
1084    }
1085
1086    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>
1087    where
1088        R: core::ops::RangeBounds<usize>,
1089    {
1090        let len = self.len();
1091        let core::ops::Range { start, end } = slice_range(range, ..len);
1092
1093        unsafe {
1094            // SAFETY: `start <= len`
1095            self.set_len(start);
1096
1097            // SAFETY: all the elements in `start..end` are initialized
1098            let range_slice = core::slice::from_raw_parts(self.as_ptr().add(start), end - start);
1099
1100            // SAFETY: all the elements in `end..len` are initialized
1101            Drain {
1102                tail_start: end,
1103                tail_len: len - end,
1104                iter: range_slice.iter(),
1105                // Since self is a &mut, passing it to a function would invalidate the slice iterator.
1106                vec: core::ptr::NonNull::new_unchecked(self as *mut _),
1107                //vec: core::ptr::NonNull::from(self),
1108            }
1109        }
1110    }
1111
1112    #[cfg(feature = "extract_if")]
1113    /// Creates an iterator which uses a closure to determine if element in the range should be removed.
1114    ///
1115    /// If the closure returns true, then the element is removed and yielded.
1116    /// If the closure returns false, the element will remain in the vector and will not be yielded
1117    /// by the iterator.
1118    ///
1119    /// Only elements that fall in the provided range are considered for extraction, but any elements
1120    /// after the range will still have to be moved if any element has been extracted.
1121    ///
1122    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1123    /// or the iteration short-circuits, then the remaining elements will be retained.
1124    /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
1125    ///
1126    /// [`retain`]: SmallVec::retain
1127    ///
1128    /// Using this method is equivalent to the following code:
1129    /// ```
1130    /// # use smallvec::SmallVec;
1131    /// # use std::cmp::min;
1132    /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1133    /// # let mut vec: SmallVec<i32, 8> = SmallVec::from(&[1i32, 2, 3, 4, 5, 6]);
1134    /// # let range = 1..4;
1135    /// let mut i = 0;
1136    /// while i < min(vec.len(), range.end) {
1137    ///     if some_predicate(&mut vec[i]) {
1138    ///         let val = vec.remove(i);
1139    ///         // your code here
1140    ///     } else {
1141    ///         i += 1;
1142    ///     }
1143    /// }
1144    ///
1145    /// # assert_eq!(vec, SmallVec::<i32, 8>::from(&[1i32, 4, 5]));
1146    /// ```
1147    ///
1148    /// But `extract_if` is easier to use. `extract_if` is also more efficient,
1149    /// because it can backshift the elements of the array in bulk.
1150    ///
1151    /// Note that `extract_if` also lets you mutate the elements passed to the filter closure,
1152    /// regardless of whether you choose to keep or remove them.
1153    ///
1154    /// # Panics
1155    ///
1156    /// If `range` is out of bounds.
1157    ///
1158    /// # Examples
1159    ///
1160    /// Splitting an array into evens and odds, reusing the original allocation:
1161    ///
1162    /// ```
1163    /// # use smallvec::SmallVec;
1164    /// let mut numbers: SmallVec<i32, 16> = SmallVec::from(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1165    ///
1166    /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<SmallVec<i32, 16>>();
1167    /// let odds = numbers;
1168    ///
1169    /// assert_eq!(evens, SmallVec::<i32, 16>::from(&[2i32, 4, 6, 8, 14]));
1170    /// assert_eq!(odds, SmallVec::<i32, 16>::from(&[1i32, 3, 5, 9, 11, 13, 15]));
1171    /// ```
1172    ///
1173    /// Using the range argument to only process a part of the vector:
1174    ///
1175    /// ```
1176    /// # use smallvec::SmallVec;
1177    /// let mut items: SmallVec<i32, 16> = SmallVec::from(&[0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
1178    /// let ones = items.extract_if(7.., |x| *x == 1).collect::<SmallVec<i32, 16>>();
1179    /// assert_eq!(items, SmallVec::<i32, 16>::from(&[0, 0, 0, 0, 0, 0, 0, 2, 2, 2]));
1180    /// assert_eq!(ones.len(), 3);
1181    /// ```
1182    pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, N, F>
1183    where
1184        F: FnMut(&mut T) -> bool,
1185        R: core::ops::RangeBounds<usize>,
1186    {
1187        let old_len = self.len();
1188        let core::ops::Range { start, end } = slice_range(range, ..old_len);
1189
1190        // Guard against us getting leaked (leak amplification)
1191        unsafe {
1192            self.set_len(0);
1193        }
1194
1195        ExtractIf {
1196            vec: self,
1197            idx: start,
1198            end,
1199            del: 0,
1200            old_len,
1201            pred: filter,
1202        }
1203    }
1204
1205    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, N>
1206    where
1207        R: core::ops::RangeBounds<usize>,
1208        I: IntoIterator<Item = T>,
1209    {
1210        Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
1211    }
1212
1213    #[inline]
1214    pub fn push(&mut self, value: T) {
1215        let len = self.len();
1216        if len == self.capacity() {
1217            self.reserve(1);
1218        }
1219        // SAFETY: both the input and output are within the allocation
1220        let ptr = unsafe { self.as_mut_ptr().add(len) };
1221        // SAFETY: we allocated enough space in case it wasn't enough, so the address is valid for
1222        // writes.
1223        unsafe { ptr.write(value) };
1224        unsafe { self.set_len(len + 1) }
1225    }
1226
1227    #[inline]
1228    pub fn pop(&mut self) -> Option<T> {
1229        if self.is_empty() {
1230            None
1231        } else {
1232            let len = self.len() - 1;
1233            // SAFETY: len < old_len since this can't overflow, because the old length is non zero
1234            unsafe { self.set_len(len) };
1235            // SAFETY: this element was initialized and we just gave up ownership of it, so we can
1236            // give it away
1237            let value = unsafe { self.as_mut_ptr().add(len).read() };
1238            Some(value)
1239        }
1240    }
1241
1242    #[inline]
1243    pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
1244        let last = self.last_mut()?;
1245        if predicate(last) { self.pop() } else { None }
1246    }
1247
1248    #[inline]
1249    pub fn append<const M: usize>(&mut self, other: &mut SmallVec<T, M>) {
1250        // can't overflow since both are smaller than isize::MAX and 2 * isize::MAX < usize::MAX
1251        let len = self.len();
1252        let other_len = other.len();
1253        let total_len = len + other_len;
1254        if total_len > self.capacity() {
1255            self.reserve(other_len);
1256        }
1257
1258        // SAFETY: see `Self::push`
1259        let ptr = unsafe { self.as_mut_ptr().add(len) };
1260        unsafe { other.set_len(0) }
1261        // SAFETY: we have a mutable reference to each vector and each uniquely owns its memory.
1262        // so the ranges can't overlap
1263        unsafe { copy_nonoverlapping(other.as_ptr(), ptr, other_len) };
1264        unsafe { self.set_len(total_len) }
1265    }
1266
1267    #[inline]
1268    pub fn grow(&mut self, new_capacity: usize) {
1269        infallible(self.try_grow(new_capacity));
1270    }
1271
1272    #[cold]
1273    pub fn try_grow(&mut self, new_capacity: usize) -> Result<(), CollectionAllocErr> {
1274        if Self::is_zst() {
1275            return Ok(());
1276        }
1277
1278        let len = self.len();
1279        assert!(new_capacity >= len);
1280
1281        if new_capacity > Self::inline_size() {
1282            // SAFETY: we checked all the preconditions
1283            let result = unsafe { self.raw.try_grow_raw(self.len, new_capacity) };
1284
1285            if result.is_ok() {
1286                // SAFETY: the allocation succeeded, so self.raw.heap is now active
1287                unsafe { self.set_on_heap() };
1288            }
1289            result
1290        } else {
1291            // new_capacity <= Self::inline_size()
1292            if self.spilled() {
1293                unsafe {
1294                    // SAFETY: heap member is active
1295                    let (ptr, old_cap) = self.raw.heap;
1296                    // inline member is now active
1297
1298                    // SAFETY: len <= new_capacity <= Self::inline_size()
1299                    // so the copy is within bounds of the inline member
1300                    copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1301                    drop(DropDealloc {
1302                        ptr: ptr.cast(),
1303                        size_bytes: old_cap * size_of::<T>(),
1304                        align: align_of::<T>(),
1305                    });
1306                    self.set_inline();
1307                }
1308            }
1309            Ok(())
1310        }
1311    }
1312
1313    #[inline]
1314    pub fn reserve(&mut self, additional: usize) {
1315        // can't overflow since len <= capacity
1316        if additional > self.capacity() - self.len() {
1317            let new_capacity = infallible(
1318                self.len()
1319                    .checked_add(additional)
1320                    .and_then(usize::checked_next_power_of_two)
1321                    .ok_or(CollectionAllocErr::CapacityOverflow),
1322            );
1323            self.grow(new_capacity);
1324        }
1325    }
1326
1327    #[inline]
1328    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1329        if additional > self.capacity() - self.len() {
1330            let new_capacity = self
1331                .len()
1332                .checked_add(additional)
1333                .and_then(usize::checked_next_power_of_two)
1334                .ok_or(CollectionAllocErr::CapacityOverflow)?;
1335            self.try_grow(new_capacity)
1336        } else {
1337            Ok(())
1338        }
1339    }
1340
1341    #[inline]
1342    pub fn reserve_exact(&mut self, additional: usize) {
1343        // can't overflow since len <= capacity
1344        if additional > self.capacity() - self.len() {
1345            let new_capacity = infallible(
1346                self.len()
1347                    .checked_add(additional)
1348                    .ok_or(CollectionAllocErr::CapacityOverflow),
1349            );
1350            self.grow(new_capacity);
1351        }
1352    }
1353
1354    #[inline]
1355    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1356        if additional > self.capacity() - self.len() {
1357            let new_capacity = self
1358                .len()
1359                .checked_add(additional)
1360                .ok_or(CollectionAllocErr::CapacityOverflow)?;
1361            self.try_grow(new_capacity)
1362        } else {
1363            Ok(())
1364        }
1365    }
1366
1367    #[inline]
1368    pub fn shrink_to_fit(&mut self) {
1369        if !self.spilled() {
1370            return;
1371        }
1372        let len = self.len();
1373        if len <= Self::inline_size() {
1374            // SAFETY: self.spilled() is true, so we're on the heap
1375            unsafe {
1376                let (ptr, capacity) = self.raw.heap;
1377                self.raw = RawSmallVec::new_inline(MaybeUninit::uninit());
1378                copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1379                self.set_inline();
1380                alloc::alloc::dealloc(
1381                    ptr.cast().as_ptr(),
1382                    Layout::from_size_align_unchecked(capacity * size_of::<T>(), align_of::<T>()),
1383                );
1384            }
1385        } else if len < self.capacity() {
1386            // SAFETY: len > Self::inline_size() >= 0
1387            // so new capacity is non zero, it is equal to the length
1388            // T can't be a ZST because SmallVec<ZST, N> is never spilled.
1389            unsafe { infallible(self.raw.try_grow_raw(self.len, len)) };
1390        }
1391    }
1392
1393    #[inline]
1394    pub fn shrink_to(&mut self, min_capacity: usize) {
1395        if !self.spilled() {
1396            return;
1397        }
1398        if self.capacity() > min_capacity {
1399            let len = self.len();
1400            let target = core::cmp::max(len, min_capacity);
1401            if target <= Self::inline_size() {
1402                // SAFETY: self.spilled() is true, so we're on the heap
1403                unsafe {
1404                    let (ptr, capacity) = self.raw.heap;
1405                    self.raw = RawSmallVec::new_inline(MaybeUninit::uninit());
1406                    copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1407                    self.set_inline();
1408                    alloc::alloc::dealloc(
1409                        ptr.cast().as_ptr(),
1410                        Layout::from_size_align_unchecked(capacity * size_of::<T>(), align_of::<T>()),
1411                    );
1412                }
1413            } else if target < self.capacity() {
1414                // SAFETY: len > Self::inline_size() >= 0
1415                // so new capacity is non zero, it is equal to the length
1416                // T can't be a ZST because SmallVec<ZST, N> is never spilled.
1417                unsafe { infallible(self.raw.try_grow_raw(self.len, target)) };
1418            }
1419        }
1420    }
1421
1422    #[inline]
1423    pub fn truncate(&mut self, len: usize) {
1424        let old_len = self.len();
1425        if len < old_len {
1426            // SAFETY: we set `len` to a smaller value
1427            // then we drop the previously initialized elements
1428            unsafe {
1429                self.set_len(len);
1430                core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
1431                    self.as_mut_ptr().add(len),
1432                    old_len - len,
1433                ))
1434            }
1435        }
1436    }
1437
1438    #[inline]
1439    pub fn swap_remove(&mut self, index: usize) -> T {
1440        let len = self.len();
1441        assert!(index < len, "swap_remove index (is {index}) should be < len (is {len})");
1442        // This can't overflow since `len > index >= 0`
1443        let new_len = len - 1;
1444        unsafe {
1445            // We replace self[index] with the last element. Note that if the
1446            // bounds check above succeeds there must be a last element (which
1447            // can be self[index] itself).
1448            let value = core::ptr::read(self.as_ptr().add(index));
1449            let base_ptr = self.as_mut_ptr();
1450            core::ptr::copy(base_ptr.add(new_len), base_ptr.add(index), 1);
1451            self.set_len(new_len);
1452            value
1453        }
1454    }
1455
1456    #[inline]
1457    pub fn clear(&mut self) {
1458        // SAFETY: we set `len` to a smaller value
1459        // then we drop the previously initialized elements
1460        unsafe {
1461            let old_len = self.len();
1462            self.set_len(0);
1463            core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
1464                self.as_mut_ptr(),
1465                old_len,
1466            ));
1467        }
1468    }
1469
1470    #[inline]
1471    pub fn remove(&mut self, index: usize) -> T {
1472        let len = self.len();
1473        assert!(index < len, "removal index (is {index}) should be < len (is {len})");
1474        let new_len = len - 1;
1475        unsafe {
1476            // SAFETY: new_len < len
1477            self.set_len(new_len);
1478            let ptr = self.as_mut_ptr();
1479            let ith = ptr.add(index);
1480            // This item is initialized since index < len
1481            let ith_item = ith.read();
1482            copy(ith.add(1), ith, new_len - index);
1483            ith_item
1484        }
1485    }
1486
1487    #[inline]
1488    pub fn insert(&mut self, index: usize, value: T) {
1489        let len = self.len();
1490        assert!(index <= len, "insertion index (is {index}) should be <= len (is {len})");
1491        self.reserve(1);
1492        let ptr = self.as_mut_ptr();
1493        unsafe {
1494            // the elements at `index + 1..len + 1` are now initialized
1495            if index < len {
1496                copy(ptr.add(index), ptr.add(index + 1), len - index);
1497            }
1498            // the element at `index` is now initialized
1499            ptr.add(index).write(value);
1500
1501            // SAFETY: all the elements are initialized
1502            self.set_len(len + 1);
1503        }
1504    }
1505
1506    #[inline]
1507    pub const fn as_slice(&self) -> &[T] {
1508        let len = self.len();
1509        let ptr = self.as_ptr();
1510        // SAFETY: all the elements in `..len` are initialized
1511        unsafe { core::slice::from_raw_parts(ptr, len) }
1512    }
1513
1514    #[inline]
1515    pub const fn as_mut_slice(&mut self) -> &mut [T] {
1516        let len = self.len();
1517        let ptr = self.as_mut_ptr();
1518        // SAFETY: see above
1519        unsafe { core::slice::from_raw_parts_mut(ptr, len) }
1520    }
1521
1522    #[inline]
1523    pub const fn as_ptr(&self) -> *const T {
1524        if self.len.on_heap(Self::is_zst()) {
1525            // SAFETY: heap member is active
1526            unsafe { self.raw.as_ptr_heap() }
1527        } else {
1528            self.raw.as_ptr_inline()
1529        }
1530    }
1531
1532    #[inline]
1533    pub const fn as_mut_ptr(&mut self) -> *mut T {
1534        if self.len.on_heap(Self::is_zst()) {
1535            // SAFETY: see above
1536            unsafe { self.raw.as_mut_ptr_heap() }
1537        } else {
1538            self.raw.as_mut_ptr_inline()
1539        }
1540    }
1541
1542    #[inline]
1543    pub fn into_vec(self) -> Vec<T> {
1544        let len = self.len();
1545        if !self.spilled() {
1546            let mut vec = Vec::with_capacity(len);
1547            let this = ManuallyDrop::new(self);
1548            // SAFETY: we create a new vector with sufficient capacity, copy our elements into it
1549            // to transfer ownership and then set the length
1550            // we don't drop the elements we previously held
1551            unsafe {
1552                copy_nonoverlapping(this.raw.as_ptr_inline(), vec.as_mut_ptr(), len);
1553                vec.set_len(len);
1554            }
1555            vec
1556        } else {
1557            let this = ManuallyDrop::new(self);
1558            // SAFETY:
1559            // - `ptr` was created with the global allocator
1560            // - `ptr` was created with the appropriate alignment for `T`
1561            // - the allocation pointed to by ptr is exactly cap * sizeof(T)
1562            // - `len` is less than or equal to `cap`
1563            // - the first `len` entries are proper `T`-values
1564            // - the allocation is not larger than `isize::MAX`
1565            unsafe {
1566                let (ptr, cap) = this.raw.heap;
1567                Vec::from_raw_parts(ptr.as_ptr(), len, cap)
1568            }
1569        }
1570    }
1571
1572    #[inline]
1573    pub fn into_boxed_slice(self) -> Box<[T]> {
1574        self.into_vec().into_boxed_slice()
1575    }
1576
1577    #[inline]
1578    pub fn into_inner(self) -> Result<[T; N], Self> {
1579        if self.len() != N {
1580            Err(self)
1581        } else {
1582            // when `this` is dropped, the memory is released if it's on the heap.
1583            let mut this = self;
1584            // SAFETY: we release ownership of the elements we hold
1585            unsafe {
1586                this.set_len(0);
1587            }
1588            let ptr = this.as_ptr() as *const [T; N];
1589            // SAFETY: these elements are initialized since the length was `N`
1590            unsafe { Ok(ptr.read()) }
1591        }
1592    }
1593
1594    #[inline]
1595    pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut f: F) {
1596        self.retain_mut(|elem| f(elem))
1597    }
1598
1599    #[inline]
1600    pub fn retain_mut<F: FnMut(&mut T) -> bool>(&mut self, mut f: F) {
1601        let mut del = 0;
1602        let len = self.len();
1603        let ptr = self.as_mut_ptr();
1604        for i in 0..len {
1605            // SAFETY: all the pointers are in bounds
1606            // `i - del` never overflows since `del <= i` is a maintained invariant
1607            unsafe {
1608                if !f(&mut *ptr.add(i)) {
1609                    del += 1;
1610                } else if del > 0 {
1611                    core::ptr::swap(ptr.add(i), ptr.add(i - del));
1612                }
1613            }
1614        }
1615        self.truncate(len - del);
1616    }
1617
1618    #[inline]
1619    pub fn dedup(&mut self)
1620    where
1621        T: PartialEq,
1622    {
1623        self.dedup_by(|a, b| a == b);
1624    }
1625
1626    #[inline]
1627    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1628    where
1629        F: FnMut(&mut T) -> K,
1630        K: PartialEq<K>,
1631    {
1632        self.dedup_by(|a, b| key(a) == key(b));
1633    }
1634
1635    #[inline]
1636    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1637    where
1638        F: FnMut(&mut T, &mut T) -> bool,
1639    {
1640        // See the implementation of Vec::dedup_by in the
1641        // standard library for an explanation of this algorithm.
1642        let len = self.len();
1643        if len <= 1 {
1644            return;
1645        }
1646
1647        let ptr = self.as_mut_ptr();
1648        let mut w: usize = 1;
1649
1650        unsafe {
1651            for r in 1..len {
1652                let p_r = ptr.add(r);
1653                let p_wm1 = ptr.add(w - 1);
1654                if !same_bucket(&mut *p_r, &mut *p_wm1) {
1655                    if r != w {
1656                        let p_w = p_wm1.add(1);
1657                        core::ptr::swap(p_r, p_w);
1658                    }
1659                    w += 1;
1660                }
1661            }
1662        }
1663
1664        self.truncate(w);
1665    }
1666
1667    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1668    where
1669        F: FnMut() -> T,
1670    {
1671        let old_len = self.len();
1672        if old_len < new_len {
1673            let mut f = f;
1674            let additional = new_len - old_len;
1675            self.reserve(additional);
1676            for _ in 0..additional {
1677                self.push(f());
1678            }
1679        } else if old_len > new_len {
1680            self.truncate(new_len);
1681        }
1682    }
1683
1684    pub fn leak<'a>(self) -> &'a mut [T] {
1685        if !self.spilled() {
1686            panic!("SmallVec::leak() called on inline (stack) SmallVec, which cannot be safely leaked");
1687        }
1688        let mut me = ManuallyDrop::new(self);
1689        unsafe { core::slice::from_raw_parts_mut(me.as_mut_ptr(), me.len()) }
1690    }
1691
1692    /// Returns the remaining spare capacity of the vector as a slice of
1693    /// `MaybeUninit<T>`.
1694    ///
1695    /// The returned slice can be used to fill the vector with data (e.g. by
1696    /// reading from a file) before marking the data as initialized using the
1697    /// [`set_len`](Self::set_len) method.
1698    #[inline]
1699    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1700        unsafe {
1701            core::slice::from_raw_parts_mut(
1702                self.as_mut_ptr().add(self.len()) as *mut MaybeUninit<T>,
1703                self.capacity() - self.len(),
1704            )
1705        }
1706    }
1707
1708    /// Creates a `SmallVec` directly from the raw components of another `SmallVec`.
1709    ///
1710    /// # Safety
1711    ///
1712    /// This is highly unsafe, due to the number of invariants that aren’t checked:
1713    ///
1714    /// - `ptr` needs to have been previously allocated via `SmallVec` from its spilled storage (at least, it’s highly likely to be incorrect if it wasn’t).
1715    /// - `ptr`’s `A::Item` type needs to be the same size and alignment that it was allocated with
1716    /// - `length` needs to be less than or equal to `capacity`.
1717    /// - `capacity` needs to be the capacity that the pointer was allocated with.
1718    ///
1719    /// Violating these may cause problems like corrupting the allocator’s internal data structures.
1720    ///
1721    /// Additionally, `capacity` must be greater than the amount of inline storage `A` has; that is, the new `SmallVec` must need to spill over into heap allocated storage. This condition is asserted against.
1722    ///
1723    /// The ownership of `ptr` is effectively transferred to the `SmallVec` which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.
1724    ///
1725    /// # Examples
1726    ///
1727    /// ```
1728    /// use smallvec::{SmallVec, smallvec};
1729    ///
1730    /// let mut v: SmallVec<_, 1> = smallvec![1, 2, 3];
1731    ///
1732    /// // Pull out the important parts of `v`.
1733    /// let p = v.as_mut_ptr();
1734    /// let len = v.len();
1735    /// let cap = v.capacity();
1736    /// let spilled = v.spilled();
1737    ///
1738    /// unsafe {
1739    ///     // Forget all about `v`. The heap allocation that stored the
1740    ///     // three values won't be deallocated.
1741    ///     std::mem::forget(v);
1742    ///
1743    ///     // Overwrite memory with [4, 5, 6].
1744    ///     //
1745    ///     // This is only safe if `spilled` is true! Otherwise, we are
1746    ///     // writing into the old `SmallVec`'s inline storage on the
1747    ///     // stack.
1748    ///     assert!(spilled);
1749    ///     for i in 0..len {
1750    ///         std::ptr::write(p.add(i), 4 + i);
1751    ///     }
1752    ///
1753    ///     // Put everything back together into a SmallVec with a different
1754    ///     // amount of inline storage, but which is still less than `cap`.
1755    ///     let rebuilt = SmallVec::<_, 2>::from_raw_parts(p, len, cap);
1756    ///     assert_eq!(&*rebuilt, &[4, 5, 6]);
1757    /// }
1758    /// ```
1759    #[inline]
1760    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> SmallVec<T, N> {
1761        assert!(!Self::is_zst());
1762
1763        // SAFETY: We require caller to provide same ptr as we alloc
1764        // and we never alloc null pointer.
1765        let ptr = unsafe {
1766            debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1767            NonNull::new_unchecked(ptr)
1768        };
1769
1770        SmallVec {
1771            len: TaggedLen::new(length, true, Self::is_zst()),
1772            raw: RawSmallVec::new_heap(ptr, capacity),
1773            _marker: PhantomData,
1774        }
1775    }
1776}
1777
1778impl<T: Clone, const N: usize> SmallVec<T, N> {
1779    #[inline]
1780    pub fn resize(&mut self, len: usize, value: T) {
1781        let old_len = self.len();
1782        if len > old_len {
1783            self.extend(core::iter::repeat_n(value, len - old_len));
1784        } else {
1785            self.truncate(len);
1786        }
1787    }
1788
1789    #[inline]
1790    pub fn extend_from_slice(&mut self, other: &[T]) {
1791        self.extend(other.iter())
1792    }
1793
1794    pub fn extend_from_within<R>(&mut self, src: R)
1795    where
1796        R: core::ops::RangeBounds<usize>,
1797    {
1798        let src = slice_range(src, ..self.len());
1799        self.reserve(src.len());
1800
1801        // SAFETY: The call to `reserve` ensures that the capacity is large enough.
1802        // The range is within bounds through the use of `core::slice::range`.
1803        unsafe {
1804            #[cfg(feature = "specialization")]
1805            {
1806                <Self as spec_traits::SpecExtendFromWithin<T>>::spec_extend_from_within(self, src);
1807            }
1808
1809            #[cfg(not(feature = "specialization"))]
1810            {
1811                self.extend_from_within_fallback(src);
1812            }
1813        }
1814    }
1815
1816    #[inline]
1817    pub fn extend_from_slice_copy(&mut self, other: &[T])
1818    where
1819        T: Copy
1820    {
1821        
1822        let len = other.len();
1823        let src = other.as_ptr();
1824        
1825        let l = self.len();
1826        self.reserve(len);
1827
1828        // SAFETY: Additional memory has been reserved,
1829        // therefore the pointer access is valid.
1830        unsafe {
1831            let dst = self.as_mut_ptr().add(l);
1832            copy_nonoverlapping(src, dst, len);
1833            self.set_len(l + len);
1834        }
1835    }
1836
1837    pub fn extend_from_within_copy<R>(&mut self, src: R)
1838    where
1839        R: core::ops::RangeBounds<usize>,
1840        T: Copy
1841    {
1842        let src = slice_range(src, ..self.len());
1843        let core::ops::Range { start, end } = src;
1844        let len = end - start;
1845        self.reserve(len);
1846
1847        // SAFETY: The call to `reserve` ensures that the capacity is large enough.
1848        // The range is within bounds through the use of `core::slice::range`.
1849        unsafe {
1850            let l = self.len();
1851            let ptr = self.as_mut_ptr();
1852            copy_nonoverlapping(ptr.add(start), ptr.add(l), len);
1853            self.set_len(l + len);
1854        }
1855    }
1856
1857    pub fn insert_from_slice_copy(&mut self, index: usize, other: &[T])
1858    where
1859        T: Copy
1860    {
1861        let l = self.len();
1862        let len = other.len();
1863        assert!(index <= l);
1864        self.reserve(len);
1865        unsafe {
1866            let base_ptr = self.as_mut_ptr();
1867            let ith_ptr = base_ptr.add(index);
1868            let shifted_ptr = base_ptr.add(index + len);
1869            // elements at `index + other_len..len + other_len` are now initialized
1870            copy(ith_ptr, shifted_ptr, l - index);
1871            // elements at `index..index + other_len` are now initialized
1872            copy_nonoverlapping(other.as_ptr(), ith_ptr, len);
1873
1874            // SAFETY: all the elements are initialized
1875            self.set_len(l + len);
1876        }
1877    }
1878
1879    /// A function for creating [`SmallVec`] values out of slices
1880    /// for types with the [`Copy`] trait.
1881    pub fn from_slice_copy(slice: &[T]) -> Self
1882    where
1883        T: Copy
1884    {
1885        let src = slice.as_ptr();
1886        let len = slice.len();
1887        let mut result = Self::with_capacity(len);
1888
1889        // SAFETY: By using `with_capacity`, the pointer will point to valid memory.
1890        unsafe {
1891            let dst = result.as_mut_ptr();
1892            copy_nonoverlapping(src, dst, len);
1893            result.set_len(len);
1894        }
1895
1896        result
1897    }
1898}
1899
1900struct DropGuard<T> {
1901    ptr: *mut T,
1902    len: usize,
1903}
1904impl<T> Drop for DropGuard<T> {
1905    #[inline]
1906    fn drop(&mut self) {
1907        unsafe {
1908            core::ptr::slice_from_raw_parts_mut(self.ptr, self.len).drop_in_place();
1909        }
1910    }
1911}
1912
1913struct DropDealloc {
1914    ptr: NonNull<u8>,
1915    size_bytes: usize,
1916    align: usize,
1917}
1918
1919impl Drop for DropDealloc {
1920    #[inline]
1921    fn drop(&mut self) {
1922        unsafe {
1923            if self.size_bytes > 0 {
1924                alloc::alloc::dealloc(
1925                    self.ptr.as_ptr(),
1926                    Layout::from_size_align_unchecked(self.size_bytes, self.align),
1927                );
1928            }
1929        }
1930    }
1931}
1932
1933#[cfg(feature = "may_dangle")]
1934unsafe impl<#[may_dangle] T, const N: usize> Drop for SmallVec<T, N> {
1935    fn drop(&mut self) {
1936        let on_heap = self.spilled();
1937        let len = self.len();
1938        let ptr = self.as_mut_ptr();
1939        // SAFETY: we first drop the elements, then `_drop_dealloc` is dropped, releasing memory we
1940        // used to own
1941        unsafe {
1942            let _drop_dealloc = if on_heap {
1943                let capacity = self.capacity();
1944                Some(DropDealloc {
1945                    ptr: NonNull::new_unchecked(ptr as *mut u8),
1946                    size_bytes: capacity * size_of::<T>(),
1947                    align: align_of::<T>(),
1948                })
1949            } else {
1950                None
1951            };
1952            core::ptr::slice_from_raw_parts_mut(ptr, len).drop_in_place();
1953        }
1954    }
1955}
1956
1957#[cfg(not(feature = "may_dangle"))]
1958impl<T, const N: usize> Drop for SmallVec<T, N> {
1959    fn drop(&mut self) {
1960        let on_heap = self.spilled();
1961        let len = self.len();
1962        let ptr = self.as_mut_ptr();
1963        // SAFETY: see above
1964        unsafe {
1965            let _drop_dealloc = if on_heap {
1966                let capacity = self.capacity();
1967                Some(DropDealloc {
1968                    ptr: NonNull::new_unchecked(ptr as *mut u8),
1969                    size_bytes: capacity * size_of::<T>(),
1970                    align: align_of::<T>(),
1971                })
1972            } else {
1973                None
1974            };
1975            core::ptr::slice_from_raw_parts_mut(ptr, len).drop_in_place();
1976        }
1977    }
1978}
1979
1980impl<T, const N: usize> Drop for IntoIter<T, N> {
1981    fn drop(&mut self) {
1982        // SAFETY: see above
1983        unsafe {
1984            let is_zst = size_of::<T>() == 0;
1985            let on_heap = self.end.on_heap(is_zst);
1986            let begin = self.begin;
1987            let end = self.end.value(is_zst);
1988            let ptr = self.as_mut_ptr();
1989            let _drop_dealloc = if on_heap {
1990                let capacity = self.raw.heap.1;
1991                Some(DropDealloc {
1992                    ptr: NonNull::new_unchecked(ptr as *mut u8),
1993                    size_bytes: capacity * size_of::<T>(),
1994                    align: align_of::<T>(),
1995                })
1996            } else {
1997                None
1998            };
1999            core::ptr::slice_from_raw_parts_mut(ptr.add(begin), end - begin).drop_in_place();
2000        }
2001    }
2002}
2003
2004impl<T, const N: usize> core::ops::Deref for SmallVec<T, N> {
2005    type Target = [T];
2006
2007    #[inline]
2008    fn deref(&self) -> &Self::Target {
2009        self.as_slice()
2010    }
2011}
2012impl<T, const N: usize> core::ops::DerefMut for SmallVec<T, N> {
2013    #[inline]
2014    fn deref_mut(&mut self) -> &mut Self::Target {
2015        self.as_mut_slice()
2016    }
2017}
2018
2019/// This function is used in the [`smallvec`] macro.
2020/// It is recommended to use the macro instead of using thís function.
2021#[doc(hidden)]
2022#[track_caller]
2023pub fn from_elem<T: Clone, const N: usize>(elem: T, n: usize) -> SmallVec<T, N> {
2024    if n > SmallVec::<T, N>::inline_size() {
2025        // Standard Rust vectors are already specialized.
2026        SmallVec::<T, N>::from_vec(vec![elem; n])
2027    } else {
2028        #[cfg(feature = "specialization")]
2029        {
2030            // SAFETY: The precondition is checked in the initial comparison above.
2031            unsafe { <SmallVec<T, N> as spec_traits::SpecFromElem<T>>::spec_from_elem(elem, n) }
2032        }
2033
2034        #[cfg(not(feature = "specialization"))]
2035        {
2036            // SAFETY: The precondition is checked in the initial comparison above.
2037            unsafe { SmallVec::<T, N>::from_elem_fallback(elem, n) }
2038        }
2039    }
2040}
2041
2042#[cfg(feature = "specialization")]
2043mod spec_traits {
2044    use super::*;
2045
2046    /// A trait for specializing the implementation of [`from_elem`].
2047    ///
2048    /// [`from_elem`]: crate::from_elem
2049    pub(crate) trait SpecFromElem<T> {
2050        /// Creates a `Smallvec` value where `elem` is repeated `n` times.
2051        /// This will use the inline storage, not the heap.
2052        ///
2053        /// # Safety
2054        ///
2055        /// The caller must ensure that `n <= Self::inline_size()`.
2056        unsafe fn spec_from_elem(elem: T, n: usize) -> Self;
2057    }
2058
2059    impl<T: Clone, const N: usize> SpecFromElem<T> for SmallVec<T, N> {
2060        #[inline]
2061        default unsafe fn spec_from_elem(elem: T, n: usize) -> Self {
2062            // SAFETY: Safety conditions are identical.
2063            unsafe { SmallVec::from_elem_fallback(elem, n) }
2064        }
2065    }
2066
2067    impl<T: Copy, const N: usize> SpecFromElem<T> for SmallVec<T, N> {
2068        unsafe fn spec_from_elem(elem: T, n: usize) -> Self {
2069            let mut result = Self::new();
2070
2071            if n > 0 {
2072                let ptr = result.raw.as_mut_ptr_inline();
2073
2074                // SAFETY: The caller ensures that the first `n`
2075                // is smaller than the inline size.
2076                unsafe {
2077                    for i in 0..n {
2078                        ptr.add(i).write(elem);
2079                    }
2080                }
2081            }
2082
2083            // SAFETY: The first `n` elements of the vector
2084            // have been initialized in the loop above.
2085            unsafe {
2086                result.set_len(n);
2087            }
2088
2089            result
2090        }
2091    }
2092
2093    /// A trait for specializing the implementations of [`Extend`] and [`extend_from_slice`].
2094    ///
2095    /// [`extend_from_slice`]: crate::SmallVec::extend_from_slice
2096    pub(crate) trait SpecExtend<T, I> {
2097        fn spec_extend(&mut self, iter: I);
2098    }
2099
2100    impl<T, I, const N: usize> SpecExtend<T, I> for SmallVec<T, N>
2101    where
2102        I: Iterator<Item = T>,
2103    {
2104        #[inline]
2105        default fn spec_extend(&mut self, iter: I) {
2106            self.extend_fallback(iter);
2107        }
2108    }
2109
2110    impl<T, I, const N: usize> SpecExtend<T, I> for SmallVec<T, N>
2111    where
2112        I: core::iter::TrustedLen<Item = T>,
2113    {
2114        fn spec_extend(&mut self, iter: I) {
2115            let (_, Some(additional)) = iter.size_hint() else {
2116                panic!("capacity overflow")
2117            };
2118            self.reserve(additional);
2119
2120            // SAFETY: A `TrustedLen` iterator provides accurate information
2121            // about its size, which was used to reserve additional memory.
2122            // This ensures that the access operations inside the loop always
2123            // operate on valid memory.
2124            unsafe {
2125                let len = self.len();
2126                let ptr = self.as_mut_ptr().add(len);
2127                let mut guard = DropGuard { ptr, len: 0 };
2128
2129                for x in iter {
2130                    ptr.add(guard.len).write(x);
2131                    guard.len += 1;
2132                }
2133
2134                // The elements have been initialized in the loop above.
2135                self.set_len(len + guard.len);
2136                core::mem::forget(guard);
2137            }
2138        }
2139    }
2140
2141    impl<T, const N: usize, const M: usize> SpecExtend<T, IntoIter<T, M>> for SmallVec<T, N> {
2142        fn spec_extend(&mut self, mut iter: IntoIter<T, M>) {
2143            let slice = iter.as_slice();
2144            let len = slice.len();
2145            let old_len = self.len();
2146
2147            self.reserve(len);
2148
2149            // SAFETY: Additional memory has been reserved above.
2150            // Therefore, the copy operates on valid memory.
2151            unsafe {
2152                let dst = self.as_mut_ptr().add(old_len);
2153                let src = slice.as_ptr();
2154                copy_nonoverlapping(src, dst, len);
2155            }
2156
2157            // SAFETY: The elements were initialized above.
2158            unsafe {
2159                self.set_len(old_len + len);
2160            }
2161
2162            // Mark the iterator as fully consumed.
2163            iter.begin = iter.end.value(Self::is_zst());
2164        }
2165    }
2166
2167    impl<'a, T: 'a, const N: usize, I> SpecExtend<&'a T, I> for SmallVec<T, N>
2168    where
2169        I: Iterator<Item = &'a T>,
2170        T: Clone,
2171    {
2172        #[inline]
2173        default fn spec_extend(&mut self, iterator: I) {
2174            self.spec_extend(iterator.cloned())
2175        }
2176    }
2177
2178    impl<'a, T: 'a, const N: usize> SpecExtend<&'a T, core::slice::Iter<'a, T>> for SmallVec<T, N>
2179    where
2180        T: Copy,
2181    {
2182        fn spec_extend(&mut self, iter: core::slice::Iter<'a, T>) {
2183            let slice = iter.as_slice();
2184            let len = slice.len();
2185            let old_len = self.len();
2186
2187            self.reserve(len);
2188
2189            // SAFETY: Additional memory has been reserved above.
2190            // Therefore, the copy operates on valid memory.
2191            unsafe {
2192                let dst = self.as_mut_ptr().add(old_len);
2193                let src = slice.as_ptr();
2194                copy_nonoverlapping(src, dst, len);
2195            }
2196
2197            // SAFETY: The elements were initialized above.
2198            unsafe {
2199                self.set_len(old_len + len);
2200            }
2201        }
2202    }
2203
2204    /// A trait for specializing the implementation of [`extend_from_within`].
2205    ///
2206    /// [`extend_from_within`]: crate::SmallVec::extend_from_within
2207    pub(crate) trait SpecExtendFromWithin<T> {
2208        /// Main worker for [`extend_from_within`].
2209        ///
2210        /// # Safety
2211        ///
2212        /// * The length of the vector is larger than or equal to `src.len()`.
2213        /// * The spare capacity of the vector is larger than or equal to `src.len()`.
2214        ///
2215        /// [`extend_from_within`]: SmallVec::extend_from_within
2216        unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>);
2217    }
2218
2219    impl<T: Clone, const N: usize> SpecExtendFromWithin<T> for SmallVec<T, N> {
2220        default unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>) {
2221            // SAFETY: Safety conditions are identical.
2222            unsafe {
2223                self.extend_from_within_fallback(src);
2224            }
2225        }
2226    }
2227
2228    impl<T: Copy, const N: usize> SpecExtendFromWithin<T> for SmallVec<T, N> {
2229        unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>) {
2230            let old_len = self.len();
2231
2232            let start = src.start;
2233            let len = src.len();
2234
2235            // SAFETY: The caller ensures that the vector has spare capacity
2236            // for at least `src.len()` elements. This is alse the amount of memory
2237            // accessed when the data is copied.
2238            unsafe {
2239                let ptr = self.as_mut_ptr();
2240                let dst = ptr.add(old_len);
2241                let src = ptr.add(start);
2242                copy_nonoverlapping(src, dst, len);
2243            }
2244
2245            // SAFETY: The elements were initialized above.
2246            unsafe {
2247                self.set_len(old_len + len);
2248            }
2249        }
2250    }
2251
2252    /// A trait for specializing the implementation of [`FromIterator`].
2253    ///
2254    /// [`clone_from`]: Clone::clone_from
2255    pub(crate) trait SpecFromIterator<T, I> {
2256        fn spec_from_iter(iter: I) -> Self;
2257    }
2258
2259    impl<T, I, const N: usize> SpecFromIterator<T, I> for SmallVec<T, N>
2260    where
2261        I: Iterator<Item = T>,
2262    {
2263        #[inline]
2264        default fn spec_from_iter(iter: I) -> Self {
2265            Self::from_iter_fallback(iter)
2266        }
2267    }
2268
2269    impl<T, I, const N: usize> SpecFromIterator<T, I> for SmallVec<T, N>
2270    where
2271        I: core::iter::TrustedLen<Item = T>,
2272    {
2273        fn spec_from_iter(iter: I) -> Self {
2274            let mut v = match iter.size_hint() {
2275                (_, Some(upper)) => SmallVec::with_capacity(upper),
2276                // TrustedLen contract guarantees that `size_hint() == (_, None)` means that there
2277                // are more than `usize::MAX` elements.
2278                // Since the previous branch would eagerly panic if the capacity is too large
2279                // (via `with_capacity`) we do the same here.
2280                _ => panic!("capacity overflow"),
2281            };
2282            // Reuse the extend specialization for TrustedLen.
2283            v.spec_extend(iter);
2284            v
2285        }
2286    }
2287
2288    /// A trait for specializing the implementation of [`clone_from`].
2289    ///
2290    /// [`clone_from`]: Clone::clone_from
2291    pub(crate) trait SpecCloneFrom<T> {
2292        fn spec_clone_from(&mut self, source: &[T]);
2293    }
2294
2295    impl<T: Clone, const N: usize> SpecCloneFrom<T> for SmallVec<T, N> {
2296        #[inline]
2297        default fn spec_clone_from(&mut self, source: &[T]) {
2298            self.clone_from_fallback(source);
2299        }
2300    }
2301
2302    impl<T: Copy, const N: usize> SpecCloneFrom<T> for SmallVec<T, N> {
2303        fn spec_clone_from(&mut self, source: &[T]) {
2304            self.clear();
2305            self.extend_from_slice(source);
2306        }
2307    }
2308
2309    /// A trait for specializing the implementation of [`From`]
2310    /// with the source type being slices.
2311    pub(crate) trait SpecFromSlice<T> {
2312        /// Creates a `SmallVec` value based on the contents of `slice`.
2313        /// This will use the inline storage, not the heap.
2314        ///
2315        /// # Safety
2316        ///
2317        /// The caller must ensure that `slice.len() <= Self::inline_size()`.
2318        unsafe fn spec_from(slice: &[T]) -> Self;
2319    }
2320
2321    impl<T: Clone, const N: usize> SpecFromSlice<T> for SmallVec<T, N> {
2322        default unsafe fn spec_from(slice: &[T]) -> Self {
2323            // SAFETY: Safety conditions are identical.
2324            unsafe { Self::from_slice_fallback(slice) }
2325        }
2326    }
2327
2328    impl<T: Copy, const N: usize> SpecFromSlice<T> for SmallVec<T, N> {
2329        unsafe fn spec_from(slice: &[T]) -> Self {
2330            let mut v = Self::new();
2331
2332            let src = slice.as_ptr();
2333            let len = slice.len();
2334            let dst = v.as_mut_ptr();
2335
2336            // SAFETY: The caller ensures that the slice length is smaller
2337            // than or equal to the inline length.
2338            unsafe {
2339                copy_nonoverlapping(src, dst, len);
2340            }
2341
2342            // SAFETY: The elements were initialized above.
2343            unsafe {
2344                v.set_len(len);
2345            }
2346
2347            v
2348        }
2349    }
2350}
2351
2352/// Fallback functions for various specialized methods. These are kept in
2353/// a separate implementation block for easy access whenever specialization is disabled.
2354impl<T, const N: usize> SmallVec<T, N> {
2355    /// Creates a `Smallvec` value where `elem` is repeated `n` times.
2356    /// This will use the inline storage, not the heap.
2357    ///
2358    /// # Safety
2359    ///
2360    /// The caller must ensure that `n <= Self::inline_size()`.
2361    unsafe fn from_elem_fallback(elem: T, n: usize) -> Self
2362    where
2363        T: Clone,
2364    {
2365        let mut result = Self::new();
2366
2367        if n > 0 {
2368            let ptr = result.raw.as_mut_ptr_inline();
2369            let mut guard = DropGuard { ptr, len: 0 };
2370
2371            // SAFETY: The caller ensures that the first `n`
2372            // is smaller than the inline size.
2373            unsafe {
2374                for i in 0..(n - 1) {
2375                    ptr.add(i).write(elem.clone());
2376                    guard.len += 1;
2377                }
2378                core::mem::forget(guard);
2379                ptr.add(n - 1).write(elem);
2380            }
2381        }
2382
2383        // SAFETY: The first `n` elements of the vector
2384        // have been initialized in the loop above.
2385        unsafe {
2386            result.set_len(n);
2387        }
2388
2389        result
2390    }
2391
2392    fn extend_fallback<I>(&mut self, iter: I)
2393    where
2394        I: IntoIterator<Item = T>,
2395    {
2396        let iter = iter.into_iter();
2397        let (size, _) = iter.size_hint();
2398        self.reserve(size);
2399        for x in iter {
2400            self.push(x);
2401        }
2402    }
2403
2404    /// Main worker for [`extend_from_within`].
2405    ///
2406    /// # Safety
2407    ///
2408    /// * The length of the vector is larger than or equal to `src.len()`.
2409    /// * The spare capacity of the vector is larger than or equal to `src.len()`.
2410    ///
2411    /// [`extend_from_within`]: SmallVec::extend_from_within
2412    unsafe fn extend_from_within_fallback(&mut self, src: core::ops::Range<usize>)
2413    where
2414        T: Clone,
2415    {
2416        let old_len = self.len();
2417
2418        let start = src.start;
2419        let len = src.len();
2420
2421        // SAFETY: The caller ensures that the vector has spare capacity
2422        // for at least `src.len()` elements. This implies that the loop
2423        // operates on valid memory.
2424        unsafe {
2425            let ptr = self.as_mut_ptr();
2426            let dst = ptr.add(old_len);
2427            let src = ptr.add(start);
2428
2429            let mut guard = DropGuard { ptr: dst, len: 0 };
2430            for i in 0..len {
2431                let val = (*src.add(i)).clone();
2432                dst.add(i).write(val);
2433                guard.len += 1;
2434            }
2435            core::mem::forget(guard);
2436        }
2437
2438        // SAFETY: The elements were initialized in the loop above.
2439        unsafe {
2440            self.set_len(old_len + len);
2441        }
2442    }
2443
2444    fn from_iter_fallback<I>(iter: I) -> Self
2445    where
2446        I: Iterator<Item = T>,
2447    {
2448        let (size, _) = iter.size_hint();
2449        let mut v = Self::with_capacity(size);
2450        for x in iter {
2451            v.push(x);
2452        }
2453        v
2454    }
2455
2456    fn clone_from_fallback(&mut self, source: &[T])
2457    where
2458        T: Clone,
2459    {
2460        // Inspired from `impl Clone for Vec`.
2461
2462        // Drop anything that will not be overwritten.
2463        self.truncate(source.len());
2464
2465        // SAFETY: self.len <= other.len due to the truncate above, so the
2466        // slices here are always in-bounds.
2467        let (init, tail) = unsafe { source.split_at_unchecked(self.len()) };
2468
2469        // Reuse the contained values' allocations/resources.
2470        self.clone_from_slice(init);
2471        self.extend(tail.iter().cloned());
2472    }
2473
2474    /// Creates a `SmallVec` value based on the contents of `slice`.
2475    /// This will use the inline storage, not the heap.
2476    ///
2477    /// # Safety
2478    ///
2479    /// The caller must ensure that `slice.len() <= Self::inline_size()`.
2480    unsafe fn from_slice_fallback(slice: &[T]) -> Self
2481    where
2482        T: Clone,
2483    {
2484        let mut v = Self::new();
2485
2486        let src = slice.as_ptr();
2487        let len = slice.len();
2488        let dst = v.as_mut_ptr();
2489
2490        // SAFETY: The caller ensures that the slice length is smaller
2491        // than or equal to the inline length.
2492        unsafe {
2493            let mut guard = DropGuard { ptr: dst, len: 0 };
2494            for i in 0..len {
2495                let val = (*src.add(i)).clone();
2496                dst.add(i).write(val);
2497                guard.len += 1;
2498            }
2499            core::mem::forget(guard);
2500        }
2501
2502        // SAFETY: The elements were initialized in the loop above.
2503        unsafe {
2504            v.set_len(len);
2505        }
2506
2507        v
2508    }
2509}
2510
2511impl<T: Clone, const N: usize> From<&[T]> for SmallVec<T, N> {
2512    #[inline]
2513    fn from(slice: &[T]) -> Self {
2514        if slice.len() > Self::inline_size() {
2515            // Standard Rust vectors are already specialized.
2516            Self::from_vec(Vec::from(slice))
2517        } else {
2518            // SAFETY: The precondition is checked in the initial comparison above.
2519            unsafe {
2520                #[cfg(feature = "specialization")]
2521                {
2522                    <Self as spec_traits::SpecFromSlice<T>>::spec_from(slice)
2523                }
2524
2525                #[cfg(not(feature = "specialization"))]
2526                {
2527                    Self::from_slice_fallback(slice)
2528                }
2529            }
2530        }
2531    }
2532}
2533
2534impl<T: Clone, const N: usize> From<&mut [T]> for SmallVec<T, N> {
2535    #[inline]
2536    fn from(slice: &mut [T]) -> Self {
2537        Self::from(slice as &[T])
2538    }
2539}
2540
2541impl<T: Clone, const M: usize, const N: usize> From<&[T; M]> for SmallVec<T, N> {
2542    #[inline]
2543    fn from(slice: &[T; M]) -> Self {
2544        Self::from(slice as &[T])
2545    }
2546}
2547
2548impl<T: Clone, const M: usize, const N: usize> From<&mut [T; M]> for SmallVec<T, N> {
2549    #[inline]
2550    fn from(slice: &mut [T; M]) -> Self {
2551        Self::from(slice as &[T])
2552    }
2553}
2554
2555impl<T, const N: usize, const M: usize> From<[T; M]> for SmallVec<T, N> {
2556    fn from(array: [T; M]) -> Self {
2557        if M > N {
2558            // If M > N, we'd have to heap allocate anyway,
2559            // so delegate for Vec for the allocation.
2560            Self::from(Vec::from(array))
2561        } else {
2562            // M <= N
2563            let mut this = Self::new();
2564            debug_assert!(M <= this.capacity());
2565            let array = ManuallyDrop::new(array);
2566            // SAFETY: M <= this.capacity()
2567            unsafe {
2568                copy_nonoverlapping(array.as_ptr(), this.as_mut_ptr(), M);
2569                this.set_len(M);
2570            }
2571            this
2572        }
2573    }
2574}
2575
2576impl<T, const N: usize> From<Vec<T>> for SmallVec<T, N> {
2577    fn from(array: Vec<T>) -> Self {
2578        Self::from_vec(array)
2579    }
2580}
2581
2582impl<T: Clone, const N: usize> Clone for SmallVec<T, N> {
2583    #[inline]
2584    fn clone(&self) -> SmallVec<T, N> {
2585        SmallVec::from(self.as_slice())
2586    }
2587
2588    #[inline]
2589    fn clone_from(&mut self, source: &Self) {
2590        #[cfg(feature = "specialization")]
2591        {
2592            <Self as spec_traits::SpecCloneFrom<T>>::spec_clone_from(self, source);
2593        }
2594
2595        #[cfg(not(feature = "specialization"))]
2596        {
2597            self.clone_from_fallback(&*source);
2598        }
2599    }
2600}
2601
2602impl<T: Clone, const N: usize> Clone for IntoIter<T, N> {
2603    #[inline]
2604    fn clone(&self) -> IntoIter<T, N> {
2605        SmallVec::from(self.as_slice()).into_iter()
2606    }
2607}
2608
2609impl<T, const N: usize> Extend<T> for SmallVec<T, N> {
2610    #[inline]
2611    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2612        #[cfg(feature = "specialization")]
2613        {
2614            spec_traits::SpecExtend::<T, _>::spec_extend(self, iter.into_iter());
2615        }
2616
2617        #[cfg(not(feature = "specialization"))]
2618        {
2619            self.extend_fallback(iter);
2620        }
2621    }
2622}
2623
2624impl<'a, T: Clone + 'a, const N: usize> Extend<&'a T> for SmallVec<T, N> {
2625    #[inline]
2626    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2627        #[cfg(feature = "specialization")]
2628        {
2629            spec_traits::SpecExtend::<&'a T, _>::spec_extend(self, iter.into_iter());
2630        }
2631
2632        #[cfg(not(feature = "specialization"))]
2633        {
2634            self.extend_fallback(iter.into_iter().cloned());
2635        }
2636    }
2637}
2638
2639impl<T, const N: usize> core::iter::FromIterator<T> for SmallVec<T, N> {
2640    #[inline]
2641    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2642        #[cfg(feature = "specialization")]
2643        {
2644            spec_traits::SpecFromIterator::<T, _>::spec_from_iter(iter.into_iter())
2645        }
2646
2647        #[cfg(not(feature = "specialization"))]
2648        {
2649            Self::from_iter_fallback(iter.into_iter())
2650        }
2651    }
2652}
2653
2654#[macro_export]
2655macro_rules! smallvec {
2656    // count helper: transform any expression into 1
2657    (@one $x:expr) => (1usize);
2658    () => (
2659        $crate::SmallVec::new()
2660    );
2661    ($elem:expr; $n:expr) => ({
2662        $crate::from_elem($elem, $n)
2663    });
2664    ($($x:expr),+$(,)?) => ({
2665        const COUNT: usize = 0usize $(+ $crate::smallvec!(@one $x))+;
2666        let mut vec = $crate::SmallVec::new();
2667        if COUNT <= vec.capacity() {
2668            $(vec.push($x);)*
2669            vec
2670        } else {
2671            $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
2672        }
2673    });
2674}
2675
2676#[macro_export]
2677macro_rules! smallvec_inline {
2678    // count helper: transform any expression into 1
2679    (@one $x:expr) => (1usize);
2680    ($elem:expr; $n:expr) => ({
2681        $crate::SmallVec::<_, $n>::from_buf([$elem; $n])
2682    });
2683    ($($x:expr),+ $(,)?) => ({
2684        const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
2685        $crate::SmallVec::<_, N>::from_buf([$($x,)*])
2686    });
2687}
2688
2689impl<T, const N: usize> IntoIterator for SmallVec<T, N> {
2690    type IntoIter = IntoIter<T, N>;
2691    type Item = T;
2692    fn into_iter(self) -> Self::IntoIter {
2693        // SAFETY: we move out of this.raw by reading the value at its address, which is fine since
2694        // we don't drop it
2695        unsafe {
2696            // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements
2697            let this = ManuallyDrop::new(self);
2698            IntoIter {
2699                raw: (&this.raw as *const RawSmallVec<T, N>).read(),
2700                begin: 0,
2701                end: this.len,
2702                _marker: PhantomData,
2703            }
2704        }
2705    }
2706}
2707
2708impl<'a, T, const N: usize> IntoIterator for &'a SmallVec<T, N> {
2709    type IntoIter = core::slice::Iter<'a, T>;
2710    type Item = &'a T;
2711    fn into_iter(self) -> Self::IntoIter {
2712        self.iter()
2713    }
2714}
2715
2716impl<'a, T, const N: usize> IntoIterator for &'a mut SmallVec<T, N> {
2717    type IntoIter = core::slice::IterMut<'a, T>;
2718    type Item = &'a mut T;
2719    fn into_iter(self) -> Self::IntoIter {
2720        self.iter_mut()
2721    }
2722}
2723
2724impl<T, U, const N: usize, const M: usize> PartialEq<SmallVec<U, M>> for SmallVec<T, N>
2725where
2726    T: PartialEq<U>,
2727{
2728    #[inline]
2729    fn eq(&self, other: &SmallVec<U, M>) -> bool {
2730        self.as_slice().eq(other.as_slice())
2731    }
2732}
2733impl<T, const N: usize> Eq for SmallVec<T, N> where T: Eq {}
2734
2735impl<T, U, const N: usize, const M: usize> PartialEq<[U; M]> for SmallVec<T, N>
2736where
2737    T: PartialEq<U>,
2738{
2739    #[inline]
2740    fn eq(&self, other: &[U; M]) -> bool {
2741        self[..] == other[..]
2742    }
2743}
2744
2745impl<T, U, const N: usize, const M: usize> PartialEq<&[U; M]> for SmallVec<T, N>
2746where
2747    T: PartialEq<U>,
2748{
2749    #[inline]
2750    fn eq(&self, other: &&[U; M]) -> bool {
2751        self[..] == other[..]
2752    }
2753}
2754
2755impl<T, U, const N: usize> PartialEq<[U]> for SmallVec<T, N>
2756where
2757    T: PartialEq<U>,
2758{
2759    #[inline]
2760    fn eq(&self, other: &[U]) -> bool {
2761        self[..] == other[..]
2762    }
2763}
2764
2765impl<T, U, const N: usize> PartialEq<&[U]> for SmallVec<T, N>
2766where
2767    T: PartialEq<U>,
2768{
2769    #[inline]
2770    fn eq(&self, other: &&[U]) -> bool {
2771        self[..] == other[..]
2772    }
2773}
2774
2775impl<T, U, const N: usize> PartialEq<&mut [U]> for SmallVec<T, N>
2776where
2777    T: PartialEq<U>,
2778{
2779    #[inline]
2780    fn eq(&self, other: &&mut [U]) -> bool {
2781        self[..] == other[..]
2782    }
2783}
2784
2785impl<T, const N: usize> PartialOrd for SmallVec<T, N>
2786where
2787    T: PartialOrd,
2788{
2789    #[inline]
2790    fn partial_cmp(&self, other: &SmallVec<T, N>) -> Option<core::cmp::Ordering> {
2791        self.as_slice().partial_cmp(other.as_slice())
2792    }
2793}
2794
2795impl<T, const N: usize> Ord for SmallVec<T, N>
2796where
2797    T: Ord,
2798{
2799    #[inline]
2800    fn cmp(&self, other: &SmallVec<T, N>) -> core::cmp::Ordering {
2801        self.as_slice().cmp(other.as_slice())
2802    }
2803}
2804
2805impl<T: Hash, const N: usize> Hash for SmallVec<T, N> {
2806    fn hash<H: Hasher>(&self, state: &mut H) {
2807        self.as_slice().hash(state)
2808    }
2809}
2810
2811impl<T, const N: usize> Borrow<[T]> for SmallVec<T, N> {
2812    #[inline]
2813    fn borrow(&self) -> &[T] {
2814        self.as_slice()
2815    }
2816}
2817
2818impl<T, const N: usize> BorrowMut<[T]> for SmallVec<T, N> {
2819    #[inline]
2820    fn borrow_mut(&mut self) -> &mut [T] {
2821        self.as_mut_slice()
2822    }
2823}
2824
2825impl<T, const N: usize> AsRef<[T]> for SmallVec<T, N> {
2826    #[inline]
2827    fn as_ref(&self) -> &[T] {
2828        self.as_slice()
2829    }
2830}
2831
2832impl<T, const N: usize> AsMut<[T]> for SmallVec<T, N> {
2833    #[inline]
2834    fn as_mut(&mut self) -> &mut [T] {
2835        self.as_mut_slice()
2836    }
2837}
2838
2839impl<T: Debug, const N: usize> Debug for SmallVec<T, N> {
2840    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2841        f.debug_list().entries(self.iter()).finish()
2842    }
2843}
2844
2845impl<T: Debug, const N: usize> Debug for IntoIter<T, N> {
2846    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2847        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2848    }
2849}
2850
2851impl<T: Debug, const N: usize> Debug for Drain<'_, T, N> {
2852    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2853        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2854    }
2855}
2856
2857#[cfg(feature = "serde")]
2858#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2859impl<T, const N: usize> Serialize for SmallVec<T, N>
2860where
2861    T: Serialize,
2862{
2863    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2864        let mut state = serializer.serialize_seq(Some(self.len()))?;
2865        for item in self {
2866            state.serialize_element(item)?;
2867        }
2868        state.end()
2869    }
2870}
2871
2872#[cfg(feature = "serde")]
2873#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2874impl<'de, T, const N: usize> Deserialize<'de> for SmallVec<T, N>
2875where
2876    T: Deserialize<'de>,
2877{
2878    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2879        deserializer.deserialize_seq(SmallVecVisitor {
2880            phantom: PhantomData,
2881        })
2882    }
2883}
2884
2885#[cfg(feature = "serde")]
2886struct SmallVecVisitor<T, const N: usize> {
2887    phantom: PhantomData<T>,
2888}
2889
2890#[cfg(feature = "serde")]
2891impl<'de, T, const N: usize> Visitor<'de> for SmallVecVisitor<T, N>
2892where
2893    T: Deserialize<'de>,
2894{
2895    type Value = SmallVec<T, N>;
2896
2897    fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2898        formatter.write_str("a sequence")
2899    }
2900
2901    fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2902    where
2903        B: SeqAccess<'de>,
2904    {
2905        use serde_core::de::Error;
2906        let len = seq.size_hint().unwrap_or(0);
2907        let mut values = SmallVec::new();
2908        values.try_reserve(len).map_err(B::Error::custom)?;
2909
2910        while let Some(value) = seq.next_element()? {
2911            values.push(value);
2912        }
2913
2914        Ok(values)
2915    }
2916}
2917
2918#[cfg(feature = "malloc_size_of")]
2919impl<T, const N: usize> MallocShallowSizeOf for SmallVec<T, N> {
2920    fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2921        if self.spilled() {
2922            unsafe { ops.malloc_size_of(self.as_ptr()) }
2923        } else {
2924            0
2925        }
2926    }
2927}
2928
2929#[cfg(feature = "malloc_size_of")]
2930impl<T: MallocSizeOf, const N: usize> MallocSizeOf for SmallVec<T, N> {
2931    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2932        let mut n = self.shallow_size_of(ops);
2933        for elem in self.iter() {
2934            n += elem.size_of(ops);
2935        }
2936        n
2937    }
2938}
2939
2940#[cfg(feature = "std")]
2941#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2942impl<const N: usize> io::Write for SmallVec<u8, N> {
2943    #[inline]
2944    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2945        self.extend_from_slice(buf);
2946        Ok(buf.len())
2947    }
2948
2949    #[inline]
2950    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2951        self.extend_from_slice(buf);
2952        Ok(())
2953    }
2954
2955    #[inline]
2956    fn flush(&mut self) -> io::Result<()> {
2957        Ok(())
2958    }
2959}
2960
2961#[cfg(feature = "bytes")]
2962unsafe impl<const N: usize> BufMut for SmallVec<u8, N> {
2963    #[inline]
2964    fn remaining_mut(&self) -> usize {
2965        // A vector can never have more than isize::MAX bytes
2966        isize::MAX as usize - self.len()
2967    }
2968
2969    #[inline]
2970    unsafe fn advance_mut(&mut self, cnt: usize) {
2971        let len = self.len();
2972        let remaining = self.capacity() - len;
2973
2974        if remaining < cnt {
2975            panic!("advance out of bounds: the len is {remaining} but advancing by {cnt}");
2976        }
2977
2978        // Addition will not overflow since the sum is at most the capacity.
2979        self.set_len(len + cnt);
2980    }
2981
2982    #[inline]
2983    fn chunk_mut(&mut self) -> &mut UninitSlice {
2984        if self.capacity() == self.len() {
2985            self.reserve(64); // Grow the smallvec
2986        }
2987
2988        let cap = self.capacity();
2989        let len = self.len();
2990
2991        let ptr = self.as_mut_ptr();
2992        // SAFETY: Since `ptr` is valid for `cap` bytes, `ptr.add(len)` must be
2993        // valid for `cap - len` bytes. The subtraction will not underflow since
2994        // `len <= cap`.
2995        unsafe { UninitSlice::from_raw_parts_mut(ptr.add(len), cap - len) }
2996    }
2997
2998    // Specialize these methods so they can skip checking `remaining_mut`
2999    // and `advance_mut`.
3000    #[inline]
3001    fn put<T: bytes::Buf>(&mut self, mut src: T)
3002    where
3003        Self: Sized,
3004    {
3005        // In case the src isn't contiguous, reserve upfront.
3006        self.reserve(src.remaining());
3007
3008        while src.has_remaining() {
3009            let s = src.chunk();
3010            let l = s.len();
3011            self.extend_from_slice(s);
3012            src.advance(l);
3013        }
3014    }
3015
3016    #[inline]
3017    fn put_slice(&mut self, src: &[u8]) {
3018        self.extend_from_slice(src);
3019    }
3020
3021    #[inline]
3022    fn put_bytes(&mut self, val: u8, cnt: usize) {
3023        // If the addition overflows, then the `resize` will fail.
3024        let new_len = self.len().saturating_add(cnt);
3025        self.resize(new_len, val);
3026    }
3027}