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