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.
67//! Small vectors in various sizes. These store a certain number of elements inline, and fall back
8//! to the heap for larger allocations. This can be a useful optimization for improving cache
9//! locality and reducing allocator traffic for workloads that fit within the inline buffer.
10//!
11//! ## `no_std` support
12//!
13//! By default, `smallvec` does not depend on `std`. However, the optional
14//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
15//! When this feature is enabled, `smallvec` depends on `std`.
16//!
17//! ## Optional features
18//!
19//! ### `serde`
20//!
21//! When this optional dependency is enabled, `SmallVec` implements the `serde::Serialize` and
22//! `serde::Deserialize` traits.
23//!
24//! ### `write`
25//!
26//! When this feature is enabled, `SmallVec<[u8; _]>` implements the `std::io::Write` trait.
27//! This feature is not compatible with `#![no_std]` programs.
28//!
29//! ### `union`
30//!
31//! **This feature requires Rust 1.49.**
32//!
33//! When the `union` feature is enabled `smallvec` will track its state (inline or spilled)
34//! without the use of an enum tag, reducing the size of the `smallvec` by one machine word.
35//! This means that there is potentially no space overhead compared to `Vec`.
36//! Note that `smallvec` can still be larger than `Vec` if the inline buffer is larger than two
37//! machine words.
38//!
39//! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml.
40//! Note that this feature requires Rust 1.49.
41//!
42//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
43//!
44//! ### `const_generics`
45//!
46//! **This feature requires Rust 1.51.**
47//!
48//! When this feature is enabled, `SmallVec` works with any arrays of any size, not just a fixed
49//! list of sizes.
50//!
51//! ### `const_new`
52//!
53//! **This feature requires Rust 1.51.**
54//!
55//! This feature exposes the functions [`SmallVec::new_const`], [`SmallVec::from_const`], and [`smallvec_inline`] which enables the `SmallVec` to be initialized from a const context.
56//! For details, see the
57//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
58//!
59//! ### `drain_filter`
60//!
61//! **This feature is unstable.** It may change to match the unstable `drain_filter` method in libstd.
62//!
63//! Enables the `drain_filter` method, which produces an iterator that calls a user-provided
64//! closure to determine which elements of the vector to remove and yield from the iterator.
65//!
66//! ### `drain_keep_rest`
67//!
68//! **This feature is unstable.** It may change to match the unstable `drain_keep_rest` method in libstd.
69//!
70//! Enables the `DrainFilter::keep_rest` method.
71//!
72//! ### `specialization`
73//!
74//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
75//!
76//! When this feature is enabled, `SmallVec::from(slice)` has improved performance for slices
77//! of `Copy` types. (Without this feature, you can use `SmallVec::from_slice` to get optimal
78//! performance for `Copy` types.)
79//!
80//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
81//!
82//! ### `may_dangle`
83//!
84//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
85//!
86//! This feature makes the Rust compiler less strict about use of vectors that contain borrowed
87//! references. For details, see the
88//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
89//!
90//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
9192#![no_std]
93#![cfg_attr(docsrs, feature(doc_cfg))]
94#![cfg_attr(feature = "specialization", allow(incomplete_features))]
95#![cfg_attr(feature = "specialization", feature(specialization))]
96#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
97#![cfg_attr(
98 feature = "debugger_visualizer",
99 feature(debugger_visualizer),
100 debugger_visualizer(natvis_file = "../debug_metadata/smallvec.natvis")
101)]
102#![deny(missing_docs)]
103104#[doc(hidden)]
105pub extern crate alloc;
106107#[cfg(any(test, feature = "write"))]
108extern crate std;
109110#[cfg(test)]
111mod tests;
112113#[allow(deprecated)]
114use alloc::alloc::{Layout, LayoutErr};
115use alloc::boxed::Box;
116use alloc::{vec, vec::Vec};
117use core::borrow::{Borrow, BorrowMut};
118use core::cmp;
119use core::fmt;
120use core::hash::{Hash, Hasher};
121use core::hint::unreachable_unchecked;
122use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator};
123use core::mem;
124use core::mem::MaybeUninit;
125use core::ops::{self, Range, RangeBounds};
126use core::ptr::{self, NonNull};
127use core::slice::{self, SliceIndex};
128129#[cfg(feature = "malloc_size_of")]
130use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
131132#[cfg(feature = "serde")]
133use serde::{
134 de::{Deserialize, Deserializer, SeqAccess, Visitor},
135 ser::{Serialize, SerializeSeq, Serializer},
136};
137138#[cfg(feature = "serde")]
139use core::marker::PhantomData;
140141#[cfg(feature = "write")]
142use std::io;
143144#[cfg(feature = "drain_keep_rest")]
145use core::mem::ManuallyDrop;
146147/// Creates a [`SmallVec`] containing the arguments.
148///
149/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array expressions.
150/// There are two forms of this macro:
151///
152/// - Create a [`SmallVec`] containing a given list of elements:
153///
154/// ```
155/// # use smallvec::{smallvec, SmallVec};
156/// # fn main() {
157/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
158/// assert_eq!(v[0], 1);
159/// assert_eq!(v[1], 2);
160/// assert_eq!(v[2], 3);
161/// # }
162/// ```
163///
164/// - Create a [`SmallVec`] from a given element and size:
165///
166/// ```
167/// # use smallvec::{smallvec, SmallVec};
168/// # fn main() {
169/// let v: SmallVec<[_; 10]> = smallvec![1; 3];
170/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
171/// # }
172/// ```
173///
174/// Note that unlike array expressions this syntax supports all elements
175/// which implement [`Clone`] and the number of elements doesn't have to be
176/// a constant.
177///
178/// This will use `clone` to duplicate an expression, so one should be careful
179/// using this with types having a nonstandard `Clone` implementation. For
180/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
181/// to the same boxed integer value, not five references pointing to independently
182/// boxed integers.
183#[macro_export]
184macro_rules!smallvec {
185// count helper: transform any expression into 1
186(@one $x:expr) => (1usize);
187 () => (
188$crate::SmallVec::new()
189 );
190 ($elem:expr; $n:expr) => ({
191$crate::SmallVec::from_elem($elem, $n)
192 });
193 ($($x:expr),+$(,)?) => ({
194let count = 0usize $(+ $crate::smallvec!(@one $x))+;
195let mut vec = $crate::SmallVec::new();
196if count <= vec.inline_size() {
197 $(vec.push($x);)*
198 vec
199 } else {
200$crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
201 }
202 });
203}
204205/// Creates an inline [`SmallVec`] containing the arguments. This macro is enabled by the feature `const_new`.
206///
207/// `smallvec_inline!` allows `SmallVec`s to be defined with the same syntax as array expressions in `const` contexts.
208/// The inline storage `A` will always be an array of the size specified by the arguments.
209/// There are two forms of this macro:
210///
211/// - Create a [`SmallVec`] containing a given list of elements:
212///
213/// ```
214/// # use smallvec::{smallvec_inline, SmallVec};
215/// # fn main() {
216/// const V: SmallVec<[i32; 3]> = smallvec_inline![1, 2, 3];
217/// assert_eq!(V[0], 1);
218/// assert_eq!(V[1], 2);
219/// assert_eq!(V[2], 3);
220/// # }
221/// ```
222///
223/// - Create a [`SmallVec`] from a given element and size:
224///
225/// ```
226/// # use smallvec::{smallvec_inline, SmallVec};
227/// # fn main() {
228/// const V: SmallVec<[i32; 3]> = smallvec_inline![1; 3];
229/// assert_eq!(V, SmallVec::from_buf([1, 1, 1]));
230/// # }
231/// ```
232///
233/// Note that the behavior mimics that of array expressions, in contrast to [`smallvec`].
234#[cfg(feature = "const_new")]
235#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
236#[macro_export]
237macro_rules! smallvec_inline {
238// count helper: transform any expression into 1
239(@one $x:expr) => (1usize);
240 ($elem:expr; $n:expr) => ({
241$crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
242 });
243 ($($x:expr),+ $(,)?) => ({
244const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
245$crate::SmallVec::<[_; N]>::from_const([$($x,)*])
246 });
247}
248249/// `panic!()` in debug builds, optimization hint in release.
250#[cfg(not(feature = "union"))]
251macro_rules! debug_unreachable {
252 () => {
253debug_unreachable!("entered unreachable code")
254 };
255 ($e:expr) => {
256if cfg!(debug_assertions) {
257panic!($e);
258 } else {
259 unreachable_unchecked();
260 }
261 };
262}
263264/// Trait to be implemented by a collection that can be extended from a slice
265///
266/// ## Example
267///
268/// ```rust
269/// use smallvec::{ExtendFromSlice, SmallVec};
270///
271/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
272/// v.extend_from_slice(b"Test!");
273/// }
274///
275/// let mut vec = Vec::new();
276/// initialize(&mut vec);
277/// assert_eq!(&vec, b"Test!");
278///
279/// let mut small_vec = SmallVec::<[u8; 8]>::new();
280/// initialize(&mut small_vec);
281/// assert_eq!(&small_vec as &[_], b"Test!");
282/// ```
283#[doc(hidden)]
284#[deprecated]
285pub trait ExtendFromSlice<T> {
286/// Extends a collection from a slice of its element type
287fn extend_from_slice(&mut self, other: &[T]);
288}
289290#[allow(deprecated)]
291impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
292fn extend_from_slice(&mut self, other: &[T]) {
293Vec::extend_from_slice(self, other)
294 }
295}
296297/// Error type for APIs with fallible heap allocation
298#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectionAllocErr {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CollectionAllocErr::CapacityOverflow =>
::core::fmt::Formatter::write_str(f, "CapacityOverflow"),
CollectionAllocErr::AllocErr { layout: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AllocErr", "layout", &__self_0),
}
}
}Debug)]
299pub enum CollectionAllocErr {
300/// Overflow `usize::MAX` or other error during size computation
301CapacityOverflow,
302/// The allocator return an error
303AllocErr {
304/// The layout that was passed to the allocator
305layout: Layout,
306 },
307}
308309impl fmt::Displayfor CollectionAllocErr {
310fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311f.write_fmt(format_args!("Allocation error: {0:?}", self))write!(f, "Allocation error: {:?}", self)312 }
313}
314315#[allow(deprecated)]
316impl From<LayoutErr> for CollectionAllocErr {
317fn from(_: LayoutErr) -> Self {
318 CollectionAllocErr::CapacityOverflow319 }
320}
321322fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
323match result {
324Ok(x) => x,
325Err(CollectionAllocErr::CapacityOverflow) => ::core::panicking::panic("capacity overflow")panic!("capacity overflow"),
326Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
327 }
328}
329330/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
331/// <https://github.com/rust-lang/rust/issues/55724>
332fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333let size = mem::size_of::<T>()
334 .checked_mul(n)
335 .ok_or(CollectionAllocErr::CapacityOverflow)?;
336let align = mem::align_of::<T>();
337Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338}
339340unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
341// This unwrap should succeed since the same did when allocating.
342let layout = layout_array::<T>(capacity).unwrap();
343 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
344}
345346/// An iterator that removes the items from a `SmallVec` and yields them by value.
347///
348/// Returned from [`SmallVec::drain`][1].
349///
350/// [1]: struct.SmallVec.html#method.drain
351pub struct Drain<'a, T: 'a + Array> {
352 tail_start: usize,
353 tail_len: usize,
354 iter: slice::Iter<'a, T::Item>,
355 vec: NonNull<SmallVec<T>>,
356}
357358impl<'a, T: 'a + Array> fmt::Debugfor Drain<'a, T>
359where
360T::Item: fmt::Debug,
361{
362fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
364 }
365}
366367unsafe impl<'a, T: Sync + Array> Syncfor Drain<'a, T> {}
368unsafe impl<'a, T: Send + Array> Sendfor Drain<'a, T> {}
369370impl<'a, T: 'a + Array> Iteratorfor Drain<'a, T> {
371type Item = T::Item;
372373#[inline]
374fn next(&mut self) -> Option<T::Item> {
375self.iter
376 .next()
377 .map(|reference| unsafe { ptr::read(reference) })
378 }
379380#[inline]
381fn size_hint(&self) -> (usize, Option<usize>) {
382self.iter.size_hint()
383 }
384}
385386impl<'a, T: 'a + Array> DoubleEndedIteratorfor Drain<'a, T> {
387#[inline]
388fn next_back(&mut self) -> Option<T::Item> {
389self.iter
390 .next_back()
391 .map(|reference| unsafe { ptr::read(reference) })
392 }
393}
394395impl<'a, T: Array> ExactSizeIteratorfor Drain<'a, T> {
396#[inline]
397fn len(&self) -> usize {
398self.iter.len()
399 }
400}
401402impl<'a, T: Array> FusedIteratorfor Drain<'a, T> {}
403404impl<'a, T: 'a + Array> Dropfor Drain<'a, T> {
405fn drop(&mut self) {
406self.for_each(drop);
407408if self.tail_len > 0 {
409unsafe {
410let source_vec = self.vec.as_mut();
411412// memmove back untouched tail, update to new length
413let start = source_vec.len();
414let tail = self.tail_start;
415if tail != start {
416// as_mut_ptr creates a &mut, invalidating other pointers.
417 // This pattern avoids calling it with a pointer already present.
418let ptr = source_vec.as_mut_ptr();
419let src = ptr.add(tail);
420let dst = ptr.add(start);
421 ptr::copy(src, dst, self.tail_len);
422 }
423source_vec.set_len(start + self.tail_len);
424 }
425 }
426 }
427}
428429#[cfg(feature = "drain_filter")]
430/// An iterator which uses a closure to determine if an element should be removed.
431///
432/// Returned from [`SmallVec::drain_filter`][1].
433///
434/// [1]: struct.SmallVec.html#method.drain_filter
435pub struct DrainFilter<'a, T, F>
436where
437F: FnMut(&mut T::Item) -> bool,
438 T: Array,
439{
440 vec: &'a mut SmallVec<T>,
441/// The index of the item that will be inspected by the next call to `next`.
442idx: usize,
443/// The number of items that have been drained (removed) thus far.
444del: usize,
445/// The original length of `vec` prior to draining.
446old_len: usize,
447/// The filter test predicate.
448pred: F,
449/// A flag that indicates a panic has occurred in the filter test predicate.
450 /// This is used as a hint in the drop implementation to prevent consumption
451 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
452 /// backshifted in the `vec`, but no further items will be dropped or
453 /// tested by the filter predicate.
454panic_flag: bool,
455}
456457#[cfg(feature = "drain_filter")]
458impl <T, F> fmt::Debug for DrainFilter<'_, T, F>
459where
460F: FnMut(&mut T::Item) -> bool,
461 T: Array,
462 T::Item: fmt::Debug,
463{
464fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 f.debug_tuple("DrainFilter").field(&self.vec.as_slice()).finish()
466 }
467}
468469#[cfg(feature = "drain_filter")]
470impl <T, F> Iterator for DrainFilter<'_, T, F>
471where
472F: FnMut(&mut T::Item) -> bool,
473 T: Array,
474{
475type Item = T::Item;
476477fn next(&mut self) -> Option<T::Item>
478 {
479unsafe {
480while self.idx < self.old_len {
481let i = self.idx;
482let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
483self.panic_flag = true;
484let drained = (self.pred)(&mut v[i]);
485self.panic_flag = false;
486// Update the index *after* the predicate is called. If the index
487 // is updated prior and the predicate panics, the element at this
488 // index would be leaked.
489self.idx += 1;
490if drained {
491self.del += 1;
492return Some(ptr::read(&v[i]));
493 } else if self.del > 0 {
494let del = self.del;
495let src: *const Self::Item = &v[i];
496let dst: *mut Self::Item = &mut v[i - del];
497 ptr::copy_nonoverlapping(src, dst, 1);
498 }
499 }
500None
501}
502 }
503504fn size_hint(&self) -> (usize, Option<usize>) {
505 (0, Some(self.old_len - self.idx))
506 }
507}
508509#[cfg(feature = "drain_filter")]
510impl <T, F> Drop for DrainFilter<'_, T, F>
511where
512F: FnMut(&mut T::Item) -> bool,
513 T: Array,
514{
515fn drop(&mut self) {
516struct BackshiftOnDrop<'a, 'b, T, F>
517where
518F: FnMut(&mut T::Item) -> bool,
519 T: Array
520 {
521 drain: &'b mut DrainFilter<'a, T, F>,
522 }
523524impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
525where
526F: FnMut(&mut T::Item) -> bool,
527 T: Array
528 {
529fn drop(&mut self) {
530unsafe {
531if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
532// This is a pretty messed up state, and there isn't really an
533 // obviously right thing to do. We don't want to keep trying
534 // to execute `pred`, so we just backshift all the unprocessed
535 // elements and tell the vec that they still exist. The backshift
536 // is required to prevent a double-drop of the last successfully
537 // drained item prior to a panic in the predicate.
538let ptr = self.drain.vec.as_mut_ptr();
539let src = ptr.add(self.drain.idx);
540let dst = src.sub(self.drain.del);
541let tail_len = self.drain.old_len - self.drain.idx;
542 src.copy_to(dst, tail_len);
543 }
544self.drain.vec.set_len(self.drain.old_len - self.drain.del);
545 }
546 }
547 }
548549let backshift = BackshiftOnDrop { drain: self };
550551// Attempt to consume any remaining elements if the filter predicate
552 // has not yet panicked. We'll backshift any remaining elements
553 // whether we've already panicked or if the consumption here panics.
554if !backshift.drain.panic_flag {
555 backshift.drain.for_each(drop);
556 }
557 }
558}
559560#[cfg(feature = "drain_keep_rest")]
561impl <T, F> DrainFilter<'_, T, F>
562where
563F: FnMut(&mut T::Item) -> bool,
564 T: Array
565{
566/// Keep unyielded elements in the source `Vec`.
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// # use smallvec::{smallvec, SmallVec};
572 ///
573 /// let mut vec: SmallVec<[char; 2]> = smallvec!['a', 'b', 'c'];
574 /// let mut drain = vec.drain_filter(|_| true);
575 ///
576 /// assert_eq!(drain.next().unwrap(), 'a');
577 ///
578 /// // This call keeps 'b' and 'c' in the vec.
579 /// drain.keep_rest();
580 ///
581 /// // If we wouldn't call `keep_rest()`,
582 /// // `vec` would be empty.
583 /// assert_eq!(vec, SmallVec::<[char; 2]>::from_slice(&['b', 'c']));
584 /// ```
585pub fn keep_rest(self)
586 {
587// At this moment layout looks like this:
588 //
589 // _____________________/-- old_len
590 // / \
591 // [kept] [yielded] [tail]
592 // \_______/ ^-- idx
593 // \-- del
594 //
595 // Normally `Drop` impl would drop [tail] (via .for_each(drop), ie still calling `pred`)
596 //
597 // 1. Move [tail] after [kept]
598 // 2. Update length of the original vec to `old_len - del`
599 // a. In case of ZST, this is the only thing we want to do
600 // 3. Do *not* drop self, as everything is put in a consistent state already, there is nothing to do
601let mut this = ManuallyDrop::new(self);
602603unsafe {
604// ZSTs have no identity, so we don't need to move them around.
605let needs_move = mem::size_of::<T::Item>() != 0;
606607if needs_move && this.idx < this.old_len && this.del > 0 {
608let ptr = this.vec.as_mut_ptr();
609let src = ptr.add(this.idx);
610let dst = src.sub(this.del);
611let tail_len = this.old_len - this.idx;
612 src.copy_to(dst, tail_len);
613 }
614615let new_len = this.old_len - this.del;
616 this.vec.set_len(new_len);
617 }
618 }
619}
620621#[cfg(feature = "union")]
622union SmallVecData<A: Array> {
623 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
624 heap: (NonNull<A::Item>, usize),
625}
626627#[cfg(all(feature = "union", feature = "const_new"))]
628impl<T, const N: usize> SmallVecData<[T; N]> {
629#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
630 #[inline]
631const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
632 SmallVecData {
633 inline: core::mem::ManuallyDrop::new(inline),
634 }
635 }
636}
637638#[cfg(feature = "union")]
639impl<A: Array> SmallVecData<A> {
640#[inline]
641unsafe fn inline(&self) -> ConstNonNull<A::Item> {
642 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
643 }
644#[inline]
645unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
646 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
647 }
648#[inline]
649fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
650 SmallVecData {
651 inline: core::mem::ManuallyDrop::new(inline),
652 }
653 }
654// Workaround for https://github.com/rust-lang/rust/issues/157743: when from_inline is
655 // called with MaybeUninit::uninit(), rustc 1.93+ GVN propagates const <uninit> into the
656 // ManuallyDrop::new() aggregate, causing LLVM to materialize a global constant that
657 // MemCpyOpt then collapses into a memset over the whole struct. Using assume_init() of a
658 // doubly-wrapped MaybeUninit produces Immediate::Uninit instead of const <uninit>, which
659 // codegen handles as undef without emitting any global. This function also avoids
660 // introducing an intermediate local that would inflate stack frames in debug builds.
661#[inline]
662fn empty() -> SmallVecData<A> {
663// SAFETY: ManuallyDrop<MaybeUninit<A>> is valid for any bit pattern including
664 // uninitialized bytes, so assume_init() on a MaybeUninit of that type is sound.
665SmallVecData { inline: unsafe { MaybeUninit::uninit().assume_init() } }
666 }
667#[inline]
668unsafe fn into_inline(self) -> MaybeUninit<A> {
669 core::mem::ManuallyDrop::into_inner(self.inline)
670 }
671#[inline]
672unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
673 (ConstNonNull(self.heap.0), self.heap.1)
674 }
675#[inline]
676unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
677let h = &mut self.heap;
678 (h.0, &mut h.1)
679 }
680#[inline]
681fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
682 SmallVecData { heap: (ptr, len) }
683 }
684}
685686#[cfg(not(feature = "union"))]
687enum SmallVecData<A: Array> {
688 Inline(MaybeUninit<A>),
689// Using NonNull and NonZero here allows to reduce size of `SmallVec`.
690Heap {
691// Since we never allocate on heap
692 // unless our capacity is bigger than inline capacity
693 // heap capacity cannot be less than 1.
694 // Therefore, pointer cannot be null too.
695ptr: NonNull<A::Item>,
696 len: usize,
697 },
698}
699700#[cfg(all(not(feature = "union"), feature = "const_new"))]
701impl<T, const N: usize> SmallVecData<[T; N]> {
702#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
703 #[inline]
704const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
705 SmallVecData::Inline(inline)
706 }
707}
708709#[cfg(not(feature = "union"))]
710impl<A: Array> SmallVecData<A> {
711#[inline]
712unsafe fn inline(&self) -> ConstNonNull<A::Item> {
713match self {
714 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
715_ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
716 }
717 }
718#[inline]
719unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
720match self {
721 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
722_ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
723 }
724 }
725#[inline]
726fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
727 SmallVecData::Inline(inline)
728 }
729// See the comment on the union variant's empty() for why this exists.
730#[inline]
731fn empty() -> SmallVecData<A> {
732// SAFETY: MaybeUninit<A> is valid for any bit pattern including uninitialized bytes,
733 // so assume_init() on a MaybeUninit of that type is sound.
734SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
735 }
736#[inline]
737unsafe fn into_inline(self) -> MaybeUninit<A> {
738match self {
739 SmallVecData::Inline(a) => a,
740_ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
741 }
742 }
743#[inline]
744unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
745match self {
746 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
747_ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
748 }
749 }
750#[inline]
751unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
752match self {
753 SmallVecData::Heap { ptr, len } => (*ptr, len),
754_ => if true {
::core::panicking::panic("entered unreachable code");
} else { unreachable_unchecked(); }debug_unreachable!(),
755 }
756 }
757#[inline]
758fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
759 SmallVecData::Heap { ptr, len }
760 }
761}
762763unsafe impl<A: Array + Send> Sendfor SmallVecData<A> {}
764unsafe impl<A: Array + Sync> Syncfor SmallVecData<A> {}
765766/// A `Vec`-like container that can store a small number of elements inline.
767///
768/// `SmallVec` acts like a vector, but can store a limited amount of data inline within the
769/// `SmallVec` struct rather than in a separate allocation. If the data exceeds this limit, the
770/// `SmallVec` will "spill" its data onto the heap, allocating a new buffer to hold it.
771///
772/// The amount of data that a `SmallVec` can store inline depends on its backing store. The backing
773/// store can be any type that implements the `Array` trait; usually it is a small fixed-sized
774/// array. For example a `SmallVec<[u64; 8]>` can hold up to eight 64-bit integers inline.
775///
776/// ## Example
777///
778/// ```rust
779/// use smallvec::SmallVec;
780/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
781///
782/// // The vector can hold up to 4 items without spilling onto the heap.
783/// v.extend(0..4);
784/// assert_eq!(v.len(), 4);
785/// assert!(!v.spilled());
786///
787/// // Pushing another element will force the buffer to spill:
788/// v.push(4);
789/// assert_eq!(v.len(), 5);
790/// assert!(v.spilled());
791/// ```
792pub struct SmallVec<A: Array> {
793// The capacity field is used to determine which of the storage variants is active:
794 // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds the current length of the vector (number of elements actually in use).
795 // If capacity > Self::inline_capacity() then the heap variant is used and capacity holds the size of the memory allocation.
796capacity: usize,
797 data: SmallVecData<A>,
798}
799800impl<A: Array> SmallVec<A> {
801/// Construct an empty vector
802#[inline]
803pub fn new() -> SmallVec<A> {
804// Try to detect invalid custom implementations of `Array`. Hopefully,
805 // this check should be optimized away entirely for valid ones.
806if !(mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() &&
mem::align_of::<A>() >= mem::align_of::<A::Item>()) {
::core::panicking::panic("assertion failed: mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() &&\n mem::align_of::<A>() >= mem::align_of::<A::Item>()")
};assert!(
807 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
808 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
809 );
810SmallVec {
811 capacity: 0,
812 data: SmallVecData::empty(),
813 }
814 }
815816/// Construct an empty vector with enough capacity pre-allocated to store at least `n`
817 /// elements.
818 ///
819 /// Will create a heap allocation only if `n` is larger than the inline capacity.
820 ///
821 /// ```
822 /// # use smallvec::SmallVec;
823 ///
824 /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
825 ///
826 /// assert!(v.is_empty());
827 /// assert!(v.capacity() >= 100);
828 /// ```
829#[inline]
830pub fn with_capacity(n: usize) -> Self {
831let mut v = SmallVec::new();
832v.reserve_exact(n);
833v834 }
835836/// Construct a new `SmallVec` from a `Vec<A::Item>`.
837 ///
838 /// Elements will be copied to the inline buffer if `vec.capacity() <= Self::inline_capacity()`.
839 ///
840 /// ```rust
841 /// use smallvec::SmallVec;
842 ///
843 /// let vec = vec![1, 2, 3, 4, 5];
844 /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
845 ///
846 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
847 /// ```
848#[inline]
849pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
850if vec.capacity() <= Self::inline_capacity() {
851// Cannot use Vec with smaller capacity
852 // because we use value of `Self::capacity` field as indicator.
853unsafe {
854let mut data = SmallVecData::<A>::empty();
855let len = vec.len();
856vec.set_len(0);
857 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
858859SmallVec {
860 capacity: len,
861data,
862 }
863 }
864 } else {
865let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
866 mem::forget(vec);
867let ptr = NonNull::new(ptr)
868// See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
869.expect("Cannot be null by `Vec` invariant");
870871SmallVec {
872 capacity: cap,
873 data: SmallVecData::from_heap(ptr, len),
874 }
875 }
876 }
877878/// Constructs a new `SmallVec` on the stack from an `A` without
879 /// copying elements.
880 ///
881 /// ```rust
882 /// use smallvec::SmallVec;
883 ///
884 /// let buf = [1, 2, 3, 4, 5];
885 /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
886 ///
887 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
888 /// ```
889#[inline]
890pub fn from_buf(buf: A) -> SmallVec<A> {
891SmallVec {
892 capacity: A::size(),
893 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
894 }
895 }
896897/// Constructs a new `SmallVec` on the stack from an `A` without
898 /// copying elements. Also sets the length, which must be less or
899 /// equal to the size of `buf`.
900 ///
901 /// ```rust
902 /// use smallvec::SmallVec;
903 ///
904 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
905 /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
906 ///
907 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
908 /// ```
909#[inline]
910pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
911if !(len <= A::size()) {
::core::panicking::panic("assertion failed: len <= A::size()")
};assert!(len <= A::size());
912unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
913 }
914915/// Constructs a new `SmallVec` on the stack from an `A` without
916 /// copying elements. Also sets the length. The user is responsible
917 /// for ensuring that `len <= A::size()`.
918 ///
919 /// ```rust
920 /// use smallvec::SmallVec;
921 /// use std::mem::MaybeUninit;
922 ///
923 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
924 /// let small_vec: SmallVec<_> = unsafe {
925 /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5)
926 /// };
927 ///
928 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
929 /// ```
930#[inline]
931pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
932SmallVec {
933 capacity: len,
934 data: SmallVecData::from_inline(buf),
935 }
936 }
937938/// Sets the length of a vector.
939 ///
940 /// This will explicitly set the size of the vector, without actually
941 /// modifying its buffers, so it is up to the caller to ensure that the
942 /// vector is actually the specified size.
943pub unsafe fn set_len(&mut self, new_len: usize) {
944let (_, len_ptr, _) = self.triple_mut();
945*len_ptr = new_len;
946 }
947948/// The maximum number of elements this vector can hold inline
949#[inline]
950fn inline_capacity() -> usize {
951if mem::size_of::<A::Item>() > 0 {
952 A::size()
953 } else {
954// For zero-size items code like `ptr.add(offset)` always returns the same pointer.
955 // Therefore all items are at the same address,
956 // and any array size has capacity for infinitely many items.
957 // The capacity is limited by the bit width of the length field.
958 //
959 // `Vec` also does this:
960 // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
961 //
962 // In our case, this also ensures that a smallvec of zero-size items never spills,
963 // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
964core::usize::MAX965 }
966 }
967968/// The maximum number of elements this vector can hold inline
969#[inline]
970pub fn inline_size(&self) -> usize {
971Self::inline_capacity()
972 }
973974/// The number of elements stored in the vector
975#[inline]
976pub fn len(&self) -> usize {
977self.triple().1
978}
979980/// Returns `true` if the vector is empty
981#[inline]
982pub fn is_empty(&self) -> bool {
983self.len() == 0
984}
985986/// The number of items the vector can hold without reallocating
987#[inline]
988pub fn capacity(&self) -> usize {
989self.triple().2
990}
991992/// Returns a tuple with (data ptr, len, capacity)
993 /// Useful to get all `SmallVec` properties with a single check of the current storage variant.
994#[inline]
995fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
996unsafe {
997if self.spilled() {
998let (ptr, len) = self.data.heap();
999 (ptr, len, self.capacity)
1000 } else {
1001 (self.data.inline(), self.capacity, Self::inline_capacity())
1002 }
1003 }
1004 }
10051006/// Returns a tuple with (data ptr, len ptr, capacity)
1007#[inline]
1008fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1009unsafe {
1010if self.spilled() {
1011let (ptr, len_ptr) = self.data.heap_mut();
1012 (ptr, len_ptr, self.capacity)
1013 } else {
1014 (
1015self.data.inline_mut(),
1016&mut self.capacity,
1017Self::inline_capacity(),
1018 )
1019 }
1020 }
1021 }
10221023/// Returns `true` if the data has spilled into a separate heap-allocated buffer.
1024#[inline]
1025pub fn spilled(&self) -> bool {
1026self.capacity > Self::inline_capacity()
1027 }
10281029/// Creates a draining iterator that removes the specified range in the vector
1030 /// and yields the removed items.
1031 ///
1032 /// Note 1: The element range is removed even if the iterator is only
1033 /// partially consumed or not consumed at all.
1034 ///
1035 /// Note 2: It is unspecified how many elements are removed from the vector
1036 /// if the `Drain` value is leaked.
1037 ///
1038 /// # Panics
1039 ///
1040 /// Panics if the starting point is greater than the end point or if
1041 /// the end point is greater than the length of the vector.
1042pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1043where
1044R: RangeBounds<usize>,
1045 {
1046use core::ops::Bound::*;
10471048let len = self.len();
1049let start = match range.start_bound() {
1050Included(&n) => n,
1051Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1052Unbounded => 0,
1053 };
1054let end = match range.end_bound() {
1055Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1056Excluded(&n) => n,
1057Unbounded => len,
1058 };
10591060if !(start <= end) {
::core::panicking::panic("assertion failed: start <= end")
};assert!(start <= end);
1061if !(end <= len) { ::core::panicking::panic("assertion failed: end <= len") };assert!(end <= len);
10621063unsafe {
1064self.set_len(start);
10651066let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
10671068Drain {
1069 tail_start: end,
1070 tail_len: len - end,
1071 iter: range_slice.iter(),
1072// Since self is a &mut, passing it to a function would invalidate the slice iterator.
1073vec: NonNull::new_unchecked(selfas *mut _),
1074 }
1075 }
1076 }
10771078#[cfg(feature = "drain_filter")]
1079/// Creates an iterator which uses a closure to determine if an element should be removed.
1080 ///
1081 /// If the closure returns true, the element is removed and yielded. If the closure returns
1082 /// false, the element will remain in the vector and will not be yielded by the iterator.
1083 ///
1084 /// Using this method is equivalent to the following code:
1085 /// ```
1086 /// # use smallvec::SmallVec;
1087 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1088 /// # let mut vec: SmallVec<[i32; 8]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6]);
1089 /// let mut i = 0;
1090 /// while i < vec.len() {
1091 /// if some_predicate(&mut vec[i]) {
1092 /// let val = vec.remove(i);
1093 /// // your code here
1094 /// } else {
1095 /// i += 1;
1096 /// }
1097 /// }
1098 ///
1099 /// # assert_eq!(vec, SmallVec::<[i32; 8]>::from_slice(&[1i32, 4, 5]));
1100 /// ```
1101 /// ///
1102 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
1103 /// because it can backshift the elements of the array in bulk.
1104 ///
1105 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
1106 /// regardless of whether you choose to keep or remove it.
1107 ///
1108 /// # Examples
1109 ///
1110 /// Splitting an array into evens and odds, reusing the original allocation:
1111 ///
1112 /// ```
1113 /// # use smallvec::SmallVec;
1114 /// let mut numbers: SmallVec<[i32; 16]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1115 ///
1116 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<SmallVec<[i32; 16]>>();
1117 /// let odds = numbers;
1118 ///
1119 /// assert_eq!(evens, SmallVec::<[i32; 16]>::from_slice(&[2i32, 4, 6, 8, 14]));
1120 /// assert_eq!(odds, SmallVec::<[i32; 16]>::from_slice(&[1i32, 3, 5, 9, 11, 13, 15]));
1121 /// ```
1122pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F,>
1123where
1124F: FnMut(&mut A::Item) -> bool,
1125 {
1126let old_len = self.len();
11271128// Guard against us getting leaked (leak amplification)
1129unsafe {
1130self.set_len(0);
1131 }
11321133 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
1134 }
11351136/// Append an item to the vector.
1137#[inline]
1138pub fn push(&mut self, value: A::Item) {
1139unsafe {
1140let (mut ptr, mut len, cap) = self.triple_mut();
1141if *len == cap {
1142self.reserve_one_unchecked();
1143let (heap_ptr, heap_len) = self.data.heap_mut();
1144ptr = heap_ptr;
1145len = heap_len;
1146 }
1147 ptr::write(ptr.as_ptr().add(*len), value);
1148*len += 1;
1149 }
1150 }
11511152/// Remove an item from the end of the vector and return it, or None if empty.
1153#[inline]
1154pub fn pop(&mut self) -> Option<A::Item> {
1155unsafe {
1156let (ptr, len_ptr, _) = self.triple_mut();
1157let ptr: *const _ = ptr.as_ptr();
1158if *len_ptr == 0 {
1159return None;
1160 }
1161let last_index = *len_ptr - 1;
1162*len_ptr = last_index;
1163Some(ptr::read(ptr.add(last_index)))
1164 }
1165 }
11661167/// Moves all the elements of `other` into `self`, leaving `other` empty.
1168 ///
1169 /// # Example
1170 ///
1171 /// ```
1172 /// # use smallvec::{SmallVec, smallvec};
1173 /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3];
1174 /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6];
1175 /// v0.append(&mut v1);
1176 /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]);
1177 /// assert_eq!(*v1, []);
1178 /// ```
1179pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1180where
1181B: Array<Item = A::Item>,
1182 {
1183self.extend(other.drain(..))
1184 }
11851186/// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1187 ///
1188 /// Panics if `new_cap` is less than the vector's length
1189 /// or if the capacity computation overflows `usize`.
1190pub fn grow(&mut self, new_cap: usize) {
1191infallible(self.try_grow(new_cap))
1192 }
11931194/// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1195 ///
1196 /// Panics if `new_cap` is less than the vector's length
1197pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1198unsafe {
1199let unspilled = !self.spilled();
1200let (ptr, &mut len, cap) = self.triple_mut();
1201if !(new_cap >= len) {
::core::panicking::panic("assertion failed: new_cap >= len")
};assert!(new_cap >= len);
1202if new_cap <= Self::inline_capacity() {
1203if unspilled {
1204return Ok(());
1205 }
1206self.data = SmallVecData::empty();
1207 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1208self.capacity = len;
1209deallocate(ptr, cap);
1210 } else if new_cap != cap {
1211let layout = layout_array::<A::Item>(new_cap)?;
1212if true {
if !(layout.size() > 0) {
::core::panicking::panic("assertion failed: layout.size() > 0")
};
};debug_assert!(layout.size() > 0);
1213let new_alloc;
1214if unspilled {
1215new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1216 .ok_or(CollectionAllocErr::AllocErr { layout })?
1217.cast();
1218 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1219 } else {
1220// This should never fail since the same succeeded
1221 // when previously allocating `ptr`.
1222let old_layout = layout_array::<A::Item>(cap)?;
12231224let new_ptr =
1225 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1226new_alloc = NonNull::new(new_ptr)
1227 .ok_or(CollectionAllocErr::AllocErr { layout })?
1228.cast();
1229 }
1230self.data = SmallVecData::from_heap(new_alloc, len);
1231self.capacity = new_cap;
1232 }
1233Ok(())
1234 }
1235 }
12361237/// Reserve capacity for `additional` more elements to be inserted.
1238 ///
1239 /// May reserve more space to avoid frequent reallocations.
1240 ///
1241 /// Panics if the capacity computation overflows `usize`.
1242#[inline]
1243pub fn reserve(&mut self, additional: usize) {
1244infallible(self.try_reserve(additional))
1245 }
12461247/// Internal method used to grow in push() and insert(), where we know already we have to grow.
1248#[cold]
1249fn reserve_one_unchecked(&mut self) {
1250if true {
{
match (&self.len(), &self.capacity()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.len(), self.capacity());
1251let new_cap = self.len()
1252 .checked_add(1)
1253 .and_then(usize::checked_next_power_of_two)
1254 .expect("capacity overflow");
1255infallible(self.try_grow(new_cap))
1256 }
12571258/// Reserve capacity for `additional` more elements to be inserted.
1259 ///
1260 /// May reserve more space to avoid frequent reallocations.
1261pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1262// prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1263 // calls to it from callers.
1264let (_, &mut len, cap) = self.triple_mut();
1265if cap - len >= additional {
1266return Ok(());
1267 }
1268let new_cap = len
1269 .checked_add(additional)
1270 .and_then(usize::checked_next_power_of_two)
1271 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1272self.try_grow(new_cap)
1273 }
12741275/// Reserve the minimum capacity for `additional` more elements to be inserted.
1276 ///
1277 /// Panics if the new capacity overflows `usize`.
1278pub fn reserve_exact(&mut self, additional: usize) {
1279infallible(self.try_reserve_exact(additional))
1280 }
12811282/// Reserve the minimum capacity for `additional` more elements to be inserted.
1283pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1284let (_, &mut len, cap) = self.triple_mut();
1285if cap - len >= additional {
1286return Ok(());
1287 }
1288let new_cap = len
1289 .checked_add(additional)
1290 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1291self.try_grow(new_cap)
1292 }
12931294/// Shrink the capacity of the vector as much as possible.
1295 ///
1296 /// When possible, this will move data from an external heap buffer to the vector's inline
1297 /// storage.
1298pub fn shrink_to_fit(&mut self) {
1299if !self.spilled() {
1300return;
1301 }
1302let len = self.len();
1303if self.inline_size() >= len {
1304unsafe {
1305let (ptr, len) = self.data.heap();
1306self.data = SmallVecData::empty();
1307 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1308deallocate(ptr.0, self.capacity);
1309self.capacity = len;
1310 }
1311 } else if self.capacity() > len {
1312self.grow(len);
1313 }
1314 }
13151316/// Shorten the vector, keeping the first `len` elements and dropping the rest.
1317 ///
1318 /// If `len` is greater than or equal to the vector's current length, this has no
1319 /// effect.
1320 ///
1321 /// This does not re-allocate. If you want the vector's capacity to shrink, call
1322 /// `shrink_to_fit` after truncating.
1323pub fn truncate(&mut self, len: usize) {
1324unsafe {
1325let (ptr, len_ptr, _) = self.triple_mut();
1326let ptr = ptr.as_ptr();
1327while len < *len_ptr {
1328let last_index = *len_ptr - 1;
1329*len_ptr = last_index;
1330 ptr::drop_in_place(ptr.add(last_index));
1331 }
1332 }
1333 }
13341335/// Extracts a slice containing the entire vector.
1336 ///
1337 /// Equivalent to `&s[..]`.
1338pub fn as_slice(&self) -> &[A::Item] {
1339self1340 }
13411342/// Extracts a mutable slice of the entire vector.
1343 ///
1344 /// Equivalent to `&mut s[..]`.
1345pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1346self1347 }
13481349/// Remove the element at position `index`, replacing it with the last element.
1350 ///
1351 /// This does not preserve ordering, but is O(1).
1352 ///
1353 /// Panics if `index` is out of bounds.
1354#[inline]
1355pub fn swap_remove(&mut self, index: usize) -> A::Item {
1356let len = self.len();
1357self.swap(len - 1, index);
1358self.pop()
1359 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1360 }
13611362/// Remove all elements from the vector.
1363#[inline]
1364pub fn clear(&mut self) {
1365self.truncate(0);
1366 }
13671368/// Remove and return the element at position `index`, shifting all elements after it to the
1369 /// left.
1370 ///
1371 /// Panics if `index` is out of bounds.
1372pub fn remove(&mut self, index: usize) -> A::Item {
1373unsafe {
1374let (ptr, len_ptr, _) = self.triple_mut();
1375let len = *len_ptr;
1376if !(index < len) {
::core::panicking::panic("assertion failed: index < len")
};assert!(index < len);
1377*len_ptr = len - 1;
1378let ptr = ptr.as_ptr().add(index);
1379let item = ptr::read(ptr);
1380 ptr::copy(ptr.add(1), ptr, len - index - 1);
1381item1382 }
1383 }
13841385/// Insert an element at position `index`, shifting all elements after it to the right.
1386 ///
1387 /// Panics if `index > len`.
1388pub fn insert(&mut self, index: usize, element: A::Item) {
1389unsafe {
1390let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1391if *len_ptr == cap {
1392self.reserve_one_unchecked();
1393let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1394ptr = heap_ptr;
1395len_ptr = heap_len_ptr;
1396 }
1397let mut ptr = ptr.as_ptr();
1398let len = *len_ptr;
1399if index > len {
1400::core::panicking::panic("index exceeds length");panic!("index exceeds length");
1401 }
1402// SAFETY: add is UB if index > len, but we panicked first
1403ptr = ptr.add(index);
1404if index < len {
1405// Shift element to the right of `index`.
1406ptr::copy(ptr, ptr.add(1), len - index);
1407 }
1408*len_ptr = len + 1;
1409 ptr::write(ptr, element);
1410 }
1411 }
14121413/// Insert multiple elements at position `index`, shifting all following elements toward the
1414 /// back.
1415pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1416let mut iter = iterable.into_iter();
1417if index == self.len() {
1418return self.extend(iter);
1419 }
14201421let (lower_size_bound, _) = iter.size_hint();
1422if !(lower_size_bound <= core::isize::MAX as usize) {
::core::panicking::panic("assertion failed: lower_size_bound <= core::isize::MAX as usize")
};assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset is indexable
1423if !(index + lower_size_bound >= index) {
::core::panicking::panic("assertion failed: index + lower_size_bound >= index")
};assert!(index + lower_size_bound >= index); // Protect against overflow
14241425let mut num_added = 0;
1426let old_len = self.len();
1427if !(index <= old_len) {
::core::panicking::panic("assertion failed: index <= old_len")
};assert!(index <= old_len);
14281429unsafe {
1430// Reserve space for `lower_size_bound` elements.
1431self.reserve(lower_size_bound);
1432let start = self.as_mut_ptr();
1433let ptr = start.add(index);
14341435// Move the trailing elements.
1436ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
14371438// In case the iterator panics, don't double-drop the items we just copied above.
1439self.set_len(0);
1440let mut guard = DropOnPanic {
1441start,
1442 skip: index..(index + lower_size_bound),
1443 len: old_len + lower_size_bound,
1444 };
14451446// The set_len above invalidates the previous pointers, so we must re-create them.
1447let start = self.as_mut_ptr();
1448let ptr = start.add(index);
14491450while num_added < lower_size_bound {
1451let element = match iter.next() {
1452Some(x) => x,
1453None => break,
1454 };
1455let cur = ptr.add(num_added);
1456 ptr::write(cur, element);
1457 guard.skip.start += 1;
1458 num_added += 1;
1459 }
14601461if num_added < lower_size_bound {
1462// Iterator provided fewer elements than the hint. Move the tail backward.
1463ptr::copy(
1464ptr.add(lower_size_bound),
1465ptr.add(num_added),
1466old_len - index,
1467 );
1468 }
1469// There are no more duplicate or uninitialized slots, so the guard is not needed.
1470self.set_len(old_len + num_added);
1471 mem::forget(guard);
1472 }
14731474// Insert any remaining elements one-by-one.
1475for element in iter {
1476self.insert(index + num_added, element);
1477 num_added += 1;
1478 }
14791480struct DropOnPanic<T> {
1481 start: *mut T,
1482 skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
1483len: usize,
1484 }
14851486impl<T> Dropfor DropOnPanic<T> {
1487fn drop(&mut self) {
1488for i in 0..self.len {
1489if !self.skip.contains(&i) {
1490unsafe {
1491 ptr::drop_in_place(self.start.add(i));
1492 }
1493 }
1494 }
1495 }
1496 }
1497 }
14981499/// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec` has already spilled onto
1500 /// the heap.
1501pub fn into_vec(mut self) -> Vec<A::Item> {
1502if self.spilled() {
1503unsafe {
1504let (ptr, &mut len) = self.data.heap_mut();
1505let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1506 mem::forget(self);
1507v1508 }
1509 } else {
1510self.into_iter().collect()
1511 }
1512 }
15131514/// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled
1515 /// onto the heap.
1516 ///
1517 /// Note that this will drop any excess capacity.
1518pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1519self.into_vec().into_boxed_slice()
1520 }
15211522/// Convert the `SmallVec` into an `A` if possible. Otherwise return `Err(Self)`.
1523 ///
1524 /// This method returns `Err(Self)` if the `SmallVec` is too short (and the `A` contains uninitialized elements),
1525 /// or if the `SmallVec` is too long (and all the elements were spilled to the heap).
1526pub fn into_inner(self) -> Result<A, Self> {
1527if self.spilled() || self.len() != A::size() {
1528// Note: A::size, not Self::inline_capacity
1529Err(self)
1530 } else {
1531unsafe {
1532let data = ptr::read(&self.data);
1533 mem::forget(self);
1534Ok(data.into_inline().assume_init())
1535 }
1536 }
1537 }
15381539/// Retains only the elements specified by the predicate.
1540 ///
1541 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1542 /// This method operates in place and preserves the order of the retained
1543 /// elements.
1544pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1545let mut del = 0;
1546let len = self.len();
1547for i in 0..len {
1548if !f(&mut self[i]) {
1549 del += 1;
1550 } else if del > 0 {
1551self.swap(i - del, i);
1552 }
1553 }
1554self.truncate(len - del);
1555 }
15561557/// Retains only the elements specified by the predicate.
1558 ///
1559 /// This method is identical in behaviour to [`retain`]; it is included only
1560 /// to maintain api-compatibility with `std::Vec`, where the methods are
1561 /// separate for historical reasons.
1562pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1563self.retain(f)
1564 }
15651566/// Removes consecutive duplicate elements.
1567pub fn dedup(&mut self)
1568where
1569A::Item: PartialEq<A::Item>,
1570 {
1571self.dedup_by(|a, b| a == b);
1572 }
15731574/// Removes consecutive duplicate elements using the given equality relation.
1575pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1576where
1577F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1578 {
1579// See the implementation of Vec::dedup_by in the
1580 // standard library for an explanation of this algorithm.
1581let len = self.len();
1582if len <= 1 {
1583return;
1584 }
15851586let ptr = self.as_mut_ptr();
1587let mut w: usize = 1;
15881589unsafe {
1590for r in 1..len {
1591let p_r = ptr.add(r);
1592let p_wm1 = ptr.add(w - 1);
1593if !same_bucket(&mut *p_r, &mut *p_wm1) {
1594if r != w {
1595let p_w = p_wm1.add(1);
1596 mem::swap(&mut *p_r, &mut *p_w);
1597 }
1598 w += 1;
1599 }
1600 }
1601 }
16021603self.truncate(w);
1604 }
16051606/// Removes consecutive elements that map to the same key.
1607pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1608where
1609F: FnMut(&mut A::Item) -> K,
1610 K: PartialEq<K>,
1611 {
1612self.dedup_by(|a, b| key(a) == key(b));
1613 }
16141615/// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1616 ///
1617 /// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each
1618 /// additional slot filled with the result of calling the closure `f`. The return values from `f`
1619 /// will end up in the `SmallVec` in the order they have been generated.
1620 ///
1621 /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1622 ///
1623 /// This method uses a closure to create new values on every push. If you'd rather `Clone` a given
1624 /// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass
1625 /// `Default::default()` as the second argument.
1626 ///
1627 /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1628 ///
1629 /// ```
1630 /// # use smallvec::{smallvec, SmallVec};
1631 /// let mut vec : SmallVec<[_; 4]> = smallvec![1, 2, 3];
1632 /// vec.resize_with(5, Default::default);
1633 /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1634 ///
1635 /// let mut vec : SmallVec<[_; 4]> = smallvec![];
1636 /// let mut p = 1;
1637 /// vec.resize_with(4, || { p *= 2; p });
1638 /// assert_eq!(&*vec, &[2, 4, 8, 16]);
1639 /// ```
1640pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1641where
1642F: FnMut() -> A::Item,
1643 {
1644let old_len = self.len();
1645if old_len < new_len {
1646let mut f = f;
1647let additional = new_len - old_len;
1648self.reserve(additional);
1649for _ in 0..additional {
1650self.push(f());
1651 }
1652 } else if old_len > new_len {
1653self.truncate(new_len);
1654 }
1655 }
16561657/// Creates a `SmallVec` directly from the raw components of another
1658 /// `SmallVec`.
1659 ///
1660 /// # Safety
1661 ///
1662 /// This is highly unsafe, due to the number of invariants that aren't
1663 /// checked:
1664 ///
1665 /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1666 /// spilled storage (at least, it's highly likely to be incorrect if it
1667 /// wasn't).
1668 /// * `ptr`'s `A::Item` type needs to be the same size and alignment that
1669 /// it was allocated with
1670 /// * `length` needs to be less than or equal to `capacity`.
1671 /// * `capacity` needs to be the capacity that the pointer was allocated
1672 /// with.
1673 ///
1674 /// Violating these may cause problems like corrupting the allocator's
1675 /// internal data structures.
1676 ///
1677 /// Additionally, `capacity` must be greater than the amount of inline
1678 /// storage `A` has; that is, the new `SmallVec` must need to spill over
1679 /// into heap allocated storage. This condition is asserted against.
1680 ///
1681 /// The ownership of `ptr` is effectively transferred to the
1682 /// `SmallVec` which may then deallocate, reallocate or change the
1683 /// contents of memory pointed to by the pointer at will. Ensure
1684 /// that nothing else uses the pointer after calling this
1685 /// function.
1686 ///
1687 /// # Examples
1688 ///
1689 /// ```
1690 /// # use smallvec::{smallvec, SmallVec};
1691 /// use std::mem;
1692 /// use std::ptr;
1693 ///
1694 /// fn main() {
1695 /// let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
1696 ///
1697 /// // Pull out the important parts of `v`.
1698 /// let p = v.as_mut_ptr();
1699 /// let len = v.len();
1700 /// let cap = v.capacity();
1701 /// let spilled = v.spilled();
1702 ///
1703 /// unsafe {
1704 /// // Forget all about `v`. The heap allocation that stored the
1705 /// // three values won't be deallocated.
1706 /// mem::forget(v);
1707 ///
1708 /// // Overwrite memory with [4, 5, 6].
1709 /// //
1710 /// // This is only safe if `spilled` is true! Otherwise, we are
1711 /// // writing into the old `SmallVec`'s inline storage on the
1712 /// // stack.
1713 /// assert!(spilled);
1714 /// for i in 0..len {
1715 /// ptr::write(p.add(i), 4 + i);
1716 /// }
1717 ///
1718 /// // Put everything back together into a SmallVec with a different
1719 /// // amount of inline storage, but which is still less than `cap`.
1720 /// let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
1721 /// assert_eq!(&*rebuilt, &[4, 5, 6]);
1722 /// }
1723 /// }
1724#[inline]
1725pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1726// SAFETY: We require caller to provide same ptr as we alloc
1727 // and we never alloc null pointer.
1728let ptr = unsafe {
1729if true {
if !!ptr.is_null() {
::core::panicking::panic("Called `from_raw_parts` with null pointer.")
};
};debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1730NonNull::new_unchecked(ptr)
1731 };
1732if !(capacity > Self::inline_capacity()) {
::core::panicking::panic("assertion failed: capacity > Self::inline_capacity()")
};assert!(capacity > Self::inline_capacity());
1733SmallVec {
1734capacity,
1735 data: SmallVecData::from_heap(ptr, length),
1736 }
1737 }
17381739/// Returns a raw pointer to the vector's buffer.
1740pub fn as_ptr(&self) -> *const A::Item {
1741// We shadow the slice method of the same name to avoid going through
1742 // `deref`, which creates an intermediate reference that may place
1743 // additional safety constraints on the contents of the slice.
1744self.triple().0.as_ptr()
1745 }
17461747/// Returns a raw mutable pointer to the vector's buffer.
1748pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1749// We shadow the slice method of the same name to avoid going through
1750 // `deref_mut`, which creates an intermediate reference that may place
1751 // additional safety constraints on the contents of the slice.
1752self.triple_mut().0.as_ptr()
1753 }
1754}
17551756impl<A: Array> SmallVec<A>
1757where
1758A::Item: Copy,
1759{
1760/// Copy the elements from a slice into a new `SmallVec`.
1761 ///
1762 /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`.
1763pub fn from_slice(slice: &[A::Item]) -> Self {
1764let len = slice.len();
1765if len <= Self::inline_capacity() {
1766SmallVec {
1767 capacity: len,
1768 data: SmallVecData::from_inline(unsafe {
1769let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1770 ptr::copy_nonoverlapping(
1771slice.as_ptr(),
1772data.as_mut_ptr() as *mut A::Item,
1773len,
1774 );
1775data1776 }),
1777 }
1778 } else {
1779let mut b = slice.to_vec();
1780let cap = b.capacity();
1781let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1782 mem::forget(b);
1783SmallVec {
1784 capacity: cap,
1785 data: SmallVecData::from_heap(ptr, len),
1786 }
1787 }
1788 }
17891790/// Copy elements from a slice into the vector at position `index`, shifting any following
1791 /// elements toward the back.
1792 ///
1793 /// For slices of `Copy` types, this is more efficient than `insert`.
1794#[inline]
1795pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1796self.reserve(slice.len());
17971798let len = self.len();
1799if !(index <= len) {
::core::panicking::panic("assertion failed: index <= len")
};assert!(index <= len);
18001801unsafe {
1802let slice_ptr = slice.as_ptr();
1803let ptr = self.as_mut_ptr().add(index);
1804 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1805 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1806self.set_len(len + slice.len());
1807 }
1808 }
18091810/// Copy elements from a slice and append them to the vector.
1811 ///
1812 /// For slices of `Copy` types, this is more efficient than `extend`.
1813#[inline]
1814pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1815let len = self.len();
1816self.insert_from_slice(len, slice);
1817 }
1818}
18191820impl<A: Array> SmallVec<A>
1821where
1822A::Item: Clone,
1823{
1824/// Resizes the vector so that its length is equal to `len`.
1825 ///
1826 /// If `len` is less than the current length, the vector simply truncated.
1827 ///
1828 /// If `len` is greater than the current length, `value` is appended to the
1829 /// vector until its length equals `len`.
1830pub fn resize(&mut self, len: usize, value: A::Item) {
1831let old_len = self.len();
18321833if len > old_len {
1834self.extend(repeat(value).take(len - old_len));
1835 } else {
1836self.truncate(len);
1837 }
1838 }
18391840/// Creates a `SmallVec` with `n` copies of `elem`.
1841 /// ```
1842 /// use smallvec::SmallVec;
1843 ///
1844 /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
1845 /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
1846 /// ```
1847pub fn from_elem(elem: A::Item, n: usize) -> Self {
1848if n > Self::inline_capacity() {
1849::alloc::vec::from_elem(elem, n)vec![elem; n].into()
1850 } else {
1851let mut v = SmallVec::<A>::new();
1852unsafe {
1853let (ptr, len_ptr, _) = v.triple_mut();
1854let ptr = ptr.as_ptr();
1855let mut local_len = SetLenOnDrop::new(len_ptr);
18561857for i in 0..n {
1858 ::core::ptr::write(ptr.add(i), elem.clone());
1859 local_len.increment_len(1);
1860 }
1861 }
1862v1863 }
1864 }
1865}
18661867impl<A: Array> ops::Dereffor SmallVec<A> {
1868type Target = [A::Item];
1869#[inline]
1870fn deref(&self) -> &[A::Item] {
1871unsafe {
1872let (ptr, len, _) = self.triple();
1873 slice::from_raw_parts(ptr.as_ptr(), len)
1874 }
1875 }
1876}
18771878impl<A: Array> ops::DerefMutfor SmallVec<A> {
1879#[inline]
1880fn deref_mut(&mut self) -> &mut [A::Item] {
1881unsafe {
1882let (ptr, &mut len, _) = self.triple_mut();
1883 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1884 }
1885 }
1886}
18871888impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1889#[inline]
1890fn as_ref(&self) -> &[A::Item] {
1891self1892 }
1893}
18941895impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1896#[inline]
1897fn as_mut(&mut self) -> &mut [A::Item] {
1898self1899 }
1900}
19011902impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1903#[inline]
1904fn borrow(&self) -> &[A::Item] {
1905self1906 }
1907}
19081909impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1910#[inline]
1911fn borrow_mut(&mut self) -> &mut [A::Item] {
1912self1913 }
1914}
19151916#[cfg(feature = "write")]
1917#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1918impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1919#[inline]
1920fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1921self.extend_from_slice(buf);
1922Ok(buf.len())
1923 }
19241925#[inline]
1926fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1927self.extend_from_slice(buf);
1928Ok(())
1929 }
19301931#[inline]
1932fn flush(&mut self) -> io::Result<()> {
1933Ok(())
1934 }
1935}
19361937#[cfg(feature = "serde")]
1938#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1939impl<A: Array> Serialize for SmallVec<A>
1940where
1941A::Item: Serialize,
1942{
1943fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1944let mut state = serializer.serialize_seq(Some(self.len()))?;
1945for item in self {
1946 state.serialize_element(&item)?;
1947 }
1948 state.end()
1949 }
1950}
19511952#[cfg(feature = "serde")]
1953#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1954impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
1955where
1956A::Item: Deserialize<'de>,
1957{
1958fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1959 deserializer.deserialize_seq(SmallVecVisitor {
1960 phantom: PhantomData,
1961 })
1962 }
1963}
19641965#[cfg(feature = "serde")]
1966struct SmallVecVisitor<A> {
1967 phantom: PhantomData<A>,
1968}
19691970#[cfg(feature = "serde")]
1971impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1972where
1973A::Item: Deserialize<'de>,
1974{
1975type Value = SmallVec<A>;
19761977fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1978 formatter.write_str("a sequence")
1979 }
19801981fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1982where
1983B: SeqAccess<'de>,
1984 {
1985use serde::de::Error;
1986let len = seq.size_hint().unwrap_or(0);
1987let mut values = SmallVec::new();
1988 values.try_reserve(len).map_err(B::Error::custom)?;
19891990while let Some(value) = seq.next_element()? {
1991 values.push(value);
1992 }
19931994Ok(values)
1995 }
1996}
19971998#[cfg(feature = "malloc_size_of")]
1999impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2000fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2001if self.spilled() {
2002unsafe { ops.malloc_size_of(self.as_ptr()) }
2003 } else {
20040
2005}
2006 }
2007}
20082009#[cfg(feature = "malloc_size_of")]
2010impl<A> MallocSizeOf for SmallVec<A>
2011where
2012A: Array,
2013 A::Item: MallocSizeOf,
2014{
2015fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2016let mut n = self.shallow_size_of(ops);
2017for elem in self.iter() {
2018 n += elem.size_of(ops);
2019 }
2020 n
2021 }
2022}
20232024#[cfg(feature = "specialization")]
2025trait SpecFrom<A: Array, S> {
2026fn spec_from(slice: S) -> SmallVec<A>;
2027}
20282029#[cfg(feature = "specialization")]
2030mod specialization;
20312032#[cfg(feature = "arbitrary")]
2033mod arbitrary;
20342035#[cfg(feature = "specialization")]
2036impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2037where
2038A::Item: Copy,
2039{
2040#[inline]
2041fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2042 SmallVec::from_slice(slice)
2043 }
2044}
20452046impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2047where
2048A::Item: Clone,
2049{
2050#[cfg(not(feature = "specialization"))]
2051 #[inline]
2052fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2053slice.iter().cloned().collect()
2054 }
20552056#[cfg(feature = "specialization")]
2057 #[inline]
2058fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2059 SmallVec::spec_from(slice)
2060 }
2061}
20622063impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2064#[inline]
2065fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2066SmallVec::from_vec(vec)
2067 }
2068}
20692070impl<A: Array> From<A> for SmallVec<A> {
2071#[inline]
2072fn from(array: A) -> SmallVec<A> {
2073SmallVec::from_buf(array)
2074 }
2075}
20762077impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2078type Output = I::Output;
20792080fn index(&self, index: I) -> &I::Output {
2081&(**self)[index]
2082 }
2083}
20842085impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2086fn index_mut(&mut self, index: I) -> &mut I::Output {
2087&mut (&mut **self)[index]
2088 }
2089}
20902091#[allow(deprecated)]
2092impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2093where
2094A::Item: Copy,
2095{
2096fn extend_from_slice(&mut self, other: &[A::Item]) {
2097SmallVec::extend_from_slice(self, other)
2098 }
2099}
21002101impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2102#[inline]
2103fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2104let mut v = SmallVec::new();
2105v.extend(iterable);
2106v2107 }
2108}
21092110impl<A: Array> Extend<A::Item> for SmallVec<A> {
2111fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2112let mut iter = iterable.into_iter();
2113let (lower_size_bound, _) = iter.size_hint();
2114self.reserve(lower_size_bound);
21152116unsafe {
2117let (ptr, len_ptr, cap) = self.triple_mut();
2118let ptr = ptr.as_ptr();
2119let mut len = SetLenOnDrop::new(len_ptr);
2120while len.get() < cap {
2121if let Some(out) = iter.next() {
2122 ptr::write(ptr.add(len.get()), out);
2123 len.increment_len(1);
2124 } else {
2125return;
2126 }
2127 }
2128 }
21292130for elem in iter {
2131self.push(elem);
2132 }
2133 }
2134}
21352136impl<A: Array> fmt::Debugfor SmallVec<A>
2137where
2138A::Item: fmt::Debug,
2139{
2140fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2141f.debug_list().entries(self.iter()).finish()
2142 }
2143}
21442145impl<A: Array> Defaultfor SmallVec<A> {
2146#[inline]
2147fn default() -> SmallVec<A> {
2148SmallVec::new()
2149 }
2150}
21512152#[cfg(feature = "may_dangle")]
2153unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2154fn drop(&mut self) {
2155unsafe {
2156if self.spilled() {
2157let (ptr, &mut len) = self.data.heap_mut();
2158 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2159 } else {
2160 ptr::drop_in_place(&mut self[..]);
2161 }
2162 }
2163 }
2164}
21652166#[cfg(not(feature = "may_dangle"))]
2167impl<A: Array> Dropfor SmallVec<A> {
2168fn drop(&mut self) {
2169unsafe {
2170if self.spilled() {
2171let (ptr, &mut len) = self.data.heap_mut();
2172drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2173 } else {
2174 ptr::drop_in_place(&mut self[..]);
2175 }
2176 }
2177 }
2178}
21792180impl<A: Array> Clonefor SmallVec<A>
2181where
2182A::Item: Clone,
2183{
2184#[inline]
2185fn clone(&self) -> SmallVec<A> {
2186SmallVec::from(self.as_slice())
2187 }
21882189fn clone_from(&mut self, source: &Self) {
2190// Inspired from `impl Clone for Vec`.
21912192 // drop anything that will not be overwritten
2193self.truncate(source.len());
21942195// self.len <= other.len due to the truncate above, so the
2196 // slices here are always in-bounds.
2197let (init, tail) = source.split_at(self.len());
21982199// reuse the contained values' allocations/resources.
2200self.clone_from_slice(init);
2201self.extend(tail.iter().cloned());
2202 }
2203}
22042205impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2206where
2207A::Item: PartialEq<B::Item>,
2208{
2209#[inline]
2210fn eq(&self, other: &SmallVec<B>) -> bool {
2211self[..] == other[..]
2212 }
2213}
22142215impl<A: Array> Eqfor SmallVec<A> where A::Item: Eq {}
22162217impl<A: Array> PartialOrdfor SmallVec<A>
2218where
2219A::Item: PartialOrd,
2220{
2221#[inline]
2222fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2223 PartialOrd::partial_cmp(&**self, &**other)
2224 }
2225}
22262227impl<A: Array> Ordfor SmallVec<A>
2228where
2229A::Item: Ord,
2230{
2231#[inline]
2232fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2233 Ord::cmp(&**self, &**other)
2234 }
2235}
22362237impl<A: Array> Hashfor SmallVec<A>
2238where
2239A::Item: Hash,
2240{
2241fn hash<H: Hasher>(&self, state: &mut H) {
2242 (**self).hash(state)
2243 }
2244}
22452246unsafe impl<A: Array> Sendfor SmallVec<A> where A::Item: Send {}
22472248/// An iterator that consumes a `SmallVec` and yields its items by value.
2249///
2250/// Returned from [`SmallVec::into_iter`][1].
2251///
2252/// [1]: struct.SmallVec.html#method.into_iter
2253pub struct IntoIter<A: Array> {
2254 data: SmallVec<A>,
2255 current: usize,
2256 end: usize,
2257}
22582259impl<A: Array> fmt::Debugfor IntoIter<A>
2260where
2261A::Item: fmt::Debug,
2262{
2263fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2264f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2265 }
2266}
22672268impl<A: Array + Clone> Clonefor IntoIter<A>
2269where
2270A::Item: Clone,
2271{
2272fn clone(&self) -> IntoIter<A> {
2273SmallVec::from(self.as_slice()).into_iter()
2274 }
2275}
22762277impl<A: Array> Dropfor IntoIter<A> {
2278fn drop(&mut self) {
2279for _ in self {}
2280 }
2281}
22822283impl<A: Array> Iteratorfor IntoIter<A> {
2284type Item = A::Item;
22852286#[inline]
2287fn next(&mut self) -> Option<A::Item> {
2288if self.current == self.end {
2289None2290 } else {
2291unsafe {
2292let current = self.current;
2293self.current += 1;
2294Some(ptr::read(self.data.as_ptr().add(current)))
2295 }
2296 }
2297 }
22982299#[inline]
2300fn size_hint(&self) -> (usize, Option<usize>) {
2301let size = self.end - self.current;
2302 (size, Some(size))
2303 }
2304}
23052306impl<A: Array> DoubleEndedIteratorfor IntoIter<A> {
2307#[inline]
2308fn next_back(&mut self) -> Option<A::Item> {
2309if self.current == self.end {
2310None2311 } else {
2312unsafe {
2313self.end -= 1;
2314Some(ptr::read(self.data.as_ptr().add(self.end)))
2315 }
2316 }
2317 }
2318}
23192320impl<A: Array> ExactSizeIteratorfor IntoIter<A> {}
2321impl<A: Array> FusedIteratorfor IntoIter<A> {}
23222323impl<A: Array> IntoIter<A> {
2324/// Returns the remaining items of this iterator as a slice.
2325pub fn as_slice(&self) -> &[A::Item] {
2326let len = self.end - self.current;
2327unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2328 }
23292330/// Returns the remaining items of this iterator as a mutable slice.
2331pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2332let len = self.end - self.current;
2333unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2334 }
2335}
23362337impl<A: Array> IntoIteratorfor SmallVec<A> {
2338type IntoIter = IntoIter<A>;
2339type Item = A::Item;
2340fn into_iter(mut self) -> Self::IntoIter {
2341unsafe {
2342// Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements
2343let len = self.len();
2344self.set_len(0);
2345IntoIter {
2346 data: self,
2347 current: 0,
2348 end: len,
2349 }
2350 }
2351 }
2352}
23532354impl<'a, A: Array> IntoIteratorfor &'a SmallVec<A> {
2355type IntoIter = slice::Iter<'a, A::Item>;
2356type Item = &'a A::Item;
2357fn into_iter(self) -> Self::IntoIter {
2358self.iter()
2359 }
2360}
23612362impl<'a, A: Array> IntoIteratorfor &'a mut SmallVec<A> {
2363type IntoIter = slice::IterMut<'a, A::Item>;
2364type Item = &'a mut A::Item;
2365fn into_iter(self) -> Self::IntoIter {
2366self.iter_mut()
2367 }
2368}
23692370/// Types that can be used as the backing store for a [`SmallVec`].
2371pub unsafe trait Array {
2372/// The type of the array's elements.
2373type Item;
2374/// Returns the number of items the array can hold.
2375fn size() -> usize;
2376}
23772378/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
2379///
2380/// Copied from <https://github.com/rust-lang/rust/pull/36355>
2381struct SetLenOnDrop<'a> {
2382 len: &'a mut usize,
2383 local_len: usize,
2384}
23852386impl<'a> SetLenOnDrop<'a> {
2387#[inline]
2388fn new(len: &'a mut usize) -> Self {
2389SetLenOnDrop {
2390 local_len: *len,
2391len,
2392 }
2393 }
23942395#[inline]
2396fn get(&self) -> usize {
2397self.local_len
2398 }
23992400#[inline]
2401fn increment_len(&mut self, increment: usize) {
2402self.local_len += increment;
2403 }
2404}
24052406impl<'a> Dropfor SetLenOnDrop<'a> {
2407#[inline]
2408fn drop(&mut self) {
2409*self.len = self.local_len;
2410 }
2411}
24122413#[cfg(feature = "const_new")]
2414impl<T, const N: usize> SmallVec<[T; N]> {
2415/// Construct an empty vector.
2416 ///
2417 /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2418#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2419 #[inline]
2420pub const fn new_const() -> Self {
2421 SmallVec {
2422 capacity: 0,
2423 data: SmallVecData::from_const(MaybeUninit::uninit()),
2424 }
2425 }
24262427/// The array passed as an argument is moved to be an inline version of `SmallVec`.
2428 ///
2429 /// This is a `const` version of [`SmallVec::from_buf`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2430#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2431 #[inline]
2432pub const fn from_const(items: [T; N]) -> Self {
2433 SmallVec {
2434 capacity: N,
2435 data: SmallVecData::from_const(MaybeUninit::new(items)),
2436 }
2437 }
24382439/// Constructs a new `SmallVec` on the stack from an array without
2440 /// copying elements. Also sets the length. The user is responsible
2441 /// for ensuring that `len <= N`.
2442 ///
2443 /// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2444#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2445 #[inline]
2446pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2447 SmallVec {
2448 capacity: len,
2449 data: SmallVecData::from_const(MaybeUninit::new(items)),
2450 }
2451 }
2452}
24532454#[cfg(feature = "const_generics")]
2455#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2456unsafe impl<T, const N: usize> Arrayfor [T; N] {
2457type Item = T;
2458#[inline]
2459fn size() -> usize {
2460N2461 }
2462}
24632464#[cfg(not(feature = "const_generics"))]
2465macro_rules! impl_array(
2466 ($($size:expr),+) => {
2467 $(
2468unsafe impl<T> Array for [T; $size] {
2469type Item = T;
2470#[inline]
2471fn size() -> usize { $size }
2472 }
2473 )+
2474 }
2475);
24762477#[cfg(not(feature = "const_generics"))]
2478impl_array!(
24790, 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,
248026, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
24810x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2482);
24832484/// Convenience trait for constructing a `SmallVec`
2485pub trait ToSmallVec<A: Array> {
2486/// Construct a new `SmallVec` from a slice.
2487fn to_smallvec(&self) -> SmallVec<A>;
2488}
24892490impl<A: Array> ToSmallVec<A> for [A::Item]
2491where
2492A::Item: Copy,
2493{
2494#[inline]
2495fn to_smallvec(&self) -> SmallVec<A> {
2496SmallVec::from_slice(self)
2497 }
2498}
24992500// Immutable counterpart for `NonNull<T>`.
2501#[repr(transparent)]
2502struct ConstNonNull<T>(NonNull<T>);
25032504impl<T> ConstNonNull<T> {
2505#[inline]
2506fn new(ptr: *const T) -> Option<Self> {
2507NonNull::new(ptras *mut T).map(Self)
2508 }
2509#[inline]
2510fn as_ptr(self) -> *const T {
2511self.0.as_ptr()
2512 }
2513}
25142515impl<T> Clonefor ConstNonNull<T> {
2516#[inline]
2517fn clone(&self) -> Self {
2518*self2519 }
2520}
25212522impl<T> Copyfor ConstNonNull<T> {}
25232524#[cfg(feature = "impl_bincode")]
2525use bincode::{
2526 de::{BorrowDecoder, Decode, Decoder, read::Reader},
2527 enc::{Encode, Encoder, write::Writer},
2528 error::{DecodeError, EncodeError},
2529 BorrowDecode,
2530};
25312532#[cfg(feature = "impl_bincode")]
2533impl<A, Context> Decode<Context> for SmallVec<A>
2534where
2535A: Array,
2536 A::Item: Decode<Context>,
2537{
2538fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2539use core::convert::TryInto;
2540let len = u64::decode(decoder)?;
2541let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2542 decoder.claim_container_read::<A::Item>(len)?;
25432544let mut vec = SmallVec::with_capacity(len);
2545if unty::type_equal::<A::Item, u8>() {
2546// Initialize the smallvec's buffer. Note that we need to do this through
2547 // the raw pointer as we cannot name the type [u8; N] even though A::Item is u8.
2548let ptr = vec.as_mut_ptr();
2549// SAFETY: A::Item is u8 and the smallvec has been allocated with enough capacity
2550unsafe {
2551 core::ptr::write_bytes(ptr, 0, len);
2552 vec.set_len(len);
2553 }
2554// Read the data into the smallvec's buffer.
2555let slice = vec.as_mut_slice();
2556// SAFETY: A::Item is u8
2557let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2558 decoder.reader().read(slice)?;
2559 } else {
2560for _ in 0..len {
2561 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2562 vec.push(A::Item::decode(decoder)?);
2563 }
2564 }
2565Ok(vec)
2566 }
2567}
25682569#[cfg(feature = "impl_bincode")]
2570impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2571where
2572A: Array,
2573 A::Item: BorrowDecode<'de, Context>,
2574{
2575fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2576use core::convert::TryInto;
2577let len = u64::decode(decoder)?;
2578let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2579 decoder.claim_container_read::<A::Item>(len)?;
25802581let mut vec = SmallVec::with_capacity(len);
2582if unty::type_equal::<A::Item, u8>() {
2583// Initialize the smallvec's buffer. Note that we need to do this through
2584 // the raw pointer as we cannot name the type [u8; N] even though A::Item is u8.
2585let ptr = vec.as_mut_ptr();
2586// SAFETY: A::Item is u8 and the smallvec has been allocated with enough capacity
2587unsafe {
2588 core::ptr::write_bytes(ptr, 0, len);
2589 vec.set_len(len);
2590 }
2591// Read the data into the smallvec's buffer.
2592let slice = vec.as_mut_slice();
2593// SAFETY: A::Item is u8
2594let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2595 decoder.reader().read(slice)?;
2596 } else {
2597for _ in 0..len {
2598 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2599 vec.push(A::Item::borrow_decode(decoder)?);
2600 }
2601 }
2602Ok(vec)
2603 }
2604}
26052606#[cfg(feature = "impl_bincode")]
2607impl<A> Encode for SmallVec<A>
2608where
2609A: Array,
2610 A::Item: Encode,
2611{
2612fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2613 (self.len() as u64).encode(encoder)?;
2614if unty::type_equal::<A::Item, u8>() {
2615// Safety: A::Item is u8
2616let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2617 encoder.writer().write(slice)?;
2618 } else {
2619for item in self.iter() {
2620 item.encode(encoder)?;
2621 }
2622 }
2623Ok(())
2624 }
2625}