smallvec/lib.rs
1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Small vectors in various sizes. These store a certain number of elements
8//! inline, and fall back to the heap for larger allocations. This can be a
9//! useful optimization for improving cache locality and reducing allocator
10//! traffic for workloads that fit within the inline buffer.
11//!
12//! ## `no_std` support
13//!
14//! By default, `smallvec` does not depend on `std`. However, the optional
15//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
16//! When this feature is enabled, `smallvec` depends on `std`.
17//!
18//! ## Optional features
19//!
20//! ### `serde`
21//!
22//! When this optional dependency is enabled, `SmallVec` implements the
23//! `serde::Serialize` and `serde::Deserialize` traits.
24//!
25//! ### `write`
26//!
27//! When this feature is enabled, `SmallVec<[u8; _]>` implements the
28//! `std::io::Write` trait. This feature is not compatible with `#![no_std]`
29//! programs.
30//!
31//! ### `union`
32//!
33//! **This feature requires Rust 1.49.**
34//!
35//! When the `union` feature is enabled `smallvec` will track its state (inline
36//! or spilled) without the use of an enum tag, reducing the size of the
37//! `smallvec` by one machine word. This means that there is potentially no
38//! space overhead compared to `Vec`. Note that `smallvec` can still be larger
39//! than `Vec` if the inline buffer is larger than two machine words.
40//!
41//! To use this feature add `features = ["union"]` in the `smallvec` section of
42//! Cargo.toml. Note that this feature requires Rust 1.49.
43//!
44//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
45//!
46//! ### `const_generics`
47//!
48//! **This feature requires Rust 1.51.**
49//!
50//! When this feature is enabled, `SmallVec` works with any arrays of any size,
51//! not just a fixed list of sizes.
52//!
53//! ### `const_new`
54//!
55//! **This feature requires Rust 1.51.**
56//!
57//! This feature exposes the functions [`SmallVec::new_const`],
58//! [`SmallVec::from_const`], and [`smallvec_inline`] which enables the
59//! `SmallVec` to be initialized from a const context. For details, see the
60//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
61//!
62//! ### `drain_filter`
63//!
64//! **This feature is unstable.** It may change to match the unstable
65//! `drain_filter` method in libstd.
66//!
67//! Enables the `drain_filter` method, which produces an iterator that calls a
68//! user-provided closure to determine which elements of the vector to remove
69//! and yield from the iterator.
70//!
71//! ### `drain_keep_rest`
72//!
73//! **This feature is unstable.** It may change to match the unstable
74//! `drain_keep_rest` method in libstd.
75//!
76//! Enables the `DrainFilter::keep_rest` method.
77//!
78//! ### `specialization`
79//!
80//! **This feature is unstable and requires a nightly build of the Rust
81//! toolchain.**
82//!
83//! When this feature is enabled, `SmallVec::from(slice)` has improved
84//! performance for slices of `Copy` types. (Without this feature, you can use
85//! `SmallVec::from_slice` to get optimal performance for `Copy` types.)
86//!
87//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
88//!
89//! ### `may_dangle`
90//!
91//! **This feature is unstable and requires a nightly build of the Rust
92//! toolchain.**
93//!
94//! This feature makes the Rust compiler less strict about use of vectors that
95//! contain borrowed references. For details, see the
96//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
97//!
98//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
99
100#![no_std]
101#![cfg_attr(docsrs, feature(doc_cfg))]
102#![cfg_attr(feature = "specialization", allow(incomplete_features))]
103#![cfg_attr(feature = "specialization", feature(specialization))]
104#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
105#![deny(missing_docs)]
106
107#[doc(hidden)]
108pub extern crate alloc;
109
110#[cfg(any(test, feature = "write"))]
111extern crate std;
112
113#[cfg(test)]
114mod tests;
115
116#[cfg(feature = "serde")]
117use core::marker::PhantomData;
118#[cfg(feature = "drain_keep_rest")]
119use core::mem::ManuallyDrop;
120#[cfg(feature = "malloc_size_of")]
121use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
122#[cfg(feature = "serde")]
123use serde::{
124 de::{Deserialize, Deserializer, SeqAccess, Visitor},
125 ser::{Serialize, SerializeSeq, Serializer},
126};
127#[cfg(feature = "write")]
128use std::io;
129#[allow(deprecated)]
130use {
131 alloc::{
132 alloc::{Layout, LayoutErr},
133 boxed::Box,
134 vec,
135 vec::Vec,
136 },
137 core::{
138 borrow::{Borrow, BorrowMut},
139 cmp, fmt,
140 hash::{Hash, Hasher},
141 hint::unreachable_unchecked,
142 iter::{repeat, FromIterator, FusedIterator, IntoIterator},
143 mem::{self, MaybeUninit},
144 ops::{self, Range, RangeBounds},
145 ptr::{self, NonNull},
146 slice::{self, SliceIndex},
147 },
148};
149
150/// Creates a [`SmallVec`] containing the arguments.
151///
152/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array
153/// expressions. There are two forms of this macro:
154///
155/// - Create a [`SmallVec`] containing a given list of elements:
156///
157/// ```
158/// # use smallvec::{smallvec, SmallVec};
159/// # fn main() {
160/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
161/// assert_eq!(v[0], 1);
162/// assert_eq!(v[1], 2);
163/// assert_eq!(v[2], 3);
164/// # }
165/// ```
166///
167/// - Create a [`SmallVec`] from a given element and size:
168///
169/// ```
170/// # use smallvec::{smallvec, SmallVec};
171/// # fn main() {
172/// let v: SmallVec<[_; 10]> = smallvec![1; 3];
173/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
174/// # }
175/// ```
176///
177/// Note that unlike array expressions this syntax supports all elements
178/// which implement [`Clone`] and the number of elements doesn't have to be
179/// a constant.
180///
181/// This will use `clone` to duplicate an expression, so one should be careful
182/// using this with types having a nonstandard `Clone` implementation. For
183/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
184/// to the same boxed integer value, not five references pointing to
185/// independently boxed integers.
186#[macro_export]
187macro_rules! smallvec {
188 // count helper: transform any expression into 1
189 (@one $x:expr) => (1usize);
190 () => (
191 $crate::SmallVec::new()
192 );
193 ($elem:expr; $n:expr) => ({
194 $crate::SmallVec::from_elem($elem, $n)
195 });
196 ($($x:expr),+$(,)?) => ({
197 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
198 let mut vec = $crate::SmallVec::new();
199 if count <= vec.inline_size() {
200 $(vec.push($x);)*
201 vec
202 } else {
203 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
204 }
205 });
206}
207
208/// Creates an inline [`SmallVec`] containing the arguments. This macro is
209/// enabled by the feature `const_new`.
210///
211/// `smallvec_inline!` allows `SmallVec`s to be defined with the same syntax as
212/// array expressions in `const` contexts. The inline storage `A` will always be
213/// an array of the size specified by the arguments. There are two forms of this
214/// macro:
215///
216/// - Create a [`SmallVec`] containing a given list of elements:
217///
218/// ```
219/// # use smallvec::{smallvec_inline, SmallVec};
220/// # fn main() {
221/// const V: SmallVec<[i32; 3]> = smallvec_inline![1, 2, 3];
222/// assert_eq!(V[0], 1);
223/// assert_eq!(V[1], 2);
224/// assert_eq!(V[2], 3);
225/// # }
226/// ```
227///
228/// - Create a [`SmallVec`] from a given element and size:
229///
230/// ```
231/// # use smallvec::{smallvec_inline, SmallVec};
232/// # fn main() {
233/// const V: SmallVec<[i32; 3]> = smallvec_inline![1; 3];
234/// assert_eq!(V, SmallVec::from_buf([1, 1, 1]));
235/// # }
236/// ```
237///
238/// Note that the behavior mimics that of array expressions, in contrast to
239/// [`smallvec`].
240#[cfg(feature = "const_new")]
241#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
242#[macro_export]
243macro_rules! smallvec_inline {
244 // count helper: transform any expression into 1
245 (@one $x:expr) => (1usize);
246 ($elem:expr; $n:expr) => ({
247 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
248 });
249 ($($x:expr),+ $(,)?) => ({
250 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
251 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
252 });
253}
254
255/// `panic!()` in debug builds, optimization hint in release.
256#[cfg(not(feature = "union"))]
257macro_rules! debug_unreachable {
258 () => {
259 debug_unreachable!("entered unreachable code")
260 };
261 ($e:expr) => {
262 if cfg!(debug_assertions) {
263 panic!($e);
264 } else {
265 unreachable_unchecked();
266 }
267 };
268}
269
270/// Trait to be implemented by a collection that can be extended from a slice
271///
272/// ## Example
273///
274/// ```rust
275/// use smallvec::{ExtendFromSlice, SmallVec};
276///
277/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
278/// v.extend_from_slice(b"Test!");
279/// }
280///
281/// let mut vec = Vec::new();
282/// initialize(&mut vec);
283/// assert_eq!(&vec, b"Test!");
284///
285/// let mut small_vec = SmallVec::<[u8; 8]>::new();
286/// initialize(&mut small_vec);
287/// assert_eq!(&small_vec as &[_], b"Test!");
288/// ```
289#[doc(hidden)]
290#[deprecated]
291pub trait ExtendFromSlice<T> {
292 /// Extends a collection from a slice of its element type
293 fn extend_from_slice(&mut self, other: &[T]);
294}
295
296#[allow(deprecated)]
297impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
298 fn extend_from_slice(&mut self, other: &[T]) {
299 Vec::extend_from_slice(self, other)
300 }
301}
302
303/// Error type for APIs with fallible heap allocation
304#[derive(Debug)]
305pub enum CollectionAllocErr {
306 /// Overflow `usize::MAX` or other error during size computation
307 CapacityOverflow,
308 /// The allocator return an error
309 AllocErr {
310 /// The layout that was passed to the allocator
311 layout: Layout,
312 },
313}
314
315impl fmt::Display for CollectionAllocErr {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 write!(f, "Allocation error: {:?}", self)
318 }
319}
320
321#[allow(deprecated)]
322impl From<LayoutErr> for CollectionAllocErr {
323 fn from(_: LayoutErr) -> Self {
324 CollectionAllocErr::CapacityOverflow
325 }
326}
327
328fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
329 match result {
330 Ok(x) => x,
331 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
332 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
333 }
334}
335
336/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
337/// <https://github.com/rust-lang/rust/issues/55724>
338fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
339 let size = mem::size_of::<T>()
340 .checked_mul(n)
341 .ok_or(CollectionAllocErr::CapacityOverflow)?;
342 let align = mem::align_of::<T>();
343 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
344}
345
346unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
347 // This unwrap should succeed since the same did when allocating.
348 let layout = layout_array::<T>(capacity).unwrap();
349 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
350}
351
352/// An iterator that removes the items from a `SmallVec` and yields them by
353/// value.
354///
355/// Returned from [`SmallVec::drain`][1].
356///
357/// [1]: struct.SmallVec.html#method.drain
358pub struct Drain<'a, T: 'a + Array> {
359 tail_start: usize,
360 tail_len: usize,
361 iter: slice::Iter<'a, T::Item>,
362 vec: NonNull<SmallVec<T>>,
363}
364
365impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
366where
367 T::Item: fmt::Debug,
368{
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
371 }
372}
373
374unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
375unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
376
377impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
378 type Item = T::Item;
379
380 #[inline]
381 fn next(&mut self) -> Option<T::Item> {
382 self.iter
383 .next()
384 .map(|reference| unsafe { ptr::read(reference) })
385 }
386
387 #[inline]
388 fn size_hint(&self) -> (usize, Option<usize>) {
389 self.iter.size_hint()
390 }
391}
392
393impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
394 #[inline]
395 fn next_back(&mut self) -> Option<T::Item> {
396 self.iter
397 .next_back()
398 .map(|reference| unsafe { ptr::read(reference) })
399 }
400}
401
402impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
403 #[inline]
404 fn len(&self) -> usize {
405 self.iter.len()
406 }
407}
408
409impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
410
411impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
412 fn drop(&mut self) {
413 self.for_each(drop);
414
415 if self.tail_len > 0 {
416 unsafe {
417 let source_vec = self.vec.as_mut();
418
419 // memmove back untouched tail, update to new length
420 let start = source_vec.len();
421 let tail = self.tail_start;
422 if tail != start {
423 // as_mut_ptr creates a &mut, invalidating other pointers.
424 // This pattern avoids calling it with a pointer already
425 // present.
426 let ptr = source_vec.as_mut_ptr();
427 let src = ptr.add(tail);
428 let dst = ptr.add(start);
429 ptr::copy(src, dst, self.tail_len);
430 }
431 source_vec.set_len(start + self.tail_len);
432 }
433 }
434 }
435}
436
437#[cfg(feature = "drain_filter")]
438/// An iterator which uses a closure to determine if an element should be
439/// removed.
440///
441/// Returned from [`SmallVec::drain_filter`][1].
442///
443/// [1]: struct.SmallVec.html#method.drain_filter
444pub struct DrainFilter<'a, T, F>
445where
446 F: FnMut(&mut T::Item) -> bool,
447 T: Array,
448{
449 vec: &'a mut SmallVec<T>,
450 /// The index of the item that will be inspected by the next call to `next`.
451 idx: usize,
452 /// The number of items that have been drained (removed) thus far.
453 del: usize,
454 /// The original length of `vec` prior to draining.
455 old_len: usize,
456 /// The filter test predicate.
457 pred: F,
458 /// A flag that indicates a panic has occurred in the filter test predicate.
459 /// This is used as a hint in the drop implementation to prevent consumption
460 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
461 /// backshifted in the `vec`, but no further items will be dropped or
462 /// tested by the filter predicate.
463 panic_flag: bool,
464}
465
466#[cfg(feature = "drain_filter")]
467impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
468where
469 F: FnMut(&mut T::Item) -> bool,
470 T: Array,
471 T::Item: fmt::Debug,
472{
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.debug_tuple("DrainFilter")
475 .field(&self.vec.as_slice())
476 .finish()
477 }
478}
479
480#[cfg(feature = "drain_filter")]
481impl<T, F> Iterator for DrainFilter<'_, T, F>
482where
483 F: FnMut(&mut T::Item) -> bool,
484 T: Array,
485{
486 type Item = T::Item;
487
488 fn next(&mut self) -> Option<T::Item> {
489 unsafe {
490 while self.idx < self.old_len {
491 let i = self.idx;
492 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
493 self.panic_flag = true;
494 let drained = (self.pred)(&mut v[i]);
495 self.panic_flag = false;
496 // Update the index *after* the predicate is called. If the
497 // index is updated prior and the predicate
498 // panics, the element at this index would be
499 // leaked.
500 self.idx += 1;
501 if drained {
502 self.del += 1;
503 return Some(ptr::read(&v[i]));
504 } else if self.del > 0 {
505 let del = self.del;
506 let src: *const Self::Item = &v[i];
507 let dst: *mut Self::Item = &mut v[i - del];
508 ptr::copy_nonoverlapping(src, dst, 1);
509 }
510 }
511 None
512 }
513 }
514
515 fn size_hint(&self) -> (usize, Option<usize>) {
516 (0, Some(self.old_len - self.idx))
517 }
518}
519
520#[cfg(feature = "drain_filter")]
521impl<T, F> Drop for DrainFilter<'_, T, F>
522where
523 F: FnMut(&mut T::Item) -> bool,
524 T: Array,
525{
526 fn drop(&mut self) {
527 struct BackshiftOnDrop<'a, 'b, T, F>
528 where
529 F: FnMut(&mut T::Item) -> bool,
530 T: Array,
531 {
532 drain: &'b mut DrainFilter<'a, T, F>,
533 }
534
535 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
536 where
537 F: FnMut(&mut T::Item) -> bool,
538 T: Array,
539 {
540 fn drop(&mut self) {
541 unsafe {
542 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
543 // This is a pretty messed up state, and there isn't
544 // really an obviously right
545 // thing to do. We don't want to keep trying
546 // to execute `pred`, so we just backshift all the
547 // unprocessed elements and tell
548 // the vec that they still exist. The backshift
549 // is required to prevent a double-drop of the last
550 // successfully drained item
551 // prior to a panic in the predicate.
552 let ptr = self.drain.vec.as_mut_ptr();
553 let src = ptr.add(self.drain.idx);
554 let dst = src.sub(self.drain.del);
555 let tail_len = self.drain.old_len - self.drain.idx;
556 src.copy_to(dst, tail_len);
557 }
558 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
559 }
560 }
561 }
562
563 let backshift = BackshiftOnDrop { drain: self };
564
565 // Attempt to consume any remaining elements if the filter predicate
566 // has not yet panicked. We'll backshift any remaining elements
567 // whether we've already panicked or if the consumption here panics.
568 if !backshift.drain.panic_flag {
569 backshift.drain.for_each(drop);
570 }
571 }
572}
573
574#[cfg(feature = "drain_keep_rest")]
575impl<T, F> DrainFilter<'_, T, F>
576where
577 F: FnMut(&mut T::Item) -> bool,
578 T: Array,
579{
580 /// Keep unyielded elements in the source `Vec`.
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// # use smallvec::{smallvec, SmallVec};
586 ///
587 /// let mut vec: SmallVec<[char; 2]> = smallvec!['a', 'b', 'c'];
588 /// let mut drain = vec.drain_filter(|_| true);
589 ///
590 /// assert_eq!(drain.next().unwrap(), 'a');
591 ///
592 /// // This call keeps 'b' and 'c' in the vec.
593 /// drain.keep_rest();
594 ///
595 /// // If we wouldn't call `keep_rest()`,
596 /// // `vec` would be empty.
597 /// assert_eq!(vec, SmallVec::<[char; 2]>::from_slice(&['b', 'c']));
598 /// ```
599 pub fn keep_rest(self) {
600 // At this moment layout looks like this:
601 //
602 // _____________________/-- old_len
603 // / \
604 // [kept] [yielded] [tail]
605 // \_______/ ^-- idx
606 // \-- del
607 //
608 // Normally `Drop` impl would drop [tail] (via .for_each(drop), ie still
609 // calling `pred`)
610 //
611 // 1. Move [tail] after [kept]
612 // 2. Update length of the original vec to `old_len - del` a. In case of
613 // ZST, this is the only thing we want to do
614 // 3. Do *not* drop self, as everything is put in a consistent state
615 // already, there is nothing to do
616 let mut this = ManuallyDrop::new(self);
617
618 unsafe {
619 // ZSTs have no identity, so we don't need to move them around.
620 let needs_move = mem::size_of::<T::Item>() != 0;
621
622 if needs_move && this.idx < this.old_len && this.del > 0 {
623 let ptr = this.vec.as_mut_ptr();
624 let src = ptr.add(this.idx);
625 let dst = src.sub(this.del);
626 let tail_len = this.old_len - this.idx;
627 src.copy_to(dst, tail_len);
628 }
629
630 let new_len = this.old_len - this.del;
631 this.vec.set_len(new_len);
632 }
633 }
634}
635
636#[cfg(feature = "union")]
637union SmallVecData<A: Array> {
638 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
639 heap: (NonNull<A::Item>, usize),
640}
641
642#[cfg(all(feature = "union", feature = "const_new"))]
643impl<T, const N: usize> SmallVecData<[T; N]> {
644 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
645 #[inline]
646 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
647 SmallVecData {
648 inline: core::mem::ManuallyDrop::new(inline),
649 }
650 }
651}
652
653#[cfg(feature = "union")]
654impl<A: Array> SmallVecData<A> {
655 #[inline]
656 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
657 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
658 }
659 #[inline]
660 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
661 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
662 }
663 #[inline]
664 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
665 SmallVecData {
666 inline: core::mem::ManuallyDrop::new(inline),
667 }
668 }
669 // Workaround for https://github.com/rust-lang/rust/issues/157743: when from_inline is
670 // called with MaybeUninit::uninit(), rustc 1.93+ GVN propagates const
671 // <uninit> into the ManuallyDrop::new() aggregate, causing LLVM to
672 // materialize a global constant that MemCpyOpt then collapses into a
673 // memset over the whole struct. Using assume_init() of a doubly-wrapped
674 // MaybeUninit produces Immediate::Uninit instead of const <uninit>,
675 // which codegen handles as undef without emitting any global. This
676 // function also avoids introducing an intermediate local that would
677 // inflate stack frames in debug builds.
678 #[inline]
679 fn empty() -> SmallVecData<A> {
680 // SAFETY: ManuallyDrop<MaybeUninit<A>> is valid for any bit pattern
681 // including uninitialized bytes, so assume_init() on a
682 // MaybeUninit of that type is sound.
683 SmallVecData {
684 inline: unsafe { MaybeUninit::uninit().assume_init() },
685 }
686 }
687 #[inline]
688 unsafe fn into_inline(self) -> MaybeUninit<A> {
689 core::mem::ManuallyDrop::into_inner(self.inline)
690 }
691 #[inline]
692 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
693 (ConstNonNull(self.heap.0), self.heap.1)
694 }
695 #[inline]
696 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
697 let h = &mut self.heap;
698 (h.0, &mut h.1)
699 }
700 #[inline]
701 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
702 SmallVecData { heap: (ptr, len) }
703 }
704}
705
706#[cfg(not(feature = "union"))]
707enum SmallVecData<A: Array> {
708 Inline(MaybeUninit<A>),
709 // Using NonNull and NonZero here allows to reduce size of `SmallVec`.
710 Heap {
711 // Since we never allocate on heap
712 // unless our capacity is bigger than inline capacity
713 // heap capacity cannot be less than 1.
714 // Therefore, pointer cannot be null too.
715 ptr: NonNull<A::Item>,
716 len: usize,
717 },
718}
719
720#[cfg(all(not(feature = "union"), feature = "const_new"))]
721impl<T, const N: usize> SmallVecData<[T; N]> {
722 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
723 #[inline]
724 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
725 SmallVecData::Inline(inline)
726 }
727}
728
729#[cfg(not(feature = "union"))]
730impl<A: Array> SmallVecData<A> {
731 #[inline]
732 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
733 match self {
734 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
735 _ => debug_unreachable!(),
736 }
737 }
738 #[inline]
739 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
740 match self {
741 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
742 _ => debug_unreachable!(),
743 }
744 }
745 #[inline]
746 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
747 SmallVecData::Inline(inline)
748 }
749 // See the comment on the union variant's empty() for why this exists.
750 #[inline]
751 fn empty() -> SmallVecData<A> {
752 // SAFETY: MaybeUninit<A> is valid for any bit pattern including
753 // uninitialized bytes, so assume_init() on a MaybeUninit of
754 // that type is sound.
755 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
756 }
757 #[inline]
758 unsafe fn into_inline(self) -> MaybeUninit<A> {
759 match self {
760 SmallVecData::Inline(a) => a,
761 _ => debug_unreachable!(),
762 }
763 }
764 #[inline]
765 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
766 match self {
767 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
768 _ => debug_unreachable!(),
769 }
770 }
771 #[inline]
772 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
773 match self {
774 SmallVecData::Heap { ptr, len } => (*ptr, len),
775 _ => debug_unreachable!(),
776 }
777 }
778 #[inline]
779 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
780 SmallVecData::Heap { ptr, len }
781 }
782}
783
784unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
785unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
786
787/// A `Vec`-like container that can store a small number of elements inline.
788///
789/// `SmallVec` acts like a vector, but can store a limited amount of data inline
790/// within the `SmallVec` struct rather than in a separate allocation. If the
791/// data exceeds this limit, the `SmallVec` will "spill" its data onto the heap,
792/// allocating a new buffer to hold it.
793///
794/// The amount of data that a `SmallVec` can store inline depends on its backing
795/// store. The backing store can be any type that implements the `Array` trait;
796/// usually it is a small fixed-sized array. For example a `SmallVec<[u64; 8]>`
797/// can hold up to eight 64-bit integers inline.
798///
799/// ## Example
800///
801/// ```rust
802/// use smallvec::SmallVec;
803/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
804///
805/// // The vector can hold up to 4 items without spilling onto the heap.
806/// v.extend(0..4);
807/// assert_eq!(v.len(), 4);
808/// assert!(!v.spilled());
809///
810/// // Pushing another element will force the buffer to spill:
811/// v.push(4);
812/// assert_eq!(v.len(), 5);
813/// assert!(v.spilled());
814/// ```
815pub struct SmallVec<A: Array> {
816 // The capacity field is used to determine which of the storage variants is active:
817 // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds
818 // the current length of the vector (number of elements actually in use). If capacity >
819 // Self::inline_capacity() then the heap variant is used and capacity holds the size of the
820 // memory allocation.
821 capacity: usize,
822 data: SmallVecData<A>,
823}
824
825impl<A: Array> SmallVec<A> {
826 /// Construct an empty vector
827 #[inline]
828 pub fn new() -> SmallVec<A> {
829 // Try to detect invalid custom implementations of `Array`. Hopefully,
830 // this check should be optimized away entirely for valid ones.
831 assert!(
832 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
833 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
834 );
835 SmallVec {
836 capacity: 0,
837 data: SmallVecData::empty(),
838 }
839 }
840
841 /// Construct an empty vector with enough capacity pre-allocated to store at
842 /// least `n` elements.
843 ///
844 /// Will create a heap allocation only if `n` is larger than the inline
845 /// capacity.
846 ///
847 /// ```
848 /// # use smallvec::SmallVec;
849 ///
850 /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
851 ///
852 /// assert!(v.is_empty());
853 /// assert!(v.capacity() >= 100);
854 /// ```
855 #[inline]
856 pub fn with_capacity(n: usize) -> Self {
857 let mut v = SmallVec::new();
858 v.reserve_exact(n);
859 v
860 }
861
862 /// Construct a new `SmallVec` from a `Vec<A::Item>`.
863 ///
864 /// Elements will be copied to the inline buffer if `vec.capacity() <=
865 /// Self::inline_capacity()`.
866 ///
867 /// ```rust
868 /// use smallvec::SmallVec;
869 ///
870 /// let vec = vec![1, 2, 3, 4, 5];
871 /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
872 ///
873 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
874 /// ```
875 #[inline]
876 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
877 if vec.capacity() <= Self::inline_capacity() {
878 // Cannot use Vec with smaller capacity
879 // because we use value of `Self::capacity` field as indicator.
880 unsafe {
881 let mut data = SmallVecData::<A>::empty();
882 let len = vec.len();
883 vec.set_len(0);
884 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
885
886 SmallVec {
887 capacity: len,
888 data,
889 }
890 }
891 } else {
892 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
893 mem::forget(vec);
894 let ptr = NonNull::new(ptr)
895 // See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
896 .expect("Cannot be null by `Vec` invariant");
897
898 SmallVec {
899 capacity: cap,
900 data: SmallVecData::from_heap(ptr, len),
901 }
902 }
903 }
904
905 /// Constructs a new `SmallVec` on the stack from an `A` without
906 /// copying elements.
907 ///
908 /// ```rust
909 /// use smallvec::SmallVec;
910 ///
911 /// let buf = [1, 2, 3, 4, 5];
912 /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
913 ///
914 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
915 /// ```
916 #[inline]
917 pub fn from_buf(buf: A) -> SmallVec<A> {
918 SmallVec {
919 capacity: A::size(),
920 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
921 }
922 }
923
924 /// Constructs a new `SmallVec` on the stack from an `A` without
925 /// copying elements. Also sets the length, which must be less or
926 /// equal to the size of `buf`.
927 ///
928 /// ```rust
929 /// use smallvec::SmallVec;
930 ///
931 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
932 /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
933 ///
934 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
935 /// ```
936 #[inline]
937 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
938 assert!(len <= A::size());
939 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
940 }
941
942 /// Constructs a new `SmallVec` on the stack from an `A` without
943 /// copying elements. Also sets the length. The user is responsible
944 /// for ensuring that `len <= A::size()`.
945 ///
946 /// ```rust
947 /// use {smallvec::SmallVec, std::mem::MaybeUninit};
948 ///
949 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
950 /// let small_vec: SmallVec<_> =
951 /// unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) };
952 ///
953 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
954 /// ```
955 #[inline]
956 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
957 SmallVec {
958 capacity: len,
959 data: SmallVecData::from_inline(buf),
960 }
961 }
962
963 /// Sets the length of a vector.
964 ///
965 /// This will explicitly set the size of the vector, without actually
966 /// modifying its buffers, so it is up to the caller to ensure that the
967 /// vector is actually the specified size.
968 pub unsafe fn set_len(&mut self, new_len: usize) {
969 let (_, len_ptr, _) = self.triple_mut();
970 *len_ptr = new_len;
971 }
972
973 /// The maximum number of elements this vector can hold inline
974 #[inline]
975 fn inline_capacity() -> usize {
976 if mem::size_of::<A::Item>() > 0 {
977 A::size()
978 } else {
979 // For zero-size items code like `ptr.add(offset)` always returns
980 // the same pointer. Therefore all items are at the same
981 // address, and any array size has capacity for
982 // infinitely many items. The capacity is limited by the
983 // bit width of the length field.
984 //
985 // `Vec` also does this:
986 // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
987 //
988 // In our case, this also ensures that a smallvec of zero-size items
989 // never spills, and we never try to allocate zero bytes
990 // which `std::alloc::alloc` disallows.
991 core::usize::MAX
992 }
993 }
994
995 /// The maximum number of elements this vector can hold inline
996 #[inline]
997 pub fn inline_size(&self) -> usize {
998 Self::inline_capacity()
999 }
1000
1001 /// The number of elements stored in the vector
1002 #[inline]
1003 pub fn len(&self) -> usize {
1004 self.triple().1
1005 }
1006
1007 /// Returns `true` if the vector is empty
1008 #[inline]
1009 pub fn is_empty(&self) -> bool {
1010 self.len() == 0
1011 }
1012
1013 /// The number of items the vector can hold without reallocating
1014 #[inline]
1015 pub fn capacity(&self) -> usize {
1016 self.triple().2
1017 }
1018
1019 /// Returns a tuple with (data ptr, len, capacity)
1020 /// Useful to get all `SmallVec` properties with a single check of the
1021 /// current storage variant.
1022 #[inline]
1023 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1024 unsafe {
1025 if self.spilled() {
1026 let (ptr, len) = self.data.heap();
1027 (ptr, len, self.capacity)
1028 } else {
1029 (self.data.inline(), self.capacity, Self::inline_capacity())
1030 }
1031 }
1032 }
1033
1034 /// Returns a tuple with (data ptr, len ptr, capacity)
1035 #[inline]
1036 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1037 unsafe {
1038 if self.spilled() {
1039 let (ptr, len_ptr) = self.data.heap_mut();
1040 (ptr, len_ptr, self.capacity)
1041 } else {
1042 (
1043 self.data.inline_mut(),
1044 &mut self.capacity,
1045 Self::inline_capacity(),
1046 )
1047 }
1048 }
1049 }
1050
1051 /// Returns `true` if the data has spilled into a separate heap-allocated
1052 /// buffer.
1053 #[inline]
1054 pub fn spilled(&self) -> bool {
1055 self.capacity > Self::inline_capacity()
1056 }
1057
1058 /// Creates a draining iterator that removes the specified range in the
1059 /// vector and yields the removed items.
1060 ///
1061 /// Note 1: The element range is removed even if the iterator is only
1062 /// partially consumed or not consumed at all.
1063 ///
1064 /// Note 2: It is unspecified how many elements are removed from the vector
1065 /// if the `Drain` value is leaked.
1066 ///
1067 /// # Panics
1068 ///
1069 /// Panics if the starting point is greater than the end point or if
1070 /// the end point is greater than the length of the vector.
1071 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1072 where
1073 R: RangeBounds<usize>,
1074 {
1075 use core::ops::Bound::*;
1076
1077 let len = self.len();
1078 let start = match range.start_bound() {
1079 Included(&n) => n,
1080 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1081 Unbounded => 0,
1082 };
1083 let end = match range.end_bound() {
1084 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1085 Excluded(&n) => n,
1086 Unbounded => len,
1087 };
1088
1089 assert!(start <= end);
1090 assert!(end <= len);
1091
1092 unsafe {
1093 self.set_len(start);
1094
1095 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1096
1097 Drain {
1098 tail_start: end,
1099 tail_len: len - end,
1100 iter: range_slice.iter(),
1101 // Since self is a &mut, passing it to a function would invalidate the slice
1102 // iterator.
1103 vec: NonNull::new_unchecked(self as *mut _),
1104 }
1105 }
1106 }
1107
1108 #[cfg(feature = "drain_filter")]
1109 /// Creates an iterator which uses a closure to determine if an element
1110 /// should be removed.
1111 ///
1112 /// If the closure returns true, the element is removed and yielded. If the
1113 /// closure returns false, the element will remain in the vector and
1114 /// will not be yielded by the iterator.
1115 ///
1116 /// Using this method is equivalent to the following code:
1117 /// ```
1118 /// # use smallvec::SmallVec;
1119 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1120 /// # let mut vec: SmallVec<[i32; 8]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6]);
1121 /// let mut i = 0;
1122 /// while i < vec.len() {
1123 /// if some_predicate(&mut vec[i]) {
1124 /// let val = vec.remove(i);
1125 /// // your code here
1126 /// } else {
1127 /// i += 1;
1128 /// }
1129 /// }
1130 ///
1131 /// # assert_eq!(vec, SmallVec::<[i32; 8]>::from_slice(&[1i32, 4, 5]));
1132 /// ```
1133 /// ///
1134 /// But `drain_filter` is easier to use. `drain_filter` is also more
1135 /// efficient, because it can backshift the elements of the array in
1136 /// bulk.
1137 ///
1138 /// Note that `drain_filter` also lets you mutate every element in the
1139 /// filter closure, regardless of whether you choose to keep or remove
1140 /// it.
1141 ///
1142 /// # Examples
1143 ///
1144 /// Splitting an array into evens and odds, reusing the original allocation:
1145 ///
1146 /// ```
1147 /// # use smallvec::SmallVec;
1148 /// let mut numbers: SmallVec<[i32; 16]> =
1149 /// SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1150 ///
1151 /// let evens = numbers
1152 /// .drain_filter(|x| *x % 2 == 0)
1153 /// .collect::<SmallVec<[i32; 16]>>();
1154 /// let odds = numbers;
1155 ///
1156 /// assert_eq!(
1157 /// evens,
1158 /// SmallVec::<[i32; 16]>::from_slice(&[2i32, 4, 6, 8, 14])
1159 /// );
1160 /// assert_eq!(
1161 /// odds,
1162 /// SmallVec::<[i32; 16]>::from_slice(&[1i32, 3, 5, 9, 11, 13, 15])
1163 /// );
1164 /// ```
1165 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1166 where
1167 F: FnMut(&mut A::Item) -> bool,
1168 {
1169 let old_len = self.len();
1170
1171 // Guard against us getting leaked (leak amplification)
1172 unsafe {
1173 self.set_len(0);
1174 }
1175
1176 DrainFilter {
1177 vec: self,
1178 idx: 0,
1179 del: 0,
1180 old_len,
1181 pred: filter,
1182 panic_flag: false,
1183 }
1184 }
1185
1186 /// Append an item to the vector.
1187 #[inline]
1188 pub fn push(&mut self, value: A::Item) {
1189 unsafe {
1190 let (mut ptr, mut len, cap) = self.triple_mut();
1191 if *len == cap {
1192 self.reserve_one_unchecked();
1193 let (heap_ptr, heap_len) = self.data.heap_mut();
1194 ptr = heap_ptr;
1195 len = heap_len;
1196 }
1197 ptr::write(ptr.as_ptr().add(*len), value);
1198 *len += 1;
1199 }
1200 }
1201
1202 /// Remove an item from the end of the vector and return it, or None if
1203 /// empty.
1204 #[inline]
1205 pub fn pop(&mut self) -> Option<A::Item> {
1206 unsafe {
1207 let (ptr, len_ptr, _) = self.triple_mut();
1208 let ptr: *const _ = ptr.as_ptr();
1209 if *len_ptr == 0 {
1210 return None;
1211 }
1212 let last_index = *len_ptr - 1;
1213 *len_ptr = last_index;
1214 Some(ptr::read(ptr.add(last_index)))
1215 }
1216 }
1217
1218 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1219 ///
1220 /// # Example
1221 ///
1222 /// ```
1223 /// # use smallvec::{SmallVec, smallvec};
1224 /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3];
1225 /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6];
1226 /// v0.append(&mut v1);
1227 /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]);
1228 /// assert_eq!(*v1, []);
1229 /// ```
1230 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1231 where
1232 B: Array<Item = A::Item>,
1233 {
1234 self.extend(other.drain(..))
1235 }
1236
1237 /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1238 ///
1239 /// Panics if `new_cap` is less than the vector's length
1240 /// or if the capacity computation overflows `usize`.
1241 pub fn grow(&mut self, new_cap: usize) {
1242 infallible(self.try_grow(new_cap))
1243 }
1244
1245 /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1246 ///
1247 /// Panics if `new_cap` is less than the vector's length
1248 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1249 unsafe {
1250 let unspilled = !self.spilled();
1251 let (ptr, &mut len, cap) = self.triple_mut();
1252 assert!(new_cap >= len);
1253 if new_cap <= Self::inline_capacity() {
1254 if unspilled {
1255 return Ok(());
1256 }
1257 self.data = SmallVecData::empty();
1258 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1259 self.capacity = len;
1260 deallocate(ptr, cap);
1261 } else if new_cap != cap {
1262 let layout = layout_array::<A::Item>(new_cap)?;
1263 debug_assert!(layout.size() > 0);
1264 let new_alloc;
1265 if unspilled {
1266 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1267 .ok_or(CollectionAllocErr::AllocErr { layout })?
1268 .cast();
1269 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1270 } else {
1271 // This should never fail since the same succeeded
1272 // when previously allocating `ptr`.
1273 let old_layout = layout_array::<A::Item>(cap)?;
1274
1275 let new_ptr =
1276 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1277 new_alloc = NonNull::new(new_ptr)
1278 .ok_or(CollectionAllocErr::AllocErr { layout })?
1279 .cast();
1280 }
1281 self.data = SmallVecData::from_heap(new_alloc, len);
1282 self.capacity = new_cap;
1283 }
1284 Ok(())
1285 }
1286 }
1287
1288 /// Reserve capacity for `additional` more elements to be inserted.
1289 ///
1290 /// May reserve more space to avoid frequent reallocations.
1291 ///
1292 /// Panics if the capacity computation overflows `usize`.
1293 #[inline]
1294 pub fn reserve(&mut self, additional: usize) {
1295 infallible(self.try_reserve(additional))
1296 }
1297
1298 /// Internal method used to grow in push() and insert(), where we know
1299 /// already we have to grow.
1300 #[cold]
1301 fn reserve_one_unchecked(&mut self) {
1302 debug_assert_eq!(self.len(), self.capacity());
1303 let new_cap = self
1304 .len()
1305 .checked_add(1)
1306 .and_then(usize::checked_next_power_of_two)
1307 .expect("capacity overflow");
1308 infallible(self.try_grow(new_cap))
1309 }
1310
1311 /// Reserve capacity for `additional` more elements to be inserted.
1312 ///
1313 /// May reserve more space to avoid frequent reallocations.
1314 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1315 // prefer triple_mut() even if triple() would work so that the optimizer
1316 // removes duplicated calls to it from callers.
1317 let (_, &mut len, cap) = self.triple_mut();
1318 if cap - len >= additional {
1319 return Ok(());
1320 }
1321 let new_cap = len
1322 .checked_add(additional)
1323 .and_then(usize::checked_next_power_of_two)
1324 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1325 self.try_grow(new_cap)
1326 }
1327
1328 /// Reserve the minimum capacity for `additional` more elements to be
1329 /// inserted.
1330 ///
1331 /// Panics if the new capacity overflows `usize`.
1332 pub fn reserve_exact(&mut self, additional: usize) {
1333 infallible(self.try_reserve_exact(additional))
1334 }
1335
1336 /// Reserve the minimum capacity for `additional` more elements to be
1337 /// inserted.
1338 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1339 let (_, &mut len, cap) = self.triple_mut();
1340 if cap - len >= additional {
1341 return Ok(());
1342 }
1343 let new_cap = len
1344 .checked_add(additional)
1345 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1346 self.try_grow(new_cap)
1347 }
1348
1349 /// Shrink the capacity of the vector as much as possible.
1350 ///
1351 /// When possible, this will move data from an external heap buffer to the
1352 /// vector's inline storage.
1353 pub fn shrink_to_fit(&mut self) {
1354 if !self.spilled() {
1355 return;
1356 }
1357 let len = self.len();
1358 if self.inline_size() >= len {
1359 unsafe {
1360 let (ptr, len) = self.data.heap();
1361 self.data = SmallVecData::empty();
1362 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1363 deallocate(ptr.0, self.capacity);
1364 self.capacity = len;
1365 }
1366 } else if self.capacity() > len {
1367 self.grow(len);
1368 }
1369 }
1370
1371 /// Shorten the vector, keeping the first `len` elements and dropping the
1372 /// rest.
1373 ///
1374 /// If `len` is greater than or equal to the vector's current length, this
1375 /// has no effect.
1376 ///
1377 /// This does not re-allocate. If you want the vector's capacity to shrink,
1378 /// call `shrink_to_fit` after truncating.
1379 pub fn truncate(&mut self, len: usize) {
1380 unsafe {
1381 let (ptr, len_ptr, _) = self.triple_mut();
1382 let ptr = ptr.as_ptr();
1383 while len < *len_ptr {
1384 let last_index = *len_ptr - 1;
1385 *len_ptr = last_index;
1386 ptr::drop_in_place(ptr.add(last_index));
1387 }
1388 }
1389 }
1390
1391 /// Extracts a slice containing the entire vector.
1392 ///
1393 /// Equivalent to `&s[..]`.
1394 pub fn as_slice(&self) -> &[A::Item] {
1395 self
1396 }
1397
1398 /// Extracts a mutable slice of the entire vector.
1399 ///
1400 /// Equivalent to `&mut s[..]`.
1401 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1402 self
1403 }
1404
1405 /// Remove the element at position `index`, replacing it with the last
1406 /// element.
1407 ///
1408 /// This does not preserve ordering, but is O(1).
1409 ///
1410 /// Panics if `index` is out of bounds.
1411 #[inline]
1412 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1413 let len = self.len();
1414 self.swap(len - 1, index);
1415 self.pop()
1416 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1417 }
1418
1419 /// Remove all elements from the vector.
1420 #[inline]
1421 pub fn clear(&mut self) {
1422 self.truncate(0);
1423 }
1424
1425 /// Remove and return the element at position `index`, shifting all elements
1426 /// after it to the left.
1427 ///
1428 /// Panics if `index` is out of bounds.
1429 pub fn remove(&mut self, index: usize) -> A::Item {
1430 unsafe {
1431 let (ptr, len_ptr, _) = self.triple_mut();
1432 let len = *len_ptr;
1433 assert!(index < len);
1434 *len_ptr = len - 1;
1435 let ptr = ptr.as_ptr().add(index);
1436 let item = ptr::read(ptr);
1437 ptr::copy(ptr.add(1), ptr, len - index - 1);
1438 item
1439 }
1440 }
1441
1442 /// Insert an element at position `index`, shifting all elements after it to
1443 /// the right.
1444 ///
1445 /// Panics if `index > len`.
1446 pub fn insert(&mut self, index: usize, element: A::Item) {
1447 unsafe {
1448 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1449 if *len_ptr == cap {
1450 self.reserve_one_unchecked();
1451 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1452 ptr = heap_ptr;
1453 len_ptr = heap_len_ptr;
1454 }
1455 let mut ptr = ptr.as_ptr();
1456 let len = *len_ptr;
1457 if index > len {
1458 panic!("index exceeds length");
1459 }
1460 // SAFETY: add is UB if index > len, but we panicked first
1461 ptr = ptr.add(index);
1462 if index < len {
1463 // Shift element to the right of `index`.
1464 ptr::copy(ptr, ptr.add(1), len - index);
1465 }
1466 *len_ptr = len + 1;
1467 ptr::write(ptr, element);
1468 }
1469 }
1470
1471 /// Insert multiple elements at position `index`, shifting all following
1472 /// elements toward the back.
1473 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1474 let mut iter = iterable.into_iter();
1475 if index == self.len() {
1476 return self.extend(iter);
1477 }
1478
1479 let (lower_size_bound, _) = iter.size_hint();
1480 assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset
1481 // is indexable
1482 assert!(index + lower_size_bound >= index); // Protect against overflow
1483
1484 let mut num_added = 0;
1485 let old_len = self.len();
1486 assert!(index <= old_len);
1487
1488 unsafe {
1489 // Reserve space for `lower_size_bound` elements.
1490 self.reserve(lower_size_bound);
1491 let start = self.as_mut_ptr();
1492 let ptr = start.add(index);
1493
1494 // Move the trailing elements.
1495 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1496
1497 // In case the iterator panics, don't double-drop the items we just
1498 // copied above.
1499 self.set_len(0);
1500 let mut guard = DropOnPanic {
1501 start,
1502 skip: index..(index + lower_size_bound),
1503 len: old_len + lower_size_bound,
1504 };
1505
1506 // The set_len above invalidates the previous pointers, so we must
1507 // re-create them.
1508 let start = self.as_mut_ptr();
1509 let ptr = start.add(index);
1510
1511 while num_added < lower_size_bound {
1512 let element = match iter.next() {
1513 Some(x) => x,
1514 None => break,
1515 };
1516 let cur = ptr.add(num_added);
1517 ptr::write(cur, element);
1518 guard.skip.start += 1;
1519 num_added += 1;
1520 }
1521
1522 if num_added < lower_size_bound {
1523 // Iterator provided fewer elements than the hint. Move the tail
1524 // backward.
1525 ptr::copy(
1526 ptr.add(lower_size_bound),
1527 ptr.add(num_added),
1528 old_len - index,
1529 );
1530 }
1531 // There are no more duplicate or uninitialized slots, so the guard
1532 // is not needed.
1533 self.set_len(old_len + num_added);
1534 mem::forget(guard);
1535 }
1536
1537 // Insert any remaining elements one-by-one.
1538 for element in iter {
1539 self.insert(index + num_added, element);
1540 num_added += 1;
1541 }
1542
1543 struct DropOnPanic<T> {
1544 start: *mut T,
1545 skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
1546 len: usize,
1547 }
1548
1549 impl<T> Drop for DropOnPanic<T> {
1550 fn drop(&mut self) {
1551 for i in 0..self.len {
1552 if !self.skip.contains(&i) {
1553 unsafe {
1554 ptr::drop_in_place(self.start.add(i));
1555 }
1556 }
1557 }
1558 }
1559 }
1560 }
1561
1562 /// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec`
1563 /// has already spilled onto the heap.
1564 pub fn into_vec(mut self) -> Vec<A::Item> {
1565 if self.spilled() {
1566 unsafe {
1567 let (ptr, &mut len) = self.data.heap_mut();
1568 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1569 mem::forget(self);
1570 v
1571 }
1572 } else {
1573 self.into_iter().collect()
1574 }
1575 }
1576
1577 /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the
1578 /// `SmallVec` has already spilled onto the heap.
1579 ///
1580 /// Note that this will drop any excess capacity.
1581 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1582 self.into_vec().into_boxed_slice()
1583 }
1584
1585 /// Convert the `SmallVec` into an `A` if possible. Otherwise return
1586 /// `Err(Self)`.
1587 ///
1588 /// This method returns `Err(Self)` if the `SmallVec` is too short (and the
1589 /// `A` contains uninitialized elements), or if the `SmallVec` is too
1590 /// long (and all the elements were spilled to the heap).
1591 pub fn into_inner(self) -> Result<A, Self> {
1592 if self.spilled() || self.len() != A::size() {
1593 // Note: A::size, not Self::inline_capacity
1594 Err(self)
1595 } else {
1596 unsafe {
1597 let data = ptr::read(&self.data);
1598 mem::forget(self);
1599 Ok(data.into_inline().assume_init())
1600 }
1601 }
1602 }
1603
1604 /// Retains only the elements specified by the predicate.
1605 ///
1606 /// In other words, remove all elements `e` such that `f(&e)` returns
1607 /// `false`. This method operates in place and preserves the order of
1608 /// the retained elements.
1609 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1610 let mut del = 0;
1611 let len = self.len();
1612 for i in 0..len {
1613 if !f(&mut self[i]) {
1614 del += 1;
1615 } else if del > 0 {
1616 self.swap(i - del, i);
1617 }
1618 }
1619 self.truncate(len - del);
1620 }
1621
1622 /// Retains only the elements specified by the predicate.
1623 ///
1624 /// This method is identical in behaviour to [`retain`]; it is included only
1625 /// to maintain api-compatibility with `std::Vec`, where the methods are
1626 /// separate for historical reasons.
1627 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1628 self.retain(f)
1629 }
1630
1631 /// Removes consecutive duplicate elements.
1632 pub fn dedup(&mut self)
1633 where
1634 A::Item: PartialEq<A::Item>,
1635 {
1636 self.dedup_by(|a, b| a == b);
1637 }
1638
1639 /// Removes consecutive duplicate elements using the given equality
1640 /// relation.
1641 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1642 where
1643 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1644 {
1645 // See the implementation of Vec::dedup_by in the
1646 // standard library for an explanation of this algorithm.
1647 let len = self.len();
1648 if len <= 1 {
1649 return;
1650 }
1651
1652 let ptr = self.as_mut_ptr();
1653 let mut w: usize = 1;
1654
1655 unsafe {
1656 for r in 1..len {
1657 let p_r = ptr.add(r);
1658 let p_wm1 = ptr.add(w - 1);
1659 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1660 if r != w {
1661 let p_w = p_wm1.add(1);
1662 mem::swap(&mut *p_r, &mut *p_w);
1663 }
1664 w += 1;
1665 }
1666 }
1667 }
1668
1669 self.truncate(w);
1670 }
1671
1672 /// Removes consecutive elements that map to the same key.
1673 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1674 where
1675 F: FnMut(&mut A::Item) -> K,
1676 K: PartialEq<K>,
1677 {
1678 self.dedup_by(|a, b| key(a) == key(b));
1679 }
1680
1681 /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1682 ///
1683 /// If `new_len` is greater than `len`, the `SmallVec` is extended by the
1684 /// difference, with each additional slot filled with the result of
1685 /// calling the closure `f`. The return values from `f` will end up in
1686 /// the `SmallVec` in the order they have been generated.
1687 ///
1688 /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1689 ///
1690 /// This method uses a closure to create new values on every push. If you'd
1691 /// rather `Clone` a given value, use `resize`. If you want to use the
1692 /// `Default` trait to generate values, you can pass
1693 /// `Default::default()` as the second argument.
1694 ///
1695 /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1696 ///
1697 /// ```
1698 /// # use smallvec::{smallvec, SmallVec};
1699 /// let mut vec: SmallVec<[_; 4]> = smallvec![1, 2, 3];
1700 /// vec.resize_with(5, Default::default);
1701 /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1702 ///
1703 /// let mut vec: SmallVec<[_; 4]> = smallvec![];
1704 /// let mut p = 1;
1705 /// vec.resize_with(4, || {
1706 /// p *= 2;
1707 /// p
1708 /// });
1709 /// assert_eq!(&*vec, &[2, 4, 8, 16]);
1710 /// ```
1711 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1712 where
1713 F: FnMut() -> A::Item,
1714 {
1715 let old_len = self.len();
1716 if old_len < new_len {
1717 let mut f = f;
1718 let additional = new_len - old_len;
1719 self.reserve(additional);
1720 for _ in 0..additional {
1721 self.push(f());
1722 }
1723 } else if old_len > new_len {
1724 self.truncate(new_len);
1725 }
1726 }
1727
1728 /// Creates a `SmallVec` directly from the raw components of another
1729 /// `SmallVec`.
1730 ///
1731 /// # Safety
1732 ///
1733 /// This is highly unsafe, due to the number of invariants that aren't
1734 /// checked:
1735 ///
1736 /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1737 /// spilled storage (at least, it's highly likely to be incorrect if it
1738 /// wasn't).
1739 /// * `ptr`'s `A::Item` type needs to be the same size and alignment that it
1740 /// was allocated with
1741 /// * `length` needs to be less than or equal to `capacity`.
1742 /// * `capacity` needs to be the capacity that the pointer was allocated
1743 /// with.
1744 ///
1745 /// Violating these may cause problems like corrupting the allocator's
1746 /// internal data structures.
1747 ///
1748 /// Additionally, `capacity` must be greater than the amount of inline
1749 /// storage `A` has; that is, the new `SmallVec` must need to spill over
1750 /// into heap allocated storage. This condition is asserted against.
1751 ///
1752 /// The ownership of `ptr` is effectively transferred to the
1753 /// `SmallVec` which may then deallocate, reallocate or change the
1754 /// contents of memory pointed to by the pointer at will. Ensure
1755 /// that nothing else uses the pointer after calling this
1756 /// function.
1757 ///
1758 /// # Examples
1759 ///
1760 /// ```
1761 /// # use smallvec::{smallvec, SmallVec};
1762 /// use std::mem;
1763 /// use std::ptr;
1764 ///
1765 /// fn main() {
1766 /// let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
1767 ///
1768 /// // Pull out the important parts of `v`.
1769 /// let p = v.as_mut_ptr();
1770 /// let len = v.len();
1771 /// let cap = v.capacity();
1772 /// let spilled = v.spilled();
1773 ///
1774 /// unsafe {
1775 /// // Forget all about `v`. The heap allocation that stored the
1776 /// // three values won't be deallocated.
1777 /// mem::forget(v);
1778 ///
1779 /// // Overwrite memory with [4, 5, 6].
1780 /// //
1781 /// // This is only safe if `spilled` is true! Otherwise, we are
1782 /// // writing into the old `SmallVec`'s inline storage on the
1783 /// // stack.
1784 /// assert!(spilled);
1785 /// for i in 0..len {
1786 /// ptr::write(p.add(i), 4 + i);
1787 /// }
1788 ///
1789 /// // Put everything back together into a SmallVec with a different
1790 /// // amount of inline storage, but which is still less than `cap`.
1791 /// let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
1792 /// assert_eq!(&*rebuilt, &[4, 5, 6]);
1793 /// }
1794 /// }
1795 #[inline]
1796 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1797 // SAFETY: We require caller to provide same ptr as we alloc
1798 // and we never alloc null pointer.
1799 let ptr = unsafe {
1800 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1801 NonNull::new_unchecked(ptr)
1802 };
1803 assert!(capacity > Self::inline_capacity());
1804 SmallVec {
1805 capacity,
1806 data: SmallVecData::from_heap(ptr, length),
1807 }
1808 }
1809
1810 /// Returns a raw pointer to the vector's buffer.
1811 pub fn as_ptr(&self) -> *const A::Item {
1812 // We shadow the slice method of the same name to avoid going through
1813 // `deref`, which creates an intermediate reference that may place
1814 // additional safety constraints on the contents of the slice.
1815 self.triple().0.as_ptr()
1816 }
1817
1818 /// Returns a raw mutable pointer to the vector's buffer.
1819 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1820 // We shadow the slice method of the same name to avoid going through
1821 // `deref_mut`, which creates an intermediate reference that may place
1822 // additional safety constraints on the contents of the slice.
1823 self.triple_mut().0.as_ptr()
1824 }
1825}
1826
1827impl<A: Array> SmallVec<A>
1828where
1829 A::Item: Copy,
1830{
1831 /// Copy the elements from a slice into a new `SmallVec`.
1832 ///
1833 /// For slices of `Copy` types, this is more efficient than
1834 /// `SmallVec::from(slice)`.
1835 pub fn from_slice(slice: &[A::Item]) -> Self {
1836 let len = slice.len();
1837 if len <= Self::inline_capacity() {
1838 SmallVec {
1839 capacity: len,
1840 data: SmallVecData::from_inline(unsafe {
1841 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1842 ptr::copy_nonoverlapping(
1843 slice.as_ptr(),
1844 data.as_mut_ptr() as *mut A::Item,
1845 len,
1846 );
1847 data
1848 }),
1849 }
1850 } else {
1851 let mut b = slice.to_vec();
1852 let cap = b.capacity();
1853 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1854 mem::forget(b);
1855 SmallVec {
1856 capacity: cap,
1857 data: SmallVecData::from_heap(ptr, len),
1858 }
1859 }
1860 }
1861
1862 /// Copy elements from a slice into the vector at position `index`, shifting
1863 /// any following elements toward the back.
1864 ///
1865 /// For slices of `Copy` types, this is more efficient than `insert`.
1866 #[inline]
1867 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1868 self.reserve(slice.len());
1869
1870 let len = self.len();
1871 assert!(index <= len);
1872
1873 unsafe {
1874 let slice_ptr = slice.as_ptr();
1875 let ptr = self.as_mut_ptr().add(index);
1876 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1877 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1878 self.set_len(len + slice.len());
1879 }
1880 }
1881
1882 /// Copy elements from a slice and append them to the vector.
1883 ///
1884 /// For slices of `Copy` types, this is more efficient than `extend`.
1885 #[inline]
1886 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1887 let len = self.len();
1888 self.insert_from_slice(len, slice);
1889 }
1890}
1891
1892impl<A: Array> SmallVec<A>
1893where
1894 A::Item: Clone,
1895{
1896 /// Resizes the vector so that its length is equal to `len`.
1897 ///
1898 /// If `len` is less than the current length, the vector simply truncated.
1899 ///
1900 /// If `len` is greater than the current length, `value` is appended to the
1901 /// vector until its length equals `len`.
1902 pub fn resize(&mut self, len: usize, value: A::Item) {
1903 let old_len = self.len();
1904
1905 if len > old_len {
1906 self.extend(repeat(value).take(len - old_len));
1907 } else {
1908 self.truncate(len);
1909 }
1910 }
1911
1912 /// Creates a `SmallVec` with `n` copies of `elem`.
1913 /// ```
1914 /// use smallvec::SmallVec;
1915 ///
1916 /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
1917 /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
1918 /// ```
1919 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1920 if n > Self::inline_capacity() {
1921 vec![elem; n].into()
1922 } else {
1923 let mut v = SmallVec::<A>::new();
1924 unsafe {
1925 let (ptr, len_ptr, _) = v.triple_mut();
1926 let ptr = ptr.as_ptr();
1927 let mut local_len = SetLenOnDrop::new(len_ptr);
1928
1929 for i in 0..n {
1930 ::core::ptr::write(ptr.add(i), elem.clone());
1931 local_len.increment_len(1);
1932 }
1933 }
1934 v
1935 }
1936 }
1937}
1938
1939impl<A: Array> ops::Deref for SmallVec<A> {
1940 type Target = [A::Item];
1941 #[inline]
1942 fn deref(&self) -> &[A::Item] {
1943 unsafe {
1944 let (ptr, len, _) = self.triple();
1945 slice::from_raw_parts(ptr.as_ptr(), len)
1946 }
1947 }
1948}
1949
1950impl<A: Array> ops::DerefMut for SmallVec<A> {
1951 #[inline]
1952 fn deref_mut(&mut self) -> &mut [A::Item] {
1953 unsafe {
1954 let (ptr, &mut len, _) = self.triple_mut();
1955 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1956 }
1957 }
1958}
1959
1960impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1961 #[inline]
1962 fn as_ref(&self) -> &[A::Item] {
1963 self
1964 }
1965}
1966
1967impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1968 #[inline]
1969 fn as_mut(&mut self) -> &mut [A::Item] {
1970 self
1971 }
1972}
1973
1974impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1975 #[inline]
1976 fn borrow(&self) -> &[A::Item] {
1977 self
1978 }
1979}
1980
1981impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1982 #[inline]
1983 fn borrow_mut(&mut self) -> &mut [A::Item] {
1984 self
1985 }
1986}
1987
1988#[cfg(feature = "write")]
1989#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1990impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1991 #[inline]
1992 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1993 self.extend_from_slice(buf);
1994 Ok(buf.len())
1995 }
1996
1997 #[inline]
1998 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1999 self.extend_from_slice(buf);
2000 Ok(())
2001 }
2002
2003 #[inline]
2004 fn flush(&mut self) -> io::Result<()> {
2005 Ok(())
2006 }
2007}
2008
2009#[cfg(feature = "serde")]
2010#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2011impl<A: Array> Serialize for SmallVec<A>
2012where
2013 A::Item: Serialize,
2014{
2015 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2016 let mut state = serializer.serialize_seq(Some(self.len()))?;
2017 for item in self {
2018 state.serialize_element(&item)?;
2019 }
2020 state.end()
2021 }
2022}
2023
2024#[cfg(feature = "serde")]
2025#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2026impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2027where
2028 A::Item: Deserialize<'de>,
2029{
2030 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2031 deserializer.deserialize_seq(SmallVecVisitor {
2032 phantom: PhantomData,
2033 })
2034 }
2035}
2036
2037#[cfg(feature = "serde")]
2038struct SmallVecVisitor<A> {
2039 phantom: PhantomData<A>,
2040}
2041
2042#[cfg(feature = "serde")]
2043impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2044where
2045 A::Item: Deserialize<'de>,
2046{
2047 type Value = SmallVec<A>;
2048
2049 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 formatter.write_str("a sequence")
2051 }
2052
2053 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2054 where
2055 B: SeqAccess<'de>,
2056 {
2057 use serde::de::Error;
2058 let len = seq.size_hint().unwrap_or(0);
2059 let mut values = SmallVec::new();
2060 values.try_reserve(len).map_err(B::Error::custom)?;
2061
2062 while let Some(value) = seq.next_element()? {
2063 values.push(value);
2064 }
2065
2066 Ok(values)
2067 }
2068}
2069
2070#[cfg(feature = "malloc_size_of")]
2071impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2072 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2073 if self.spilled() {
2074 unsafe { ops.malloc_size_of(self.as_ptr()) }
2075 } else {
2076 0
2077 }
2078 }
2079}
2080
2081#[cfg(feature = "malloc_size_of")]
2082impl<A> MallocSizeOf for SmallVec<A>
2083where
2084 A: Array,
2085 A::Item: MallocSizeOf,
2086{
2087 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2088 let mut n = self.shallow_size_of(ops);
2089 for elem in self.iter() {
2090 n += elem.size_of(ops);
2091 }
2092 n
2093 }
2094}
2095
2096#[cfg(feature = "specialization")]
2097trait SpecFrom<A: Array, S> {
2098 fn spec_from(slice: S) -> SmallVec<A>;
2099}
2100
2101#[cfg(feature = "specialization")]
2102mod specialization;
2103
2104#[cfg(feature = "arbitrary")]
2105mod arbitrary;
2106
2107#[cfg(feature = "specialization")]
2108impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2109where
2110 A::Item: Copy,
2111{
2112 #[inline]
2113 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2114 SmallVec::from_slice(slice)
2115 }
2116}
2117
2118impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2119where
2120 A::Item: Clone,
2121{
2122 #[cfg(not(feature = "specialization"))]
2123 #[inline]
2124 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2125 slice.iter().cloned().collect()
2126 }
2127
2128 #[cfg(feature = "specialization")]
2129 #[inline]
2130 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2131 SmallVec::spec_from(slice)
2132 }
2133}
2134
2135impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2136 #[inline]
2137 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2138 SmallVec::from_vec(vec)
2139 }
2140}
2141
2142impl<A: Array> From<A> for SmallVec<A> {
2143 #[inline]
2144 fn from(array: A) -> SmallVec<A> {
2145 SmallVec::from_buf(array)
2146 }
2147}
2148
2149impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2150 type Output = I::Output;
2151
2152 fn index(&self, index: I) -> &I::Output {
2153 &(**self)[index]
2154 }
2155}
2156
2157impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2158 fn index_mut(&mut self, index: I) -> &mut I::Output {
2159 &mut (&mut **self)[index]
2160 }
2161}
2162
2163#[allow(deprecated)]
2164impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2165where
2166 A::Item: Copy,
2167{
2168 fn extend_from_slice(&mut self, other: &[A::Item]) {
2169 SmallVec::extend_from_slice(self, other)
2170 }
2171}
2172
2173impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2174 #[inline]
2175 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2176 let mut v = SmallVec::new();
2177 v.extend(iterable);
2178 v
2179 }
2180}
2181
2182impl<A: Array> Extend<A::Item> for SmallVec<A> {
2183 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2184 let mut iter = iterable.into_iter();
2185 let (lower_size_bound, _) = iter.size_hint();
2186 self.reserve(lower_size_bound);
2187
2188 unsafe {
2189 let (ptr, len_ptr, cap) = self.triple_mut();
2190 let ptr = ptr.as_ptr();
2191 let mut len = SetLenOnDrop::new(len_ptr);
2192 while len.get() < cap {
2193 if let Some(out) = iter.next() {
2194 ptr::write(ptr.add(len.get()), out);
2195 len.increment_len(1);
2196 } else {
2197 return;
2198 }
2199 }
2200 }
2201
2202 for elem in iter {
2203 self.push(elem);
2204 }
2205 }
2206}
2207
2208impl<A: Array> fmt::Debug for SmallVec<A>
2209where
2210 A::Item: fmt::Debug,
2211{
2212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2213 f.debug_list().entries(self.iter()).finish()
2214 }
2215}
2216
2217impl<A: Array> Default for SmallVec<A> {
2218 #[inline]
2219 fn default() -> SmallVec<A> {
2220 SmallVec::new()
2221 }
2222}
2223
2224#[cfg(feature = "may_dangle")]
2225unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2226 fn drop(&mut self) {
2227 unsafe {
2228 if self.spilled() {
2229 let (ptr, &mut len) = self.data.heap_mut();
2230 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2231 } else {
2232 ptr::drop_in_place(&mut self[..]);
2233 }
2234 }
2235 }
2236}
2237
2238#[cfg(not(feature = "may_dangle"))]
2239impl<A: Array> Drop for SmallVec<A> {
2240 fn drop(&mut self) {
2241 unsafe {
2242 if self.spilled() {
2243 let (ptr, &mut len) = self.data.heap_mut();
2244 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2245 } else {
2246 ptr::drop_in_place(&mut self[..]);
2247 }
2248 }
2249 }
2250}
2251
2252impl<A: Array> Clone for SmallVec<A>
2253where
2254 A::Item: Clone,
2255{
2256 #[inline]
2257 fn clone(&self) -> SmallVec<A> {
2258 SmallVec::from(self.as_slice())
2259 }
2260
2261 fn clone_from(&mut self, source: &Self) {
2262 // Inspired from `impl Clone for Vec`.
2263
2264 // drop anything that will not be overwritten
2265 self.truncate(source.len());
2266
2267 // self.len <= other.len due to the truncate above, so the
2268 // slices here are always in-bounds.
2269 let (init, tail) = source.split_at(self.len());
2270
2271 // reuse the contained values' allocations/resources.
2272 self.clone_from_slice(init);
2273 self.extend(tail.iter().cloned());
2274 }
2275}
2276
2277impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2278where
2279 A::Item: PartialEq<B::Item>,
2280{
2281 #[inline]
2282 fn eq(&self, other: &SmallVec<B>) -> bool {
2283 self[..] == other[..]
2284 }
2285}
2286
2287impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2288
2289impl<A: Array> PartialOrd for SmallVec<A>
2290where
2291 A::Item: PartialOrd,
2292{
2293 #[inline]
2294 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2295 PartialOrd::partial_cmp(&**self, &**other)
2296 }
2297}
2298
2299impl<A: Array> Ord for SmallVec<A>
2300where
2301 A::Item: Ord,
2302{
2303 #[inline]
2304 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2305 Ord::cmp(&**self, &**other)
2306 }
2307}
2308
2309impl<A: Array> Hash for SmallVec<A>
2310where
2311 A::Item: Hash,
2312{
2313 fn hash<H: Hasher>(&self, state: &mut H) {
2314 (**self).hash(state)
2315 }
2316}
2317
2318unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2319
2320/// An iterator that consumes a `SmallVec` and yields its items by value.
2321///
2322/// Returned from [`SmallVec::into_iter`][1].
2323///
2324/// [1]: struct.SmallVec.html#method.into_iter
2325pub struct IntoIter<A: Array> {
2326 data: SmallVec<A>,
2327 current: usize,
2328 end: usize,
2329}
2330
2331impl<A: Array> fmt::Debug for IntoIter<A>
2332where
2333 A::Item: fmt::Debug,
2334{
2335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2336 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2337 }
2338}
2339
2340impl<A: Array + Clone> Clone for IntoIter<A>
2341where
2342 A::Item: Clone,
2343{
2344 fn clone(&self) -> IntoIter<A> {
2345 SmallVec::from(self.as_slice()).into_iter()
2346 }
2347}
2348
2349impl<A: Array> Drop for IntoIter<A> {
2350 fn drop(&mut self) {
2351 for _ in self {}
2352 }
2353}
2354
2355impl<A: Array> Iterator for IntoIter<A> {
2356 type Item = A::Item;
2357
2358 #[inline]
2359 fn next(&mut self) -> Option<A::Item> {
2360 if self.current == self.end {
2361 None
2362 } else {
2363 unsafe {
2364 let current = self.current;
2365 self.current += 1;
2366 Some(ptr::read(self.data.as_ptr().add(current)))
2367 }
2368 }
2369 }
2370
2371 #[inline]
2372 fn size_hint(&self) -> (usize, Option<usize>) {
2373 let size = self.end - self.current;
2374 (size, Some(size))
2375 }
2376}
2377
2378impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2379 #[inline]
2380 fn next_back(&mut self) -> Option<A::Item> {
2381 if self.current == self.end {
2382 None
2383 } else {
2384 unsafe {
2385 self.end -= 1;
2386 Some(ptr::read(self.data.as_ptr().add(self.end)))
2387 }
2388 }
2389 }
2390}
2391
2392impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2393impl<A: Array> FusedIterator for IntoIter<A> {}
2394
2395impl<A: Array> IntoIter<A> {
2396 /// Returns the remaining items of this iterator as a slice.
2397 pub fn as_slice(&self) -> &[A::Item] {
2398 let len = self.end - self.current;
2399 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2400 }
2401
2402 /// Returns the remaining items of this iterator as a mutable slice.
2403 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2404 let len = self.end - self.current;
2405 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2406 }
2407}
2408
2409impl<A: Array> IntoIterator for SmallVec<A> {
2410 type IntoIter = IntoIter<A>;
2411 type Item = A::Item;
2412 fn into_iter(mut self) -> Self::IntoIter {
2413 unsafe {
2414 // Set SmallVec len to zero as `IntoIter` drop handles dropping of
2415 // the elements
2416 let len = self.len();
2417 self.set_len(0);
2418 IntoIter {
2419 data: self,
2420 current: 0,
2421 end: len,
2422 }
2423 }
2424 }
2425}
2426
2427impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2428 type IntoIter = slice::Iter<'a, A::Item>;
2429 type Item = &'a A::Item;
2430 fn into_iter(self) -> Self::IntoIter {
2431 self.iter()
2432 }
2433}
2434
2435impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2436 type IntoIter = slice::IterMut<'a, A::Item>;
2437 type Item = &'a mut A::Item;
2438 fn into_iter(self) -> Self::IntoIter {
2439 self.iter_mut()
2440 }
2441}
2442
2443/// Types that can be used as the backing store for a [`SmallVec`].
2444pub unsafe trait Array {
2445 /// The type of the array's elements.
2446 type Item;
2447 /// Returns the number of items the array can hold.
2448 fn size() -> usize;
2449}
2450
2451/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
2452///
2453/// Copied from <https://github.com/rust-lang/rust/pull/36355>
2454struct SetLenOnDrop<'a> {
2455 len: &'a mut usize,
2456 local_len: usize,
2457}
2458
2459impl<'a> SetLenOnDrop<'a> {
2460 #[inline]
2461 fn new(len: &'a mut usize) -> Self {
2462 SetLenOnDrop {
2463 local_len: *len,
2464 len,
2465 }
2466 }
2467
2468 #[inline]
2469 fn get(&self) -> usize {
2470 self.local_len
2471 }
2472
2473 #[inline]
2474 fn increment_len(&mut self, increment: usize) {
2475 self.local_len += increment;
2476 }
2477}
2478
2479impl<'a> Drop for SetLenOnDrop<'a> {
2480 #[inline]
2481 fn drop(&mut self) {
2482 *self.len = self.local_len;
2483 }
2484}
2485
2486#[cfg(feature = "const_new")]
2487impl<T, const N: usize> SmallVec<[T; N]> {
2488 /// Construct an empty vector.
2489 ///
2490 /// This is a `const` version of [`SmallVec::new`] that is enabled by the
2491 /// feature `const_new`, with the limitation that it only works for arrays.
2492 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2493 #[inline]
2494 pub const fn new_const() -> Self {
2495 SmallVec {
2496 capacity: 0,
2497 data: SmallVecData::from_const(MaybeUninit::uninit()),
2498 }
2499 }
2500
2501 /// The array passed as an argument is moved to be an inline version of
2502 /// `SmallVec`.
2503 ///
2504 /// This is a `const` version of [`SmallVec::from_buf`] that is enabled by
2505 /// the feature `const_new`, with the limitation that it only works for
2506 /// arrays.
2507 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2508 #[inline]
2509 pub const fn from_const(items: [T; N]) -> Self {
2510 SmallVec {
2511 capacity: N,
2512 data: SmallVecData::from_const(MaybeUninit::new(items)),
2513 }
2514 }
2515
2516 /// Constructs a new `SmallVec` on the stack from an array without
2517 /// copying elements. Also sets the length. The user is responsible
2518 /// for ensuring that `len <= N`.
2519 ///
2520 /// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`]
2521 /// that is enabled by the feature `const_new`, with the limitation that it
2522 /// only works for arrays.
2523 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2524 #[inline]
2525 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2526 SmallVec {
2527 capacity: len,
2528 data: SmallVecData::from_const(MaybeUninit::new(items)),
2529 }
2530 }
2531}
2532
2533#[cfg(feature = "const_generics")]
2534#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2535unsafe impl<T, const N: usize> Array for [T; N] {
2536 type Item = T;
2537 #[inline]
2538 fn size() -> usize {
2539 N
2540 }
2541}
2542
2543#[cfg(not(feature = "const_generics"))]
2544macro_rules! impl_array(
2545 ($($size:expr),+) => {
2546 $(
2547 unsafe impl<T> Array for [T; $size] {
2548 type Item = T;
2549 #[inline]
2550 fn size() -> usize { $size }
2551 }
2552 )+
2553 }
2554);
2555
2556#[cfg(not(feature = "const_generics"))]
2557impl_array!(
2558 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
2559 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2560 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2561);
2562
2563/// Convenience trait for constructing a `SmallVec`
2564pub trait ToSmallVec<A: Array> {
2565 /// Construct a new `SmallVec` from a slice.
2566 fn to_smallvec(&self) -> SmallVec<A>;
2567}
2568
2569impl<A: Array> ToSmallVec<A> for [A::Item]
2570where
2571 A::Item: Copy,
2572{
2573 #[inline]
2574 fn to_smallvec(&self) -> SmallVec<A> {
2575 SmallVec::from_slice(self)
2576 }
2577}
2578
2579// Immutable counterpart for `NonNull<T>`.
2580#[repr(transparent)]
2581struct ConstNonNull<T>(NonNull<T>);
2582
2583impl<T> ConstNonNull<T> {
2584 #[inline]
2585 fn new(ptr: *const T) -> Option<Self> {
2586 NonNull::new(ptr as *mut T).map(Self)
2587 }
2588 #[inline]
2589 fn as_ptr(self) -> *const T {
2590 self.0.as_ptr()
2591 }
2592}
2593
2594impl<T> Clone for ConstNonNull<T> {
2595 #[inline]
2596 fn clone(&self) -> Self {
2597 *self
2598 }
2599}
2600
2601impl<T> Copy for ConstNonNull<T> {}
2602
2603#[cfg(feature = "impl_bincode")]
2604use bincode::{
2605 de::{read::Reader, BorrowDecoder, Decode, Decoder},
2606 enc::{write::Writer, Encode, Encoder},
2607 error::{DecodeError, EncodeError},
2608 BorrowDecode,
2609};
2610
2611#[cfg(feature = "impl_bincode")]
2612impl<A, Context> Decode<Context> for SmallVec<A>
2613where
2614 A: Array,
2615 A::Item: Decode<Context>,
2616{
2617 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2618 use core::convert::TryInto;
2619 let len = u64::decode(decoder)?;
2620 let len = len
2621 .try_into()
2622 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2623 decoder.claim_container_read::<A::Item>(len)?;
2624
2625 let mut vec = SmallVec::with_capacity(len);
2626 if unty::type_equal::<A::Item, u8>() {
2627 // Initialize the smallvec's buffer. Note that we need to do this
2628 // through the raw pointer as we cannot name the type
2629 // [u8; N] even though A::Item is u8.
2630 let ptr = vec.as_mut_ptr();
2631 // SAFETY: A::Item is u8 and the smallvec has been allocated with
2632 // enough capacity
2633 unsafe {
2634 core::ptr::write_bytes(ptr, 0, len);
2635 vec.set_len(len);
2636 }
2637 // Read the data into the smallvec's buffer.
2638 let slice = vec.as_mut_slice();
2639 // SAFETY: A::Item is u8
2640 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2641 decoder.reader().read(slice)?;
2642 } else {
2643 for _ in 0..len {
2644 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2645 vec.push(A::Item::decode(decoder)?);
2646 }
2647 }
2648 Ok(vec)
2649 }
2650}
2651
2652#[cfg(feature = "impl_bincode")]
2653impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2654where
2655 A: Array,
2656 A::Item: BorrowDecode<'de, Context>,
2657{
2658 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2659 decoder: &mut D,
2660 ) -> Result<Self, DecodeError> {
2661 use core::convert::TryInto;
2662 let len = u64::decode(decoder)?;
2663 let len = len
2664 .try_into()
2665 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2666 decoder.claim_container_read::<A::Item>(len)?;
2667
2668 let mut vec = SmallVec::with_capacity(len);
2669 if unty::type_equal::<A::Item, u8>() {
2670 // Initialize the smallvec's buffer. Note that we need to do this
2671 // through the raw pointer as we cannot name the type
2672 // [u8; N] even though A::Item is u8.
2673 let ptr = vec.as_mut_ptr();
2674 // SAFETY: A::Item is u8 and the smallvec has been allocated with
2675 // enough capacity
2676 unsafe {
2677 core::ptr::write_bytes(ptr, 0, len);
2678 vec.set_len(len);
2679 }
2680 // Read the data into the smallvec's buffer.
2681 let slice = vec.as_mut_slice();
2682 // SAFETY: A::Item is u8
2683 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2684 decoder.reader().read(slice)?;
2685 } else {
2686 for _ in 0..len {
2687 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2688 vec.push(A::Item::borrow_decode(decoder)?);
2689 }
2690 }
2691 Ok(vec)
2692 }
2693}
2694
2695#[cfg(feature = "impl_bincode")]
2696impl<A> Encode for SmallVec<A>
2697where
2698 A: Array,
2699 A::Item: Encode,
2700{
2701 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2702 (self.len() as u64).encode(encoder)?;
2703 if unty::type_equal::<A::Item, u8>() {
2704 // Safety: A::Item is u8
2705 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2706 encoder.writer().write(slice)?;
2707 } else {
2708 for item in self.iter() {
2709 item.encode(encoder)?;
2710 }
2711 }
2712 Ok(())
2713 }
2714}