Struct SmallVec
struct SmallVec<A: Array> { ... }
A Vec-like container that can store a small number of elements inline.
SmallVec acts like a vector, but can store a limited amount of data inline within the
SmallVec struct rather than in a separate allocation. If the data exceeds this limit, the
SmallVec will "spill" its data onto the heap, allocating a new buffer to hold it.
The amount of data that a SmallVec can store inline depends on its backing store. The backing
store can be any type that implements the Array trait; usually it is a small fixed-sized
array. For example a SmallVec<[u64; 8]> can hold up to eight 64-bit integers inline.
Example
use SmallVec;
let mut v = new; // initialize an empty vector
// The vector can hold up to 4 items without spilling onto the heap.
v.extend;
assert_eq!;
assert!;
// Pushing another element will force the buffer to spill:
v.push;
assert_eq!;
assert!;
Implementations
impl<A: Array> SmallVec<A>
fn resize(self: &mut Self, len: usize, value: <A as >::Item)Resizes the vector so that its length is equal to
len.If
lenis less than the current length, the vector simply truncated.If
lenis greater than the current length,valueis appended to the vector until its length equalslen.fn from_elem(elem: <A as >::Item, n: usize) -> SelfCreates a
SmallVecwithncopies ofelem.use SmallVec; let v = from_elem; assert_eq!;
impl<A: Array> SmallVec<A>
fn from_slice(slice: &[<A as >::Item]) -> SelfCopy the elements from a slice into a new
SmallVec.For slices of
Copytypes, this is more efficient thanSmallVec::from(slice).fn insert_from_slice(self: &mut Self, index: usize, slice: &[<A as >::Item])Copy elements from a slice into the vector at position
index, shifting any following elements toward the back.For slices of
Copytypes, this is more efficient thaninsert.fn extend_from_slice(self: &mut Self, slice: &[<A as >::Item])Copy elements from a slice and append them to the vector.
For slices of
Copytypes, this is more efficient thanextend.
impl<A: Array> SmallVec<A>
fn new() -> SmallVec<A>Construct an empty vector
fn with_capacity(n: usize) -> SelfConstruct an empty vector with enough capacity pre-allocated to store at least
nelements.Will create a heap allocation only if
nis larger than the inline capacity.# use SmallVec; let v: = with_capacity; assert!; assert!;fn from_vec(vec: Vec<<A as >::Item>) -> SmallVec<A>Construct a new
SmallVecfrom aVec<A::Item>.Elements will be copied to the inline buffer if
vec.capacity() <= Self::inline_capacity().use SmallVec; let vec = vec!; let small_vec: = from_vec; assert_eq!;fn from_buf(buf: A) -> SmallVec<A>Constructs a new
SmallVecon the stack from anAwithout copying elements.use SmallVec; let buf = ; let small_vec: = from_buf; assert_eq!;fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A>Constructs a new
SmallVecon the stack from anAwithout copying elements. Also sets the length, which must be less or equal to the size ofbuf.use SmallVec; let buf = ; let small_vec: = from_buf_and_len; assert_eq!;unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A>Constructs a new
SmallVecon the stack from anAwithout copying elements. Also sets the length. The user is responsible for ensuring thatlen <= A::size().use SmallVec; use MaybeUninit; let buf = ; let small_vec: = unsafe ; assert_eq!;unsafe fn set_len(self: &mut Self, new_len: usize)Sets the length of a vector.
This will explicitly set the size of the vector, without actually modifying its buffers, so it is up to the caller to ensure that the vector is actually the specified size.
fn inline_size(self: &Self) -> usizeThe maximum number of elements this vector can hold inline
fn len(self: &Self) -> usizeThe number of elements stored in the vector
fn is_empty(self: &Self) -> boolReturns
trueif the vector is emptyfn capacity(self: &Self) -> usizeThe number of items the vector can hold without reallocating
fn spilled(self: &Self) -> boolReturns
trueif the data has spilled into a separate heap-allocated buffer.fn drain<R>(self: &mut Self, range: R) -> Drain<'_, A> where R: RangeBounds<usize>Creates a draining iterator that removes the specified range in the vector and yields the removed items.
Note 1: The element range is removed even if the iterator is only partially consumed or not consumed at all.
Note 2: It is unspecified how many elements are removed from the vector if the
Drainvalue is leaked.Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.
fn push(self: &mut Self, value: <A as >::Item)Append an item to the vector.
fn pop(self: &mut Self) -> Option<<A as >::Item>Remove an item from the end of the vector and return it, or None if empty.
fn append<B>(self: &mut Self, other: &mut SmallVec<B>) where B: Array<Item = <A as >::Item>Moves all the elements of
otherintoself, leavingotherempty.Example
# use ; let mut v0: = smallvec!; let mut v1: = smallvec!; v0.append; assert_eq!; assert_eq!;fn grow(self: &mut Self, new_cap: usize)Re-allocate to set the capacity to
max(new_cap, inline_size()).Panics if
new_capis less than the vector's length or if the capacity computation overflowsusize.fn try_grow(self: &mut Self, new_cap: usize) -> Result<(), CollectionAllocErr>Re-allocate to set the capacity to
max(new_cap, inline_size()).Panics if
new_capis less than the vector's lengthfn reserve(self: &mut Self, additional: usize)Reserve capacity for
additionalmore elements to be inserted.May reserve more space to avoid frequent reallocations.
Panics if the capacity computation overflows
usize.fn try_reserve(self: &mut Self, additional: usize) -> Result<(), CollectionAllocErr>Reserve capacity for
additionalmore elements to be inserted.May reserve more space to avoid frequent reallocations.
fn reserve_exact(self: &mut Self, additional: usize)Reserve the minimum capacity for
additionalmore elements to be inserted.Panics if the new capacity overflows
usize.fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), CollectionAllocErr>Reserve the minimum capacity for
additionalmore elements to be inserted.fn shrink_to_fit(self: &mut Self)Shrink the capacity of the vector as much as possible.
When possible, this will move data from an external heap buffer to the vector's inline storage.
fn truncate(self: &mut Self, len: usize)Shorten the vector, keeping the first
lenelements and dropping the rest.If
lenis greater than or equal to the vector's current length, this has no effect.This does not re-allocate. If you want the vector's capacity to shrink, call
shrink_to_fitafter truncating.fn as_slice(self: &Self) -> &[<A as >::Item]Extracts a slice containing the entire vector.
Equivalent to
&s[..].fn as_mut_slice(self: &mut Self) -> &mut [<A as >::Item]Extracts a mutable slice of the entire vector.
Equivalent to
&mut s[..].fn swap_remove(self: &mut Self, index: usize) -> <A as >::ItemRemove the element at position
index, replacing it with the last element.This does not preserve ordering, but is O(1).
Panics if
indexis out of bounds.fn clear(self: &mut Self)Remove all elements from the vector.
fn remove(self: &mut Self, index: usize) -> <A as >::ItemRemove and return the element at position
index, shifting all elements after it to the left.Panics if
indexis out of bounds.fn insert(self: &mut Self, index: usize, element: <A as >::Item)Insert an element at position
index, shifting all elements after it to the right.Panics if
index > len.fn insert_many<I: IntoIterator<Item = <A as >::Item>>(self: &mut Self, index: usize, iterable: I)Insert multiple elements at position
index, shifting all following elements toward the back.fn into_vec(self: Self) -> Vec<<A as >::Item>Convert a
SmallVecto aVec, without reallocating if theSmallVechas already spilled onto the heap.fn into_boxed_slice(self: Self) -> Box<[<A as >::Item]>Converts a
SmallVecinto aBox<[T]>without reallocating if theSmallVechas already spilled onto the heap.Note that this will drop any excess capacity.
fn into_inner(self: Self) -> Result<A, Self>Convert the
SmallVecinto anAif possible. Otherwise returnErr(Self).This method returns
Err(Self)if theSmallVecis too short (and theAcontains uninitialized elements), or if theSmallVecis too long (and all the elements were spilled to the heap).fn retain<F: FnMut(&mut <A as >::Item) -> bool>(self: &mut Self, f: F)Retains only the elements specified by the predicate.
In other words, remove all elements
esuch thatf(&e)returnsfalse. This method operates in place and preserves the order of the retained elements.fn retain_mut<F: FnMut(&mut <A as >::Item) -> bool>(self: &mut Self, f: F)Retains only the elements specified by the predicate.
This method is identical in behaviour to
retain; it is included only to maintain api-compatibility withstd::Vec, where the methods are separate for historical reasons.fn dedup(self: &mut Self) where <A as >::Item: PartialEq<<A as >::Item>Removes consecutive duplicate elements.
fn dedup_by<F>(self: &mut Self, same_bucket: F) where F: FnMut(&mut <A as >::Item, &mut <A as >::Item) -> boolRemoves consecutive duplicate elements using the given equality relation.
fn dedup_by_key<F, K>(self: &mut Self, key: F) where F: FnMut(&mut <A as >::Item) -> K, K: PartialEq<K>Removes consecutive elements that map to the same key.
fn resize_with<F>(self: &mut Self, new_len: usize, f: F) where F: FnMut() -> <A as >::ItemResizes the
SmallVecin-place so thatlenis equal tonew_len.If
new_lenis greater thanlen, theSmallVecis extended by the difference, with each additional slot filled with the result of calling the closuref. The return values fromfwill end up in theSmallVecin the order they have been generated.If
new_lenis less thanlen, theSmallVecis simply truncated.This method uses a closure to create new values on every push. If you'd rather
Clonea given value, useresize. If you want to use theDefaulttrait to generate values, you can passDefault::default()as the second argument.Added for
std::vec::Veccompatibility (added in Rust 1.33.0)# use ; let mut vec : = smallvec!; vec.resize_with; assert_eq!; let mut vec : = smallvec!; let mut p = 1; vec.resize_with; assert_eq!;unsafe fn from_raw_parts(ptr: *mut <A as >::Item, length: usize, capacity: usize) -> SmallVec<A>Creates a
SmallVecdirectly from the raw components of anotherSmallVec.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
ptrneeds to have been previously allocated viaSmallVecfor its spilled storage (at least, it's highly likely to be incorrect if it wasn't).ptr'sA::Itemtype needs to be the same size and alignment that it was allocated withlengthneeds to be less than or equal tocapacity.capacityneeds to be the capacity that the pointer was allocated with.
Violating these may cause problems like corrupting the allocator's internal data structures.
Additionally,
capacitymust be greater than the amount of inline storageAhas; that is, the newSmallVecmust need to spill over into heap allocated storage. This condition is asserted against.The ownership of
ptris effectively transferred to theSmallVecwhich may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
# use ; use mem; use ptr;fn as_ptr(self: &Self) -> *const <A as >::ItemReturns a raw pointer to the vector's buffer.
fn as_mut_ptr(self: &mut Self) -> *mut <A as >::ItemReturns a raw mutable pointer to the vector's buffer.
impl<T, N: usize> SmallVec<[T; N]>
const fn new_const() -> SelfConstruct an empty vector.
This is a
constversion ofSmallVec::newthat is enabled by the featureconst_new, with the limitation that it only works for arrays.const fn from_const(items: [T; N]) -> SelfThe array passed as an argument is moved to be an inline version of
SmallVec.This is a
constversion ofSmallVec::from_bufthat is enabled by the featureconst_new, with the limitation that it only works for arrays.unsafe const fn from_const_with_len_unchecked(items: [T; N], len: usize) -> SelfConstructs a new
SmallVecon the stack from an array without copying elements. Also sets the length. The user is responsible for ensuring thatlen <= N.This is a
constversion ofSmallVec::from_buf_and_len_uncheckedthat is enabled by the featureconst_new, with the limitation that it only works for arrays.
impl<'a, A: Array> From for SmallVec<A>
fn from(slice: &'a [<A as >::Item]) -> SmallVec<A>
impl<A> Freeze for SmallVec<A>
impl<A> RefUnwindSafe for SmallVec<A>
impl<A> Sync for SmallVec<A>
impl<A> Unpin for SmallVec<A>
impl<A> UnsafeUnpin for SmallVec<A>
impl<A> UnwindSafe for SmallVec<A>
impl<A: Array> AsMut for SmallVec<A>
fn as_mut(self: &mut Self) -> &mut [<A as >::Item]
impl<A: Array> AsRef for SmallVec<A>
fn as_ref(self: &Self) -> &[<A as >::Item]
impl<A: Array> Borrow for SmallVec<A>
fn borrow(self: &Self) -> &[<A as >::Item]
impl<A: Array> BorrowMut for SmallVec<A>
fn borrow_mut(self: &mut Self) -> &mut [<A as >::Item]
impl<A: Array> Clone for SmallVec<A>
fn clone(self: &Self) -> SmallVec<A>fn clone_from(self: &mut Self, source: &Self)
impl<A: Array> Debug for SmallVec<A>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<A: Array> Default for SmallVec<A>
fn default() -> SmallVec<A>
impl<A: Array> Deref for SmallVec<A>
fn deref(self: &Self) -> &[<A as >::Item]
impl<A: Array> DerefMut for SmallVec<A>
fn deref_mut(self: &mut Self) -> &mut [<A as >::Item]
impl<A: Array> Drop for SmallVec<A>
fn drop(self: &mut Self)
impl<A: Array> Eq for SmallVec<A>
impl<A: Array> Extend for SmallVec<A>
fn extend<I: IntoIterator<Item = <A as >::Item>>(self: &mut Self, iterable: I)
impl<A: Array> From for SmallVec<A>
fn from(array: A) -> SmallVec<A>
impl<A: Array> From for SmallVec<A>
fn from(vec: Vec<<A as >::Item>) -> SmallVec<A>
impl<A: Array> FromIterator for SmallVec<A>
fn from_iter<I: IntoIterator<Item = <A as >::Item>>(iterable: I) -> SmallVec<A>
impl<A: Array> Hash for SmallVec<A>
fn hash<H: Hasher>(self: &Self, state: &mut H)
impl<A: Array> IntoIterator for SmallVec<A>
fn into_iter(self: Self) -> <Self as >::IntoIter
impl<A: Array> Ord for SmallVec<A>
fn cmp(self: &Self, other: &SmallVec<A>) -> Ordering
impl<A: Array> PartialOrd for SmallVec<A>
fn partial_cmp(self: &Self, other: &SmallVec<A>) -> Option<Ordering>
impl<A: Array> Send for SmallVec<A>
impl<A: Array, B: Array> PartialEq for SmallVec<A>
fn eq(self: &Self, other: &SmallVec<B>) -> bool
impl<A: Array, I: SliceIndex<[<A as >::Item]>> Index for SmallVec<A>
fn index(self: &Self, index: I) -> &<I as >::Output
impl<A: Array, I: SliceIndex<[<A as >::Item]>> IndexMut for SmallVec<A>
fn index_mut(self: &mut Self, index: I) -> &mut <I as >::Output
impl<P, T> Receiver for SmallVec<A>
impl<T> Any for SmallVec<A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for SmallVec<A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for SmallVec<A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for SmallVec<A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for SmallVec<A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for SmallVec<A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for SmallVec<A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for SmallVec<A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for SmallVec<A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>