Skip to main content

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
8//! inline, and fall back to the heap for larger allocations.  This can be a
9//! useful optimization for improving cache locality and reducing allocator
10//! traffic for workloads that fit within the inline buffer.
11//!
12//! ## `no_std` support
13//!
14//! By default, `smallvec` does not depend on `std`.  However, the optional
15//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
16//! When this feature is enabled, `smallvec` depends on `std`.
17//!
18//! ## Optional features
19//!
20//! ### `serde`
21//!
22//! When this optional dependency is enabled, `SmallVec` implements the
23//! `serde::Serialize` and `serde::Deserialize` traits.
24//!
25//! ### `write`
26//!
27//! When this feature is enabled, `SmallVec<[u8; _]>` implements the
28//! `std::io::Write` trait. This feature is not compatible with `#![no_std]`
29//! programs.
30//!
31//! ### `union`
32//!
33//! **This feature requires Rust 1.49.**
34//!
35//! When the `union` feature is enabled `smallvec` will track its state (inline
36//! or spilled) without the use of an enum tag, reducing the size of the
37//! `smallvec` by one machine word. This means that there is potentially no
38//! space overhead compared to `Vec`. Note that `smallvec` can still be larger
39//! than `Vec` if the inline buffer is larger than two machine words.
40//!
41//! To use this feature add `features = ["union"]` in the `smallvec` section of
42//! Cargo.toml. Note that this feature requires Rust 1.49.
43//!
44//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
45//!
46//! ### `const_generics`
47//!
48//! **This feature requires Rust 1.51.**
49//!
50//! When this feature is enabled, `SmallVec` works with any arrays of any size,
51//! not just a fixed list of sizes.
52//!
53//! ### `const_new`
54//!
55//! **This feature requires Rust 1.51.**
56//!
57//! This feature exposes the functions [`SmallVec::new_const`],
58//! [`SmallVec::from_const`], and [`smallvec_inline`] which enables the
59//! `SmallVec` to be initialized from a const context. For details, see the
60//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
61//!
62//! ### `drain_filter`
63//!
64//! **This feature is unstable.** It may change to match the unstable
65//! `drain_filter` method in libstd.
66//!
67//! Enables the `drain_filter` method, which produces an iterator that calls a
68//! user-provided closure to determine which elements of the vector to remove
69//! and yield from the iterator.
70//!
71//! ### `drain_keep_rest`
72//!
73//! **This feature is unstable.** It may change to match the unstable
74//! `drain_keep_rest` method in libstd.
75//!
76//! Enables the `DrainFilter::keep_rest` method.
77//!
78//! ### `specialization`
79//!
80//! **This feature is unstable and requires a nightly build of the Rust
81//! toolchain.**
82//!
83//! When this feature is enabled, `SmallVec::from(slice)` has improved
84//! performance for slices of `Copy` types.  (Without this feature, you can use
85//! `SmallVec::from_slice` to get optimal performance for `Copy` types.)
86//!
87//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
88//!
89//! ### `may_dangle`
90//!
91//! **This feature is unstable and requires a nightly build of the Rust
92//! toolchain.**
93//!
94//! This feature makes the Rust compiler less strict about use of vectors that
95//! contain borrowed references. For details, see the
96//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
97//!
98//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
99
100#![no_std]
101#![cfg_attr(docsrs, feature(doc_cfg))]
102#![cfg_attr(feature = "specialization", allow(incomplete_features))]
103#![cfg_attr(feature = "specialization", feature(specialization))]
104#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
105#![deny(missing_docs)]
106
107#[doc(hidden)]
108pub extern crate alloc;
109
110#[cfg(any(test, feature = "write"))]
111extern crate std;
112
113#[cfg(test)]
114mod tests;
115
116#[cfg(feature = "drain_keep_rest")]
117use core::mem::ManuallyDrop;
118#[cfg(feature = "malloc_size_of")]
119use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
120#[cfg(feature = "serde")]
121use serde::{
122    de::{Deserialize, Deserializer, SeqAccess, Visitor},
123    ser::{Serialize, SerializeSeq, Serializer},
124};
125#[cfg(feature = "write")]
126use std::io;
127#[allow(deprecated)]
128use {
129    alloc::{
130        alloc::{Layout, LayoutErr},
131        boxed::Box,
132        vec,
133        vec::Vec,
134    },
135    core::{
136        borrow::{Borrow, BorrowMut},
137        cmp, fmt,
138        hash::{Hash, Hasher},
139        hint::unreachable_unchecked,
140        iter::{repeat, FromIterator, FusedIterator, IntoIterator},
141        marker::PhantomData,
142        mem::{self, MaybeUninit},
143        ops::{self, Range, RangeBounds},
144        ptr::{self, NonNull},
145        slice::{self, SliceIndex},
146    },
147};
148
149/// Creates a [`SmallVec`] containing the arguments.
150///
151/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array
152/// expressions. There are two forms of this macro:
153///
154/// - Create a [`SmallVec`] containing a given list of elements:
155///
156/// ```
157/// # use smallvec::{smallvec, SmallVec};
158/// # fn main() {
159/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
160/// assert_eq!(v[0], 1);
161/// assert_eq!(v[1], 2);
162/// assert_eq!(v[2], 3);
163/// # }
164/// ```
165///
166/// - Create a [`SmallVec`] from a given element and size:
167///
168/// ```
169/// # use smallvec::{smallvec, SmallVec};
170/// # fn main() {
171/// let v: SmallVec<[_; 10]> = smallvec![1; 3];
172/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
173/// # }
174/// ```
175///
176/// Note that unlike array expressions this syntax supports all elements
177/// which implement [`Clone`] and the number of elements doesn't have to be
178/// a constant.
179///
180/// This will use `clone` to duplicate an expression, so one should be careful
181/// using this with types having a nonstandard `Clone` implementation. For
182/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
183/// to the same boxed integer value, not five references pointing to
184/// independently boxed integers.
185#[macro_export]
186macro_rules! smallvec {
187    // count helper: transform any expression into 1
188    (@one $x:expr) => (1usize);
189    () => (
190        $crate::SmallVec::new()
191    );
192    ($elem:expr; $n:expr) => ({
193        $crate::SmallVec::from_elem($elem, $n)
194    });
195    ($($x:expr),+$(,)?) => ({
196        let count = 0usize $(+ $crate::smallvec!(@one $x))+;
197        let mut vec = $crate::SmallVec::new();
198        if count <= vec.inline_size() {
199            $(vec.push($x);)*
200            vec
201        } else {
202            $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
203        }
204    });
205}
206
207/// Creates an inline [`SmallVec`] containing the arguments. This macro is
208/// enabled by the feature `const_new`.
209///
210/// `smallvec_inline!` allows `SmallVec`s to be defined with the same syntax as
211/// array expressions in `const` contexts. The inline storage `A` will always be
212/// an array of the size specified by the arguments. There are two forms of this
213/// macro:
214///
215/// - Create a [`SmallVec`] containing a given list of elements:
216///
217/// ```
218/// # use smallvec::{smallvec_inline, SmallVec};
219/// # fn main() {
220/// const V: SmallVec<[i32; 3]> = smallvec_inline![1, 2, 3];
221/// assert_eq!(V[0], 1);
222/// assert_eq!(V[1], 2);
223/// assert_eq!(V[2], 3);
224/// # }
225/// ```
226///
227/// - Create a [`SmallVec`] from a given element and size:
228///
229/// ```
230/// # use smallvec::{smallvec_inline, SmallVec};
231/// # fn main() {
232/// const V: SmallVec<[i32; 3]> = smallvec_inline![1; 3];
233/// assert_eq!(V, SmallVec::from_buf([1, 1, 1]));
234/// # }
235/// ```
236///
237/// Note that the behavior mimics that of array expressions, in contrast to
238/// [`smallvec`].
239#[cfg(feature = "const_new")]
240#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
241#[macro_export]
242macro_rules! smallvec_inline {
243    // count helper: transform any expression into 1
244    (@one $x:expr) => (1usize);
245    ($elem:expr; $n:expr) => ({
246        $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
247    });
248    ($($x:expr),+ $(,)?) => ({
249        const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
250        $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
251    });
252}
253
254/// `panic!()` in debug builds, optimization hint in release.
255#[cfg(not(feature = "union"))]
256macro_rules! debug_unreachable {
257    () => {
258        debug_unreachable!("entered unreachable code")
259    };
260    ($e:expr) => {
261        if cfg!(debug_assertions) {
262            panic!($e);
263        } else {
264            unreachable_unchecked();
265        }
266    };
267}
268
269/// Trait to be implemented by a collection that can be extended from a slice
270///
271/// ## Example
272///
273/// ```rust
274/// use smallvec::{ExtendFromSlice, SmallVec};
275///
276/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
277///     v.extend_from_slice(b"Test!");
278/// }
279///
280/// let mut vec = Vec::new();
281/// initialize(&mut vec);
282/// assert_eq!(&vec, b"Test!");
283///
284/// let mut small_vec = SmallVec::<[u8; 8]>::new();
285/// initialize(&mut small_vec);
286/// assert_eq!(&small_vec as &[_], b"Test!");
287/// ```
288#[doc(hidden)]
289#[deprecated]
290pub trait ExtendFromSlice<T> {
291    /// Extends a collection from a slice of its element type
292    fn extend_from_slice(&mut self, other: &[T]);
293}
294
295#[allow(deprecated)]
296impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
297    fn extend_from_slice(&mut self, other: &[T]) {
298        Vec::extend_from_slice(self, other)
299    }
300}
301
302/// Error type for APIs with fallible heap allocation
303#[derive(Debug)]
304pub enum CollectionAllocErr {
305    /// Overflow `usize::MAX` or other error during size computation
306    CapacityOverflow,
307    /// The allocator return an error
308    AllocErr {
309        /// The layout that was passed to the allocator
310        layout: Layout,
311    },
312}
313
314impl fmt::Display for CollectionAllocErr {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        write!(f, "Allocation error: {:?}", self)
317    }
318}
319
320#[allow(deprecated)]
321impl From<LayoutErr> for CollectionAllocErr {
322    fn from(_: LayoutErr) -> Self {
323        CollectionAllocErr::CapacityOverflow
324    }
325}
326
327fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
328    match result {
329        Ok(x) => x,
330        Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
331        Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
332    }
333}
334
335/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
336/// <https://github.com/rust-lang/rust/issues/55724>
337fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
338    let size = mem::size_of::<T>()
339        .checked_mul(n)
340        .ok_or(CollectionAllocErr::CapacityOverflow)?;
341    let align = mem::align_of::<T>();
342    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
343}
344
345unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
346    // This unwrap should succeed since the same did when allocating.
347    let layout = layout_array::<T>(capacity).unwrap();
348    alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
349}
350
351/// An iterator that removes the items from a `SmallVec` and yields them by
352/// value.
353///
354/// Returned from [`SmallVec::drain`][1].
355///
356/// [1]: struct.SmallVec.html#method.drain
357pub struct Drain<'a, T: 'a + Array> {
358    tail_start: usize,
359    tail_len: usize,
360    iter: slice::Iter<'a, T::Item>,
361    vec: NonNull<SmallVec<T>>,
362}
363
364impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
365where
366    T::Item: fmt::Debug,
367{
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
370    }
371}
372
373unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
374unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
375
376impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
377    type Item = T::Item;
378
379    #[inline]
380    fn next(&mut self) -> Option<T::Item> {
381        self.iter
382            .next()
383            .map(|reference| unsafe { ptr::read(reference) })
384    }
385
386    #[inline]
387    fn size_hint(&self) -> (usize, Option<usize>) {
388        self.iter.size_hint()
389    }
390}
391
392impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
393    #[inline]
394    fn next_back(&mut self) -> Option<T::Item> {
395        self.iter
396            .next_back()
397            .map(|reference| unsafe { ptr::read(reference) })
398    }
399}
400
401impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
402    #[inline]
403    fn len(&self) -> usize {
404        self.iter.len()
405    }
406}
407
408impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
409
410impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
411    fn drop(&mut self) {
412        self.for_each(drop);
413
414        if self.tail_len > 0 {
415            unsafe {
416                let source_vec = self.vec.as_mut();
417
418                // memmove back untouched tail, update to new length
419                let start = source_vec.len();
420                let tail = self.tail_start;
421                if tail != start {
422                    // as_mut_ptr creates a &mut, invalidating other pointers.
423                    // This pattern avoids calling it with a pointer already
424                    // present.
425                    let ptr = source_vec.as_mut_ptr();
426                    let src = ptr.add(tail);
427                    let dst = ptr.add(start);
428                    ptr::copy(src, dst, self.tail_len);
429                }
430                source_vec.set_len(start + self.tail_len);
431            }
432        }
433    }
434}
435
436#[cfg(feature = "drain_filter")]
437/// An iterator which uses a closure to determine if an element should be
438/// removed.
439///
440/// Returned from [`SmallVec::drain_filter`][1].
441///
442/// [1]: struct.SmallVec.html#method.drain_filter
443pub struct DrainFilter<'a, T, F>
444where
445    F: FnMut(&mut T::Item) -> bool,
446    T: Array,
447{
448    vec: &'a mut SmallVec<T>,
449    /// The index of the item that will be inspected by the next call to `next`.
450    idx: usize,
451    /// The number of items that have been drained (removed) thus far.
452    del: usize,
453    /// The original length of `vec` prior to draining.
454    old_len: usize,
455    /// The filter test predicate.
456    pred: F,
457    /// A flag that indicates a panic has occurred in the filter test predicate.
458    /// This is used as a hint in the drop implementation to prevent consumption
459    /// of the remainder of the `DrainFilter`. Any unprocessed items will be
460    /// backshifted in the `vec`, but no further items will be dropped or
461    /// tested by the filter predicate.
462    panic_flag: bool,
463}
464
465#[cfg(feature = "drain_filter")]
466impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
467where
468    F: FnMut(&mut T::Item) -> bool,
469    T: Array,
470    T::Item: fmt::Debug,
471{
472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473        f.debug_tuple("DrainFilter")
474            .field(&self.vec.as_slice())
475            .finish()
476    }
477}
478
479#[cfg(feature = "drain_filter")]
480impl<T, F> Iterator for DrainFilter<'_, T, F>
481where
482    F: FnMut(&mut T::Item) -> bool,
483    T: Array,
484{
485    type Item = T::Item;
486
487    fn next(&mut self) -> Option<T::Item> {
488        unsafe {
489            while self.idx < self.old_len {
490                let i = self.idx;
491                let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
492                self.panic_flag = true;
493                let drained = (self.pred)(&mut v[i]);
494                self.panic_flag = false;
495                // Update the index *after* the predicate is called. If the
496                // index is updated prior and the predicate
497                // panics, the element at this index would be
498                // leaked.
499                self.idx += 1;
500                if drained {
501                    self.del += 1;
502                    return Some(ptr::read(&v[i]));
503                } else if self.del > 0 {
504                    let del = self.del;
505                    let src: *const Self::Item = &v[i];
506                    let dst: *mut Self::Item = &mut v[i - del];
507                    ptr::copy_nonoverlapping(src, dst, 1);
508                }
509            }
510            None
511        }
512    }
513
514    fn size_hint(&self) -> (usize, Option<usize>) {
515        (0, Some(self.old_len - self.idx))
516    }
517}
518
519#[cfg(feature = "drain_filter")]
520impl<T, F> Drop for DrainFilter<'_, T, F>
521where
522    F: FnMut(&mut T::Item) -> bool,
523    T: Array,
524{
525    fn drop(&mut self) {
526        struct BackshiftOnDrop<'a, 'b, T, F>
527        where
528            F: FnMut(&mut T::Item) -> bool,
529            T: Array,
530        {
531            drain: &'b mut DrainFilter<'a, T, F>,
532        }
533
534        impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
535        where
536            F: FnMut(&mut T::Item) -> bool,
537            T: Array,
538        {
539            fn drop(&mut self) {
540                unsafe {
541                    if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
542                        // This is a pretty messed up state, and there isn't
543                        // really an obviously right
544                        // thing to do. We don't want to keep trying
545                        // to execute `pred`, so we just backshift all the
546                        // unprocessed elements and tell
547                        // the vec that they still exist. The backshift
548                        // is required to prevent a double-drop of the last
549                        // successfully drained item
550                        // prior to a panic in the predicate.
551                        let ptr = self.drain.vec.as_mut_ptr();
552                        let src = ptr.add(self.drain.idx);
553                        let dst = src.sub(self.drain.del);
554                        let tail_len = self.drain.old_len - self.drain.idx;
555                        src.copy_to(dst, tail_len);
556                    }
557                    self.drain.vec.set_len(self.drain.old_len - self.drain.del);
558                }
559            }
560        }
561
562        let backshift = BackshiftOnDrop { drain: self };
563
564        // Attempt to consume any remaining elements if the filter predicate
565        // has not yet panicked. We'll backshift any remaining elements
566        // whether we've already panicked or if the consumption here panics.
567        if !backshift.drain.panic_flag {
568            backshift.drain.for_each(drop);
569        }
570    }
571}
572
573#[cfg(feature = "drain_keep_rest")]
574impl<T, F> DrainFilter<'_, T, F>
575where
576    F: FnMut(&mut T::Item) -> bool,
577    T: Array,
578{
579    /// Keep unyielded elements in the source `Vec`.
580    ///
581    /// # Examples
582    ///
583    /// ```
584    /// # use smallvec::{smallvec, SmallVec};
585    ///
586    /// let mut vec: SmallVec<[char; 2]> = smallvec!['a', 'b', 'c'];
587    /// let mut drain = vec.drain_filter(|_| true);
588    ///
589    /// assert_eq!(drain.next().unwrap(), 'a');
590    ///
591    /// // This call keeps 'b' and 'c' in the vec.
592    /// drain.keep_rest();
593    ///
594    /// // If we wouldn't call `keep_rest()`,
595    /// // `vec` would be empty.
596    /// assert_eq!(vec, SmallVec::<[char; 2]>::from_slice(&['b', 'c']));
597    /// ```
598    pub fn keep_rest(self) {
599        // At this moment layout looks like this:
600        //
601        //  _____________________/-- old_len
602        // /                     \
603        // [kept] [yielded] [tail]
604        //        \_______/ ^-- idx
605        //                \-- del
606        //
607        // Normally `Drop` impl would drop [tail] (via .for_each(drop), ie still
608        // calling `pred`)
609        //
610        // 1. Move [tail] after [kept]
611        // 2. Update length of the original vec to `old_len - del` a. In case of
612        //    ZST, this is the only thing we want to do
613        // 3. Do *not* drop self, as everything is put in a consistent state
614        //    already, there is nothing to do
615        let mut this = ManuallyDrop::new(self);
616
617        unsafe {
618            // ZSTs have no identity, so we don't need to move them around.
619            let needs_move = mem::size_of::<T::Item>() != 0;
620
621            if needs_move && this.idx < this.old_len && this.del > 0 {
622                let ptr = this.vec.as_mut_ptr();
623                let src = ptr.add(this.idx);
624                let dst = src.sub(this.del);
625                let tail_len = this.old_len - this.idx;
626                src.copy_to(dst, tail_len);
627            }
628
629            let new_len = this.old_len - this.del;
630            this.vec.set_len(new_len);
631        }
632    }
633}
634
635#[cfg(feature = "union")]
636union SmallVecData<A: Array> {
637    inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
638    heap: (NonNull<A::Item>, usize),
639}
640
641#[cfg(all(feature = "union", feature = "const_new"))]
642impl<T, const N: usize> SmallVecData<[T; N]> {
643    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
644    #[inline]
645    const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
646        SmallVecData {
647            inline: core::mem::ManuallyDrop::new(inline),
648        }
649    }
650}
651
652#[cfg(feature = "union")]
653impl<A: Array> SmallVecData<A> {
654    #[inline]
655    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
656        ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
657    }
658    #[inline]
659    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
660        NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
661    }
662    #[inline]
663    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
664        SmallVecData {
665            inline: core::mem::ManuallyDrop::new(inline),
666        }
667    }
668    // Workaround for https://github.com/rust-lang/rust/issues/157743: when from_inline is
669    // called with MaybeUninit::uninit(), rustc 1.93+ GVN propagates const
670    // <uninit> into the ManuallyDrop::new() aggregate, causing LLVM to
671    // materialize a global constant that MemCpyOpt then collapses into a
672    // memset over the whole struct. Using assume_init() of a doubly-wrapped
673    // MaybeUninit produces Immediate::Uninit instead of const <uninit>,
674    // which codegen handles as undef without emitting any global. This
675    // function also avoids introducing an intermediate local that would
676    // inflate stack frames in debug builds.
677    #[inline]
678    fn empty() -> SmallVecData<A> {
679        // SAFETY: ManuallyDrop<MaybeUninit<A>> is valid for any bit pattern
680        // including uninitialized bytes, so assume_init() on a
681        // MaybeUninit of that type is sound.
682        SmallVecData {
683            inline: unsafe { MaybeUninit::uninit().assume_init() },
684        }
685    }
686    #[inline]
687    unsafe fn into_inline(self) -> MaybeUninit<A> {
688        core::mem::ManuallyDrop::into_inner(self.inline)
689    }
690    #[inline]
691    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
692        (ConstNonNull(self.heap.0), self.heap.1)
693    }
694    #[inline]
695    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
696        let h = &mut self.heap;
697        (h.0, &mut h.1)
698    }
699    #[inline]
700    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
701        SmallVecData { heap: (ptr, len) }
702    }
703}
704
705#[cfg(not(feature = "union"))]
706enum SmallVecData<A: Array> {
707    Inline(MaybeUninit<A>),
708    // Using NonNull and NonZero here allows to reduce size of `SmallVec`.
709    Heap {
710        // Since we never allocate on heap
711        // unless our capacity is bigger than inline capacity
712        // heap capacity cannot be less than 1.
713        // Therefore, pointer cannot be null too.
714        ptr: NonNull<A::Item>,
715        len: usize,
716    },
717}
718
719#[cfg(all(not(feature = "union"), feature = "const_new"))]
720impl<T, const N: usize> SmallVecData<[T; N]> {
721    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
722    #[inline]
723    const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
724        SmallVecData::Inline(inline)
725    }
726}
727
728#[cfg(not(feature = "union"))]
729impl<A: Array> SmallVecData<A> {
730    #[inline]
731    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
732        match self {
733            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
734            _ => debug_unreachable!(),
735        }
736    }
737    #[inline]
738    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
739        match self {
740            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
741            _ => debug_unreachable!(),
742        }
743    }
744    #[inline]
745    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
746        SmallVecData::Inline(inline)
747    }
748    // See the comment on the union variant's empty() for why this exists.
749    #[inline]
750    fn empty() -> SmallVecData<A> {
751        // SAFETY: MaybeUninit<A> is valid for any bit pattern including
752        // uninitialized bytes, so assume_init() on a MaybeUninit of
753        // that type is sound.
754        SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
755    }
756    #[inline]
757    unsafe fn into_inline(self) -> MaybeUninit<A> {
758        match self {
759            SmallVecData::Inline(a) => a,
760            _ => debug_unreachable!(),
761        }
762    }
763    #[inline]
764    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
765        match self {
766            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
767            _ => debug_unreachable!(),
768        }
769    }
770    #[inline]
771    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
772        match self {
773            SmallVecData::Heap { ptr, len } => (*ptr, len),
774            _ => debug_unreachable!(),
775        }
776    }
777    #[inline]
778    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
779        SmallVecData::Heap { ptr, len }
780    }
781}
782
783unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
784unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
785
786/// A `Vec`-like container that can store a small number of elements inline.
787///
788/// `SmallVec` acts like a vector, but can store a limited amount of data inline
789/// within the `SmallVec` struct rather than in a separate allocation.  If the
790/// data exceeds this limit, the `SmallVec` will "spill" its data onto the heap,
791/// allocating a new buffer to hold it.
792///
793/// The amount of data that a `SmallVec` can store inline depends on its backing
794/// store. The backing store can be any type that implements the `Array` trait;
795/// usually it is a small fixed-sized array.  For example a `SmallVec<[u64; 8]>`
796/// can hold up to eight 64-bit integers inline.
797///
798/// ## Example
799///
800/// ```rust
801/// use smallvec::SmallVec;
802/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
803///
804/// // The vector can hold up to 4 items without spilling onto the heap.
805/// v.extend(0..4);
806/// assert_eq!(v.len(), 4);
807/// assert!(!v.spilled());
808///
809/// // Pushing another element will force the buffer to spill:
810/// v.push(4);
811/// assert_eq!(v.len(), 5);
812/// assert!(v.spilled());
813/// ```
814///
815/// References used by an element's destructor must outlive the vector, even
816/// with the `may_dangle` feature and no inline storage:
817///
818/// ```compile_fail,E0597
819/// use smallvec::SmallVec;
820///
821/// struct PrintOnDrop<'a>(&'a str);
822/// impl Drop for PrintOnDrop<'_> {
823///     fn drop(&mut self) {
824///         println!("{}", self.0);
825///     }
826/// }
827///
828/// let mut v = SmallVec::<[PrintOnDrop<'_>; 0]>::new();
829/// let text = String::from("borrowed");
830/// v.push(PrintOnDrop(&text));
831/// // `text` is dropped before `v`, whose elements still need it.
832/// ```
833pub struct SmallVec<A: Array> {
834    // The capacity field is used to determine which of the storage variants is
835    // active: If capacity <= Self::inline_capacity() then the inline variant is
836    // used and capacity holds the current length of the vector (number of
837    // elements actually in use). If capacity > Self::inline_capacity() then the
838    // heap variant is used and capacity holds the size of the
839    // memory allocation.
840    capacity: usize,
841    data: SmallVecData<A>,
842    // Own A::Item, including when A has length zero and all items are on the
843    // heap. This is required for sound drop checking with #[may_dangle].
844    _marker: PhantomData<A::Item>,
845}
846
847impl<A: Array> SmallVec<A> {
848    /// Construct an empty vector
849    #[inline]
850    pub fn new() -> SmallVec<A> {
851        // Try to detect invalid custom implementations of `Array`. Hopefully,
852        // this check should be optimized away entirely for valid ones.
853        assert!(
854            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
855                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
856        );
857        SmallVec {
858            capacity: 0,
859            data: SmallVecData::empty(),
860            _marker: PhantomData,
861        }
862    }
863
864    /// Construct an empty vector with enough capacity pre-allocated to store at
865    /// least `n` elements.
866    ///
867    /// Will create a heap allocation only if `n` is larger than the inline
868    /// capacity.
869    ///
870    /// ```
871    /// # use smallvec::SmallVec;
872    ///
873    /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
874    ///
875    /// assert!(v.is_empty());
876    /// assert!(v.capacity() >= 100);
877    /// ```
878    #[inline]
879    pub fn with_capacity(n: usize) -> Self {
880        let mut v = SmallVec::new();
881        v.reserve_exact(n);
882        v
883    }
884
885    /// Construct a new `SmallVec` from a `Vec<A::Item>`.
886    ///
887    /// Elements will be copied to the inline buffer if `vec.capacity() <=
888    /// Self::inline_capacity()`.
889    ///
890    /// ```rust
891    /// use smallvec::SmallVec;
892    ///
893    /// let vec = vec![1, 2, 3, 4, 5];
894    /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
895    ///
896    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
897    /// ```
898    #[inline]
899    pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
900        if vec.capacity() <= Self::inline_capacity() {
901            // Cannot use Vec with smaller capacity
902            // because we use value of `Self::capacity` field as indicator.
903            unsafe {
904                let mut data = SmallVecData::<A>::empty();
905                let len = vec.len();
906                vec.set_len(0);
907                ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
908
909                SmallVec {
910                    capacity: len,
911                    data,
912                    _marker: PhantomData,
913                }
914            }
915        } else {
916            let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
917            mem::forget(vec);
918            let ptr = NonNull::new(ptr)
919                // See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
920                .expect("Cannot be null by `Vec` invariant");
921
922            SmallVec {
923                capacity: cap,
924                data: SmallVecData::from_heap(ptr, len),
925                _marker: PhantomData,
926            }
927        }
928    }
929
930    /// Constructs a new `SmallVec` on the stack from an `A` without
931    /// copying elements.
932    ///
933    /// ```rust
934    /// use smallvec::SmallVec;
935    ///
936    /// let buf = [1, 2, 3, 4, 5];
937    /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
938    ///
939    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
940    /// ```
941    #[inline]
942    pub fn from_buf(buf: A) -> SmallVec<A> {
943        SmallVec {
944            capacity: A::size(),
945            data: SmallVecData::from_inline(MaybeUninit::new(buf)),
946            _marker: PhantomData,
947        }
948    }
949
950    /// Constructs a new `SmallVec` on the stack from an `A` without
951    /// copying elements. Also sets the length, which must be less or
952    /// equal to the size of `buf`.
953    ///
954    /// ```rust
955    /// use smallvec::SmallVec;
956    ///
957    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
958    /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
959    ///
960    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
961    /// ```
962    #[inline]
963    pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
964        assert!(len <= A::size());
965        unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
966    }
967
968    /// Constructs a new `SmallVec` on the stack from an `A` without
969    /// copying elements. Also sets the length. The user is responsible
970    /// for ensuring that `len <= A::size()`.
971    ///
972    /// ```rust
973    /// use {smallvec::SmallVec, std::mem::MaybeUninit};
974    ///
975    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
976    /// let small_vec: SmallVec<_> =
977    ///     unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) };
978    ///
979    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
980    /// ```
981    #[inline]
982    pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
983        SmallVec {
984            capacity: len,
985            data: SmallVecData::from_inline(buf),
986            _marker: PhantomData,
987        }
988    }
989
990    /// Sets the length of a vector.
991    ///
992    /// This will explicitly set the size of the vector, without actually
993    /// modifying its buffers, so it is up to the caller to ensure that the
994    /// vector is actually the specified size.
995    pub unsafe fn set_len(&mut self, new_len: usize) {
996        let (_, len_ptr, _) = self.triple_mut();
997        *len_ptr = new_len;
998    }
999
1000    /// The maximum number of elements this vector can hold inline
1001    #[inline]
1002    fn inline_capacity() -> usize {
1003        if mem::size_of::<A::Item>() > 0 {
1004            A::size()
1005        } else {
1006            // For zero-size items code like `ptr.add(offset)` always returns
1007            // the same pointer. Therefore all items are at the same
1008            // address, and any array size has capacity for
1009            // infinitely many items. The capacity is limited by the
1010            // bit width of the length field.
1011            //
1012            // `Vec` also does this:
1013            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
1014            //
1015            // In our case, this also ensures that a smallvec of zero-size items
1016            // never spills, and we never try to allocate zero bytes
1017            // which `std::alloc::alloc` disallows.
1018            #[allow(deprecated)]
1019            core::usize::MAX
1020        }
1021    }
1022
1023    /// The maximum number of elements this vector can hold inline
1024    #[inline]
1025    pub fn inline_size(&self) -> usize {
1026        Self::inline_capacity()
1027    }
1028
1029    /// The number of elements stored in the vector
1030    #[inline]
1031    pub fn len(&self) -> usize {
1032        self.triple().1
1033    }
1034
1035    /// Returns `true` if the vector is empty
1036    #[inline]
1037    pub fn is_empty(&self) -> bool {
1038        self.len() == 0
1039    }
1040
1041    /// The number of items the vector can hold without reallocating
1042    #[inline]
1043    pub fn capacity(&self) -> usize {
1044        self.triple().2
1045    }
1046
1047    /// Returns a tuple with (data ptr, len, capacity)
1048    /// Useful to get all `SmallVec` properties with a single check of the
1049    /// current storage variant.
1050    #[inline]
1051    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1052        unsafe {
1053            if self.spilled() {
1054                let (ptr, len) = self.data.heap();
1055                (ptr, len, self.capacity)
1056            } else {
1057                (self.data.inline(), self.capacity, Self::inline_capacity())
1058            }
1059        }
1060    }
1061
1062    /// Returns a tuple with (data ptr, len ptr, capacity)
1063    #[inline]
1064    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1065        unsafe {
1066            if self.spilled() {
1067                let (ptr, len_ptr) = self.data.heap_mut();
1068                (ptr, len_ptr, self.capacity)
1069            } else {
1070                (
1071                    self.data.inline_mut(),
1072                    &mut self.capacity,
1073                    Self::inline_capacity(),
1074                )
1075            }
1076        }
1077    }
1078
1079    /// Returns `true` if the data has spilled into a separate heap-allocated
1080    /// buffer.
1081    #[inline]
1082    pub fn spilled(&self) -> bool {
1083        self.capacity > Self::inline_capacity()
1084    }
1085
1086    /// Creates a draining iterator that removes the specified range in the
1087    /// vector and yields the removed items.
1088    ///
1089    /// Note 1: The element range is removed even if the iterator is only
1090    /// partially consumed or not consumed at all.
1091    ///
1092    /// Note 2: It is unspecified how many elements are removed from the vector
1093    /// if the `Drain` value is leaked.
1094    ///
1095    /// # Panics
1096    ///
1097    /// Panics if the starting point is greater than the end point or if
1098    /// the end point is greater than the length of the vector.
1099    pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1100    where
1101        R: RangeBounds<usize>,
1102    {
1103        use core::ops::Bound::*;
1104
1105        let len = self.len();
1106        let start = match range.start_bound() {
1107            Included(&n) => n,
1108            Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1109            Unbounded => 0,
1110        };
1111        let end = match range.end_bound() {
1112            Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1113            Excluded(&n) => n,
1114            Unbounded => len,
1115        };
1116
1117        assert!(start <= end);
1118        assert!(end <= len);
1119
1120        unsafe {
1121            self.set_len(start);
1122
1123            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1124
1125            Drain {
1126                tail_start: end,
1127                tail_len: len - end,
1128                iter: range_slice.iter(),
1129                // Since self is a &mut, passing it to a function would
1130                // invalidate the slice iterator.
1131                vec: NonNull::new_unchecked(self as *mut _),
1132            }
1133        }
1134    }
1135
1136    #[cfg(feature = "drain_filter")]
1137    /// Creates an iterator which uses a closure to determine if an element
1138    /// should be removed.
1139    ///
1140    /// If the closure returns true, the element is removed and yielded. If the
1141    /// closure returns false, the element will remain in the vector and
1142    /// will not be yielded by the iterator.
1143    ///
1144    /// Using this method is equivalent to the following code:
1145    /// ```
1146    /// # use smallvec::SmallVec;
1147    /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1148    /// # let mut vec: SmallVec<[i32; 8]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6]);
1149    /// let mut i = 0;
1150    /// while i < vec.len() {
1151    ///     if some_predicate(&mut vec[i]) {
1152    ///         let val = vec.remove(i);
1153    ///         // your code here
1154    ///     } else {
1155    ///         i += 1;
1156    ///     }
1157    /// }
1158    ///
1159    /// # assert_eq!(vec, SmallVec::<[i32; 8]>::from_slice(&[1i32, 4, 5]));
1160    /// ```
1161    /// ///
1162    /// But `drain_filter` is easier to use. `drain_filter` is also more
1163    /// efficient, because it can backshift the elements of the array in
1164    /// bulk.
1165    ///
1166    /// Note that `drain_filter` also lets you mutate every element in the
1167    /// filter closure, regardless of whether you choose to keep or remove
1168    /// it.
1169    ///
1170    /// # Examples
1171    ///
1172    /// Splitting an array into evens and odds, reusing the original allocation:
1173    ///
1174    /// ```
1175    /// # use smallvec::SmallVec;
1176    /// let mut numbers: SmallVec<[i32; 16]> =
1177    ///     SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1178    ///
1179    /// let evens = numbers
1180    ///     .drain_filter(|x| *x % 2 == 0)
1181    ///     .collect::<SmallVec<[i32; 16]>>();
1182    /// let odds = numbers;
1183    ///
1184    /// assert_eq!(
1185    ///     evens,
1186    ///     SmallVec::<[i32; 16]>::from_slice(&[2i32, 4, 6, 8, 14])
1187    /// );
1188    /// assert_eq!(
1189    ///     odds,
1190    ///     SmallVec::<[i32; 16]>::from_slice(&[1i32, 3, 5, 9, 11, 13, 15])
1191    /// );
1192    /// ```
1193    pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1194    where
1195        F: FnMut(&mut A::Item) -> bool,
1196    {
1197        let old_len = self.len();
1198
1199        // Guard against us getting leaked (leak amplification)
1200        unsafe {
1201            self.set_len(0);
1202        }
1203
1204        DrainFilter {
1205            vec: self,
1206            idx: 0,
1207            del: 0,
1208            old_len,
1209            pred: filter,
1210            panic_flag: false,
1211        }
1212    }
1213
1214    /// Append an item to the vector.
1215    #[inline]
1216    pub fn push(&mut self, value: A::Item) {
1217        unsafe {
1218            if self.spilled() {
1219                let (mut ptr, mut len_ptr) = self.data.heap_mut();
1220                if *len_ptr == self.capacity {
1221                    self.reserve_one_unchecked();
1222                    let (heap_ptr, heap_len) = self.data.heap_mut();
1223                    ptr = heap_ptr;
1224                    len_ptr = heap_len;
1225                }
1226                ptr::write(ptr.as_ptr().add(*len_ptr), value);
1227                *len_ptr += 1;
1228            } else {
1229                let mut ptr = self.data.inline_mut();
1230                let mut len_ptr = &mut self.capacity;
1231                if *len_ptr == Self::inline_capacity() {
1232                    self.reserve_one_unchecked();
1233                    let (heap_ptr, heap_len) = self.data.heap_mut();
1234                    ptr = heap_ptr;
1235                    len_ptr = heap_len;
1236                }
1237                ptr::write(ptr.as_ptr().add(*len_ptr), value);
1238                *len_ptr += 1;
1239            };
1240        }
1241    }
1242
1243    /// Remove an item from the end of the vector and return it, or None if
1244    /// empty.
1245    #[inline]
1246    pub fn pop(&mut self) -> Option<A::Item> {
1247        unsafe {
1248            let (ptr, len_ptr, _) = self.triple_mut();
1249            let ptr: *const _ = ptr.as_ptr();
1250            if *len_ptr == 0 {
1251                return None;
1252            }
1253            let last_index = *len_ptr - 1;
1254            *len_ptr = last_index;
1255            Some(ptr::read(ptr.add(last_index)))
1256        }
1257    }
1258
1259    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1260    ///
1261    /// # Example
1262    ///
1263    /// ```
1264    /// # use smallvec::{SmallVec, smallvec};
1265    /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3];
1266    /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6];
1267    /// v0.append(&mut v1);
1268    /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]);
1269    /// assert_eq!(*v1, []);
1270    /// ```
1271    pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1272    where
1273        B: Array<Item = A::Item>,
1274    {
1275        self.extend(other.drain(..))
1276    }
1277
1278    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1279    ///
1280    /// If `new_cap` is less than the vector's length, this is a no-op.
1281    /// Panics if the capacity computation overflows `usize`.
1282    pub fn grow(&mut self, new_cap: usize) {
1283        infallible(self.try_grow(new_cap))
1284    }
1285
1286    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1287    ///
1288    /// If `new_cap` is less than the vector's length, this is a no-op.
1289    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1290        unsafe {
1291            let unspilled = !self.spilled();
1292            let (ptr, &mut len, cap) = self.triple_mut();
1293            if new_cap < len {
1294                return Ok(());
1295            }
1296            if new_cap <= Self::inline_capacity() {
1297                if unspilled {
1298                    return Ok(());
1299                }
1300                self.data = SmallVecData::empty();
1301                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1302                self.capacity = len;
1303                deallocate(ptr, cap);
1304            } else if new_cap != cap {
1305                let layout = layout_array::<A::Item>(new_cap)?;
1306                debug_assert!(layout.size() > 0);
1307                let new_alloc;
1308                if unspilled {
1309                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1310                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1311                        .cast();
1312                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1313                } else {
1314                    // This should never fail since the same succeeded
1315                    // when previously allocating `ptr`.
1316                    let old_layout = layout_array::<A::Item>(cap)?;
1317
1318                    let new_ptr =
1319                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1320                    new_alloc = NonNull::new(new_ptr)
1321                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1322                        .cast();
1323                }
1324                self.data = SmallVecData::from_heap(new_alloc, len);
1325                self.capacity = new_cap;
1326            }
1327            Ok(())
1328        }
1329    }
1330
1331    /// Reserve capacity for `additional` more elements to be inserted.
1332    ///
1333    /// May reserve more space to avoid frequent reallocations.
1334    ///
1335    /// Panics if the capacity computation overflows `usize`.
1336    #[inline]
1337    pub fn reserve(&mut self, additional: usize) {
1338        infallible(self.try_reserve(additional))
1339    }
1340
1341    /// Internal method used to grow in push() and insert(), where we know
1342    /// already we have to grow.
1343    #[cold]
1344    fn reserve_one_unchecked(&mut self) {
1345        debug_assert_eq!(self.len(), self.capacity());
1346        let new_cap = self
1347            .len()
1348            .checked_add(1)
1349            .and_then(usize::checked_next_power_of_two)
1350            .expect("capacity overflow");
1351        infallible(self.try_grow(new_cap))
1352    }
1353
1354    /// Reserve capacity for `additional` more elements to be inserted.
1355    ///
1356    /// May reserve more space to avoid frequent reallocations.
1357    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1358        // prefer triple_mut() even if triple() would work so that the optimizer
1359        // removes duplicated calls to it from callers.
1360        let (_, &mut len, cap) = self.triple_mut();
1361        if cap - len >= additional {
1362            return Ok(());
1363        }
1364        let new_cap = len
1365            .checked_add(additional)
1366            .and_then(usize::checked_next_power_of_two)
1367            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1368        self.try_grow(new_cap)
1369    }
1370
1371    /// Reserve the minimum capacity for `additional` more elements to be
1372    /// inserted.
1373    ///
1374    /// Panics if the new capacity overflows `usize`.
1375    pub fn reserve_exact(&mut self, additional: usize) {
1376        infallible(self.try_reserve_exact(additional))
1377    }
1378
1379    /// Reserve the minimum capacity for `additional` more elements to be
1380    /// inserted.
1381    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1382        let (_, &mut len, cap) = self.triple_mut();
1383        if cap - len >= additional {
1384            return Ok(());
1385        }
1386        let new_cap = len
1387            .checked_add(additional)
1388            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1389        self.try_grow(new_cap)
1390    }
1391
1392    /// Shrink the capacity of the vector as much as possible.
1393    ///
1394    /// When possible, this will move data from an external heap buffer to the
1395    /// vector's inline storage.
1396    pub fn shrink_to_fit(&mut self) {
1397        if !self.spilled() {
1398            return;
1399        }
1400        let len = self.len();
1401        if self.inline_size() >= len {
1402            unsafe {
1403                let (ptr, len) = self.data.heap();
1404                self.data = SmallVecData::empty();
1405                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1406                deallocate(ptr.0, self.capacity);
1407                self.capacity = len;
1408            }
1409        } else if self.capacity() > len {
1410            self.grow(len);
1411        }
1412    }
1413
1414    /// Shorten the vector, keeping the first `len` elements and dropping the
1415    /// rest.
1416    ///
1417    /// If `len` is greater than or equal to the vector's current length, this
1418    /// has no effect.
1419    ///
1420    /// This does not re-allocate.  If you want the vector's capacity to shrink,
1421    /// call `shrink_to_fit` after truncating.
1422    pub fn truncate(&mut self, len: usize) {
1423        unsafe {
1424            let (ptr, len_ptr, _) = self.triple_mut();
1425            let ptr = ptr.as_ptr();
1426            while len < *len_ptr {
1427                let last_index = *len_ptr - 1;
1428                *len_ptr = last_index;
1429                ptr::drop_in_place(ptr.add(last_index));
1430            }
1431        }
1432    }
1433
1434    /// Extracts a slice containing the entire vector.
1435    ///
1436    /// Equivalent to `&s[..]`.
1437    pub fn as_slice(&self) -> &[A::Item] {
1438        self
1439    }
1440
1441    /// Extracts a mutable slice of the entire vector.
1442    ///
1443    /// Equivalent to `&mut s[..]`.
1444    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1445        self
1446    }
1447
1448    /// Remove the element at position `index`, replacing it with the last
1449    /// element.
1450    ///
1451    /// This does not preserve ordering, but is O(1).
1452    ///
1453    /// Panics if `index` is out of bounds.
1454    #[inline]
1455    pub fn swap_remove(&mut self, index: usize) -> A::Item {
1456        let len = self.len();
1457        self.swap(len - 1, index);
1458        self.pop()
1459            .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1460    }
1461
1462    /// Remove all elements from the vector.
1463    #[inline]
1464    pub fn clear(&mut self) {
1465        self.truncate(0);
1466    }
1467
1468    /// Remove and return the element at position `index`, shifting all elements
1469    /// after it to the left.
1470    ///
1471    /// Panics if `index` is out of bounds.
1472    pub fn remove(&mut self, index: usize) -> A::Item {
1473        unsafe {
1474            let (ptr, len_ptr, _) = self.triple_mut();
1475            let len = *len_ptr;
1476            assert!(index < len);
1477            *len_ptr = len - 1;
1478            let ptr = ptr.as_ptr().add(index);
1479            let item = ptr::read(ptr);
1480            ptr::copy(ptr.add(1), ptr, len - index - 1);
1481            item
1482        }
1483    }
1484
1485    /// Insert an element at position `index`, shifting all elements after it to
1486    /// the right.
1487    ///
1488    /// Panics if `index > len`.
1489    pub fn insert(&mut self, index: usize, element: A::Item) {
1490        unsafe {
1491            let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1492            if *len_ptr == cap {
1493                self.reserve_one_unchecked();
1494                let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1495                ptr = heap_ptr;
1496                len_ptr = heap_len_ptr;
1497            }
1498            let mut ptr = ptr.as_ptr();
1499            let len = *len_ptr;
1500            if index > len {
1501                panic!("index exceeds length");
1502            }
1503            // SAFETY: add is UB if index > len, but we panicked first
1504            ptr = ptr.add(index);
1505            if index < len {
1506                // Shift element to the right of `index`.
1507                ptr::copy(ptr, ptr.add(1), len - index);
1508            }
1509            *len_ptr = len + 1;
1510            ptr::write(ptr, element);
1511        }
1512    }
1513
1514    /// Insert multiple elements at position `index`, shifting all following
1515    /// elements toward the back.
1516    pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1517        let mut iter = iterable.into_iter();
1518        if index == self.len() {
1519            return self.extend(iter);
1520        }
1521
1522        let (lower_size_bound, _) = iter.size_hint();
1523        #[allow(deprecated)]
1524        {
1525            assert!(lower_size_bound <= core::isize::MAX as usize)
1526        } // Ensure offset is indexable
1527        assert!(index + lower_size_bound >= index); // Protect against overflow
1528
1529        let mut num_added = 0;
1530        let old_len = self.len();
1531        assert!(index <= old_len);
1532
1533        unsafe {
1534            // Reserve space for `lower_size_bound` elements.
1535            self.reserve(lower_size_bound);
1536            let start = self.as_mut_ptr();
1537            let ptr = start.add(index);
1538
1539            // Move the trailing elements.
1540            ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1541
1542            // In case the iterator panics, don't double-drop the items we just
1543            // copied above.
1544            self.set_len(0);
1545            let mut guard = DropOnPanic {
1546                start,
1547                skip: index..(index + lower_size_bound),
1548                len: old_len + lower_size_bound,
1549            };
1550
1551            // The set_len above invalidates the previous pointers, so we must
1552            // re-create them.
1553            let start = self.as_mut_ptr();
1554            let ptr = start.add(index);
1555
1556            while num_added < lower_size_bound {
1557                let element = match iter.next() {
1558                    Some(x) => x,
1559                    None => break,
1560                };
1561                let cur = ptr.add(num_added);
1562                ptr::write(cur, element);
1563                guard.skip.start += 1;
1564                num_added += 1;
1565            }
1566
1567            if num_added < lower_size_bound {
1568                // Iterator provided fewer elements than the hint. Move the tail
1569                // backward.
1570                ptr::copy(
1571                    ptr.add(lower_size_bound),
1572                    ptr.add(num_added),
1573                    old_len - index,
1574                );
1575            }
1576            // There are no more duplicate or uninitialized slots, so the guard
1577            // is not needed.
1578            self.set_len(old_len + num_added);
1579            mem::forget(guard);
1580        }
1581
1582        // Insert any remaining elements one-by-one.
1583        for element in iter {
1584            self.insert(index + num_added, element);
1585            num_added += 1;
1586        }
1587
1588        struct DropOnPanic<T> {
1589            start: *mut T,
1590            skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
1591            len: usize,
1592        }
1593
1594        impl<T> Drop for DropOnPanic<T> {
1595            fn drop(&mut self) {
1596                for i in 0..self.len {
1597                    if !self.skip.contains(&i) {
1598                        unsafe {
1599                            ptr::drop_in_place(self.start.add(i));
1600                        }
1601                    }
1602                }
1603            }
1604        }
1605    }
1606
1607    /// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec`
1608    /// has already spilled onto the heap.
1609    pub fn into_vec(mut self) -> Vec<A::Item> {
1610        if self.spilled() {
1611            unsafe {
1612                let (ptr, &mut len) = self.data.heap_mut();
1613                let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1614                mem::forget(self);
1615                v
1616            }
1617        } else {
1618            self.into_iter().collect()
1619        }
1620    }
1621
1622    /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the
1623    /// `SmallVec` has already spilled onto the heap.
1624    ///
1625    /// Note that this will drop any excess capacity.
1626    pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1627        self.into_vec().into_boxed_slice()
1628    }
1629
1630    /// Convert the `SmallVec` into an `A` if possible. Otherwise return
1631    /// `Err(Self)`.
1632    ///
1633    /// This method returns `Err(Self)` if the `SmallVec` is too short (and the
1634    /// `A` contains uninitialized elements), or if the `SmallVec` is too
1635    /// long (and all the elements were spilled to the heap).
1636    pub fn into_inner(self) -> Result<A, Self> {
1637        if self.spilled() || self.len() != A::size() {
1638            // Note: A::size, not Self::inline_capacity
1639            Err(self)
1640        } else {
1641            unsafe {
1642                let data = ptr::read(&self.data);
1643                mem::forget(self);
1644                Ok(data.into_inline().assume_init())
1645            }
1646        }
1647    }
1648
1649    /// Retains only the elements specified by the predicate.
1650    ///
1651    /// In other words, remove all elements `e` such that `f(&e)` returns
1652    /// `false`. This method operates in place and preserves the order of
1653    /// the retained elements.
1654    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1655        let original_len = self.len();
1656
1657        if original_len == 0 {
1658            // Empty case: explicit return allows better optimization, vs
1659            // letting compiler infer it
1660            return;
1661        }
1662
1663        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1664        //      |            ^- write                ^- read             |
1665        //      |<-              original_len                          ->|
1666        // Kept: Elements which predicate returns true on.
1667        // Hole: Moved or dropped element slot.
1668        // Unchecked: Unchecked valid elements.
1669        //
1670        // This drop guard will be invoked when predicate or `drop` of element
1671        // panicked. It shifts unchecked elements to cover holes and
1672        // `set_len` to the correct length. In cases when predicate and
1673        // `drop` never panic, it will be optimized out.
1674        struct PanicGuard<'a, A: Array> {
1675            v: &'a mut SmallVec<A>,
1676            read: usize,
1677            write: usize,
1678            original_len: usize,
1679        }
1680
1681        impl<A: Array> Drop for PanicGuard<'_, A> {
1682            #[cold]
1683            fn drop(&mut self) {
1684                let remaining = self.original_len - self.read;
1685                // SAFETY: Trailing unchecked items must be valid since we never
1686                // touch them.
1687                unsafe {
1688                    let ptr = self.v.as_mut_ptr();
1689                    ptr::copy(ptr.add(self.read), ptr.add(self.write), remaining);
1690                }
1691                // SAFETY: After filling holes, all items are in contiguous
1692                // memory.
1693                unsafe {
1694                    self.v.set_len(self.write + remaining);
1695                }
1696            }
1697        }
1698
1699        let mut read = 0;
1700        loop {
1701            // SAFETY: read < original_len
1702            let cur = unsafe { self.get_unchecked_mut(read) };
1703            if !f(cur) {
1704                break;
1705            }
1706            read += 1;
1707            if read == original_len {
1708                // All elements are kept, return early.
1709                return;
1710            }
1711        }
1712
1713        // Critical section starts here and at least one element is going to be
1714        // removed. Advance `g.read` early to avoid double drop if
1715        // `drop_in_place` panicked.
1716        let mut g = PanicGuard {
1717            v: self,
1718            read: read + 1,
1719            write: read,
1720            original_len,
1721        };
1722        // SAFETY: previous `read` is always less than original_len.
1723        unsafe { ptr::drop_in_place(g.v.as_mut_ptr().add(read)) }
1724
1725        let ptr = g.v.as_mut_ptr();
1726        while g.read < g.original_len {
1727            // SAFETY: `read` is always less than original_len.
1728            let cur = unsafe { &mut *ptr.add(g.read) };
1729            if !f(cur) {
1730                // Advance `read` early to avoid double drop if `drop_in_place`
1731                // panicked.
1732                g.read += 1;
1733                // SAFETY: We never touch this element again after dropped.
1734                unsafe { ptr::drop_in_place(cur) };
1735            } else {
1736                // SAFETY: `read` > `write`, so the slots don't overlap.
1737                // We use copy for move, and never touch the source element
1738                // again.
1739                unsafe {
1740                    let hole = ptr.add(g.write);
1741                    ptr::copy_nonoverlapping(cur, hole, 1);
1742                }
1743                g.write += 1;
1744                g.read += 1;
1745            }
1746        }
1747
1748        // We are leaving the critical section and no panic happened,
1749        // Commit the length change and forget the guard.
1750        // SAFETY: `write` is always less than or equal to original_len.
1751        unsafe { g.v.set_len(g.write) };
1752        core::mem::forget(g);
1753    }
1754
1755    /// Retains only the elements specified by the predicate.
1756    ///
1757    /// This method is identical in behaviour to [`SmallVec::retain`]; it is
1758    /// included only to maintain api-compatibility with `std::Vec`, where
1759    /// the methods are separate for historical reasons.
1760    pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1761        self.retain(f)
1762    }
1763
1764    /// Removes consecutive duplicate elements.
1765    pub fn dedup(&mut self)
1766    where
1767        A::Item: PartialEq<A::Item>,
1768    {
1769        self.dedup_by(|a, b| a == b);
1770    }
1771
1772    /// Removes consecutive duplicate elements using the given equality
1773    /// relation.
1774    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1775    where
1776        F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1777    {
1778        // See the implementation of Vec::dedup_by in the
1779        // standard library for an explanation of this algorithm.
1780        let len = self.len();
1781        if len <= 1 {
1782            return;
1783        }
1784
1785        let ptr = self.as_mut_ptr();
1786        let mut w: usize = 1;
1787
1788        unsafe {
1789            for r in 1..len {
1790                let p_r = ptr.add(r);
1791                let p_wm1 = ptr.add(w - 1);
1792                if !same_bucket(&mut *p_r, &mut *p_wm1) {
1793                    if r != w {
1794                        let p_w = p_wm1.add(1);
1795                        mem::swap(&mut *p_r, &mut *p_w);
1796                    }
1797                    w += 1;
1798                }
1799            }
1800        }
1801
1802        self.truncate(w);
1803    }
1804
1805    /// Removes consecutive elements that map to the same key.
1806    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1807    where
1808        F: FnMut(&mut A::Item) -> K,
1809        K: PartialEq<K>,
1810    {
1811        self.dedup_by(|a, b| key(a) == key(b));
1812    }
1813
1814    /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1815    ///
1816    /// If `new_len` is greater than `len`, the `SmallVec` is extended by the
1817    /// difference, with each additional slot filled with the result of
1818    /// calling the closure `f`. The return values from `f` will end up in
1819    /// the `SmallVec` in the order they have been generated.
1820    ///
1821    /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1822    ///
1823    /// This method uses a closure to create new values on every push. If you'd
1824    /// rather `Clone` a given value, use `resize`. If you want to use the
1825    /// `Default` trait to generate values, you can pass
1826    /// `Default::default()` as the second argument.
1827    ///
1828    /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1829    ///
1830    /// ```
1831    /// # use smallvec::{smallvec, SmallVec};
1832    /// let mut vec: SmallVec<[_; 4]> = smallvec![1, 2, 3];
1833    /// vec.resize_with(5, Default::default);
1834    /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1835    ///
1836    /// let mut vec: SmallVec<[_; 4]> = smallvec![];
1837    /// let mut p = 1;
1838    /// vec.resize_with(4, || {
1839    ///     p *= 2;
1840    ///     p
1841    /// });
1842    /// assert_eq!(&*vec, &[2, 4, 8, 16]);
1843    /// ```
1844    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1845    where
1846        F: FnMut() -> A::Item,
1847    {
1848        let old_len = self.len();
1849        if old_len < new_len {
1850            let mut f = f;
1851            let additional = new_len - old_len;
1852            self.reserve(additional);
1853            for _ in 0..additional {
1854                self.push(f());
1855            }
1856        } else if old_len > new_len {
1857            self.truncate(new_len);
1858        }
1859    }
1860
1861    /// Creates a `SmallVec` directly from the raw components of another
1862    /// `SmallVec`.
1863    ///
1864    /// # Safety
1865    ///
1866    /// This is highly unsafe, due to the number of invariants that aren't
1867    /// checked:
1868    ///
1869    /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1870    ///   spilled storage (at least, it's highly likely to be incorrect if it
1871    ///   wasn't).
1872    /// * `ptr`'s `A::Item` type needs to be the same size and alignment that it
1873    ///   was allocated with
1874    /// * `length` needs to be less than or equal to `capacity`.
1875    /// * `capacity` needs to be the capacity that the pointer was allocated
1876    ///   with.
1877    ///
1878    /// Violating these may cause problems like corrupting the allocator's
1879    /// internal data structures.
1880    ///
1881    /// Additionally, `capacity` must be greater than the amount of inline
1882    /// storage `A` has; that is, the new `SmallVec` must need to spill over
1883    /// into heap allocated storage. This condition is asserted against.
1884    ///
1885    /// The ownership of `ptr` is effectively transferred to the
1886    /// `SmallVec` which may then deallocate, reallocate or change the
1887    /// contents of memory pointed to by the pointer at will. Ensure
1888    /// that nothing else uses the pointer after calling this
1889    /// function.
1890    ///
1891    /// # Examples
1892    ///
1893    /// ```
1894    /// # use smallvec::{smallvec, SmallVec};
1895    /// use std::mem;
1896    /// use std::ptr;
1897    ///
1898    /// fn main() {
1899    ///     let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
1900    ///
1901    ///     // Pull out the important parts of `v`.
1902    ///     let p = v.as_mut_ptr();
1903    ///     let len = v.len();
1904    ///     let cap = v.capacity();
1905    ///     let spilled = v.spilled();
1906    ///
1907    ///     unsafe {
1908    ///         // Forget all about `v`. The heap allocation that stored the
1909    ///         // three values won't be deallocated.
1910    ///         mem::forget(v);
1911    ///
1912    ///         // Overwrite memory with [4, 5, 6].
1913    ///         //
1914    ///         // This is only safe if `spilled` is true! Otherwise, we are
1915    ///         // writing into the old `SmallVec`'s inline storage on the
1916    ///         // stack.
1917    ///         assert!(spilled);
1918    ///         for i in 0..len {
1919    ///             ptr::write(p.add(i), 4 + i);
1920    ///         }
1921    ///
1922    ///         // Put everything back together into a SmallVec with a different
1923    ///         // amount of inline storage, but which is still less than `cap`.
1924    ///         let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
1925    ///         assert_eq!(&*rebuilt, &[4, 5, 6]);
1926    ///     }
1927    /// }
1928    #[inline]
1929    pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1930        // SAFETY: We require caller to provide same ptr as we alloc
1931        // and we never alloc null pointer.
1932        let ptr = unsafe {
1933            debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1934            NonNull::new_unchecked(ptr)
1935        };
1936        assert!(capacity > Self::inline_capacity());
1937        SmallVec {
1938            capacity,
1939            data: SmallVecData::from_heap(ptr, length),
1940            _marker: PhantomData,
1941        }
1942    }
1943
1944    /// Returns a raw pointer to the vector's buffer.
1945    pub fn as_ptr(&self) -> *const A::Item {
1946        // We shadow the slice method of the same name to avoid going through
1947        // `deref`, which creates an intermediate reference that may place
1948        // additional safety constraints on the contents of the slice.
1949        self.triple().0.as_ptr()
1950    }
1951
1952    /// Returns a raw mutable pointer to the vector's buffer.
1953    pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1954        // We shadow the slice method of the same name to avoid going through
1955        // `deref_mut`, which creates an intermediate reference that may place
1956        // additional safety constraints on the contents of the slice.
1957        self.triple_mut().0.as_ptr()
1958    }
1959}
1960
1961impl<A: Array> SmallVec<A>
1962where
1963    A::Item: Copy,
1964{
1965    /// Copy the elements from a slice into a new `SmallVec`.
1966    ///
1967    /// For slices of `Copy` types, this is more efficient than
1968    /// `SmallVec::from(slice)`.
1969    pub fn from_slice(slice: &[A::Item]) -> Self {
1970        let len = slice.len();
1971        if len <= Self::inline_capacity() {
1972            SmallVec {
1973                capacity: len,
1974                data: SmallVecData::from_inline(unsafe {
1975                    let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1976                    ptr::copy_nonoverlapping(
1977                        slice.as_ptr(),
1978                        data.as_mut_ptr() as *mut A::Item,
1979                        len,
1980                    );
1981                    data
1982                }),
1983                _marker: PhantomData,
1984            }
1985        } else {
1986            let mut b = slice.to_vec();
1987            let cap = b.capacity();
1988            let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1989            mem::forget(b);
1990            SmallVec {
1991                capacity: cap,
1992                data: SmallVecData::from_heap(ptr, len),
1993                _marker: PhantomData,
1994            }
1995        }
1996    }
1997
1998    /// Copy elements from a slice into the vector at position `index`, shifting
1999    /// any following elements toward the back.
2000    ///
2001    /// For slices of `Copy` types, this is more efficient than `insert`.
2002    #[inline]
2003    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
2004        self.reserve(slice.len());
2005
2006        let len = self.len();
2007        assert!(index <= len);
2008
2009        unsafe {
2010            let slice_ptr = slice.as_ptr();
2011            let ptr = self.as_mut_ptr().add(index);
2012            ptr::copy(ptr, ptr.add(slice.len()), len - index);
2013            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
2014            self.set_len(len + slice.len());
2015        }
2016    }
2017
2018    /// Copy elements from a slice and append them to the vector.
2019    ///
2020    /// For slices of `Copy` types, this is more efficient than `extend`.
2021    #[inline]
2022    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
2023        let len = self.len();
2024        self.insert_from_slice(len, slice);
2025    }
2026}
2027
2028impl<A: Array> SmallVec<A>
2029where
2030    A::Item: Clone,
2031{
2032    /// Resizes the vector so that its length is equal to `len`.
2033    ///
2034    /// If `len` is less than the current length, the vector simply truncated.
2035    ///
2036    /// If `len` is greater than the current length, `value` is appended to the
2037    /// vector until its length equals `len`.
2038    pub fn resize(&mut self, len: usize, value: A::Item) {
2039        let old_len = self.len();
2040
2041        if len > old_len {
2042            self.extend(repeat(value).take(len - old_len));
2043        } else {
2044            self.truncate(len);
2045        }
2046    }
2047
2048    /// Creates a `SmallVec` with `n` copies of `elem`.
2049    /// ```
2050    /// use smallvec::SmallVec;
2051    ///
2052    /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
2053    /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
2054    /// ```
2055    pub fn from_elem(elem: A::Item, n: usize) -> Self {
2056        if n > Self::inline_capacity() {
2057            vec![elem; n].into()
2058        } else {
2059            let mut v = SmallVec::<A>::new();
2060            unsafe {
2061                let (ptr, len_ptr, _) = v.triple_mut();
2062                let ptr = ptr.as_ptr();
2063                let mut local_len = SetLenOnDrop::new(len_ptr);
2064
2065                for i in 0..n {
2066                    ::core::ptr::write(ptr.add(i), elem.clone());
2067                    local_len.increment_len(1);
2068                }
2069            }
2070            v
2071        }
2072    }
2073}
2074
2075impl<A: Array> ops::Deref for SmallVec<A> {
2076    type Target = [A::Item];
2077    #[inline]
2078    fn deref(&self) -> &[A::Item] {
2079        unsafe {
2080            let (ptr, len, _) = self.triple();
2081            slice::from_raw_parts(ptr.as_ptr(), len)
2082        }
2083    }
2084}
2085
2086impl<A: Array> ops::DerefMut for SmallVec<A> {
2087    #[inline]
2088    fn deref_mut(&mut self) -> &mut [A::Item] {
2089        unsafe {
2090            let (ptr, &mut len, _) = self.triple_mut();
2091            slice::from_raw_parts_mut(ptr.as_ptr(), len)
2092        }
2093    }
2094}
2095
2096impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
2097    #[inline]
2098    fn as_ref(&self) -> &[A::Item] {
2099        self
2100    }
2101}
2102
2103impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
2104    #[inline]
2105    fn as_mut(&mut self) -> &mut [A::Item] {
2106        self
2107    }
2108}
2109
2110impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
2111    #[inline]
2112    fn borrow(&self) -> &[A::Item] {
2113        self
2114    }
2115}
2116
2117impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
2118    #[inline]
2119    fn borrow_mut(&mut self) -> &mut [A::Item] {
2120        self
2121    }
2122}
2123
2124#[cfg(feature = "write")]
2125#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
2126impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
2127    #[inline]
2128    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2129        self.extend_from_slice(buf);
2130        Ok(buf.len())
2131    }
2132
2133    #[inline]
2134    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2135        self.extend_from_slice(buf);
2136        Ok(())
2137    }
2138
2139    #[inline]
2140    fn flush(&mut self) -> io::Result<()> {
2141        Ok(())
2142    }
2143}
2144
2145#[cfg(feature = "serde")]
2146#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2147impl<A: Array> Serialize for SmallVec<A>
2148where
2149    A::Item: Serialize,
2150{
2151    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2152        let mut state = serializer.serialize_seq(Some(self.len()))?;
2153        for item in self {
2154            state.serialize_element(&item)?;
2155        }
2156        state.end()
2157    }
2158}
2159
2160#[cfg(feature = "serde")]
2161#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2162impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2163where
2164    A::Item: Deserialize<'de>,
2165{
2166    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2167        deserializer.deserialize_seq(SmallVecVisitor {
2168            phantom: PhantomData,
2169        })
2170    }
2171}
2172
2173#[cfg(feature = "serde")]
2174struct SmallVecVisitor<A> {
2175    phantom: PhantomData<A>,
2176}
2177
2178#[cfg(feature = "serde")]
2179impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2180where
2181    A::Item: Deserialize<'de>,
2182{
2183    type Value = SmallVec<A>;
2184
2185    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2186        formatter.write_str("a sequence")
2187    }
2188
2189    fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2190    where
2191        B: SeqAccess<'de>,
2192    {
2193        use serde::de::Error;
2194        let len = seq.size_hint().unwrap_or(0);
2195        let mut values = SmallVec::new();
2196        values.try_reserve(len).map_err(B::Error::custom)?;
2197
2198        while let Some(value) = seq.next_element()? {
2199            values.push(value);
2200        }
2201
2202        Ok(values)
2203    }
2204}
2205
2206#[cfg(feature = "malloc_size_of")]
2207impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2208    fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2209        if self.spilled() {
2210            unsafe { ops.malloc_size_of(self.as_ptr()) }
2211        } else {
2212            0
2213        }
2214    }
2215}
2216
2217#[cfg(feature = "malloc_size_of")]
2218impl<A> MallocSizeOf for SmallVec<A>
2219where
2220    A: Array,
2221    A::Item: MallocSizeOf,
2222{
2223    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2224        let mut n = self.shallow_size_of(ops);
2225        for elem in self.iter() {
2226            n += elem.size_of(ops);
2227        }
2228        n
2229    }
2230}
2231
2232#[cfg(feature = "specialization")]
2233trait SpecFrom<A: Array, S> {
2234    fn spec_from(slice: S) -> SmallVec<A>;
2235}
2236
2237#[cfg(feature = "specialization")]
2238mod specialization;
2239
2240#[cfg(feature = "arbitrary")]
2241mod arbitrary;
2242
2243#[cfg(feature = "specialization")]
2244impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2245where
2246    A::Item: Copy,
2247{
2248    #[inline]
2249    fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2250        SmallVec::from_slice(slice)
2251    }
2252}
2253
2254impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2255where
2256    A::Item: Clone,
2257{
2258    #[cfg(not(feature = "specialization"))]
2259    #[inline]
2260    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2261        slice.iter().cloned().collect()
2262    }
2263
2264    #[cfg(feature = "specialization")]
2265    #[inline]
2266    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2267        SmallVec::spec_from(slice)
2268    }
2269}
2270
2271impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2272    #[inline]
2273    fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2274        SmallVec::from_vec(vec)
2275    }
2276}
2277
2278impl<A: Array> From<A> for SmallVec<A> {
2279    #[inline]
2280    fn from(array: A) -> SmallVec<A> {
2281        SmallVec::from_buf(array)
2282    }
2283}
2284
2285impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2286    type Output = I::Output;
2287
2288    fn index(&self, index: I) -> &I::Output {
2289        &(**self)[index]
2290    }
2291}
2292
2293impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2294    fn index_mut(&mut self, index: I) -> &mut I::Output {
2295        &mut (&mut **self)[index]
2296    }
2297}
2298
2299#[allow(deprecated)]
2300impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2301where
2302    A::Item: Copy,
2303{
2304    fn extend_from_slice(&mut self, other: &[A::Item]) {
2305        SmallVec::extend_from_slice(self, other)
2306    }
2307}
2308
2309impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2310    #[inline]
2311    fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2312        let mut v = SmallVec::new();
2313        v.extend(iterable);
2314        v
2315    }
2316}
2317
2318impl<A: Array> Extend<A::Item> for SmallVec<A> {
2319    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2320        let mut iter = iterable.into_iter();
2321        let (lower_size_bound, _) = iter.size_hint();
2322        self.reserve(lower_size_bound);
2323
2324        unsafe {
2325            let (ptr, len_ptr, cap) = self.triple_mut();
2326            let ptr = ptr.as_ptr();
2327            let mut len = SetLenOnDrop::new(len_ptr);
2328            while len.get() < cap {
2329                if let Some(out) = iter.next() {
2330                    ptr::write(ptr.add(len.get()), out);
2331                    len.increment_len(1);
2332                } else {
2333                    return;
2334                }
2335            }
2336        }
2337
2338        for elem in iter {
2339            self.push(elem);
2340        }
2341    }
2342}
2343
2344impl<A: Array> fmt::Debug for SmallVec<A>
2345where
2346    A::Item: fmt::Debug,
2347{
2348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2349        f.debug_list().entries(self.iter()).finish()
2350    }
2351}
2352
2353impl<A: Array> Default for SmallVec<A> {
2354    #[inline]
2355    fn default() -> SmallVec<A> {
2356        SmallVec::new()
2357    }
2358}
2359
2360#[cfg(feature = "may_dangle")]
2361unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2362    fn drop(&mut self) {
2363        unsafe {
2364            if self.spilled() {
2365                let (ptr, &mut len) = self.data.heap_mut();
2366                Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2367            } else {
2368                ptr::drop_in_place(&mut self[..]);
2369            }
2370        }
2371    }
2372}
2373
2374#[cfg(not(feature = "may_dangle"))]
2375impl<A: Array> Drop for SmallVec<A> {
2376    fn drop(&mut self) {
2377        unsafe {
2378            if self.spilled() {
2379                let (ptr, &mut len) = self.data.heap_mut();
2380                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2381            } else {
2382                ptr::drop_in_place(&mut self[..]);
2383            }
2384        }
2385    }
2386}
2387
2388impl<A: Array> Clone for SmallVec<A>
2389where
2390    A::Item: Clone,
2391{
2392    #[inline]
2393    fn clone(&self) -> SmallVec<A> {
2394        SmallVec::from(self.as_slice())
2395    }
2396
2397    fn clone_from(&mut self, source: &Self) {
2398        // Inspired from `impl Clone for Vec`.
2399
2400        // drop anything that will not be overwritten
2401        self.truncate(source.len());
2402
2403        // self.len <= other.len due to the truncate above, so the
2404        // slices here are always in-bounds.
2405        let (init, tail) = source.split_at(self.len());
2406
2407        // reuse the contained values' allocations/resources.
2408        self.clone_from_slice(init);
2409        self.extend(tail.iter().cloned());
2410    }
2411}
2412
2413impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2414where
2415    A::Item: PartialEq<B::Item>,
2416{
2417    #[inline]
2418    fn eq(&self, other: &SmallVec<B>) -> bool {
2419        self[..] == other[..]
2420    }
2421}
2422
2423impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2424
2425impl<A: Array> PartialOrd for SmallVec<A>
2426where
2427    A::Item: PartialOrd,
2428{
2429    #[inline]
2430    fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2431        PartialOrd::partial_cmp(&**self, &**other)
2432    }
2433}
2434
2435impl<A: Array> Ord for SmallVec<A>
2436where
2437    A::Item: Ord,
2438{
2439    #[inline]
2440    fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2441        Ord::cmp(&**self, &**other)
2442    }
2443}
2444
2445impl<A: Array> Hash for SmallVec<A>
2446where
2447    A::Item: Hash,
2448{
2449    fn hash<H: Hasher>(&self, state: &mut H) {
2450        (**self).hash(state)
2451    }
2452}
2453
2454unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2455
2456/// An iterator that consumes a `SmallVec` and yields its items by value.
2457///
2458/// Returned from [`SmallVec::into_iter`][1].
2459///
2460/// [1]: struct.SmallVec.html#method.into_iter
2461pub struct IntoIter<A: Array> {
2462    data: SmallVec<A>,
2463    current: usize,
2464    end: usize,
2465}
2466
2467impl<A: Array> fmt::Debug for IntoIter<A>
2468where
2469    A::Item: fmt::Debug,
2470{
2471    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2472        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2473    }
2474}
2475
2476impl<A: Array + Clone> Clone for IntoIter<A>
2477where
2478    A::Item: Clone,
2479{
2480    fn clone(&self) -> IntoIter<A> {
2481        SmallVec::from(self.as_slice()).into_iter()
2482    }
2483}
2484
2485impl<A: Array> Drop for IntoIter<A> {
2486    fn drop(&mut self) {
2487        for _ in self {}
2488    }
2489}
2490
2491impl<A: Array> Iterator for IntoIter<A> {
2492    type Item = A::Item;
2493
2494    #[inline]
2495    fn next(&mut self) -> Option<A::Item> {
2496        if self.current == self.end {
2497            None
2498        } else {
2499            unsafe {
2500                let current = self.current;
2501                self.current += 1;
2502                Some(ptr::read(self.data.as_ptr().add(current)))
2503            }
2504        }
2505    }
2506
2507    #[inline]
2508    fn size_hint(&self) -> (usize, Option<usize>) {
2509        let size = self.end - self.current;
2510        (size, Some(size))
2511    }
2512}
2513
2514impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2515    #[inline]
2516    fn next_back(&mut self) -> Option<A::Item> {
2517        if self.current == self.end {
2518            None
2519        } else {
2520            unsafe {
2521                self.end -= 1;
2522                Some(ptr::read(self.data.as_ptr().add(self.end)))
2523            }
2524        }
2525    }
2526}
2527
2528impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2529impl<A: Array> FusedIterator for IntoIter<A> {}
2530
2531impl<A: Array> IntoIter<A> {
2532    /// Returns the remaining items of this iterator as a slice.
2533    pub fn as_slice(&self) -> &[A::Item] {
2534        let len = self.end - self.current;
2535        unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2536    }
2537
2538    /// Returns the remaining items of this iterator as a mutable slice.
2539    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2540        let len = self.end - self.current;
2541        unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2542    }
2543}
2544
2545impl<A: Array> IntoIterator for SmallVec<A> {
2546    type IntoIter = IntoIter<A>;
2547    type Item = A::Item;
2548    fn into_iter(mut self) -> Self::IntoIter {
2549        unsafe {
2550            // Set SmallVec len to zero as `IntoIter` drop handles dropping of
2551            // the elements
2552            let len = self.len();
2553            self.set_len(0);
2554            IntoIter {
2555                data: self,
2556                current: 0,
2557                end: len,
2558            }
2559        }
2560    }
2561}
2562
2563impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2564    type IntoIter = slice::Iter<'a, A::Item>;
2565    type Item = &'a A::Item;
2566    fn into_iter(self) -> Self::IntoIter {
2567        self.iter()
2568    }
2569}
2570
2571impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2572    type IntoIter = slice::IterMut<'a, A::Item>;
2573    type Item = &'a mut A::Item;
2574    fn into_iter(self) -> Self::IntoIter {
2575        self.iter_mut()
2576    }
2577}
2578
2579/// Types that can be used as the backing store for a [`SmallVec`].
2580pub unsafe trait Array {
2581    /// The type of the array's elements.
2582    type Item;
2583    /// Returns the number of items the array can hold.
2584    fn size() -> usize;
2585}
2586
2587/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
2588///
2589/// Copied from <https://github.com/rust-lang/rust/pull/36355>
2590struct SetLenOnDrop<'a> {
2591    len: &'a mut usize,
2592    local_len: usize,
2593}
2594
2595impl<'a> SetLenOnDrop<'a> {
2596    #[inline]
2597    fn new(len: &'a mut usize) -> Self {
2598        SetLenOnDrop {
2599            local_len: *len,
2600            len,
2601        }
2602    }
2603
2604    #[inline]
2605    fn get(&self) -> usize {
2606        self.local_len
2607    }
2608
2609    #[inline]
2610    fn increment_len(&mut self, increment: usize) {
2611        self.local_len += increment;
2612    }
2613}
2614
2615impl<'a> Drop for SetLenOnDrop<'a> {
2616    #[inline]
2617    fn drop(&mut self) {
2618        *self.len = self.local_len;
2619    }
2620}
2621
2622#[cfg(feature = "const_new")]
2623impl<T, const N: usize> SmallVec<[T; N]> {
2624    /// Construct an empty vector.
2625    ///
2626    /// This is a `const` version of [`SmallVec::new`] that is enabled by the
2627    /// feature `const_new`, with the limitation that it only works for arrays.
2628    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2629    #[inline]
2630    pub const fn new_const() -> Self {
2631        SmallVec {
2632            capacity: 0,
2633            data: SmallVecData::from_const(MaybeUninit::uninit()),
2634            _marker: PhantomData,
2635        }
2636    }
2637
2638    /// The array passed as an argument is moved to be an inline version of
2639    /// `SmallVec`.
2640    ///
2641    /// This is a `const` version of [`SmallVec::from_buf`] that is enabled by
2642    /// the feature `const_new`, with the limitation that it only works for
2643    /// arrays.
2644    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2645    #[inline]
2646    pub const fn from_const(items: [T; N]) -> Self {
2647        SmallVec {
2648            capacity: N,
2649            data: SmallVecData::from_const(MaybeUninit::new(items)),
2650            _marker: PhantomData,
2651        }
2652    }
2653
2654    /// Constructs a new `SmallVec` on the stack from an array without
2655    /// copying elements. Also sets the length. The user is responsible
2656    /// for ensuring that `len <= N`.
2657    ///
2658    /// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`]
2659    /// that is enabled by the feature `const_new`, with the limitation that it
2660    /// only works for arrays.
2661    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2662    #[inline]
2663    pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2664        SmallVec {
2665            capacity: len,
2666            data: SmallVecData::from_const(MaybeUninit::new(items)),
2667            _marker: PhantomData,
2668        }
2669    }
2670}
2671
2672#[cfg(feature = "const_generics")]
2673#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2674unsafe impl<T, const N: usize> Array for [T; N] {
2675    type Item = T;
2676    #[inline]
2677    fn size() -> usize {
2678        N
2679    }
2680}
2681
2682#[cfg(not(feature = "const_generics"))]
2683macro_rules! impl_array(
2684    ($($size:expr),+) => {
2685        $(
2686            unsafe impl<T> Array for [T; $size] {
2687                type Item = T;
2688                #[inline]
2689                fn size() -> usize { $size }
2690            }
2691        )+
2692    }
2693);
2694
2695#[cfg(not(feature = "const_generics"))]
2696impl_array!(
2697    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
2698    26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2699    0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2700);
2701
2702/// Convenience trait for constructing a `SmallVec`
2703pub trait ToSmallVec<A: Array> {
2704    /// Construct a new `SmallVec` from a slice.
2705    fn to_smallvec(&self) -> SmallVec<A>;
2706}
2707
2708impl<A: Array> ToSmallVec<A> for [A::Item]
2709where
2710    A::Item: Copy,
2711{
2712    #[inline]
2713    fn to_smallvec(&self) -> SmallVec<A> {
2714        SmallVec::from_slice(self)
2715    }
2716}
2717
2718// Immutable counterpart for `NonNull<T>`.
2719#[repr(transparent)]
2720struct ConstNonNull<T>(NonNull<T>);
2721
2722impl<T> ConstNonNull<T> {
2723    #[inline]
2724    fn new(ptr: *const T) -> Option<Self> {
2725        NonNull::new(ptr as *mut T).map(Self)
2726    }
2727    #[inline]
2728    fn as_ptr(self) -> *const T {
2729        self.0.as_ptr()
2730    }
2731}
2732
2733impl<T> Clone for ConstNonNull<T> {
2734    #[inline]
2735    fn clone(&self) -> Self {
2736        *self
2737    }
2738}
2739
2740impl<T> Copy for ConstNonNull<T> {}
2741
2742#[cfg(feature = "impl_bincode")]
2743use bincode::{
2744    de::{read::Reader, BorrowDecoder, Decode, Decoder},
2745    enc::{write::Writer, Encode, Encoder},
2746    error::{DecodeError, EncodeError},
2747    BorrowDecode,
2748};
2749
2750#[cfg(feature = "impl_bincode")]
2751impl<A, Context> Decode<Context> for SmallVec<A>
2752where
2753    A: Array,
2754    A::Item: Decode<Context>,
2755{
2756    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2757        use core::convert::TryInto;
2758        let len = u64::decode(decoder)?;
2759        let len = len
2760            .try_into()
2761            .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2762        decoder.claim_container_read::<A::Item>(len)?;
2763
2764        let mut vec = SmallVec::with_capacity(len);
2765        if unty::type_equal::<A::Item, u8>() {
2766            // Initialize the smallvec's buffer.  Note that we need to do this
2767            // through the raw pointer as we cannot name the type
2768            // [u8; N] even though A::Item is u8.
2769            let ptr = vec.as_mut_ptr();
2770            // SAFETY: A::Item is u8 and the smallvec has been allocated with
2771            // enough capacity
2772            unsafe {
2773                core::ptr::write_bytes(ptr, 0, len);
2774                vec.set_len(len);
2775            }
2776            // Read the data into the smallvec's buffer.
2777            let slice = vec.as_mut_slice();
2778            // SAFETY: A::Item is u8
2779            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2780            decoder.reader().read(slice)?;
2781        } else {
2782            for _ in 0..len {
2783                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2784                vec.push(A::Item::decode(decoder)?);
2785            }
2786        }
2787        Ok(vec)
2788    }
2789}
2790
2791#[cfg(feature = "impl_bincode")]
2792impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2793where
2794    A: Array,
2795    A::Item: BorrowDecode<'de, Context>,
2796{
2797    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2798        decoder: &mut D,
2799    ) -> Result<Self, DecodeError> {
2800        use core::convert::TryInto;
2801        let len = u64::decode(decoder)?;
2802        let len = len
2803            .try_into()
2804            .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2805        decoder.claim_container_read::<A::Item>(len)?;
2806
2807        let mut vec = SmallVec::with_capacity(len);
2808        if unty::type_equal::<A::Item, u8>() {
2809            // Initialize the smallvec's buffer.  Note that we need to do this
2810            // through the raw pointer as we cannot name the type
2811            // [u8; N] even though A::Item is u8.
2812            let ptr = vec.as_mut_ptr();
2813            // SAFETY: A::Item is u8 and the smallvec has been allocated with
2814            // enough capacity
2815            unsafe {
2816                core::ptr::write_bytes(ptr, 0, len);
2817                vec.set_len(len);
2818            }
2819            // Read the data into the smallvec's buffer.
2820            let slice = vec.as_mut_slice();
2821            // SAFETY: A::Item is u8
2822            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2823            decoder.reader().read(slice)?;
2824        } else {
2825            for _ in 0..len {
2826                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2827                vec.push(A::Item::borrow_decode(decoder)?);
2828            }
2829        }
2830        Ok(vec)
2831    }
2832}
2833
2834#[cfg(feature = "impl_bincode")]
2835impl<A> Encode for SmallVec<A>
2836where
2837    A: Array,
2838    A::Item: Encode,
2839{
2840    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2841        (self.len() as u64).encode(encoder)?;
2842        if unty::type_equal::<A::Item, u8>() {
2843            // Safety: A::Item is u8
2844            let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2845            encoder.writer().write(slice)?;
2846        } else {
2847            for item in self.iter() {
2848                item.encode(encoder)?;
2849            }
2850        }
2851        Ok(())
2852    }
2853}