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