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