Skip to main content

piece_tree/
smallvec_vendor.rs

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