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