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