tiny_vec/
lib.rs

1/*  Copyright (C) 2025 Saúl Valdelvira
2 *
3 *  This program is free software: you can redistribute it and/or modify
4 *  it under the terms of the GNU General Public License as published by
5 *  the Free Software Foundation, version 3.
6 *
7 *  This program is distributed in the hope that it will be useful,
8 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *  GNU General Public License for more details.
11 *
12 *  You should have received a copy of the GNU General Public License
13 *  along with this program.  If not, see <https://www.gnu.org/licenses/>. */
14
15//! Tiny Vec
16//!
17//! A dynamic array that can store a small amount of elements on the stack.
18//!
19//! This struct provides a vec-like API, but performs small-vector optimization.
20//! This means that a `TinyVec<T, N>` stores up to N elements on the stack.
21//! If the vector grows bigger than that, it moves the contents to the heap.
22#![cfg_attr(not(feature = "alloc"), doc = "
23# WARNING
24The `alloc` feature is disabled. This means that a `TinyVec` won't be able to
25grow over it's stack capacity.
26
27The following functions from [TinyVec] can cause the program to panic if the vector exceeds its
28capacity.
29- [with_capacity]
30- [from_array](TinyVec::from_array)
31- [from_tiny_vec](TinyVec::from_tiny_vec)
32- [from_slice_copied](TinyVec::from_slice_copied)
33- [repeat](TinyVec::repeat)
34- [reserve]
35- [reserve_exact]
36- [push]
37- [push_unchecked](TinyVec::push_unchecked)
38- [insert](TinyVec::insert)
39- [insert_unchecked](TinyVec::insert_unchecked)
40- [insert_slice](TinyVec::insert_slice)
41- [insert_slice_copied](TinyVec::insert_slice_copied)
42- [insert_iter](TinyVec::insert_iter)
43- [resize](TinyVec::resize)
44- [reserve](TinyVec::reserve)
45- [resize_with](TinyVec::resize_with)
46- [resize_zeroed](TinyVec::resize_zeroed)
47- [extend_from_slice](TinyVec::extend_from_slice)
48- [extend_from_slice_copied](TinyVec::extend_from_slice_copied)
49- [extend_from_within](TinyVec::extend_from_within)
50- [extend_from_within_copied](TinyVec::extend_from_within_copied)
51- [append](TinyVec::append)
52
53## Alternatives
54| May Panic | No Panic |
55| --------- | -------- |
56|  [push]   | [push_within_capacity](TinyVec::push_within_capacity) |
57|  [reserve]   | [try_reserve](TinyVec::try_reserve) |
58|  [reserve_exact]   | [try_reserve_exact](TinyVec::try_reserve) |
59| [with_capacity] | [try_with_capacity](TinyVec::try_with_capacity) |
60
61[push]: TinyVec::push
62[reserve]: TinyVec::reserve
63[reserve_exact]: TinyVec::reserve_exact
64[with_capacity]: TinyVec::with_capacity
65")]
66//!
67//! # Example
68//! ```
69//! use tiny_vec::TinyVec;
70//!
71//! let mut tv = TinyVec::<u8, 16>::new();
72//!
73//! for n in 0..16 {
74//!     tv.push(n);
75//! }
76//!
77//! // Up to this point, no heap allocations are needed.
78//! // All the elements are stored on the stack.
79//!
80//! tv.push(123); // This moves the vector to the heap
81//!
82//! assert_eq!(&tv[..], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
83//!                       10, 11, 12, 13, 14, 15, 123])
84//! ```
85//!
86//! # Memory layout
87//! For a TinyVec<T, N>
88//!
89//! On the stack (length <= N)
90//! - [T; N] : Data
91//! - usize  : Length
92//!
93//! On the heap (length > N)
94//! - T*    : Data
95//! - usize : Capacity
96//! - usize : Length
97//!
98//! If N is equal to `sizeof (T*, usize) / sizeof T`, the
99//! TinyVec is the same size as a regular vector \
100//! NOTE: The [n_elements_for_stack] function returns the maximun
101//! number of elements for a type, such that it doesn't waste extra
102//! space when moved to the heap
103
104#![allow(incomplete_features)]
105#![cfg_attr(feature = "use-nightly-features", feature(min_specialization, slice_swap_unchecked, generic_const_exprs))]
106#![cfg_attr(feature = "use-nightly-features", feature(extend_one, extend_one_unchecked))]
107#![cfg_attr(feature = "use-nightly-features", feature(iter_advance_by))]
108
109#![no_std]
110
111#[cfg(feature = "alloc")]
112extern crate alloc;
113#[cfg(feature = "alloc")]
114use alloc::{
115    vec::Vec,
116    boxed::Box
117};
118use drain::Drain;
119use extract_if::ExtractIf;
120
121use core::marker::PhantomData;
122use core::mem::{self, ManuallyDrop, MaybeUninit};
123use core::ops::{Bound, Deref, DerefMut, Range, RangeBounds};
124use core::ptr::NonNull;
125use core::{fmt, ptr};
126use core::slice;
127
128mod raw;
129use raw::RawVec;
130pub use raw::ResizeError;
131
132mod cow;
133pub use cow::Cow;
134
135pub mod iter;
136pub mod drain;
137pub mod extract_if;
138
139union TinyVecInner<T, const N: usize> {
140    stack: ManuallyDrop<[MaybeUninit<T>; N]>,
141    raw: RawVec<T>,
142}
143
144impl<T, const N: usize> TinyVecInner<T, N> {
145    #[inline(always)]
146    const unsafe fn as_ptr_stack(&self) -> *const T {
147        unsafe { &raw const self.stack as *const T }
148    }
149
150    #[inline(always)]
151    const unsafe fn as_ptr_stack_mut(&mut self) -> *mut T {
152        unsafe { &raw mut self.stack as *mut T }
153    }
154
155    #[inline(always)]
156    const unsafe fn as_ptr_heap(&self) -> *const T {
157        unsafe { self.raw.ptr.as_ptr() }
158    }
159
160    #[inline(always)]
161    const unsafe fn as_ptr_heap_mut(&mut self) -> *mut T {
162        unsafe { self.raw.ptr.as_ptr() }
163    }
164}
165
166#[repr(transparent)]
167struct Length(usize);
168
169impl Length {
170    #[inline(always)]
171    const fn new_stack(len: usize) -> Self {
172        Self(len << 1)
173    }
174
175    #[inline(always)]
176    #[cfg(feature = "alloc")]
177    const fn new_heap(len: usize) -> Self {
178        Self(len << 1 | 0b1)
179    }
180
181    #[inline(always)]
182    const fn is_stack(&self) -> bool {
183        (self.0 & 0b1) == 0
184    }
185
186    #[inline(always)]
187    const fn set_heap(&mut self) {
188        self.0 |= 0b1;
189    }
190
191    #[inline(always)]
192    #[cfg(feature = "alloc")]
193    const fn set_stack(&mut self) {
194        self.0 &= 0b0;
195    }
196
197    #[inline(always)]
198    const fn set(&mut self, n: usize) {
199        self.0 &= 0b1;
200        self.0 |= n << 1;
201    }
202
203    #[inline(always)]
204    const fn get(&self) -> usize {
205        self.0 >> 1
206    }
207
208    #[inline(always)]
209    const fn add(&mut self, n: usize) {
210        self.0 += n << 1;
211    }
212
213    #[inline(always)]
214    const fn sub(&mut self, n: usize) {
215        self.0 -= n << 1;
216    }
217}
218
219/// Macro to create [TinyVec]s
220///
221/// # Example
222/// ```
223/// use tiny_vec::{TinyVec, tinyvec};
224///
225/// // Create a TinyVec with a list of elements
226/// let v: TinyVec<_, 10> = tinyvec![1, 2, 3, 4];
227/// assert_eq!(&v[0..4], &[1, 2, 3, 4]);
228///
229/// // Create a TinyVec with 100 zeroes
230/// let v: TinyVec<_, 10> = tinyvec![0; 100];
231/// assert_eq!(v[20], 0);
232/// ```
233#[macro_export]
234macro_rules! tinyvec {
235    (@one $e:expr) => { 1 };
236    () => {
237        $crate::TinyVec::new()
238    };
239    ($elem:expr; $n:expr) => ({
240        let mut tv = $crate::TinyVec::new();
241        tv.resize($n, $elem);
242        tv
243    });
244    ($($x:expr),+ $(,)?) => ({
245        let n = const {
246            0 $( + $crate::tinyvec!(@one $x) )+
247        };
248        let mut vec = $crate::TinyVec::with_capacity(n);
249        $(vec.push($x);)+
250        vec
251    });
252}
253
254/// The maximun number of elements that can be stored in the stack
255/// for the vector, without incrementing it's size
256///
257/// This means, that [`n_elements_for_stack`] for T returns the max
258/// number of elements, so that when switching to a heap allocated
259/// buffer, no stack size is wasted
260///
261/// # Examples
262/// ```
263/// use tiny_vec::n_elements_for_stack;
264///
265/// assert_eq!(n_elements_for_stack::<u8>(), 16);
266/// assert_eq!(n_elements_for_stack::<u16>(), 8);
267/// assert_eq!(n_elements_for_stack::<i32>(), 4);
268/// ```
269pub const fn n_elements_for_stack<T>() -> usize {
270    n_elements_for_bytes::<T>(mem::size_of::<RawVec<T>>())
271}
272
273/// The maximun number of elements of type T, that can be stored on
274/// the given byte size
275///
276/// # Examples
277/// ```
278/// use tiny_vec::n_elements_for_bytes;
279///
280/// assert_eq!(n_elements_for_bytes::<u8>(2), 2);
281/// assert_eq!(n_elements_for_bytes::<u16>(4), 2);
282/// assert_eq!(n_elements_for_bytes::<i32>(17), 4);
283/// ```
284pub const fn n_elements_for_bytes<T>(n: usize) -> usize {
285    let size = mem::size_of::<T>();
286    if size == 0 {
287        isize::MAX as usize
288    } else {
289        n / size
290    }
291}
292
293fn slice_range<R>(range: R, len: usize) -> Range<usize>
294where
295    R: RangeBounds<usize>
296{
297    let start = match range.start_bound() {
298        Bound::Included(n) => *n,
299        Bound::Excluded(n) => *n + 1,
300        Bound::Unbounded => 0,
301    };
302
303    let end = match range.end_bound() {
304        Bound::Included(n) => *n + 1,
305        Bound::Excluded(n) => *n,
306        Bound::Unbounded => len,
307    };
308
309    assert!(start <= end);
310    assert!(end <= len);
311
312    Range { start, end }
313}
314
315/// A dynamic array that can store a small amount of elements on the stack.
316pub struct TinyVec<T,
317    #[cfg(not(feature = "use-nightly-features"))]
318    const N: usize,
319
320    #[cfg(feature = "use-nightly-features")]
321    const N: usize = { n_elements_for_stack::<T>() },
322> {
323    inner: TinyVecInner<T, N>,
324    len: Length,
325}
326
327impl<T, const N: usize> TinyVec<T, N> {
328
329    unsafe fn switch_to_heap(&mut self, n: usize, exact: bool) -> Result<(), ResizeError> {
330        debug_assert!(self.lives_on_stack());
331        debug_assert_ne!(mem::size_of::<T>(), 0);
332
333        let mut vec = RawVec::new();
334        if exact {
335            vec.try_expand_if_needed_exact(0, self.len.get() + n)?;
336        } else {
337            vec.try_expand_if_needed(0, self.len.get() + n)?;
338        }
339        unsafe {
340            let src = self.inner.as_ptr_stack();
341            let dst = vec.ptr.as_ptr();
342            ptr::copy_nonoverlapping(src, dst, self.len());
343            self.inner.raw = vec;
344        }
345        self.len.set_heap();
346
347        Ok(())
348    }
349
350    #[cfg(feature = "alloc")]
351    unsafe fn switch_to_stack(&mut self) {
352        debug_assert!(!self.lives_on_stack());
353        debug_assert_ne!(mem::size_of::<T>(), 0,
354            "We shouldn't call switch_to_stack, since T is a ZST, and\
355            shouldn't be moved to the heap in the first place");
356
357        let mut rv = unsafe { self.inner.raw };
358
359        let mut stack = [const { MaybeUninit::uninit() }; N];
360
361        unsafe {
362            let src = rv.ptr.as_ptr();
363            let dst = stack.as_mut_ptr() as *mut T;
364            ptr::copy_nonoverlapping(src,dst,self.len());
365            rv.destroy();
366        }
367
368        self.inner.stack =  ManuallyDrop::new(stack);
369        self.len.set_stack();
370    }
371
372    const unsafe fn split_at_spare_mut_with_len(&mut self) -> (&mut [T], &mut [MaybeUninit<T>], &mut Length) {
373        unsafe {
374            let len = self.len();
375            let ptr = self.as_mut_ptr();
376
377            let spare_ptr = ptr.add(len).cast::<MaybeUninit<T>>();
378            let spare_len = self.capacity() - len;
379
380            let slice = slice::from_raw_parts_mut(ptr, len);
381            let spare_slice = slice::from_raw_parts_mut(spare_ptr, spare_len);
382
383            (slice, spare_slice, &mut self.len)
384        }
385    }
386
387    fn _shrink(&mut self, cap: usize) {
388        assert!(!self.lives_on_stack());
389        assert!(cap >= self.len.get());
390
391        /* SAFETY: It's safe to assume that we are on the heap,
392         * because of the assertion above */
393        if cap <= N {
394            unsafe { self.switch_to_stack(); }
395        } else {
396            unsafe { self.inner.raw.shrink_to_fit(cap); };
397        }
398    }
399}
400
401impl<T, const N: usize> TinyVec<T, N> {
402
403    /// Creates a new [TinyVec]
404    pub const fn new() -> Self {
405        let stack = [ const { MaybeUninit::uninit() }; N ];
406        Self {
407            inner: TinyVecInner { stack: ManuallyDrop::new(stack) },
408            len: Length::new_stack(0),
409        }
410    }
411
412    /// Creates a new [TinyVec] with the specified initial capacity
413    pub fn with_capacity(cap: usize) -> Self {
414        Self::try_with_capacity(cap).unwrap_or_else(|err| err.handle())
415    }
416
417    /// Like [with_capacity](Self::with_capacity), but it returns a [Result].
418    ///
419    /// If an allocation error hapens when reserving the memory, returns
420    /// a [ResizeError] unlike [with_capacity](Self::with_capacity), which
421    /// panics in such case.
422    pub fn try_with_capacity(cap: usize) -> Result<Self,ResizeError> {
423        let mut len = Length(0);
424        let inner = if cap <= N {
425            let s = [const { MaybeUninit::uninit() }; N];
426            TinyVecInner {
427                stack: ManuallyDrop::new(s)
428            }
429        } else {
430            len.set_heap();
431            TinyVecInner {
432                raw: RawVec::try_with_capacity(cap)?
433            }
434        };
435
436        Ok(Self { inner, len })
437    }
438
439    /// Creates a new [TinyVec] from the given array
440    ///
441    /// # Example
442    /// ```
443    /// use tiny_vec::TinyVec;
444    ///
445    /// let tv = TinyVec::<i32, 10>::from_array([1, 2, 3, 4]);
446    ///
447    /// assert_eq!(tv.capacity(), 10);
448    /// assert!(tv.lives_on_stack());
449    /// ```
450    pub fn from_array<const M: usize>(arr: [T; M]) -> Self {
451        let arr = ManuallyDrop::new(arr);
452        let mut tv = Self::with_capacity(M);
453
454        let src = arr.as_ptr();
455        let dst = tv.as_mut_ptr();
456
457        unsafe {
458            ptr::copy(src, dst, M);
459            tv.set_len(M);
460        }
461
462        tv
463    }
464
465    /// Like [from_array](Self::from_array), but the array's length
466    /// and the TinyVec's N are equal, so we can call it on const functions.
467    ///
468    /// # Example
469    /// ```
470    /// use tiny_vec::TinyVec;
471    ///
472    /// let tv = TinyVec::from_array_eq_size([1, 2, 3, 4]);
473    ///
474    /// assert_eq!(tv.capacity(), 4);
475    /// assert!(tv.lives_on_stack());
476    /// ```
477    pub const fn from_array_eq_size(arr: [T; N]) -> Self {
478        let mut tv = Self::new();
479
480        let src = arr.as_ptr();
481        let dst = tv.as_mut_ptr();
482
483        unsafe {
484            ptr::copy(src, dst, N);
485            tv.set_len(N);
486        }
487
488        mem::forget(arr);
489        tv
490    }
491
492    /// Creates a new [TinyVec] from the given [Vec]
493    ///
494    /// # Example
495    /// ```
496    /// use tiny_vec::TinyVec;
497    ///
498    /// let vec = vec![1, 2, 3, 4, 5];
499    ///
500    /// let tv = TinyVec::<i32, 10>::from_vec(vec);
501    ///
502    /// assert_eq!(tv, &[1, 2, 3, 4, 5]);
503    /// ```
504    #[cfg(feature = "alloc")]
505    pub fn from_vec(vec: Vec<T>) -> Self {
506        let mut vec = ManuallyDrop::new(vec);
507
508        let ptr = vec.as_mut_ptr();
509        let ptr = unsafe { NonNull::new_unchecked(ptr) };
510
511        let len = Length::new_heap(vec.len());
512        let cap = vec.capacity();
513        let raw = RawVec { cap, ptr };
514
515        let inner = TinyVecInner { raw };
516        Self { inner, len }
517    }
518
519    /// Creates a TinyVec from a boxed slice of T
520    #[cfg(feature = "alloc")]
521    pub fn from_boxed_slice(boxed: Box<[T]>) -> Self {
522        let len = boxed.len();
523        let ptr = Box::into_raw(boxed);
524        let ptr = unsafe { NonNull::new_unchecked(ptr as *mut T) };
525
526        let raw = RawVec { ptr, cap: len };
527
528        Self {
529            inner: TinyVecInner { raw },
530            len: Length::new_heap(len)
531        }
532    }
533
534    /// Builds a TinyVec from a TinyVec with a different capacity generic parameter
535    ///
536    /// # Example
537    /// ```
538    /// use tiny_vec::TinyVec;
539    ///
540    /// let v1 = TinyVec::<i32, 10>::from(&[1, 2, 3, 4]);
541    ///
542    /// let v2 = TinyVec::<i32, 7>::from_tiny_vec(v1.clone());
543    /// assert!(v2.lives_on_stack());
544    ///
545    /// let v3 = TinyVec::<i32, 2>::from_tiny_vec(v1);
546    /// /* v3 must be heap-allocated, since it can only store 2 elements
547    ///    on the stack, and v1 has 3*/
548    /// assert!(!v3.lives_on_stack());
549    /// ```
550    pub fn from_tiny_vec<const M: usize>(mut vec: TinyVec<T, M>) -> Self {
551        let len = vec.len();
552        if len > N && len > M {
553            #[cfg(feature = "alloc")] {
554                /* If the buffer must be on the heap on both src and dest,
555                * just copy the RawVec from vec to Self */
556                let tv = Self {
557                    len: Length::new_heap(len),
558                    inner: TinyVecInner {
559                        raw: unsafe { vec.inner.raw }
560                    }
561                };
562                mem::forget(vec);
563                return tv
564            }
565            #[cfg(not(feature = "alloc"))]
566            unreachable!("The length of vec won't be higher that it's capacity, \
567                so this branch will NEVER be reached");
568        }
569
570        let mut tv = Self::with_capacity(len);
571        let src = vec.as_ptr();
572        let dst = tv.as_mut_ptr();
573        unsafe {
574            /* SAFETY: src points to vec, and dst to tv. They are two different
575             * objects, so their buffers can't overap */
576            ptr::copy_nonoverlapping(src, dst, len);
577            vec.set_len(0);
578            tv.set_len(len);
579        }
580        tv
581    }
582
583    /// Creates a new [TinyVec] from the given slice.
584    ///
585    /// This function clones the elements in the slice.
586    /// If the type T is [Copy], the [from_slice_copied](Self::from_slice_copied)
587    /// function is a more optimized alternative
588    pub fn from_slice(slice: &[T]) -> Self
589    where
590        T: Clone
591    {
592        let mut v = Self::with_capacity(slice.len());
593        v.extend_from_slice_impl(slice);
594        v
595    }
596
597    /// Creates a new [TinyVec] from the given slice.
598    ///
599    /// This function copies the slice into the buffer, which
600    /// is faster that calling [clone](Clone::clone).
601    /// That's why it requires T to implement [Copy].
602    ///
603    /// For a cloning alternative, use [from_slice](Self::from_slice)
604    pub fn from_slice_copied(slice: &[T]) -> Self
605    where
606        T: Copy
607    {
608        let mut v = Self::with_capacity(slice.len());
609        v.extend_from_slice_copied(slice);
610        v
611    }
612
613    /// Creates a new [TinyVec] by copying the given
614    /// `slice` `n` times.
615    ///
616    /// # Example
617    /// ```
618    /// use tiny_vec::TinyVec;
619    ///
620    /// let vec = TinyVec::<i32, 10>::repeat(
621    ///     &[1, 2, 3, 4],
622    ///     3
623    /// );
624    ///
625    /// assert_eq!(vec, &[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]);
626    /// ```
627    pub fn repeat(slice: &[T], n: usize) -> Self
628    where
629        T: Copy
630    {
631        let mut s = Self::with_capacity(slice.len() * n);
632        let mut dst = s.as_mut_ptr();
633        let src = slice.as_ptr();
634        let len = slice.len();
635        for _ in 0..n {
636            unsafe {
637                ptr::copy(src, dst, len);
638                dst = dst.add(len);
639            }
640        }
641        s.len.set(len * n);
642        s
643    }
644
645    /// Returns the number of elements inside this vec
646    #[inline]
647    pub const fn len(&self) -> usize { self.len.get() }
648
649    /// Returns true if the vector is empty
650    #[inline]
651    pub const fn is_empty(&self) -> bool { self.len.get() == 0 }
652
653    /// Returns the allocated capacity for this vector
654    #[inline]
655    pub const fn capacity(&self) -> usize {
656        if mem::size_of::<T>() == 0 {
657            return isize::MAX as usize
658        }
659        if self.len.is_stack() {
660            N
661        } else {
662            unsafe { self.inner.raw.cap }
663        }
664    }
665
666    /// Returns true if the vector is currently using stack memory.
667    ///
668    /// This means that [Self::len] <= `N`
669    ///
670    /// # Example
671    /// ```
672    /// use tiny_vec::TinyVec;
673    ///
674    /// let mut vec = TinyVec::<i32, 5>::new();
675    ///
676    /// for n in 0..5 {
677    ///     vec.push(n)
678    /// }
679    ///
680    /// assert!(vec.lives_on_stack());
681    /// vec.push(6);
682    /// assert!(!vec.lives_on_stack());
683    /// ```
684    #[inline]
685    pub const fn lives_on_stack(&self) -> bool { self.len.is_stack() }
686
687    /// Gets a const pointer to the vec's buffer
688    #[inline]
689    pub const fn as_ptr(&self) -> *const T {
690        unsafe {
691            if self.len.is_stack() {
692                self.inner.as_ptr_stack()
693            } else {
694                self.inner.as_ptr_heap()
695            }
696        }
697    }
698
699    /// Gets a mutable pointer to the vec's buffer
700    #[inline]
701    pub const fn as_mut_ptr(&mut self) -> *mut T {
702        unsafe {
703            if self.len.is_stack() {
704                self.inner.as_ptr_stack_mut()
705            } else {
706                self.inner.as_ptr_heap_mut()
707            }
708        }
709    }
710
711    /// Gets a mutable pointer to the vec's buffer as a [NonNull]
712    #[inline]
713    pub const fn as_non_null(&mut self) -> NonNull<T> {
714        debug_assert!(!self.as_mut_ptr().is_null());
715        unsafe {
716            /* SAFETY: as_mut_ptr should never return a null ptr */
717            NonNull::new_unchecked(self.as_mut_ptr())
718        }
719    }
720
721    /// Gets a slice of the whole vector
722    #[inline]
723    pub const fn as_slice(&self) -> &[T] {
724        unsafe {
725            slice::from_raw_parts(self.as_ptr(), self.len.get())
726        }
727    }
728
729    /// Gets a mutable slice of the whole vector
730    #[inline]
731    pub const fn as_mut_slice(&mut self) -> &mut [T] {
732        unsafe {
733            slice::from_raw_parts_mut(self.as_mut_ptr(), self.len.get())
734        }
735    }
736
737    /// Reserves space for, at least, n elements
738    ///
739    /// # Panics
740    /// If an allocation error happens. For a non-panicking version
741    /// see [try_reserve](Self::try_reserve)
742    ///
743    /// # Example
744    /// ```
745    /// use tiny_vec::TinyVec;
746    ///
747    /// let mut vec = TinyVec::<i32, 5>::new();
748    ///
749    /// assert_eq!(vec.capacity(), 5);
750    /// assert!(vec.lives_on_stack());
751    /// vec.reserve(10);
752    /// assert!(vec.capacity() >= 10);
753    /// assert!(!vec.lives_on_stack());
754    /// ```
755    #[inline]
756    pub fn reserve(&mut self, n: usize) {
757        self.try_reserve(n).unwrap_or_else(|err| err.handle());
758    }
759
760    /// Like [reserve](Self::reserve), but on failure returns an [Err] variant
761    /// with a [ResizeError], instead of panicking.
762    ///
763    /// # Example
764    /// ```
765    /// use tiny_vec::{TinyVec, ResizeError};
766    ///
767    /// let mut tv = TinyVec::<u64, 10>::new();
768    ///
769    /// assert_eq!(
770    ///     tv.try_reserve(isize::MAX as usize),
771    ///     Err(ResizeError::AllocationExceedsMaximun)
772    /// );
773    /// ```
774    pub fn try_reserve(&mut self, n: usize) -> Result<(), ResizeError> {
775        if self.len.is_stack() {
776            if self.len.get() + n > self.capacity() {
777                unsafe { self.switch_to_heap(n, false)?; }
778            }
779        } else {
780            unsafe {
781                self.inner.raw.try_expand_if_needed(self.len.get(), n)?;
782            }
783        }
784        Ok(())
785    }
786
787    /// Reserves space for n more elements, but unline
788    /// [reserve](Self::reserve), this function doesn't over-allocate.
789    ///
790    /// # Panics
791    /// If an allocation error happens. For a non-panicking version
792    /// see [try_reserve_exact](Self::try_reserve_exact)
793    ///
794    /// # Example
795    /// ```
796    /// use tiny_vec::TinyVec;
797    ///
798    /// let mut vec = TinyVec::<i32, 5>::new();
799    ///
800    /// assert_eq!(vec.capacity(), 5);
801    /// assert!(vec.lives_on_stack());
802    /// vec.reserve_exact(10);
803    /// assert_eq!(vec.capacity(), 10);
804    /// assert!(!vec.lives_on_stack());
805    /// ```
806    pub fn reserve_exact(&mut self, n: usize) {
807        self.try_reserve_exact(n).unwrap_or_else(|err| err.handle())
808    }
809
810    /// Like [resize](Self::resize), but on failure returns an [Err] variant
811    /// with a [ResizeError], instead of panicking.
812    pub fn try_reserve_exact(&mut self, n: usize) -> Result<(), ResizeError> {
813        if self.len.is_stack() {
814            if self.len.get() + n > self.capacity() {
815                unsafe { self.switch_to_heap(n, true)?; }
816            }
817        } else {
818            let vec = unsafe { &mut self.inner.raw };
819            let len = self.len.get();
820            let new_cap = vec.cap.max(len + n);
821            vec.try_expand_if_needed_exact(len, new_cap)?;
822        }
823        Ok(())
824    }
825
826    /// Appends an element to the back of the vector
827    /// This operation is O(1), if no resize takes place.
828    /// If the buffer needs to be resized, it has an O(n)
829    /// time complexity.
830    ///
831    /// See also: [push_within_capacity](Self::push_within_capacity)
832    ///
833    /// # Example
834    /// ```
835    /// use tiny_vec::TinyVec;
836    ///
837    /// let mut vec = TinyVec::<i32, 5>::from(&[1, 2, 3, 4]);
838    ///
839    /// vec.push(5); // No resize. O(1)
840    /// vec.push(6); // Resize, must realloc. O(n)
841    ///
842    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5, 6]);
843    /// ```
844    #[inline]
845    pub fn push(&mut self, elem: T) {
846        self.reserve(1);
847        unsafe { self.push_unchecked(elem); }
848    }
849
850    /// Appends an element to the back of the vector without
851    /// checking for space.
852    ///
853    /// # Safety
854    /// The caller must ensure that there's enought capacity
855    /// for this element.
856    /// This means that [Self::len] < [Self::capacity]
857    ///
858    /// # Example
859    /// ```
860    /// use tiny_vec::TinyVec;
861    ///
862    /// let mut vec = TinyVec::<i32, 10>::with_capacity(10);
863    ///
864    /// // We've allocated a TinyVec with an initial capacity of 10.
865    /// // We can skip the bounds checking, since there will be room
866    /// // for all the elements on the iterator
867    /// for n in 0..10 {
868    ///     unsafe { vec.push_unchecked(n); }
869    /// }
870    /// assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
871    /// ```
872    pub unsafe fn push_unchecked(&mut self, elem: T) {
873        unsafe {
874            let dst = self.as_mut_ptr().add(self.len.get());
875            dst.write(elem);
876        }
877        self.len.add(1);
878    }
879
880    /// Try to push an element inside the vector, only if
881    /// there's room for it. If the push would've caused a
882    /// reallocation of the buffer, returns the value wrapped
883    /// on an [Err] variant.
884    ///
885    /// This operation has O(1) time complexity in all cases.
886    ///
887    /// # Example
888    /// ```
889    /// use tiny_vec::TinyVec;
890    ///
891    /// let mut vec = TinyVec::<i32, 5>::from(&[1, 2, 3, 4]);
892    ///
893    /// assert!(vec.push_within_capacity(5).is_ok());
894    ///
895    /// // No room left, the value is returned
896    /// assert_eq!(vec.push_within_capacity(6), Err(6));
897    /// ```
898    pub fn push_within_capacity(&mut self, val: T) -> Result<(),T> {
899        if self.len.get() < self.capacity() {
900            unsafe { self.push_unchecked(val); }
901            Ok(())
902        } else {
903            Err(val)
904        }
905    }
906    /// Removes the last element of this vector (if present)
907    pub const fn pop(&mut self) -> Option<T> {
908        if self.len.get() == 0 {
909            None
910        } else {
911            self.len.sub(1);
912            let val = unsafe {
913                self.as_ptr()
914                    .add(self.len.get())
915                    .read()
916            };
917            Some(val)
918        }
919    }
920
921    /// Removes and returns the last element from a vector if the `predicate`
922    /// returns true, or [None] if the predicate returns false or the vector
923    /// is empty (the predicate will not be called in that case).
924    ///
925    /// # Example
926    /// ```
927    /// use tiny_vec::TinyVec;
928    ///
929    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
930    /// let pred = |x: &mut i32| *x % 2 == 0;
931    ///
932    /// assert_eq!(vec.pop_if(pred), Some(4));
933    /// assert_eq!(vec, [1, 2, 3]);
934    /// assert_eq!(vec.pop_if(pred), None);
935    /// ```
936    pub fn pop_if<F>(&mut self, predicate: F) -> Option<T>
937    where
938        F: FnOnce(&mut T) -> bool
939    {
940        let len = self.len();
941        if len == 0 { return None }
942
943        unsafe {
944            let last = self.as_mut_ptr().add(len - 1);
945            predicate(&mut *last).then(|| {
946                self.len.sub(1);
947                last.read()
948            })
949        }
950    }
951
952    /// Inserts an element in the given index position
953    ///
954    /// This operation has a worst case time complexity of O(n),
955    /// since it needs to move elements on range [index, len) one
956    /// position to the right.
957    ///
958    /// # Example
959    /// ```
960    /// use tiny_vec::TinyVec;
961    ///
962    /// let mut vec = TinyVec::<i32, 10>::from(&[1, 2, 3, 4]);
963    ///
964    /// vec.insert(2, -1);
965    /// assert_eq!(vec.as_slice(), &[1, 2, -1, 3, 4]);
966    ///
967    /// // An insert on vec.len() behaves like a push
968    /// vec.insert(vec.len(), 5);
969    /// assert_eq!(vec.as_slice(), &[1, 2, -1, 3, 4, 5]);
970    /// ```
971    pub fn insert(&mut self, index: usize, elem: T) -> Result<(),T> {
972        if index > self.len.get() {
973            return Err(elem)
974        }
975        unsafe { self.insert_unchecked(index, elem); }
976        Ok(())
977    }
978
979    /// Like [insert](Self::insert), but without bounds checking
980    ///
981    /// # Safety
982    /// The index should be <= self.len
983    pub unsafe fn insert_unchecked(&mut self, index: usize, elem: T) {
984        self.reserve(1);
985        unsafe {
986            let ptr = self.as_mut_ptr();
987            ptr::copy(
988                ptr.add(index),
989                ptr.add(index + 1),
990                self.len.get() - index,
991            );
992            ptr.add(index).write(elem);
993        }
994        self.len.add(1);
995    }
996
997    /// Inserts all the elements of the given slice into the
998    /// vector, at the given index
999    ///
1000    /// This function clones the elements in the slice.
1001    ///
1002    /// If the type T is [Copy], the [insert_slice_copied]
1003    /// function is a more optimized alternative
1004    ///
1005    /// # Errors
1006    /// If the index is out of bounds, returns the slice as an [Err] variant
1007    ///
1008    /// # Example
1009    /// ```
1010    /// use tiny_vec::TinyVec;
1011    ///
1012    /// let mut vec = TinyVec::from(["abc".to_string(), "ghi".to_string()]);
1013    /// vec.insert_slice(1, &[
1014    ///     "__".to_string(),
1015    ///     "def".to_string(),
1016    ///     "__".to_string(),
1017    /// ]);
1018    ///
1019    /// assert_eq!(vec.as_slice(), &["abc", "__", "def", "__", "ghi"]);
1020    /// ```
1021    /// [insert_slice_copied]: Self::insert_slice_copied
1022    #[inline]
1023    pub fn insert_slice<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>
1024    where
1025        T: Clone
1026    {
1027        self.insert_slice_impl(index, elems)
1028    }
1029
1030    /// Inserts all the elements of the given slice into the
1031    /// vector, at the given index
1032    ///
1033    /// This function copies the slice into the buffer, which
1034    /// is faster that calling [clone]
1035    /// That's why it requires T to implement [Copy].
1036    ///
1037    /// For a cloning alternative, use [insert_slice]
1038    ///
1039    /// # Example
1040    /// ```
1041    /// use tiny_vec::TinyVec;
1042    ///
1043    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
1044    /// vec.insert_slice_copied(2, &[-1, -2, -3]);
1045    /// assert_eq!(vec.as_slice(), &[1, 2, -1, -2, -3, 3, 4]);
1046    /// ```
1047    /// [clone]: Clone::clone
1048    /// [insert_slice]: Self::insert_slice
1049    pub fn insert_slice_copied<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>
1050    where
1051        T: Copy
1052    {
1053        if index > self.len() {
1054            return Err(elems)
1055        }
1056
1057        let len = elems.len();
1058        self.reserve(len);
1059        unsafe {
1060            let ptr = self.as_mut_ptr();
1061            ptr::copy(
1062                ptr.add(index),
1063                ptr.add(index + len),
1064                self.len.get() - index,
1065            );
1066            ptr::copy_nonoverlapping(
1067                elems.as_ptr(),
1068                ptr.add(index),
1069                len
1070            );
1071        }
1072        self.len.add(len);
1073
1074        Ok(())
1075    }
1076
1077    /// Inserts all the elements on the given iterator at the given index
1078    ///
1079    /// # Errors
1080    /// If the index is out of bounds, returns the passed iterator, wrapped
1081    /// on an [Err] variant.
1082    ///
1083    /// # Example
1084    /// ```
1085    /// use tiny_vec::TinyVec;
1086    ///
1087    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
1088    ///
1089    /// vec.insert_iter(2, (-3..-1));
1090    /// assert_eq!(vec.as_slice(), &[1, 2, -3, -2, 3, 4]);
1091    /// ```
1092    pub fn insert_iter<I>(&mut self, index: usize, it: I) -> Result<(), I>
1093    where
1094        I: IntoIterator<Item = T>,
1095        <I as IntoIterator>::IntoIter: ExactSizeIterator,
1096    {
1097        if index > self.len() {
1098            return Err(it);
1099        }
1100
1101        let it = it.into_iter();
1102        let len = it.len();
1103        self.reserve(len);
1104        unsafe {
1105            let ptr = self.as_mut_ptr();
1106            ptr::copy(
1107                ptr.add(index),
1108                ptr.add(index + len),
1109                self.len.get() - index,
1110            );
1111            let mut ptr = ptr.add(index);
1112            for elem in it {
1113                ptr.write(elem);
1114                ptr = ptr.add(1);
1115                self.len.add(1);
1116            }
1117        }
1118        Ok(())
1119    }
1120
1121    /// Resizes the vector, cloning elem to fill any possible new slots
1122    ///
1123    /// If new_len < self.len, behaves like [truncate](Self::truncate)
1124    ///
1125    /// # Example
1126    /// ```
1127    /// use tiny_vec::TinyVec;
1128    ///
1129    /// let mut vec = TinyVec::<i32, 5>::new();
1130    ///
1131    /// vec.resize(5, 0);
1132    /// assert_eq!(vec.len(), 5);
1133    /// assert_eq!(vec.as_slice(), &[0, 0, 0, 0, 0]);
1134    /// ```
1135    pub fn resize(&mut self, new_len: usize, elem: T)
1136    where
1137        T: Clone
1138    {
1139        if new_len < self.len() {
1140            self.truncate(new_len);
1141        } else {
1142            self.resize_impl(new_len, elem);
1143        }
1144    }
1145
1146    /// Resizes the vector, using the given generator closure
1147    /// to fill any possible new slots
1148    ///
1149    /// If new_len < self.len, behaves like [truncate](Self::truncate)
1150    ///
1151    /// # Example
1152    /// ```
1153    /// use tiny_vec::TinyVec;
1154    ///
1155    /// let mut v = TinyVec::<i32, 10>::new();
1156    ///
1157    /// let mut n = 0;
1158    /// v.resize_with(5, || {
1159    ///     n += 1;
1160    ///     n
1161    /// });
1162    ///
1163    /// assert_eq!(v.len(), 5);
1164    /// assert_eq!(v.as_slice(), &[1, 2, 3, 4, 5]);
1165    /// ```
1166    pub fn resize_with<F>(&mut self, cap: usize, mut f: F)
1167    where
1168        F: FnMut() -> T
1169    {
1170        if cap < self.len() {
1171            self.truncate(cap);
1172        } else {
1173            let n = cap - self.len();
1174            self.reserve(n);
1175
1176            unsafe {
1177                let mut ptr = self.as_mut_ptr().add(self.len());
1178                let len = &mut self.len;
1179
1180                for _ in 0..n {
1181                    ptr::write(ptr, f());
1182                    ptr = ptr.add(1);
1183                    len.add(1);
1184                }
1185            }
1186        }
1187    }
1188
1189    /// Resizes the vector, initializing the new memory to 0
1190    ///
1191    /// # Safety
1192    /// The caller must ensure that an all-zero byte representation
1193    /// is valid for T.
1194    ///
1195    /// If [mem::zeroed] is valid for T, this function is valid too.
1196    ///
1197    /// # Example
1198    /// ```
1199    /// use tiny_vec::TinyVec;
1200    ///
1201    /// let mut v = TinyVec::<_, 10>::from(&[1, 2, 3]);
1202    ///
1203    /// /* SAFETY: i32 can be initialized to 0b0 */
1204    /// unsafe { v.resize_zeroed(8); }
1205    ///
1206    /// /* The above is the same as
1207    ///    v.resize_with(8, || unsafe { core::mem::zeroed() }); */
1208    ///
1209    /// assert_eq!(v.len(), 8);
1210    /// assert_eq!(v.as_slice(), &[1, 2, 3, 0, 0, 0, 0, 0]);
1211    /// ```
1212    pub unsafe fn resize_zeroed(&mut self, cap: usize) {
1213        if cap < self.len() {
1214            self.truncate(cap);
1215        } else {
1216            let n = cap - self.len();
1217            self.reserve(n);
1218            unsafe {
1219                let ptr = self.as_mut_ptr().add(self.len());
1220                ptr.write_bytes(0, n);
1221            }
1222            self.len.add(n);
1223        }
1224    }
1225
1226    /// Like [remove](Self::remove), but without bounds checking
1227    ///
1228    /// # Safety
1229    /// index must be within bounds (less than self.len)
1230    pub const unsafe fn remove_unchecked(&mut self, index: usize) -> T {
1231        debug_assert!(index < self.len());
1232
1233        unsafe {
1234            self.len.sub(1);
1235            let result = self.as_mut_ptr().add(index).read();
1236            ptr::copy(
1237                self.as_ptr().add(index + 1),
1238                self.as_mut_ptr().add(index),
1239                self.len.get() - index,
1240            );
1241            result
1242        }
1243    }
1244
1245    /// Removes the element at the given index.
1246    /// If the index is out of bounds, returns [None]
1247    #[inline]
1248    pub const fn remove(&mut self, index: usize) -> Option<T> {
1249        if index >= self.len.get() { return None }
1250        /* SAFETY: We've just checked that index is < self.len */
1251        Some(unsafe { self.remove_unchecked(index) })
1252    }
1253
1254    /// Removes and returns the element at the given `index` from a `self`
1255    /// if the `predicate` returns true, or [None] if the predicate returns
1256    /// false or the `index` is out of bounds (the predicate will not be called
1257    /// in that case).
1258    ///
1259    /// # Example
1260    /// ```
1261    /// use tiny_vec::TinyVec;
1262    ///
1263    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
1264    /// let pred = |x: &mut i32| *x % 2 == 0;
1265    ///
1266    /// assert_eq!(vec.remove_if(1, pred), Some(2));
1267    /// assert_eq!(vec, [1, 3, 4]);
1268    /// assert_eq!(vec.remove_if(0, pred), None);
1269    /// ```
1270    pub fn remove_if<F>(&mut self, index: usize, predicate: F) -> Option<T>
1271    where
1272        F: FnOnce(&mut T) -> bool
1273    {
1274        let len = self.len.get();
1275        if index >= len { return None }
1276
1277        unsafe {
1278            let ptr = self.as_mut_ptr().add(index);
1279            predicate(&mut *ptr).then(|| {
1280                let elem = ptr.read();
1281                ptr::copy(
1282                    ptr.add(1),
1283                    ptr,
1284                    len - index - 1
1285                );
1286                self.len.sub(1);
1287                elem
1288            })
1289        }
1290    }
1291
1292    /// Swaps the elements on index a and b
1293    ///
1294    /// # Errors
1295    /// If an index is out of bounds for [0, len),
1296    /// returns that index inside an [Err] variant.
1297    pub const fn swap_checked(&mut self, a: usize, b: usize) -> Result<(),usize> {
1298        if a >= self.len.get() {
1299            return Err(a)
1300        };
1301        if b >= self.len.get() {
1302            return Err(b)
1303        };
1304        /* SAFETY: a and b are in bounds */
1305        unsafe { self.swap_unchecked(a, b); }
1306        Ok(())
1307    }
1308    /// Swaps the elements on index a and b, without checking bounds
1309    ///
1310    /// # Safety
1311    /// The caller must ensure that both `a` and `b` are in bounds [0, len)
1312    /// For a checked version of this function, check [swap_checked](Self::swap_checked)
1313    #[cfg(not(feature = "use-nightly-features"))]
1314    pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
1315        unsafe {
1316            let ptr = self.as_mut_ptr();
1317            let ap = ptr.add(a);
1318            let bp = ptr.add(b);
1319            ptr::swap(ap, bp);
1320        }
1321    }
1322
1323    #[cfg(feature = "use-nightly-features")]
1324    #[inline(always)]
1325    const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
1326        unsafe { self.as_mut_slice().swap_unchecked(a, b); }
1327    }
1328
1329    /// Removes the element at the given index by swaping it with the last one
1330    pub const fn swap_remove(&mut self, index: usize) -> Option<T> {
1331        if index >= self.len.get() {
1332            None
1333        } else if index == self.len.get() - 1 {
1334            self.pop()
1335        } else {
1336            /* SAFETY: index in < self.len */
1337            unsafe { self.swap_unchecked(index, self.len.get() - 1) }
1338            self.pop()
1339        }
1340    }
1341
1342    /// Removes consecutive repeated elements in `self` according to the
1343    /// [`PartialEq`] trait implementation.
1344    ///
1345    /// If the vector is sorted, this removes all duplicates.
1346    ///
1347    /// # Examples
1348    /// ```
1349    /// use tiny_vec::TinyVec;
1350    /// let mut vec = TinyVec::from([1, 2, 2, 3, 2]);
1351    /// vec.dedup();
1352    /// assert_eq!(vec, [1, 2, 3, 2]);
1353    /// ```
1354    #[inline]
1355    pub fn dedup(&mut self)
1356    where
1357        T: PartialEq
1358    {
1359        self.dedup_by(|a, b| a == b);
1360    }
1361
1362    /// Removes all but the first of consecutive elements in the
1363    /// vector that resolve to the same key.
1364    ///
1365    /// If the vector is sorted, this removes all duplicates.
1366    ///
1367    /// # Examples
1368    /// ```
1369    /// use tiny_vec::TinyVec;
1370    /// let mut vec = TinyVec::from([10, 20, 21, 30, 20]);
1371    ///
1372    /// vec.dedup_by_key(|i| *i / 10);
1373    /// assert_eq!(vec, [10, 20, 30, 20]);
1374    /// ```
1375    #[inline]
1376    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1377    where
1378        F: FnMut(&mut T) -> K,
1379        K: PartialEq
1380    {
1381        self.dedup_by(|a, b| key(a) == key(b));
1382    }
1383
1384    /// Removes all but the first of consecutive elements in `self` satisfying
1385    /// a given equality relation.
1386    ///
1387    /// The `are_equal` function is passed references to two elements from the vector and
1388    /// must determine if the elements compare equal. The elements are passed in opposite order
1389    /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1390    ///
1391    /// If the vector is sorted, this removes all duplicates.
1392    ///
1393    /// # Examples
1394    /// ```
1395    /// use tiny_vec::TinyVec;
1396    /// let mut vec = TinyVec::from(["foo", "bar", "Bar", "baz", "bar"]);
1397    ///
1398    /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1399    ///
1400    /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1401    /// ```
1402    pub fn dedup_by<F>(&mut self, mut are_equal: F)
1403    where
1404        F: FnMut(&mut T, &mut T) -> bool
1405    {
1406        let (ptr, _, len) = unsafe { self.split_at_spare_mut_with_len() };
1407        let ptr = ptr.as_mut_ptr();
1408
1409        if len.get() <= 1 {
1410            return
1411        }
1412
1413        let mut first_dup = 1;
1414        while first_dup != len.get() {
1415           let is_dup = unsafe {
1416                let a = ptr.add(first_dup - 1);
1417                let b = ptr.add(first_dup);
1418                are_equal(&mut *b, &mut *a)
1419           };
1420           if is_dup {
1421               break
1422           }
1423           first_dup += 1;
1424        }
1425        if first_dup == len.get() {
1426            return;
1427        }
1428
1429        struct DropGuard<'a, T> {
1430            len: &'a mut Length,
1431            ptr: *mut T,
1432            right: usize,
1433            left: usize,
1434        }
1435
1436        impl<T> Drop for DropGuard<'_, T> {
1437            fn drop(&mut self) {
1438                unsafe {
1439                    let len = self.len.get();
1440
1441                    let shift = len - self.right;
1442                    let src = self.ptr.add(self.right);
1443                    let dst = self.ptr.add(self.left);
1444                    ptr::copy(src, dst, shift);
1445
1446                    let deleted = self.right - self.left;
1447                    self.len.sub(deleted);
1448                }
1449            }
1450        }
1451
1452        let mut guard = DropGuard { right: first_dup + 1, left: first_dup, ptr, len };
1453        unsafe { ptr::drop_in_place(ptr.add(first_dup)); }
1454        while guard.right < guard.len.get() {
1455            unsafe {
1456                let a = ptr.add(guard.left - 1);
1457                let b = ptr.add(guard.right);
1458
1459                if are_equal(&mut *b, &mut *a) {
1460                    guard.right += 1;
1461                    ptr::drop_in_place(b);
1462                } else {
1463                    let dst = ptr.add(guard.left);
1464                    ptr::copy_nonoverlapping(b, dst, 1);
1465                    guard.left += 1;
1466                    guard.right += 1;
1467                }
1468            }
1469        }
1470
1471        guard.len.set(guard.left);
1472        mem::forget(guard);
1473    }
1474
1475    /// Shrinks the capacity of the vector with a lower bound.
1476    ///
1477    /// The capacity will remain at least as large as both the length
1478    /// and the supplied value.
1479    ///
1480    /// If the current capacity is less than the lower limit, this is a no-op.
1481    ///
1482    /// # Examples
1483    /// ```
1484    /// use tiny_vec::TinyVec;
1485    /// let mut vec = TinyVec::<i32, 4>::with_capacity(10);
1486    /// vec.extend([1, 2, 3]);
1487    /// assert!(vec.capacity() >= 10);
1488    /// vec.shrink_to(4);
1489    /// assert!(vec.capacity() >= 4);
1490    /// vec.shrink_to(0);
1491    /// assert!(vec.capacity() >= 3);
1492    /// ```
1493    pub fn shrink_to(&mut self, min_capacity: usize) {
1494        if !self.lives_on_stack() && self.capacity() > min_capacity {
1495            let new_cap = usize::max(self.len.get(), min_capacity);
1496            self._shrink(new_cap);
1497        }
1498    }
1499
1500    /// Shrinks the capacity of the vector to fit exactly it's length
1501    ///
1502    /// If the vector lives on the heap, but it's length fits inside the
1503    /// stack-allocated buffer `self.len <= N`, it deallocates the heap
1504    /// buffer and moves the contents to the stack.
1505    ///
1506    /// If you need a function that doesn't move the buffer to the stack,
1507    /// use the [shrink_to_fit_heap_only](Self::shrink_to_fit_heap_only) function.
1508    #[cfg(feature = "alloc")]
1509    pub fn shrink_to_fit(&mut self) {
1510        if self.len.is_stack() { return }
1511        self._shrink(self.len.get());
1512    }
1513
1514    /// Moves this `TinyVec` to the heap
1515    #[cfg(feature = "alloc")]
1516    pub fn move_to_heap(&mut self) {
1517        self.try_move_to_heap().unwrap_or_else(|err| err.handle());
1518    }
1519
1520    /// Like [move_to_heap](Self::move_to_heap), but returns a result
1521    /// in case the allocation fail
1522    #[cfg(feature = "alloc")]
1523    pub fn try_move_to_heap(&mut self) -> Result<(), ResizeError> {
1524        if self.lives_on_stack() {
1525            unsafe { self.switch_to_heap(0, false)? };
1526        }
1527        Ok(())
1528    }
1529
1530    /// Moves this `TinyVec` to the heap, without allocating more
1531    /// than `self.len` elements
1532    #[cfg(feature = "alloc")]
1533    pub fn move_to_heap_exact(&mut self) {
1534        self.try_move_to_heap_exact().unwrap_or_else(|err| err.handle());
1535    }
1536
1537    /// Like [move_to_heap_exact](Self::move_to_heap_exact), but returns a result
1538    /// in case the allocation fail
1539    #[cfg(feature = "alloc")]
1540    pub fn try_move_to_heap_exact(&mut self) -> Result<(), ResizeError> {
1541        if self.lives_on_stack() {
1542            unsafe { self.switch_to_heap(0, true)? };
1543        }
1544        Ok(())
1545    }
1546
1547    /// Shrinks the capacity of the vector to fit exactly it's length.
1548    ///
1549    /// Unlike [shrink_to_fit](Self::shrink_to_fit), this function doesn't
1550    /// move the buffer to the stack, even if the length of `self`, could
1551    /// fit on the stack space.
1552    #[cfg(feature = "alloc")]
1553    pub fn shrink_to_fit_heap_only(&mut self) {
1554        if !self.len.is_stack() {
1555            unsafe { self.inner.raw.shrink_to_fit(self.len.get()); };
1556        }
1557    }
1558
1559    /// Clears all the elements of this vector
1560    ///
1561    /// # Example
1562    /// ```
1563    /// use tiny_vec::{TinyVec, tinyvec};
1564    ///
1565    /// let mut vec: TinyVec<_, 5> = tinyvec![1, 2, 3, 4, 5];
1566    /// vec.clear();
1567    ///
1568    /// assert!(vec.is_empty());
1569    /// assert_eq!(vec.as_slice(), &[]);
1570    /// ```
1571    pub fn clear(&mut self) {
1572        let ptr = self.as_mut_slice() as *mut [T];
1573        unsafe {
1574            self.len.set(0);
1575            ptr::drop_in_place(ptr);
1576        }
1577    }
1578
1579    /// Sets the length of the vector.
1580    ///
1581    /// # Safety
1582    /// The caller must ensure that changing the length doesn't
1583    /// leave the vector in an inconsistent state. This is:
1584    ///
1585    /// - If you reduce de length, you may leak memory, if the type
1586    ///   stored need to be droped
1587    /// - If you extend the length, you may access uninitialized memory
1588    #[inline]
1589    pub const unsafe fn set_len(&mut self, len: usize) {
1590        self.len.set(len);
1591    }
1592
1593    /// Updates the length of the vector using the given closure.
1594    ///
1595    /// This is just the same as getting the len using [Self::len], and
1596    /// then using [Self::set_len].
1597    ///
1598    /// *This is a low level api*. Use it only if you know what you're doing.
1599    ///
1600    /// # Safety
1601    /// Just like [Self::set_len], you need to make sure that changing the
1602    /// vector length doesn't leave the vector in an inconsistent state, or
1603    /// leaks memory.
1604    ///
1605    /// # Example
1606    /// ```
1607    /// use tiny_vec::TinyVec;
1608    ///
1609    /// let mut vec = TinyVec::<i32, 10>::with_capacity(10);
1610    ///
1611    /// unsafe {
1612    ///     let mut dst = vec.as_mut_ptr();
1613    ///     let src = &[1, 2, 3, 4] as *const i32;
1614    ///     core::ptr::copy(src, dst, 4);
1615    ///     vec.update_len(|len| *len += 4);
1616    ///     // Same as:
1617    ///     // let len = vec.len();
1618    ///     // len.set_len(len + 4);
1619    /// }
1620    /// ```
1621    pub unsafe fn update_len<F>(&mut self, mut f: F)
1622    where
1623        F: FnMut(&mut usize)
1624    {
1625        let mut len = self.len.get();
1626        f(&mut len);
1627        self.len.set(len);
1628    }
1629
1630    /// Reduces the length in the vector, dropping the elements
1631    /// in range [new_len, old_len)
1632    ///
1633    /// If the new_len is >= old_len, this function does nothing.
1634    ///
1635    /// # Example
1636    /// ```
1637    /// use tiny_vec::TinyVec;
1638    ///
1639    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5]);
1640    /// vec.truncate(3);
1641    /// assert_eq!(vec.as_slice(), &[1, 2, 3]);
1642    /// ```
1643    pub fn truncate(&mut self, len: usize) {
1644        if len < self.len.get() {
1645            for e in &mut self[len..] {
1646                unsafe { ptr::drop_in_place(e) }
1647            }
1648            unsafe { self.set_len(len); }
1649        }
1650    }
1651
1652    /// Copies all the elements of the given slice into the vector
1653    ///
1654    /// # Example
1655    /// ```
1656    /// use tiny_vec::TinyVec;
1657    ///
1658    /// let mut vec = TinyVec::<String, 5>::new();
1659    /// vec.extend_from_slice(&[
1660    ///     "abc".to_string(),
1661    ///     "def".to_string(),
1662    ///     "__".to_string(),
1663    /// ]);
1664    ///
1665    /// assert_eq!(vec.as_slice(), &["abc", "def", "__"]);
1666    /// ```
1667    /// [extend_from_slice_copied]: Self::extend_from_slice_copied
1668    #[inline]
1669    pub fn extend_from_slice(&mut self, s: &[T])
1670    where
1671        T: Clone
1672    {
1673        self.extend_from_slice_impl(s);
1674    }
1675
1676    /// Copies all the elements of the given slice into the vector
1677    ///
1678    /// This function copies the slice into the buffer, which
1679    /// is faster that calling [clone]
1680    /// That's why it requires T to implement [Copy].
1681    ///
1682    /// For a cloning alternative, use [extend_from_slice]
1683    ///
1684    /// # Example
1685    /// ```
1686    /// use tiny_vec::TinyVec;
1687    ///
1688    /// let mut vec = TinyVec::<i32, 5>::new();
1689    /// vec.extend_from_slice_copied(&[1, 2, 3, 4]);
1690    ///
1691    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4]);
1692    /// ```
1693    /// [clone]: Clone::clone
1694    /// [extend_from_slice]: Self::extend_from_slice
1695    #[inline]
1696    pub fn extend_from_slice_copied(&mut self, s: &[T])
1697    where
1698        T: Copy
1699    {
1700        let len = s.len();
1701        self.reserve(len);
1702
1703        unsafe {
1704            /* SAFETY: We've just reserved space for `len` elements */
1705            ptr::copy(
1706                s.as_ptr(),
1707                self.as_mut_ptr().add(self.len.get()),
1708                len
1709            )
1710        }
1711
1712        self.len.add(len);
1713    }
1714
1715    /// Copies the slice from the given range to the back
1716    /// of this vector.
1717    ///
1718    /// # Panics
1719    /// Panics if the range is invalid for [0, self.len)
1720    ///
1721    /// # Example
1722    /// ```
1723    /// use tiny_vec::TinyVec;
1724    ///
1725    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
1726    ///
1727    /// vec.extend_from_within(3..=5);
1728    ///
1729    /// assert_eq!(vec, &[1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6]);
1730    /// ```
1731    #[inline]
1732    pub fn extend_from_within<R>(&mut self, range: R)
1733    where
1734        T: Clone,
1735        R: RangeBounds<usize>,
1736    {
1737        self.extend_from_within_impl(range);
1738    }
1739
1740    /// Like [extend_from_within](Self::extend_from_within),
1741    /// but optimized for [Copy] types
1742    pub fn extend_from_within_copied<R>(&mut self, range: R)
1743    where
1744        T: Copy,
1745        R: RangeBounds<usize>,
1746    {
1747        let len = self.len();
1748        let Range { start, end } = slice_range(range, len);
1749
1750        let new_len = end - start;
1751        self.reserve(new_len);
1752
1753        let ptr = self.as_mut_ptr();
1754        unsafe {
1755            let src = ptr.add(start);
1756            let dst = ptr.add(len);
1757            ptr::copy(src, dst, new_len);
1758        }
1759        self.len.add(new_len);
1760    }
1761
1762    /// Retains in this vector only the elements that match
1763    /// the given predicate
1764    ///
1765    /// This is the same as calling
1766    /// `self.extract_if(.., |e| !pred(e)).for_each(|e| drop(e))`
1767    ///
1768    /// # Example
1769    /// ```
1770    /// use tiny_vec::TinyVec;
1771    ///
1772    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
1773    /// vec.retain(|&n| n % 2 == 0);
1774    /// assert_eq!(vec, &[2, 4, 6, 8]);
1775    /// ```
1776    pub fn retain<F>(&mut self, mut pred: F)
1777    where
1778        F: FnMut(&T) -> bool
1779    {
1780        self.retain_mut(|e| pred(e));
1781    }
1782
1783    /// Like [retain](Self::retain), but the predicate receives a
1784    /// mutable reference to the element.
1785    ///
1786    /// # Example
1787    /// ```
1788    /// use tiny_vec::TinyVec;
1789    ///
1790    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
1791    /// vec.retain_mut(|n| {
1792    ///     let is_even = *n % 2 == 0;
1793    ///     *n *= 2;
1794    ///     is_even
1795    /// });
1796    /// assert_eq!(vec, &[4, 8, 12, 16]);
1797    /// ```
1798    pub fn retain_mut<F>(&mut self, mut pred: F)
1799    where
1800        F: FnMut(&mut T) -> bool
1801    {
1802        /* TODO: We can probably optimize this */
1803        for e in self.extract_if(.., |e| !pred(e)) {
1804            drop(e)
1805        }
1806    }
1807
1808    /// Returns vector content as a slice of `T`, along with the remaining spare
1809    /// capacity of the vector as a slice of `MaybeUninit<T>`.
1810    ///
1811    /// The returned spare capacity slice can be used to fill the vector with data
1812    /// (e.g. by reading from a file) before marking the data as initialized using
1813    /// the [`set_len`], or [`update_len`] methods.
1814    ///
1815    /// [`set_len`]: TinyVec::set_len
1816    /// [`update_len`]: TinyVec::update_len
1817    ///
1818    /// Note that this is a low-level API, which should be used with care for
1819    /// optimization purposes. If you need to append data to a `Vec`
1820    /// you can use [`push`], [`extend`], [`extend_from_slice`],
1821    /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
1822    /// [`resize_with`], depending on your exact needs.
1823    ///
1824    /// [`push`]: TinyVec::push
1825    /// [`extend`]: TinyVec::extend
1826    /// [`extend_from_slice`]: TinyVec::extend_from_slice
1827    /// [`extend_from_within`]: TinyVec::extend_from_within
1828    /// [`insert`]: TinyVec::insert
1829    /// [`append`]: TinyVec::append
1830    /// [`resize`]: TinyVec::resize
1831    /// [`resize_with`]: TinyVec::resize_with
1832    ///
1833    /// # Examples
1834    ///
1835    /// ```
1836    /// use tiny_vec::TinyVec;
1837    ///
1838    /// let mut v = TinyVec::from([1, 1, 2]);
1839    ///
1840    /// // Reserve additional space big enough for 10 elements.
1841    /// v.reserve(10);
1842    ///
1843    /// let (init, uninit) = v.split_at_spare_mut();
1844    /// let sum = init.iter().copied().sum::<u32>();
1845    ///
1846    /// // Fill in the next 4 elements.
1847    /// uninit[0].write(sum);
1848    /// uninit[1].write(sum * 2);
1849    /// uninit[2].write(sum * 3);
1850    /// uninit[3].write(sum * 4);
1851    ///
1852    /// // Mark the 4 elements of the vector as being initialized.
1853    /// unsafe {
1854    ///     let len = v.len();
1855    ///     v.set_len(len + 4);
1856    /// }
1857    ///
1858    /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
1859    /// ```
1860    pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
1861        let (init, uninit, _) = unsafe { self.split_at_spare_mut_with_len() };
1862        (init, uninit)
1863    }
1864
1865    /// Splits the collection into two at the given index.
1866    ///
1867    /// Returns a newly allocated vector containing the elements in the range
1868    /// `[at, len)`. After the call, the original vector will be left containing
1869    /// the elements `[0, at)` with its previous capacity unchanged.
1870    ///
1871    /// - If you want to take ownership of the entire contents and capacity of
1872    ///   the vector, see [`mem::take`] or [`mem::replace`].
1873    /// - If you don't need the returned vector at all, see [`TinyVec::truncate`].
1874    /// - If you want to take ownership of an arbitrary subslice, or you don't
1875    ///   necessarily want to store the removed items in a vector, see [`TinyVec::drain`].
1876    ///
1877    /// # Panics
1878    ///
1879    /// Panics if `at > len`.
1880    ///
1881    /// # Examples
1882    ///
1883    /// ```
1884    /// use tiny_vec::TinyVec;
1885    ///
1886    /// let mut vec = TinyVec::from(['a', 'b', 'c']);
1887    /// let vec2 = vec.split_off(1);
1888    /// assert_eq!(vec, ['a']);
1889    /// assert_eq!(vec2, ['b', 'c']);
1890    /// ```
1891    #[must_use = "use `.truncate()` if you don't need the other half"]
1892    pub fn split_off(&mut self, at: usize) -> TinyVec<T , N>  {
1893        if at >= self.len() {
1894            panic!("Index out of bounds");
1895        }
1896        let other_len = self.len() - at;
1897        let mut other = TinyVec::<T, N>::with_capacity(other_len);
1898
1899        unsafe {
1900            let src = self.as_ptr().add(at);
1901            let dst = other.as_mut_ptr();
1902            ptr::copy_nonoverlapping(src, dst, other_len);
1903            other.set_len(other_len);
1904            self.len.sub(other_len);
1905        }
1906        other
1907    }
1908
1909    /// Consumes and leaks the `TinyVec`, returning a mutable reference to the contents,
1910    /// `&'a mut [T]`.
1911    ///
1912    /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
1913    /// has only static references, or none at all, then this may be chosen to be
1914    /// `'static`.
1915    ///
1916    /// This method shrinks the buffer, and moves it to the heap in case it lived
1917    /// on the stack.
1918    ///
1919    /// This function is mainly useful for data that lives for the remainder of
1920    /// the program's life. Dropping the returned reference will cause a memory
1921    /// leak.
1922    ///
1923    /// # Examples
1924    ///
1925    /// ```
1926    /// let x = tiny_vec::TinyVec::from([1, 2, 3]);
1927    ///
1928    /// let static_ref: &'static mut [usize] = x.leak();
1929    /// static_ref[0] += 1;
1930    ///
1931    /// assert_eq!(static_ref, &[2, 2, 3]);
1932    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1933    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1934    /// # drop(unsafe { Box::from_raw(static_ref) });
1935    /// ```
1936    #[cfg(feature = "alloc")]
1937    pub fn leak<'a>(self) -> &'a mut [T]
1938    where
1939        T: 'a
1940    {
1941        let mut slf = ManuallyDrop::new(self);
1942        unsafe {
1943            let len = slf.len();
1944            slf.shrink_to_fit_heap_only();
1945            slf.move_to_heap_exact();
1946            let ptr = slf.as_mut_ptr();
1947            slice::from_raw_parts_mut(ptr, len)
1948        }
1949    }
1950
1951    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1952    ///
1953    /// # Panics
1954    ///
1955    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1956    ///
1957    /// # Examples
1958    ///
1959    /// ```
1960    /// use tiny_vec::TinyVec;
1961    ///
1962    /// let mut vec = TinyVec::from([1, 2, 3]);
1963    /// let mut vec2 = TinyVec::from([4, 5, 6]);
1964    /// vec.append(&mut vec2);
1965    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1966    /// assert_eq!(vec2, []);
1967    /// ```
1968    pub fn append<const M: usize>(&mut self, other: &mut TinyVec<T, M>) {
1969       unsafe {
1970           let other_len = other.len();
1971           self.reserve(other_len);
1972
1973           let src = other.as_slice().as_ptr();
1974           let dst = self.as_mut_ptr().add(self.len());
1975           ptr::copy(src, dst, other_len);
1976
1977           other.set_len(0);
1978           self.len.add(other_len);
1979       }
1980    }
1981
1982    /// Removes the subslice indicated by the given range from the vector,
1983    /// returning a double-ended iterator over the removed subslice.
1984    ///
1985    /// If the iterator is dropped before being fully consumed,
1986    /// it drops the remaining removed elements.
1987    ///
1988    /// # Panics
1989    ///
1990    /// Panics if the starting point is greater than the end point or if
1991    /// the end point is greater than the length of the vector.
1992    ///
1993    /// # Leaking
1994    ///
1995    /// If the returned iterator goes out of scope without being dropped (due to
1996    /// [`mem::forget`], for example), the vector may have lost and leaked
1997    /// elements arbitrarily, including elements outside the range.
1998    ///
1999    /// # Examples
2000    ///
2001    /// ```
2002    /// use tiny_vec::{tinyvec, TinyVec};
2003    /// let mut v: TinyVec<_, 10> = tinyvec![0, 1, 2, 3, 4, 5, 6];
2004    /// let mut drain = v.drain(2..=4);
2005    /// assert_eq!(drain.next(), Some(2));
2006    /// assert_eq!(drain.next(), Some(3));
2007    /// assert_eq!(drain.next(), Some(4));
2008    /// assert_eq!(drain.next(), None);
2009    /// drop(drain);
2010    ///
2011    /// assert_eq!(v, &[0, 1, 5, 6]);
2012    ///
2013    /// // A full range clears the vector, like `clear()` does
2014    /// v.drain(..);
2015    /// assert_eq!(v, &[]);
2016    /// ```
2017    pub fn drain<R>(&mut self, range: R) -> Drain<T, N>
2018    where
2019        R: RangeBounds<usize>
2020    {
2021
2022        let len = self.len();
2023        let Range { start, end } = slice_range(range, len);
2024
2025        unsafe {
2026            self.set_len(start);
2027
2028            Drain {
2029                vec: NonNull::new_unchecked(self as *mut _),
2030                remaining_start: start,
2031                remaining_len: end - start,
2032                tail_start: end,
2033                tail_len: len - end,
2034                _marker: PhantomData,
2035            }
2036        }
2037    }
2038
2039    /// Creates an iterator which uses a closure to determine if the element in the range should be removed.
2040    ///
2041    /// If the closure returns true, then the element is removed and yielded.
2042    /// If the closure returns false, the element will remain in the vector and will not be yielded
2043    /// by the iterator.
2044    ///
2045    /// Only elements that fall in the provided range are considered for extraction, but any elements
2046    /// after the range will still have to be moved if any element has been extracted.
2047    ///
2048    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
2049    /// or the iteration short-circuits, then the remaining elements will be retained.
2050    ///
2051    /// Note that `extract_if` also lets you mutate the elements passed to the filter closure,
2052    /// regardless of whether you choose to keep or remove them.
2053    ///
2054    /// # Panics
2055    ///
2056    /// If `range` is out of bounds.
2057    ///
2058    /// # Examples
2059    ///
2060    /// Splitting an array into evens and odds, reusing the original allocation:
2061    ///
2062    /// ```
2063    /// use tiny_vec::TinyVec;
2064    /// let mut numbers = TinyVec::<i32, 10>::from(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
2065    ///
2066    /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<TinyVec<_, 8>>();
2067    /// let odds = numbers;
2068    ///
2069    /// assert_eq!(evens, &[2, 4, 6, 8, 14]);
2070    /// assert_eq!(odds, &[1, 3, 5, 9, 11, 13, 15]);
2071    /// ```
2072    ///
2073    /// Using the range argument to only process a part of the vector:
2074    ///
2075    /// ```
2076    /// use tiny_vec::TinyVec;
2077    /// let mut items = TinyVec::<i32, 10>::from(&[0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
2078    /// let ones = items.extract_if(7.., |x| *x == 1).collect::<TinyVec<_, 4>>();
2079    /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
2080    /// assert_eq!(ones.len(), 3);
2081    /// ```
2082    pub fn extract_if<R, F>(&mut self, range: R, pred: F) -> ExtractIf<'_, T, N, F>
2083    where
2084        R: RangeBounds<usize>,
2085        F: FnMut(&mut T) -> bool,
2086    {
2087        let len = self.len();
2088        let Range { start, end } = slice_range(range, len);
2089
2090        unsafe { self.set_len(start) }
2091
2092        ExtractIf {
2093            original_len: len,
2094            deleted: 0,
2095            next: start,
2096            last: end,
2097            vec: self,
2098            pred,
2099        }
2100    }
2101
2102    /// Converts this [TinyVec] into a boxed slice
2103    ///
2104    /// # Example
2105    /// ```
2106    /// use tiny_vec::TinyVec;
2107    ///
2108    /// let mut v = TinyVec::<_, 10>::from(&[1, 2, 3, 4]);
2109    /// let b = v.into_boxed_slice();
2110    ///
2111    /// assert_eq!(&b[..], [1, 2, 3, 4]);
2112    /// ```
2113    #[cfg(feature = "alloc")]
2114    pub fn into_boxed_slice(self) -> Box<[T]> {
2115        let mut slf = ManuallyDrop::new(self);
2116
2117        if slf.lives_on_stack() {
2118            unsafe { slf.switch_to_heap(0, true).unwrap_or_else(|err| err.handle()) };
2119        }
2120        debug_assert!(!slf.lives_on_stack());
2121
2122        let len = slf.len();
2123        slf.shrink_to_fit_heap_only();
2124        debug_assert_eq!(len, slf.capacity());
2125
2126        let ptr = slf.as_mut_ptr();
2127        unsafe {
2128            let slice = slice::from_raw_parts_mut(ptr, len);
2129            Box::from_raw(slice)
2130        }
2131    }
2132
2133    /// Converts this [TinyVec] into a standard [Vec]
2134    ///
2135    /// # Example
2136    /// ```
2137    /// use tiny_vec::TinyVec;
2138    ///
2139    /// let mut v = TinyVec::from([1, 2, 3, 4]);
2140    /// let b = v.into_vec();
2141    ///
2142    /// assert_eq!(&b[..], &[1, 2, 3, 4]);
2143    /// ```
2144    #[cfg(feature = "alloc")]
2145    pub fn into_vec(self) -> Vec<T> {
2146        let mut vec = ManuallyDrop::new(self);
2147        vec.move_to_heap();
2148
2149        let ptr = vec.as_mut_ptr();
2150        let len = vec.len();
2151        let cap = vec.capacity();
2152
2153        unsafe { Vec::from_raw_parts(ptr, len, cap) }
2154    }
2155}
2156
2157impl<T, const N: usize> Extend<T> for TinyVec<T, N> {
2158    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2159        let iter = iter.into_iter();
2160
2161        let (lower, _) = iter.size_hint();
2162        self.reserve(lower);
2163
2164        for elem in iter {
2165            unsafe { self.push_unchecked(elem); }
2166        }
2167    }
2168
2169    #[cfg(feature = "use-nightly-features")]
2170    fn extend_one(&mut self, item: T) {
2171        self.push(item);
2172    }
2173
2174    #[cfg(feature = "use-nightly-features")]
2175    fn extend_reserve(&mut self, additional: usize) {
2176        self.reserve(additional);
2177    }
2178
2179    #[cfg(feature = "use-nightly-features")]
2180    unsafe fn extend_one_unchecked(&mut self, item: T) {
2181        /* SAFETY: The caller guarantees that self.len < self.capacity */
2182        unsafe { self.push_unchecked(item); }
2183    }
2184}
2185
2186#[cfg(feature = "use-nightly-features")]
2187macro_rules! maybe_default {
2188    ($($t:tt)*) => {
2189        default $($t)*
2190    };
2191}
2192
2193#[cfg(not(feature = "use-nightly-features"))]
2194macro_rules! maybe_default {
2195    ($($t:tt)*) => {
2196        $($t)*
2197    };
2198}
2199
2200trait CopyOptimization<T> {
2201    fn extend_from_slice_impl(&mut self, s: &[T]);
2202    fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>;
2203    fn resize_impl(&mut self, new_len: usize, elem: T);
2204    fn extend_from_within_impl<R>(&mut self, range: R)
2205    where
2206        R: RangeBounds<usize>;
2207}
2208
2209impl<T: Clone, const N: usize> CopyOptimization<T> for TinyVec<T, N> {
2210    maybe_default! {
2211        fn extend_from_slice_impl(&mut self, s: &[T]) {
2212            self.extend(s.iter().cloned());
2213        }
2214    }
2215
2216    maybe_default! {
2217        fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]> {
2218            self.insert_iter(index, elems.iter().cloned()).map_err(|_| elems)
2219        }
2220    }
2221
2222    maybe_default! {
2223        fn extend_from_within_impl<R>(&mut self, range: R)
2224        where
2225            R: RangeBounds<usize>
2226        {
2227            let len = self.len();
2228            let Range { start, end } = slice_range(range, len);
2229
2230            self.reserve(end - start);
2231
2232            let (slice, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2233            let slice = &slice[start..end];
2234
2235            for (src, dst) in slice.iter().zip(spare.iter_mut()) {
2236                dst.write(src.clone());
2237                len.add(1);
2238            }
2239        }
2240    }
2241
2242    maybe_default! {
2243        fn resize_impl(&mut self, new_len: usize, elem: T) {
2244            let n = new_len - self.len();
2245            self.reserve(n);
2246
2247            unsafe {
2248                let mut ptr = self.as_mut_ptr().add(self.len());
2249                let len = &mut self.len;
2250
2251                for _ in 1..n {
2252                    ptr::write(ptr, elem.clone());
2253                    ptr = ptr.add(1);
2254                    len.add(1);
2255                }
2256
2257                if n > 0 {
2258                    ptr::write(ptr, elem);
2259                    len.add(1);
2260                }
2261            }
2262        }
2263    }
2264
2265}
2266
2267#[cfg(feature = "use-nightly-features")]
2268impl<T: Copy, const N: usize> CopyOptimization<T> for TinyVec<T, N> {
2269
2270    #[inline]
2271    fn extend_from_slice_impl(&mut self, s: &[T]) {
2272        self.extend_from_slice_copied(s);
2273    }
2274
2275    #[inline]
2276    fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]> {
2277        self.insert_slice_copied(index, elems)
2278    }
2279
2280    #[inline]
2281    fn extend_from_within_impl<R>(&mut self, range: R)
2282    where
2283        R: RangeBounds<usize>
2284    {
2285        self.extend_from_within_copied(range);
2286    }
2287
2288    #[inline]
2289    fn resize_impl(&mut self, new_len: usize, elem: T) {
2290        let n = new_len - self.len();
2291        self.reserve(n);
2292
2293        unsafe {
2294            let mut ptr = self.as_mut_ptr().add(self.len());
2295
2296            for _ in 0..n {
2297                ptr::write(ptr, elem);
2298                ptr = ptr.add(1);
2299            }
2300
2301            self.len.add(n);
2302        }
2303    }
2304}
2305
2306impl<T, const N: usize> Default for TinyVec<T, N> {
2307    #[inline]
2308    fn default() -> Self {
2309        Self::new()
2310    }
2311}
2312
2313impl<T: fmt::Debug, const N: usize> fmt::Debug for TinyVec<T, N> {
2314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2315        fmt::Debug::fmt(self.as_slice(), f)
2316    }
2317}
2318
2319impl<T: PartialEq, const N: usize, S> PartialEq<S> for TinyVec<T, N>
2320where
2321    S: AsRef<[T]>,
2322{
2323    fn eq(&self, other: &S) -> bool {
2324        self.as_slice() == other.as_ref()
2325    }
2326}
2327
2328impl<T: PartialEq, const N: usize> Eq for TinyVec<T, N> {}
2329
2330impl<T, const N: usize> Deref for TinyVec<T, N> {
2331    type Target = [T];
2332
2333    #[inline]
2334    fn deref(&self) -> &Self::Target {
2335        self.as_slice()
2336    }
2337}
2338
2339impl<T, const N: usize> DerefMut for TinyVec<T, N> {
2340    #[inline]
2341    fn deref_mut(&mut self) -> &mut Self::Target {
2342        self.as_mut_slice()
2343    }
2344}
2345
2346impl<T, const N: usize> Drop for TinyVec<T, N> {
2347    fn drop(&mut self) {
2348        if mem::needs_drop::<T>() {
2349            for e in self.as_mut_slice() {
2350                unsafe { ptr::drop_in_place(e) };
2351            }
2352        }
2353        if !self.len.is_stack() {
2354            unsafe { self.inner.raw.destroy(); }
2355        }
2356    }
2357}
2358
2359macro_rules! impl_from_call {
2360    ($( $({$($im:tt)*})? $(where { $($w:tt)* })? $t:ty => $c:ident ),* $(,)?) => {
2361       $(
2362            impl<T, const N: usize, $($($im)*)?> From<$t> for TinyVec<T, N>
2363            $(where $($w)* )?
2364            {
2365                fn from(value: $t) -> Self {
2366                    Self:: $c (value)
2367                }
2368            }
2369       )*
2370    };
2371}
2372
2373#[cfg(feature = "alloc")]
2374impl_from_call! {
2375    Vec<T> => from_vec,
2376    Box<[T]> => from_boxed_slice,
2377}
2378
2379impl_from_call! {
2380    [T; N] => from_array_eq_size,
2381
2382    where { T: Clone } &[T] => from_slice,
2383    where { T: Clone } &mut [T] => from_slice,
2384
2385    { const M: usize } where { T: Clone } &[T; M] => from_slice,
2386    { const M: usize } where { T: Clone } &mut [T; M] => from_slice,
2387}
2388
2389impl<T, const N: usize> FromIterator<T> for TinyVec<T, N> {
2390    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2391        let iter = iter.into_iter();
2392        let cap = match iter.size_hint() {
2393            (_, Some(max)) => max,
2394            (n, None) => n,
2395        };
2396        let mut vec = Self::with_capacity(cap);
2397        for elem in iter {
2398            unsafe { vec.push_unchecked(elem) };
2399        }
2400        vec
2401    }
2402}
2403
2404#[cfg(feature = "alloc")]
2405impl<T, const N: usize> From<TinyVec<T, N>> for Vec<T> {
2406    #[inline]
2407    fn from(value: TinyVec<T, N>) -> Self {
2408        value.into_vec()
2409    }
2410}
2411
2412impl<T, const N: usize> AsRef<[T]> for TinyVec<T, N> {
2413    #[inline]
2414    fn as_ref(&self) -> &[T] {
2415        self.as_slice()
2416    }
2417}
2418
2419impl<T, const N: usize> AsMut<[T]> for TinyVec<T, N> {
2420    #[inline]
2421    fn as_mut(&mut self) -> &mut [T] {
2422        self.as_mut_slice()
2423    }
2424}
2425
2426impl<T: Clone, const N: usize> Clone for TinyVec<T, N> {
2427    fn clone(&self) -> Self {
2428        Self::from_slice(self.as_slice())
2429    }
2430}
2431
2432#[cfg(test)]
2433mod test;