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