Skip to main content

piece_tree/
smallvec_vendor.rs

1// Portions of this file are copied from the `smallvec` crate.
2// Copyright (c) The Servo Project Developers.
3// Licensed under the MIT License (https://opensource.org/licenses/MIT).
4// Modified by Mark Tyrkba (rakivo) in 2026.
5
6// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9// option. This file may not be copied, modified, or distributed
10// except according to those terms.
11
12//! Small vectors in various sizes. These store a certain number of elements inline, and fall back
13//! to the heap for larger allocations.  This can be a useful optimization for improving cache
14//! locality and reducing allocator traffic for workloads that fit within the inline buffer.
15//!
16//! ## `no_std` support
17//!
18//! By default, `smallvec` does not depend on `std`.  However, the optional
19//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
20//! When this feature is enabled, `smallvec` depends on `std`.
21//!
22//! ## Optional features
23//!
24//! ### `serde`
25//!
26//! When this optional dependency is enabled, `SmallVec` implements the `serde::Serialize` and
27//! `serde::Deserialize` traits.
28//!
29//! ### `write`
30//!
31//! When this feature is enabled, `SmallVec<[u8; _]>` implements the `std::io::Write` trait.
32//! This feature is not compatible with `#![no_std]` programs.
33//!
34//! ### `union`
35//!
36//! **This feature requires Rust 1.49.**
37//!
38//! When the `union` feature is enabled `smallvec` will track its state (inline or spilled)
39//! without the use of an enum tag, reducing the size of the `smallvec` by one machine word.
40//! This means that there is potentially no space overhead compared to `Vec`.
41//! Note that `smallvec` can still be larger than `Vec` if the inline buffer is larger than two
42//! machine words.
43//!
44//! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml.
45//! Note that this feature requires Rust 1.49.
46//!
47//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
48//!
49//! ### `const_generics`
50//!
51//! **This feature requires Rust 1.51.**
52//!
53//! When this feature is enabled, `SmallVec` works with any arrays of any size, not just a fixed
54//! list of sizes.
55//!
56//! ### `const_new`
57//!
58//! **This feature requires Rust 1.51.**
59//!
60//! This feature exposes the functions [`SmallVec::new_const`], [`SmallVec::from_const`], and [`smallvec_inline`] which enables the `SmallVec` to be initialized from a const context.
61//! For details, see the
62//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
63//!
64//! ### `drain_filter`
65//!
66//! **This feature is unstable.** It may change to match the unstable `drain_filter` method in libstd.
67//!
68//! Enables the `drain_filter` method, which produces an iterator that calls a user-provided
69//! closure to determine which elements of the vector to remove and yield from the iterator.
70//!
71//! ### `drain_keep_rest`
72//!
73//! **This feature is unstable.** It may change to match the unstable `drain_keep_rest` method in libstd.
74//!
75//! Enables the `DrainFilter::keep_rest` method.
76//!
77//! ### `specialization`
78//!
79//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
80//!
81//! When this feature is enabled, `SmallVec::from(slice)` has improved performance for slices
82//! of `Copy` types.  (Without this feature, you can use `SmallVec::from_slice` to get optimal
83//! performance for `Copy` types.)
84//!
85//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
86//!
87//! ### `may_dangle`
88//!
89//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
90//!
91//! This feature makes the Rust compiler less strict about use of vectors that contain borrowed
92//! references. For details, see the
93//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
94//!
95//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
96
97#![cfg_attr(docsrs, feature(doc_cfg))]
98#![deny(missing_docs)]
99
100#[doc(hidden)]
101pub extern crate alloc;
102
103#[cfg(any(test, feature = "write"))]
104extern crate std;
105
106#[allow(deprecated)]
107use alloc::alloc::{Layout, LayoutErr};
108use alloc::boxed::Box;
109use alloc::{vec, vec::Vec};
110use core::borrow::{Borrow, BorrowMut};
111use core::cmp;
112use core::fmt;
113use core::hash::{Hash, Hasher};
114use core::hint::unreachable_unchecked;
115use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator};
116use core::mem;
117use core::mem::MaybeUninit;
118use core::ops::{self, Range, RangeBounds};
119use core::ptr::{self, NonNull};
120use core::slice::{self, SliceIndex};
121
122#[cfg(feature = "write")]
123use std::io;
124
125/// Creates a [`SmallVec`] containing the arguments.
126///
127/// Note that unlike array expressions this syntax supports all elements
128/// which implement [`Clone`] and the number of elements doesn't have to be
129/// a constant.
130///
131/// This will use `clone` to duplicate an expression, so one should be careful
132/// using this with types having a nonstandard `Clone` implementation. For
133/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
134/// to the same boxed integer value, not five references pointing to independently
135/// boxed integers.
136#[macro_export]
137macro_rules! smallvec {
138    // count helper: transform any expression into 1
139    (@one $x:expr) => (1usize);
140    () => (
141        $crate::SmallVec::new()
142    );
143    ($elem:expr; $n:expr) => ({
144        $crate::SmallVec::from_elem($elem, $n)
145    });
146    ($($x:expr),+$(,)?) => ({
147        let count = 0usize $(+ $crate::smallvec!(@one $x))+;
148        let mut vec = $crate::SmallVec::new();
149        if count <= vec.inline_size() {
150            $(vec.push($x);)*
151            vec
152        } else {
153            $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
154        }
155    });
156}
157
158/// Error type for APIs with fallible heap allocation
159#[derive(Debug)]
160pub enum CollectionAllocErr {
161    /// Overflow `usize::MAX` or other error during size computation
162    CapacityOverflow,
163    /// The allocator return an error
164    AllocErr {
165        /// The layout that was passed to the allocator
166        layout: Layout,
167    },
168}
169
170impl fmt::Display for CollectionAllocErr {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(f, "Allocation error: {:?}", self)
173    }
174}
175
176#[allow(deprecated)]
177impl From<LayoutErr> for CollectionAllocErr {
178    fn from(_: LayoutErr) -> Self {
179        CollectionAllocErr::CapacityOverflow
180    }
181}
182
183fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
184    match result {
185        Ok(x) => x,
186        Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
187        Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
188    }
189}
190
191/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
192/// <https://github.com/rust-lang/rust/issues/55724>
193fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
194    let size = mem::size_of::<T>()
195        .checked_mul(n)
196        .ok_or(CollectionAllocErr::CapacityOverflow)?;
197    let align = mem::align_of::<T>();
198    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
199}
200
201unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
202    // This unwrap should succeed since the same did when allocating.
203    let layout = layout_array::<T>(capacity).unwrap();
204    unsafe { alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout) }
205}
206
207/// An iterator that removes the items from a `SmallVec` and yields them by value.
208///
209/// Returned from [`SmallVec::drain`][1].
210///
211/// [1]: struct.SmallVec.html#method.drain
212pub struct Drain<'a, T: 'a + Array> {
213    tail_start: usize,
214    tail_len: usize,
215    iter: slice::Iter<'a, T::Item>,
216    vec: NonNull<SmallVec<T>>,
217}
218
219impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
220where
221    T::Item: fmt::Debug,
222{
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
225    }
226}
227
228unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
229unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
230
231impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
232    type Item = T::Item;
233
234    #[inline]
235    fn next(&mut self) -> Option<T::Item> {
236        self.iter
237            .next()
238            .map(|reference| unsafe { ptr::read(reference) })
239    }
240
241    #[inline]
242    fn size_hint(&self) -> (usize, Option<usize>) {
243        self.iter.size_hint()
244    }
245}
246
247impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
248    #[inline]
249    fn next_back(&mut self) -> Option<T::Item> {
250        self.iter
251            .next_back()
252            .map(|reference| unsafe { ptr::read(reference) })
253    }
254}
255
256impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
257    #[inline]
258    fn len(&self) -> usize {
259        self.iter.len()
260    }
261}
262
263impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
264
265impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
266    fn drop(&mut self) {
267        self.for_each(drop);
268
269        if self.tail_len > 0 {
270            unsafe {
271                let source_vec = self.vec.as_mut();
272
273                // memmove back untouched tail, update to new length
274                let start = source_vec.len();
275                let tail = self.tail_start;
276                if tail != start {
277                    // as_mut_ptr creates a &mut, invalidating other pointers.
278                    // This pattern avoids calling it with a pointer already present.
279                    let ptr = source_vec.as_mut_ptr();
280                    let src = ptr.add(tail);
281                    let dst = ptr.add(start);
282                    ptr::copy(src, dst, self.tail_len);
283                }
284                source_vec.set_len(start + self.tail_len);
285            }
286        }
287    }
288}
289
290enum SmallVecData<A: Array> {
291    Inline(MaybeUninit<A>),
292    // Using NonNull and NonZero here allows to reduce size of `SmallVec`.
293    Heap {
294        // Since we never allocate on heap
295        // unless our capacity is bigger than inline capacity
296        // heap capacity cannot be less than 1.
297        // Therefore, pointer cannot be null too.
298        ptr: NonNull<A::Item>,
299        len: usize,
300    },
301}
302
303impl<A: Array> SmallVecData<A> {
304    #[inline]
305    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
306        match self {
307            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
308            _ => unreachable!(),
309        }
310    }
311    #[inline]
312    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
313        match self {
314            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
315            _ => unreachable!(),
316        }
317    }
318    #[inline]
319    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
320        SmallVecData::Inline(inline)
321    }
322    #[inline]
323    unsafe fn into_inline(self) -> MaybeUninit<A> {
324        match self {
325            SmallVecData::Inline(a) => a,
326            _ => unreachable!(),
327        }
328    }
329    #[inline]
330    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
331        match self {
332            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
333            _ => unreachable!(),
334        }
335    }
336    #[inline]
337    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
338        match self {
339            SmallVecData::Heap { ptr, len } => (*ptr, len),
340            _ => unreachable!(),
341        }
342    }
343    #[inline]
344    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
345        SmallVecData::Heap { ptr, len }
346    }
347}
348
349unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
350unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
351
352/// A `Vec`-like container that can store a small number of elements inline.
353///
354/// `SmallVec` acts like a vector, but can store a limited amount of data inline within the
355/// `SmallVec` struct rather than in a separate allocation.  If the data exceeds this limit, the
356/// `SmallVec` will "spill" its data onto the heap, allocating a new buffer to hold it.
357///
358/// The amount of data that a `SmallVec` can store inline depends on its backing store. The backing
359/// store can be any type that implements the `Array` trait; usually it is a small fixed-sized
360/// array.  For example a `SmallVec<[u64; 8]>` can hold up to eight 64-bit integers inline.
361///
362/// ## Example
363///
364pub struct SmallVec<A: Array> {
365    // The capacity field is used to determine which of the storage variants is active:
366    // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds the current length of the vector (number of elements actually in use).
367    // If capacity > Self::inline_capacity() then the heap variant is used and capacity holds the size of the memory allocation.
368    capacity: usize,
369    data: SmallVecData<A>,
370}
371
372impl<A: Array> SmallVec<A> {
373    /// Construct an empty vector
374    #[inline]
375    pub fn new() -> SmallVec<A> {
376        // Try to detect invalid custom implementations of `Array`. Hopefully,
377        // this check should be optimized away entirely for valid ones.
378        assert!(
379            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
380                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
381        );
382        SmallVec {
383            capacity: 0,
384            data: SmallVecData::from_inline(MaybeUninit::uninit()),
385        }
386    }
387
388    /// Construct an empty vector with enough capacity pre-allocated to store at least `n`
389    /// elements.
390    ///
391    /// Will create a heap allocation only if `n` is larger than the inline capacity.
392    #[inline]
393    pub fn with_capacity(n: usize) -> Self {
394        let mut v = SmallVec::new();
395        v.reserve_exact(n);
396        v
397    }
398
399    /// Construct a new `SmallVec` from a `Vec<A::Item>`.
400    ///
401    /// Elements will be copied to the inline buffer if `vec.capacity() <= Self::inline_capacity()`.
402    #[inline]
403    pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
404        if vec.capacity() <= Self::inline_capacity() {
405            // Cannot use Vec with smaller capacity
406            // because we use value of `Self::capacity` field as indicator.
407            unsafe {
408                let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit());
409                let len = vec.len();
410                vec.set_len(0);
411                ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
412
413                SmallVec {
414                    capacity: len,
415                    data,
416                }
417            }
418        } else {
419            let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
420            mem::forget(vec);
421            let ptr = NonNull::new(ptr)
422                // See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
423                .expect("Cannot be null by `Vec` invariant");
424
425            SmallVec {
426                capacity: cap,
427                data: SmallVecData::from_heap(ptr, len),
428            }
429        }
430    }
431
432    #[inline]
433    pub fn from_buf(buf: A) -> SmallVec<A> {
434        SmallVec {
435            capacity: A::size(),
436            data: SmallVecData::from_inline(MaybeUninit::new(buf)),
437        }
438    }
439
440    /// Constructs a new `SmallVec` on the stack from an `A` without
441    /// copying elements. Also sets the length, which must be less or
442    /// equal to the size of `buf`.
443    ///
444    #[inline]
445    pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
446        assert!(len <= A::size());
447        unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
448    }
449
450    /// Constructs a new `SmallVec` on the stack from an `A` without
451    /// copying elements. Also sets the length. The user is responsible
452    /// for ensuring that `len <= A::size()`.
453    #[inline]
454    pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
455        SmallVec {
456            capacity: len,
457            data: SmallVecData::from_inline(buf),
458        }
459    }
460
461    /// Sets the length of a vector.
462    ///
463    /// This will explicitly set the size of the vector, without actually
464    /// modifying its buffers, so it is up to the caller to ensure that the
465    /// vector is actually the specified size.
466    pub unsafe fn set_len(&mut self, new_len: usize) {
467        let (_, len_ptr, _) = self.triple_mut();
468        *len_ptr = new_len;
469    }
470
471    /// The maximum number of elements this vector can hold inline
472    #[inline]
473    fn inline_capacity() -> usize {
474        if mem::size_of::<A::Item>() > 0 {
475            A::size()
476        } else {
477            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
478            // Therefore all items are at the same address,
479            // and any array size has capacity for infinitely many items.
480            // The capacity is limited by the bit width of the length field.
481            //
482            // `Vec` also does this:
483            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
484            //
485            // In our case, this also ensures that a smallvec of zero-size items never spills,
486            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
487            core::usize::MAX
488        }
489    }
490
491    /// The maximum number of elements this vector can hold inline
492    #[inline]
493    pub fn inline_size(&self) -> usize {
494        Self::inline_capacity()
495    }
496
497    /// The number of elements stored in the vector
498    #[inline]
499    pub fn len(&self) -> usize {
500        self.triple().1
501    }
502
503    /// Returns `true` if the vector is empty
504    #[inline]
505    pub fn is_empty(&self) -> bool {
506        self.len() == 0
507    }
508
509    /// The number of items the vector can hold without reallocating
510    #[inline]
511    pub fn capacity(&self) -> usize {
512        self.triple().2
513    }
514
515    /// Returns a tuple with (data ptr, len, capacity)
516    /// Useful to get all `SmallVec` properties with a single check of the current storage variant.
517    #[inline]
518    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
519        unsafe {
520            if self.spilled() {
521                let (ptr, len) = self.data.heap();
522                (ptr, len, self.capacity)
523            } else {
524                (self.data.inline(), self.capacity, Self::inline_capacity())
525            }
526        }
527    }
528
529    /// Returns a tuple with (data ptr, len ptr, capacity)
530    #[inline]
531    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
532        unsafe {
533            if self.spilled() {
534                let (ptr, len_ptr) = self.data.heap_mut();
535                (ptr, len_ptr, self.capacity)
536            } else {
537                (
538                    self.data.inline_mut(),
539                    &mut self.capacity,
540                    Self::inline_capacity(),
541                )
542            }
543        }
544    }
545
546    /// Returns `true` if the data has spilled into a separate heap-allocated buffer.
547    #[inline]
548    pub fn spilled(&self) -> bool {
549        self.capacity > Self::inline_capacity()
550    }
551
552    /// Creates a draining iterator that removes the specified range in the vector
553    /// and yields the removed items.
554    ///
555    /// Note 1: The element range is removed even if the iterator is only
556    /// partially consumed or not consumed at all.
557    ///
558    /// Note 2: It is unspecified how many elements are removed from the vector
559    /// if the `Drain` value is leaked.
560    ///
561    /// # Panics
562    ///
563    /// Panics if the starting point is greater than the end point or if
564    /// the end point is greater than the length of the vector.
565    pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
566    where
567        R: RangeBounds<usize>,
568    {
569        use core::ops::Bound::*;
570
571        let len = self.len();
572        let start = match range.start_bound() {
573            Included(&n) => n,
574            Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
575            Unbounded => 0,
576        };
577        let end = match range.end_bound() {
578            Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
579            Excluded(&n) => n,
580            Unbounded => len,
581        };
582
583        assert!(start <= end);
584        assert!(end <= len);
585
586        unsafe {
587            self.set_len(start);
588
589            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
590
591            Drain {
592                tail_start: end,
593                tail_len: len - end,
594                iter: range_slice.iter(),
595                // Since self is a &mut, passing it to a function would invalidate the slice iterator.
596                vec: NonNull::new_unchecked(self as *mut _),
597            }
598        }
599    }
600
601    /// Append an item to the vector.
602    #[inline]
603    pub fn push(&mut self, value: A::Item) {
604        unsafe {
605            let (mut ptr, mut len, cap) = self.triple_mut();
606            if *len == cap {
607                self.reserve_one_unchecked();
608                let (heap_ptr, heap_len) = self.data.heap_mut();
609                ptr = heap_ptr;
610                len = heap_len;
611            }
612            ptr::write(ptr.as_ptr().add(*len), value);
613            *len += 1;
614        }
615    }
616
617    /// Remove an item from the end of the vector and return it, or None if empty.
618    #[inline]
619    pub fn pop(&mut self) -> Option<A::Item> {
620        unsafe {
621            let (ptr, len_ptr, _) = self.triple_mut();
622            let ptr: *const _ = ptr.as_ptr();
623            if *len_ptr == 0 {
624                return None;
625            }
626            let last_index = *len_ptr - 1;
627            *len_ptr = last_index;
628            Some(ptr::read(ptr.add(last_index)))
629        }
630    }
631
632    /// Moves all the elements of `other` into `self`, leaving `other` empty.
633    pub fn append<B>(&mut self, other: &mut SmallVec<B>)
634    where
635        B: Array<Item = A::Item>,
636    {
637        self.extend(other.drain(..))
638    }
639
640    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
641    ///
642    /// Panics if `new_cap` is less than the vector's length
643    /// or if the capacity computation overflows `usize`.
644    pub fn grow(&mut self, new_cap: usize) {
645        infallible(self.try_grow(new_cap))
646    }
647
648    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
649    ///
650    /// Panics if `new_cap` is less than the vector's length
651    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
652        unsafe {
653            let unspilled = !self.spilled();
654            let (ptr, &mut len, cap) = self.triple_mut();
655            assert!(new_cap >= len);
656            if new_cap <= Self::inline_capacity() {
657                if unspilled {
658                    return Ok(());
659                }
660                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
661                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
662                self.capacity = len;
663                deallocate(ptr, cap);
664            } else if new_cap != cap {
665                let layout = layout_array::<A::Item>(new_cap)?;
666                debug_assert!(layout.size() > 0);
667                let new_alloc;
668                if unspilled {
669                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
670                        .ok_or(CollectionAllocErr::AllocErr { layout })?
671                        .cast();
672                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
673                } else {
674                    // This should never fail since the same succeeded
675                    // when previously allocating `ptr`.
676                    let old_layout = layout_array::<A::Item>(cap)?;
677
678                    let new_ptr =
679                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
680                    new_alloc = NonNull::new(new_ptr)
681                        .ok_or(CollectionAllocErr::AllocErr { layout })?
682                        .cast();
683                }
684                self.data = SmallVecData::from_heap(new_alloc, len);
685                self.capacity = new_cap;
686            }
687            Ok(())
688        }
689    }
690
691    /// Reserve capacity for `additional` more elements to be inserted.
692    ///
693    /// May reserve more space to avoid frequent reallocations.
694    ///
695    /// Panics if the capacity computation overflows `usize`.
696    #[inline]
697    pub fn reserve(&mut self, additional: usize) {
698        infallible(self.try_reserve(additional))
699    }
700
701    /// Internal method used to grow in push() and insert(), where we know already we have to grow.
702    #[cold]
703    fn reserve_one_unchecked(&mut self) {
704        debug_assert_eq!(self.len(), self.capacity());
705        let new_cap = self.len()
706            .checked_add(1)
707            .and_then(usize::checked_next_power_of_two)
708            .expect("capacity overflow");
709        infallible(self.try_grow(new_cap))
710    }
711
712    /// Reserve capacity for `additional` more elements to be inserted.
713    ///
714    /// May reserve more space to avoid frequent reallocations.
715    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
716        // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
717        // calls to it from callers.
718        let (_, &mut len, cap) = self.triple_mut();
719        if cap - len >= additional {
720            return Ok(());
721        }
722        let new_cap = len
723            .checked_add(additional)
724            .and_then(usize::checked_next_power_of_two)
725            .ok_or(CollectionAllocErr::CapacityOverflow)?;
726        self.try_grow(new_cap)
727    }
728
729    /// Reserve the minimum capacity for `additional` more elements to be inserted.
730    ///
731    /// Panics if the new capacity overflows `usize`.
732    pub fn reserve_exact(&mut self, additional: usize) {
733        infallible(self.try_reserve_exact(additional))
734    }
735
736    /// Reserve the minimum capacity for `additional` more elements to be inserted.
737    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
738        let (_, &mut len, cap) = self.triple_mut();
739        if cap - len >= additional {
740            return Ok(());
741        }
742        let new_cap = len
743            .checked_add(additional)
744            .ok_or(CollectionAllocErr::CapacityOverflow)?;
745        self.try_grow(new_cap)
746    }
747
748    /// Shrink the capacity of the vector as much as possible.
749    ///
750    /// When possible, this will move data from an external heap buffer to the vector's inline
751    /// storage.
752    pub fn shrink_to_fit(&mut self) {
753        if !self.spilled() {
754            return;
755        }
756        let len = self.len();
757        if self.inline_size() >= len {
758            unsafe {
759                let (ptr, len) = self.data.heap();
760                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
761                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
762                deallocate(ptr.0, self.capacity);
763                self.capacity = len;
764            }
765        } else if self.capacity() > len {
766            self.grow(len);
767        }
768    }
769
770    /// Shorten the vector, keeping the first `len` elements and dropping the rest.
771    ///
772    /// If `len` is greater than or equal to the vector's current length, this has no
773    /// effect.
774    ///
775    /// This does not re-allocate.  If you want the vector's capacity to shrink, call
776    /// `shrink_to_fit` after truncating.
777    pub fn truncate(&mut self, len: usize) {
778        unsafe {
779            let (ptr, len_ptr, _) = self.triple_mut();
780            let ptr = ptr.as_ptr();
781            while len < *len_ptr {
782                let last_index = *len_ptr - 1;
783                *len_ptr = last_index;
784                ptr::drop_in_place(ptr.add(last_index));
785            }
786        }
787    }
788
789    /// Extracts a slice containing the entire vector.
790    ///
791    /// Equivalent to `&s[..]`.
792    pub fn as_slice(&self) -> &[A::Item] {
793        self
794    }
795
796    /// Extracts a mutable slice of the entire vector.
797    ///
798    /// Equivalent to `&mut s[..]`.
799    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
800        self
801    }
802
803    /// Remove the element at position `index`, replacing it with the last element.
804    ///
805    /// This does not preserve ordering, but is O(1).
806    ///
807    /// Panics if `index` is out of bounds.
808    #[inline]
809    pub fn swap_remove(&mut self, index: usize) -> A::Item {
810        let len = self.len();
811        self.swap(len - 1, index);
812        self.pop()
813            .unwrap_or_else(|| unsafe { unreachable_unchecked() })
814    }
815
816    /// Remove all elements from the vector.
817    #[inline]
818    pub fn clear(&mut self) {
819        self.truncate(0);
820    }
821
822    /// Remove and return the element at position `index`, shifting all elements after it to the
823    /// left.
824    ///
825    /// Panics if `index` is out of bounds.
826    pub fn remove(&mut self, index: usize) -> A::Item {
827        unsafe {
828            let (ptr, len_ptr, _) = self.triple_mut();
829            let len = *len_ptr;
830            assert!(index < len);
831            *len_ptr = len - 1;
832            let ptr = ptr.as_ptr().add(index);
833            let item = ptr::read(ptr);
834            ptr::copy(ptr.add(1), ptr, len - index - 1);
835            item
836        }
837    }
838
839    /// Insert an element at position `index`, shifting all elements after it to the right.
840    ///
841    /// Panics if `index > len`.
842    pub fn insert(&mut self, index: usize, element: A::Item) {
843        unsafe {
844            let (mut ptr, mut len_ptr, cap) = self.triple_mut();
845            if *len_ptr == cap {
846                self.reserve_one_unchecked();
847                let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
848                ptr = heap_ptr;
849                len_ptr = heap_len_ptr;
850            }
851            let mut ptr = ptr.as_ptr();
852            let len = *len_ptr;
853            if index > len {
854                panic!("index exceeds length");
855            }
856            // SAFETY: add is UB if index > len, but we panicked first
857            ptr = ptr.add(index);
858            if index < len {
859                // Shift element to the right of `index`.
860                ptr::copy(ptr, ptr.add(1), len - index);
861            }
862            *len_ptr = len + 1;
863            ptr::write(ptr, element);
864        }
865    }
866
867    /// Insert multiple elements at position `index`, shifting all following elements toward the
868    /// back.
869    pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
870        let mut iter = iterable.into_iter();
871        if index == self.len() {
872            return self.extend(iter);
873        }
874
875        let (lower_size_bound, _) = iter.size_hint();
876        assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset is indexable
877        assert!(index + lower_size_bound >= index); // Protect against overflow
878
879        let mut num_added = 0;
880        let old_len = self.len();
881        assert!(index <= old_len);
882
883        unsafe {
884            // Reserve space for `lower_size_bound` elements.
885            self.reserve(lower_size_bound);
886            let start = self.as_mut_ptr();
887            let ptr = start.add(index);
888
889            // Move the trailing elements.
890            ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
891
892            // In case the iterator panics, don't double-drop the items we just copied above.
893            self.set_len(0);
894            let mut guard = DropOnPanic {
895                start,
896                skip: index..(index + lower_size_bound),
897                len: old_len + lower_size_bound,
898            };
899
900            // The set_len above invalidates the previous pointers, so we must re-create them.
901            let start = self.as_mut_ptr();
902            let ptr = start.add(index);
903
904            while num_added < lower_size_bound {
905                let element = match iter.next() {
906                    Some(x) => x,
907                    None => break,
908                };
909                let cur = ptr.add(num_added);
910                ptr::write(cur, element);
911                guard.skip.start += 1;
912                num_added += 1;
913            }
914
915            if num_added < lower_size_bound {
916                // Iterator provided fewer elements than the hint. Move the tail backward.
917                ptr::copy(
918                    ptr.add(lower_size_bound),
919                    ptr.add(num_added),
920                    old_len - index,
921                );
922            }
923            // There are no more duplicate or uninitialized slots, so the guard is not needed.
924            self.set_len(old_len + num_added);
925            mem::forget(guard);
926        }
927
928        // Insert any remaining elements one-by-one.
929        for element in iter {
930            self.insert(index + num_added, element);
931            num_added += 1;
932        }
933
934        struct DropOnPanic<T> {
935            start: *mut T,
936            skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
937            len: usize,
938        }
939
940        impl<T> Drop for DropOnPanic<T> {
941            fn drop(&mut self) {
942                for i in 0..self.len {
943                    if !self.skip.contains(&i) {
944                        unsafe {
945                            ptr::drop_in_place(self.start.add(i));
946                        }
947                    }
948                }
949            }
950        }
951    }
952
953    /// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec` has already spilled onto
954    /// the heap.
955    pub fn into_vec(mut self) -> Vec<A::Item> {
956        if self.spilled() {
957            unsafe {
958                let (ptr, &mut len) = self.data.heap_mut();
959                let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
960                mem::forget(self);
961                v
962            }
963        } else {
964            self.into_iter().collect()
965        }
966    }
967
968    /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled
969    /// onto the heap.
970    ///
971    /// Note that this will drop any excess capacity.
972    pub fn into_boxed_slice(self) -> Box<[A::Item]> {
973        self.into_vec().into_boxed_slice()
974    }
975
976    /// Convert the `SmallVec` into an `A` if possible. Otherwise return `Err(Self)`.
977    ///
978    /// This method returns `Err(Self)` if the `SmallVec` is too short (and the `A` contains uninitialized elements),
979    /// or if the `SmallVec` is too long (and all the elements were spilled to the heap).
980    pub fn into_inner(self) -> Result<A, Self> {
981        if self.spilled() || self.len() != A::size() {
982            // Note: A::size, not Self::inline_capacity
983            Err(self)
984        } else {
985            unsafe {
986                let data = ptr::read(&self.data);
987                mem::forget(self);
988                Ok(data.into_inline().assume_init())
989            }
990        }
991    }
992
993    /// Retains only the elements specified by the predicate.
994    ///
995    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
996    /// This method operates in place and preserves the order of the retained
997    /// elements.
998    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
999        let mut del = 0;
1000        let len = self.len();
1001        for i in 0..len {
1002            if !f(&mut self[i]) {
1003                del += 1;
1004            } else if del > 0 {
1005                self.swap(i - del, i);
1006            }
1007        }
1008        self.truncate(len - del);
1009    }
1010
1011    /// Retains only the elements specified by the predicate.
1012    ///
1013    /// This method is identical in behaviour to [`retain`]; it is included only
1014    /// to maintain api-compatibility with `std::Vec`, where the methods are
1015    /// separate for historical reasons.
1016    pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1017        self.retain(f)
1018    }
1019
1020    /// Removes consecutive duplicate elements.
1021    pub fn dedup(&mut self)
1022    where
1023        A::Item: PartialEq<A::Item>,
1024    {
1025        self.dedup_by(|a, b| a == b);
1026    }
1027
1028    /// Removes consecutive duplicate elements using the given equality relation.
1029    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1030    where
1031        F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1032    {
1033        // See the implementation of Vec::dedup_by in the
1034        // standard library for an explanation of this algorithm.
1035        let len = self.len();
1036        if len <= 1 {
1037            return;
1038        }
1039
1040        let ptr = self.as_mut_ptr();
1041        let mut w: usize = 1;
1042
1043        unsafe {
1044            for r in 1..len {
1045                let p_r = ptr.add(r);
1046                let p_wm1 = ptr.add(w - 1);
1047                if !same_bucket(&mut *p_r, &mut *p_wm1) {
1048                    if r != w {
1049                        let p_w = p_wm1.add(1);
1050                        mem::swap(&mut *p_r, &mut *p_w);
1051                    }
1052                    w += 1;
1053                }
1054            }
1055        }
1056
1057        self.truncate(w);
1058    }
1059
1060    /// Removes consecutive elements that map to the same key.
1061    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1062    where
1063        F: FnMut(&mut A::Item) -> K,
1064        K: PartialEq<K>,
1065    {
1066        self.dedup_by(|a, b| key(a) == key(b));
1067    }
1068
1069    /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1070    ///
1071    /// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each
1072    /// additional slot filled with the result of calling the closure `f`. The return values from `f`
1073    /// will end up in the `SmallVec` in the order they have been generated.
1074    ///
1075    /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1076    ///
1077    /// This method uses a closure to create new values on every push. If you'd rather `Clone` a given
1078    /// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass
1079    /// `Default::default()` as the second argument.
1080    ///
1081    /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1082    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1083    where
1084        F: FnMut() -> A::Item,
1085    {
1086        let old_len = self.len();
1087        if old_len < new_len {
1088            let mut f = f;
1089            let additional = new_len - old_len;
1090            self.reserve(additional);
1091            for _ in 0..additional {
1092                self.push(f());
1093            }
1094        } else if old_len > new_len {
1095            self.truncate(new_len);
1096        }
1097    }
1098
1099    /// Creates a `SmallVec` directly from the raw components of another
1100    /// `SmallVec`.
1101    ///
1102    /// # Safety
1103    ///
1104    /// This is highly unsafe, due to the number of invariants that aren't
1105    /// checked:
1106    ///
1107    /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1108    ///   spilled storage (at least, it's highly likely to be incorrect if it
1109    ///   wasn't).
1110    /// * `ptr`'s `A::Item` type needs to be the same size and alignment that
1111    ///   it was allocated with
1112    /// * `length` needs to be less than or equal to `capacity`.
1113    /// * `capacity` needs to be the capacity that the pointer was allocated
1114    ///   with.
1115    ///
1116    /// Violating these may cause problems like corrupting the allocator's
1117    /// internal data structures.
1118    ///
1119    /// Additionally, `capacity` must be greater than the amount of inline
1120    /// storage `A` has; that is, the new `SmallVec` must need to spill over
1121    /// into heap allocated storage. This condition is asserted against.
1122    ///
1123    /// The ownership of `ptr` is effectively transferred to the
1124    /// `SmallVec` which may then deallocate, reallocate or change the
1125    /// contents of memory pointed to by the pointer at will. Ensure
1126    /// that nothing else uses the pointer after calling this
1127    /// function.
1128    #[inline]
1129    pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1130        // SAFETY: We require caller to provide same ptr as we alloc
1131        // and we never alloc null pointer.
1132        let ptr = unsafe {
1133            debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1134            NonNull::new_unchecked(ptr)
1135        };
1136        assert!(capacity > Self::inline_capacity());
1137        SmallVec {
1138            capacity,
1139            data: SmallVecData::from_heap(ptr, length),
1140        }
1141    }
1142
1143    /// Returns a raw pointer to the vector's buffer.
1144    pub fn as_ptr(&self) -> *const A::Item {
1145        // We shadow the slice method of the same name to avoid going through
1146        // `deref`, which creates an intermediate reference that may place
1147        // additional safety constraints on the contents of the slice.
1148        self.triple().0.as_ptr()
1149    }
1150
1151    /// Returns a raw mutable pointer to the vector's buffer.
1152    pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1153        // We shadow the slice method of the same name to avoid going through
1154        // `deref_mut`, which creates an intermediate reference that may place
1155        // additional safety constraints on the contents of the slice.
1156        self.triple_mut().0.as_ptr()
1157    }
1158}
1159
1160impl<A: Array> SmallVec<A>
1161where
1162    A::Item: Copy,
1163{
1164    /// Copy the elements from a slice into a new `SmallVec`.
1165    ///
1166    /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`.
1167    pub fn from_slice(slice: &[A::Item]) -> Self {
1168        let len = slice.len();
1169        if len <= Self::inline_capacity() {
1170            SmallVec {
1171                capacity: len,
1172                data: SmallVecData::from_inline(unsafe {
1173                    let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1174                    ptr::copy_nonoverlapping(
1175                        slice.as_ptr(),
1176                        data.as_mut_ptr() as *mut A::Item,
1177                        len,
1178                    );
1179                    data
1180                }),
1181            }
1182        } else {
1183            let mut b = slice.to_vec();
1184            let cap = b.capacity();
1185            let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1186            mem::forget(b);
1187            SmallVec {
1188                capacity: cap,
1189                data: SmallVecData::from_heap(ptr, len),
1190            }
1191        }
1192    }
1193
1194    /// Copy elements from a slice into the vector at position `index`, shifting any following
1195    /// elements toward the back.
1196    ///
1197    /// For slices of `Copy` types, this is more efficient than `insert`.
1198    #[inline]
1199    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1200        self.reserve(slice.len());
1201
1202        let len = self.len();
1203        assert!(index <= len);
1204
1205        unsafe {
1206            let slice_ptr = slice.as_ptr();
1207            let ptr = self.as_mut_ptr().add(index);
1208            ptr::copy(ptr, ptr.add(slice.len()), len - index);
1209            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1210            self.set_len(len + slice.len());
1211        }
1212    }
1213
1214    /// Copy elements from a slice and append them to the vector.
1215    ///
1216    /// For slices of `Copy` types, this is more efficient than `extend`.
1217    #[inline]
1218    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1219        let len = self.len();
1220        self.insert_from_slice(len, slice);
1221    }
1222}
1223
1224impl<A: Array> SmallVec<A>
1225where
1226    A::Item: Clone,
1227{
1228    /// Resizes the vector so that its length is equal to `len`.
1229    ///
1230    /// If `len` is less than the current length, the vector simply truncated.
1231    ///
1232    /// If `len` is greater than the current length, `value` is appended to the
1233    /// vector until its length equals `len`.
1234    pub fn resize(&mut self, len: usize, value: A::Item) {
1235        let old_len = self.len();
1236
1237        if len > old_len {
1238            self.extend(repeat(value).take(len - old_len));
1239        } else {
1240            self.truncate(len);
1241        }
1242    }
1243
1244    /// Creates a `SmallVec` with `n` copies of `elem`.
1245    pub fn from_elem(elem: A::Item, n: usize) -> Self {
1246        if n > Self::inline_capacity() {
1247            vec![elem; n].into()
1248        } else {
1249            let mut v = SmallVec::<A>::new();
1250            unsafe {
1251                let (ptr, len_ptr, _) = v.triple_mut();
1252                let ptr = ptr.as_ptr();
1253                let mut local_len = SetLenOnDrop::new(len_ptr);
1254
1255                for i in 0..n {
1256                    ::core::ptr::write(ptr.add(i), elem.clone());
1257                    local_len.increment_len(1);
1258                }
1259            }
1260            v
1261        }
1262    }
1263}
1264
1265impl<A: Array> ops::Deref for SmallVec<A> {
1266    type Target = [A::Item];
1267    #[inline]
1268    fn deref(&self) -> &[A::Item] {
1269        unsafe {
1270            let (ptr, len, _) = self.triple();
1271            slice::from_raw_parts(ptr.as_ptr(), len)
1272        }
1273    }
1274}
1275
1276impl<A: Array> ops::DerefMut for SmallVec<A> {
1277    #[inline]
1278    fn deref_mut(&mut self) -> &mut [A::Item] {
1279        unsafe {
1280            let (ptr, &mut len, _) = self.triple_mut();
1281            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1282        }
1283    }
1284}
1285
1286impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1287    #[inline]
1288    fn as_ref(&self) -> &[A::Item] {
1289        self
1290    }
1291}
1292
1293impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1294    #[inline]
1295    fn as_mut(&mut self) -> &mut [A::Item] {
1296        self
1297    }
1298}
1299
1300impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1301    #[inline]
1302    fn borrow(&self) -> &[A::Item] {
1303        self
1304    }
1305}
1306
1307impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1308    #[inline]
1309    fn borrow_mut(&mut self) -> &mut [A::Item] {
1310        self
1311    }
1312}
1313
1314#[cfg(feature = "write")]
1315impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1316    #[inline]
1317    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1318        self.extend_from_slice(buf);
1319        Ok(buf.len())
1320    }
1321
1322    #[inline]
1323    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1324        self.extend_from_slice(buf);
1325        Ok(())
1326    }
1327
1328    #[inline]
1329    fn flush(&mut self) -> io::Result<()> {
1330        Ok(())
1331    }
1332}
1333
1334impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
1335where
1336    A::Item: Clone,
1337{
1338    #[inline]
1339    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
1340        slice.iter().cloned().collect()
1341    }
1342}
1343
1344impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
1345    #[inline]
1346    fn from(vec: Vec<A::Item>) -> SmallVec<A> {
1347        SmallVec::from_vec(vec)
1348    }
1349}
1350
1351impl<A: Array> From<A> for SmallVec<A> {
1352    #[inline]
1353    fn from(array: A) -> SmallVec<A> {
1354        SmallVec::from_buf(array)
1355    }
1356}
1357
1358impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
1359    type Output = I::Output;
1360
1361    fn index(&self, index: I) -> &I::Output {
1362        &(**self)[index]
1363    }
1364}
1365
1366impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
1367    fn index_mut(&mut self, index: I) -> &mut I::Output {
1368        &mut (&mut **self)[index]
1369    }
1370}
1371
1372impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
1373    #[inline]
1374    fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
1375        let mut v = SmallVec::new();
1376        v.extend(iterable);
1377        v
1378    }
1379}
1380
1381impl<A: Array> Extend<A::Item> for SmallVec<A> {
1382    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
1383        let mut iter = iterable.into_iter();
1384        let (lower_size_bound, _) = iter.size_hint();
1385        self.reserve(lower_size_bound);
1386
1387        unsafe {
1388            let (ptr, len_ptr, cap) = self.triple_mut();
1389            let ptr = ptr.as_ptr();
1390            let mut len = SetLenOnDrop::new(len_ptr);
1391            while len.get() < cap {
1392                if let Some(out) = iter.next() {
1393                    ptr::write(ptr.add(len.get()), out);
1394                    len.increment_len(1);
1395                } else {
1396                    return;
1397                }
1398            }
1399        }
1400
1401        for elem in iter {
1402            self.push(elem);
1403        }
1404    }
1405}
1406
1407impl<A: Array> fmt::Debug for SmallVec<A>
1408where
1409    A::Item: fmt::Debug,
1410{
1411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1412        f.debug_list().entries(self.iter()).finish()
1413    }
1414}
1415
1416impl<A: Array> Default for SmallVec<A> {
1417    #[inline]
1418    fn default() -> SmallVec<A> {
1419        SmallVec::new()
1420    }
1421}
1422
1423impl<A: Array> Drop for SmallVec<A> {
1424    fn drop(&mut self) {
1425        unsafe {
1426            if self.spilled() {
1427                let (ptr, &mut len) = self.data.heap_mut();
1428                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
1429            } else {
1430                ptr::drop_in_place(&mut self[..]);
1431            }
1432        }
1433    }
1434}
1435
1436impl<A: Array> Clone for SmallVec<A>
1437where
1438    A::Item: Clone,
1439{
1440    #[inline]
1441    fn clone(&self) -> SmallVec<A> {
1442        SmallVec::from(self.as_slice())
1443    }
1444
1445    fn clone_from(&mut self, source: &Self) {
1446        // Inspired from `impl Clone for Vec`.
1447
1448        // drop anything that will not be overwritten
1449        self.truncate(source.len());
1450
1451        // self.len <= other.len due to the truncate above, so the
1452        // slices here are always in-bounds.
1453        let (init, tail) = source.split_at(self.len());
1454
1455        // reuse the contained values' allocations/resources.
1456        self.clone_from_slice(init);
1457        self.extend(tail.iter().cloned());
1458    }
1459}
1460
1461impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
1462where
1463    A::Item: PartialEq<B::Item>,
1464{
1465    #[inline]
1466    fn eq(&self, other: &SmallVec<B>) -> bool {
1467        self[..] == other[..]
1468    }
1469}
1470
1471impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
1472
1473impl<A: Array> PartialOrd for SmallVec<A>
1474where
1475    A::Item: PartialOrd,
1476{
1477    #[inline]
1478    fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
1479        PartialOrd::partial_cmp(&**self, &**other)
1480    }
1481}
1482
1483impl<A: Array> Ord for SmallVec<A>
1484where
1485    A::Item: Ord,
1486{
1487    #[inline]
1488    fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
1489        Ord::cmp(&**self, &**other)
1490    }
1491}
1492
1493impl<A: Array> Hash for SmallVec<A>
1494where
1495    A::Item: Hash,
1496{
1497    fn hash<H: Hasher>(&self, state: &mut H) {
1498        (**self).hash(state)
1499    }
1500}
1501
1502unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
1503
1504/// An iterator that consumes a `SmallVec` and yields its items by value.
1505///
1506/// Returned from [`SmallVec::into_iter`][1].
1507///
1508/// [1]: struct.SmallVec.html#method.into_iter
1509pub struct IntoIter<A: Array> {
1510    data: SmallVec<A>,
1511    current: usize,
1512    end: usize,
1513}
1514
1515impl<A: Array> fmt::Debug for IntoIter<A>
1516where
1517    A::Item: fmt::Debug,
1518{
1519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1520        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
1521    }
1522}
1523
1524impl<A: Array + Clone> Clone for IntoIter<A>
1525where
1526    A::Item: Clone,
1527{
1528    fn clone(&self) -> IntoIter<A> {
1529        SmallVec::from(self.as_slice()).into_iter()
1530    }
1531}
1532
1533impl<A: Array> Drop for IntoIter<A> {
1534    fn drop(&mut self) {
1535        for _ in self {}
1536    }
1537}
1538
1539impl<A: Array> Iterator for IntoIter<A> {
1540    type Item = A::Item;
1541
1542    #[inline]
1543    fn next(&mut self) -> Option<A::Item> {
1544        if self.current == self.end {
1545            None
1546        } else {
1547            unsafe {
1548                let current = self.current;
1549                self.current += 1;
1550                Some(ptr::read(self.data.as_ptr().add(current)))
1551            }
1552        }
1553    }
1554
1555    #[inline]
1556    fn size_hint(&self) -> (usize, Option<usize>) {
1557        let size = self.end - self.current;
1558        (size, Some(size))
1559    }
1560}
1561
1562impl<A: Array> DoubleEndedIterator for IntoIter<A> {
1563    #[inline]
1564    fn next_back(&mut self) -> Option<A::Item> {
1565        if self.current == self.end {
1566            None
1567        } else {
1568            unsafe {
1569                self.end -= 1;
1570                Some(ptr::read(self.data.as_ptr().add(self.end)))
1571            }
1572        }
1573    }
1574}
1575
1576impl<A: Array> ExactSizeIterator for IntoIter<A> {}
1577impl<A: Array> FusedIterator for IntoIter<A> {}
1578
1579impl<A: Array> IntoIter<A> {
1580    /// Returns the remaining items of this iterator as a slice.
1581    pub fn as_slice(&self) -> &[A::Item] {
1582        let len = self.end - self.current;
1583        unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
1584    }
1585
1586    /// Returns the remaining items of this iterator as a mutable slice.
1587    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1588        let len = self.end - self.current;
1589        unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
1590    }
1591}
1592
1593impl<A: Array> IntoIterator for SmallVec<A> {
1594    type IntoIter = IntoIter<A>;
1595    type Item = A::Item;
1596    fn into_iter(mut self) -> Self::IntoIter {
1597        unsafe {
1598            // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements
1599            let len = self.len();
1600            self.set_len(0);
1601            IntoIter {
1602                data: self,
1603                current: 0,
1604                end: len,
1605            }
1606        }
1607    }
1608}
1609
1610impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
1611    type IntoIter = slice::Iter<'a, A::Item>;
1612    type Item = &'a A::Item;
1613    fn into_iter(self) -> Self::IntoIter {
1614        self.iter()
1615    }
1616}
1617
1618impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
1619    type IntoIter = slice::IterMut<'a, A::Item>;
1620    type Item = &'a mut A::Item;
1621    fn into_iter(self) -> Self::IntoIter {
1622        self.iter_mut()
1623    }
1624}
1625
1626/// Types that can be used as the backing store for a [`SmallVec`].
1627pub unsafe trait Array {
1628    /// The type of the array's elements.
1629    type Item;
1630    /// Returns the number of items the array can hold.
1631    fn size() -> usize;
1632}
1633
1634/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1635///
1636/// Copied from <https://github.com/rust-lang/rust/pull/36355>
1637struct SetLenOnDrop<'a> {
1638    len: &'a mut usize,
1639    local_len: usize,
1640}
1641
1642impl<'a> SetLenOnDrop<'a> {
1643    #[inline]
1644    fn new(len: &'a mut usize) -> Self {
1645        SetLenOnDrop {
1646            local_len: *len,
1647            len,
1648        }
1649    }
1650
1651    #[inline]
1652    fn get(&self) -> usize {
1653        self.local_len
1654    }
1655
1656    #[inline]
1657    fn increment_len(&mut self, increment: usize) {
1658        self.local_len += increment;
1659    }
1660}
1661
1662impl<'a> Drop for SetLenOnDrop<'a> {
1663    #[inline]
1664    fn drop(&mut self) {
1665        *self.len = self.local_len;
1666    }
1667}
1668
1669unsafe impl<T, const N: usize> Array for [T; N] {
1670    type Item = T;
1671    #[inline]
1672    fn size() -> usize {
1673        N
1674    }
1675}
1676
1677// Immutable counterpart for `NonNull<T>`.
1678#[repr(transparent)]
1679struct ConstNonNull<T>(NonNull<T>);
1680
1681impl<T> ConstNonNull<T> {
1682    #[inline]
1683    fn new(ptr: *const T) -> Option<Self> {
1684        NonNull::new(ptr as *mut T).map(Self)
1685    }
1686    #[inline]
1687    fn as_ptr(self) -> *const T {
1688        self.0.as_ptr()
1689    }
1690}
1691
1692impl<T> Clone for ConstNonNull<T> {
1693    #[inline]
1694    fn clone(&self) -> Self {
1695        *self
1696    }
1697}
1698
1699impl<T> Copy for ConstNonNull<T> {}