pub type Traces = Vec<(TraceKind, SparsedTraceArena)>;
Aliased Type§
struct Traces { /* private fields */ }
Layout§
Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...)
attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.
Size: 24 bytes
Implementations
Source§impl<T> Vec<T>
impl<T> Vec<T>
1.0.0 (const: 1.39.0) · Sourcepub const fn new() -> Vec<T>
pub const fn new() -> Vec<T>
Constructs a new, empty Vec<T>
.
The vector will not allocate until elements are pushed onto it.
§Examples
let mut vec: Vec<i32> = Vec::new();
1.0.0 · Sourcepub fn with_capacity(capacity: usize) -> Vec<T>
Available on non-no_global_oom_handling
only.
pub fn with_capacity(capacity: usize) -> Vec<T>
no_global_oom_handling
only.Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the vector will not allocate.
It is important to note that although the returned vector has the minimum capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.
If it is important to know the exact allocated capacity of a Vec
,
always use the capacity
method after construction.
For Vec<T>
where T
is a zero-sized type, there will be no allocation
and the capacity will always be usize::MAX
.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = Vec::with_capacity(10);
// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);
// These are all done without reallocating...
for i in 0..10 {
vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);
// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);
// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<()>::with_capacity(10);
assert_eq!(vec_units.capacity(), usize::MAX);
Sourcepub fn try_with_capacity(capacity: usize) -> Result<Vec<T>, TryReserveError>
🔬This is a nightly-only experimental API. (try_with_capacity
)
pub fn try_with_capacity(capacity: usize) -> Result<Vec<T>, TryReserveError>
try_with_capacity
)Constructs a new, empty Vec<T>
with at least the specified capacity.
The vector will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the vector will not allocate.
§Errors
Returns an error if the capacity exceeds isize::MAX
bytes,
or if the allocator reports allocation failure.
1.0.0 · Sourcepub unsafe fn from_raw_parts(
ptr: *mut T,
length: usize,
capacity: usize,
) -> Vec<T>
pub unsafe fn from_raw_parts( ptr: *mut T, length: usize, capacity: usize, ) -> Vec<T>
Creates a Vec<T>
directly from a pointer, a length, and a capacity.
§Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
ptr
must have been allocated using the global allocator, such as via thealloc::alloc
function.T
needs to have the same alignment as whatptr
was allocated with. (T
having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedealloc
requirement that memory must be allocated and deallocated with the same layout.)- The size of
T
times thecapacity
(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,dealloc
must be called with the same layoutsize
.) length
needs to be less than or equal tocapacity
.- The first
length
values must be properly initialized values of typeT
. capacity
needs to be the capacity that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX
. See the safety documentation ofpointer::offset
.
These requirements are always upheld by any ptr
that has been allocated
via Vec<T>
. Other allocation sources are allowed if the invariants are
upheld.
Violating these may cause problems like corrupting the allocator’s
internal data structures. For example it is normally not safe
to build a Vec<u8>
from a pointer to a C char
array with length
size_t
, doing so is only safe if the array was initially allocated by
a Vec
or String
.
It’s also not safe to build one from a Vec<u16>
and its length, because
the allocator cares about the alignment, and these two types have different
alignments. The buffer was allocated with alignment 2 (for u16
), but after
turning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid
these issues, it is often preferable to do casting/transmuting using
slice::from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the
Vec<T>
which 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 std::ptr;
use std::mem;
let v = vec![1, 2, 3];
// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);
// Pull out the various important pieces of information about `v`
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();
unsafe {
// Overwrite memory with 4, 5, 6
for i in 0..len {
ptr::write(p.add(i), 4 + i);
}
// Put everything back together into a Vec
let rebuilt = Vec::from_raw_parts(p, len, cap);
assert_eq!(rebuilt, [4, 5, 6]);
}
Using memory that was allocated elsewhere:
use std::alloc::{alloc, Layout};
fn main() {
let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
let vec = unsafe {
let mem = alloc(layout).cast::<u32>();
if mem.is_null() {
return;
}
mem.write(1_000_000);
Vec::from_raw_parts(mem, 1, 16)
};
assert_eq!(vec, &[1_000_000]);
assert_eq!(vec.capacity(), 16);
}
Sourcepub unsafe fn from_parts(
ptr: NonNull<T>,
length: usize,
capacity: usize,
) -> Vec<T>
🔬This is a nightly-only experimental API. (box_vec_non_null
)
pub unsafe fn from_parts( ptr: NonNull<T>, length: usize, capacity: usize, ) -> Vec<T>
box_vec_non_null
)Creates a Vec<T>
directly from a NonNull
pointer, a length, and a capacity.
§Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
ptr
must have been allocated using the global allocator, such as via thealloc::alloc
function.T
needs to have the same alignment as whatptr
was allocated with. (T
having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedealloc
requirement that memory must be allocated and deallocated with the same layout.)- The size of
T
times thecapacity
(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,dealloc
must be called with the same layoutsize
.) length
needs to be less than or equal tocapacity
.- The first
length
values must be properly initialized values of typeT
. capacity
needs to be the capacity that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX
. See the safety documentation ofpointer::offset
.
These requirements are always upheld by any ptr
that has been allocated
via Vec<T>
. Other allocation sources are allowed if the invariants are
upheld.
Violating these may cause problems like corrupting the allocator’s
internal data structures. For example it is normally not safe
to build a Vec<u8>
from a pointer to a C char
array with length
size_t
, doing so is only safe if the array was initially allocated by
a Vec
or String
.
It’s also not safe to build one from a Vec<u16>
and its length, because
the allocator cares about the alignment, and these two types have different
alignments. The buffer was allocated with alignment 2 (for u16
), but after
turning it into a Vec<u8>
it’ll be deallocated with alignment 1. To avoid
these issues, it is often preferable to do casting/transmuting using
NonNull::slice_from_raw_parts
instead.
The ownership of ptr
is effectively transferred to the
Vec<T>
which 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
#![feature(box_vec_non_null)]
use std::ptr::NonNull;
use std::mem;
let v = vec![1, 2, 3];
// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);
// Pull out the various important pieces of information about `v`
let p = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };
let len = v.len();
let cap = v.capacity();
unsafe {
// Overwrite memory with 4, 5, 6
for i in 0..len {
p.add(i).write(4 + i);
}
// Put everything back together into a Vec
let rebuilt = Vec::from_parts(p, len, cap);
assert_eq!(rebuilt, [4, 5, 6]);
}
Using memory that was allocated elsewhere:
#![feature(box_vec_non_null)]
use std::alloc::{alloc, Layout};
use std::ptr::NonNull;
fn main() {
let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
let vec = unsafe {
let Some(mem) = NonNull::new(alloc(layout).cast::<u32>()) else {
return;
};
mem.write(1_000_000);
Vec::from_parts(mem, 1, 16)
};
assert_eq!(vec, &[1_000_000]);
assert_eq!(vec.capacity(), 16);
}
Source§impl<T, A> Vec<T, A>
impl<T, A> Vec<T, A>
1.5.0 · Sourcepub fn resize(&mut self, new_len: usize, value: T)
Available on non-no_global_oom_handling
only.
pub fn resize(&mut self, new_len: usize, value: T)
no_global_oom_handling
only.Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the
difference, with each additional slot filled with value
.
If new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,
in order to be able to clone the passed value.
If you need more flexibility (or want to rely on Default
instead of
Clone
), use Vec::resize_with
.
If you only need to resize to a smaller size, use Vec::truncate
.
§Examples
let mut vec = vec!["hello"];
vec.resize(3, "world");
assert_eq!(vec, ["hello", "world", "world"]);
let mut vec = vec!['a', 'b', 'c', 'd'];
vec.resize(2, '_');
assert_eq!(vec, ['a', 'b']);
1.6.0 · Sourcepub fn extend_from_slice(&mut self, other: &[T])
Available on non-no_global_oom_handling
only.
pub fn extend_from_slice(&mut self, other: &[T])
no_global_oom_handling
only.Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends
it to this Vec
. The other
slice is traversed in-order.
Note that this function is same as extend
except that it is
specialized to work with slices instead. If and when Rust gets
specialization this function will likely be deprecated (but still
available).
§Examples
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);
1.53.0 · Sourcepub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
Available on non-no_global_oom_handling
only.
pub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
no_global_oom_handling
only.Given a range src
, clones a slice of elements in that range and appends it to the end.
src
must be a range that can form a valid subslice of the Vec
.
§Panics
Panics if starting index is greater than the end index or if the index is greater than the length of the vector.
§Examples
let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
characters.extend_from_within(2..);
assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
let mut numbers = vec![0, 1, 2, 3, 4];
numbers.extend_from_within(..2);
assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
strings.extend_from_within(1..=2);
assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
Source§impl<T, A> Vec<T, A>where
A: Allocator,
impl<T, A> Vec<T, A>where
A: Allocator,
1.21.0 · Sourcepub fn splice<R, I>(
&mut self,
range: R,
replace_with: I,
) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
Available on non-no_global_oom_handling
only.
pub fn splice<R, I>( &mut self, range: R, replace_with: I, ) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
no_global_oom_handling
only.Creates a splicing iterator that replaces the specified range in the vector
with the given replace_with
iterator and yields the removed items.
replace_with
does not need to be the same length as range
.
range
is removed even if the iterator is not consumed until the end.
It is unspecified how many elements are removed from the vector
if the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
- The tail (elements in the vector after
range
) is empty, - or
replace_with
yields fewer or equal elements thanrange
’s length - or the lower bound of its
size_hint()
is exact.
Otherwise, a temporary vector is allocated and the tail is moved twice.
§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.
§Examples
let mut v = vec![1, 2, 3, 4];
let new = [7, 8, 9];
let u: Vec<_> = v.splice(1..3, new).collect();
assert_eq!(v, &[1, 7, 8, 9, 4]);
assert_eq!(u, &[2, 3]);
Sourcepub fn extract_if<F, R>(
&mut self,
range: R,
filter: F,
) -> ExtractIf<'_, T, F, A> ⓘ
🔬This is a nightly-only experimental API. (extract_if
)
pub fn extract_if<F, R>( &mut self, range: R, filter: F, ) -> ExtractIf<'_, T, F, A> ⓘ
extract_if
)Creates an iterator which uses a closure to determine if element in the range should be removed.
If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the vector and will not be yielded by the iterator.
Only elements that fall in the provided range are considered for extraction, but any elements after the range will still have to be moved if any element has been extracted.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
let mut i = range.start;
while i < min(vec.len(), range.end) {
if some_predicate(&mut vec[i]) {
let val = vec.remove(i);
// your code here
} else {
i += 1;
}
}
But extract_if
is easier to use. extract_if
is also more efficient,
because it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate the elements passed to the filter closure,
regardless of whether you choose to keep or remove them.
§Panics
If range
is out of bounds.
§Examples
Splitting an array into evens and odds, reusing the original allocation:
#![feature(extract_if)]
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;
assert_eq!(evens, vec![2, 4, 6, 8, 14]);
assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
Using the range argument to only process a part of the vector:
#![feature(extract_if)]
let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
assert_eq!(ones.len(), 3);
Source§impl<T, A> Vec<T, A>where
A: Allocator,
impl<T, A> Vec<T, A>where
A: Allocator,
Sourcepub const fn new_in(alloc: A) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub const fn new_in(alloc: A) -> Vec<T, A>
allocator_api
)Constructs a new, empty Vec<T, A>
.
The vector will not allocate until elements are pushed onto it.
§Examples
#![feature(allocator_api)]
use std::alloc::System;
let mut vec: Vec<i32, _> = Vec::new_in(System);
Sourcepub fn with_capacity_in(capacity: usize, alloc: A) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)Available on non-no_global_oom_handling
only.
pub fn with_capacity_in(capacity: usize, alloc: A) -> Vec<T, A>
allocator_api
)no_global_oom_handling
only.Constructs a new, empty Vec<T, A>
with at least the specified capacity
with the provided allocator.
The vector will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the vector will not allocate.
It is important to note that although the returned vector has the minimum capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.
If it is important to know the exact allocated capacity of a Vec
,
always use the capacity
method after construction.
For Vec<T, A>
where T
is a zero-sized type, there will be no allocation
and the capacity will always be usize::MAX
.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
#![feature(allocator_api)]
use std::alloc::System;
let mut vec = Vec::with_capacity_in(10, System);
// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);
// These are all done without reallocating...
for i in 0..10 {
vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);
// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);
// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<(), System>::with_capacity_in(10, System);
assert_eq!(vec_units.capacity(), usize::MAX);
Sourcepub fn try_with_capacity_in(
capacity: usize,
alloc: A,
) -> Result<Vec<T, A>, TryReserveError>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result<Vec<T, A>, TryReserveError>
allocator_api
)Constructs a new, empty Vec<T, A>
with at least the specified capacity
with the provided allocator.
The vector will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is zero, the vector will not allocate.
§Errors
Returns an error if the capacity exceeds isize::MAX
bytes,
or if the allocator reports allocation failure.
Sourcepub unsafe fn from_raw_parts_in(
ptr: *mut T,
length: usize,
capacity: usize,
alloc: A,
) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub unsafe fn from_raw_parts_in( ptr: *mut T, length: usize, capacity: usize, alloc: A, ) -> Vec<T, A>
allocator_api
)Creates a Vec<T, A>
directly from a pointer, a length, a capacity,
and an allocator.
§Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
ptr
must be currently allocated via the given allocatoralloc
.T
needs to have the same alignment as whatptr
was allocated with. (T
having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedealloc
requirement that memory must be allocated and deallocated with the same layout.)- The size of
T
times thecapacity
(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,dealloc
must be called with the same layoutsize
.) length
needs to be less than or equal tocapacity
.- The first
length
values must be properly initialized values of typeT
. capacity
needs to fit the layout size that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX
. See the safety documentation ofpointer::offset
.
These requirements are always upheld by any ptr
that has been allocated
via Vec<T, A>
. Other allocation sources are allowed if the invariants are
upheld.
Violating these may cause problems like corrupting the allocator’s
internal data structures. For example it is not safe
to build a Vec<u8>
from a pointer to a C char
array with length size_t
.
It’s also not safe to build one from a Vec<u16>
and its length, because
the allocator cares about the alignment, and these two types have different
alignments. The buffer was allocated with alignment 2 (for u16
), but after
turning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the
Vec<T>
which 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
#![feature(allocator_api)]
use std::alloc::System;
use std::ptr;
use std::mem;
let mut v = Vec::with_capacity_in(3, System);
v.push(1);
v.push(2);
v.push(3);
// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);
// Pull out the various important pieces of information about `v`
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();
let alloc = v.allocator();
unsafe {
// Overwrite memory with 4, 5, 6
for i in 0..len {
ptr::write(p.add(i), 4 + i);
}
// Put everything back together into a Vec
let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
assert_eq!(rebuilt, [4, 5, 6]);
}
Using memory that was allocated elsewhere:
#![feature(allocator_api)]
use std::alloc::{AllocError, Allocator, Global, Layout};
fn main() {
let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
let vec = unsafe {
let mem = match Global.allocate(layout) {
Ok(mem) => mem.cast::<u32>().as_ptr(),
Err(AllocError) => return,
};
mem.write(1_000_000);
Vec::from_raw_parts_in(mem, 1, 16, Global)
};
assert_eq!(vec, &[1_000_000]);
assert_eq!(vec.capacity(), 16);
}
Sourcepub unsafe fn from_parts_in(
ptr: NonNull<T>,
length: usize,
capacity: usize,
alloc: A,
) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub unsafe fn from_parts_in( ptr: NonNull<T>, length: usize, capacity: usize, alloc: A, ) -> Vec<T, A>
allocator_api
)Creates a Vec<T, A>
directly from a NonNull
pointer, a length, a capacity,
and an allocator.
§Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
ptr
must be currently allocated via the given allocatoralloc
.T
needs to have the same alignment as whatptr
was allocated with. (T
having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedealloc
requirement that memory must be allocated and deallocated with the same layout.)- The size of
T
times thecapacity
(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,dealloc
must be called with the same layoutsize
.) length
needs to be less than or equal tocapacity
.- The first
length
values must be properly initialized values of typeT
. capacity
needs to fit the layout size that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX
. See the safety documentation ofpointer::offset
.
These requirements are always upheld by any ptr
that has been allocated
via Vec<T, A>
. Other allocation sources are allowed if the invariants are
upheld.
Violating these may cause problems like corrupting the allocator’s
internal data structures. For example it is not safe
to build a Vec<u8>
from a pointer to a C char
array with length size_t
.
It’s also not safe to build one from a Vec<u16>
and its length, because
the allocator cares about the alignment, and these two types have different
alignments. The buffer was allocated with alignment 2 (for u16
), but after
turning it into a Vec<u8>
it’ll be deallocated with alignment 1.
The ownership of ptr
is effectively transferred to the
Vec<T>
which 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
#![feature(allocator_api, box_vec_non_null)]
use std::alloc::System;
use std::ptr::NonNull;
use std::mem;
let mut v = Vec::with_capacity_in(3, System);
v.push(1);
v.push(2);
v.push(3);
// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);
// Pull out the various important pieces of information about `v`
let p = unsafe { NonNull::new_unchecked(v.as_mut_ptr()) };
let len = v.len();
let cap = v.capacity();
let alloc = v.allocator();
unsafe {
// Overwrite memory with 4, 5, 6
for i in 0..len {
p.add(i).write(4 + i);
}
// Put everything back together into a Vec
let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone());
assert_eq!(rebuilt, [4, 5, 6]);
}
Using memory that was allocated elsewhere:
#![feature(allocator_api, box_vec_non_null)]
use std::alloc::{AllocError, Allocator, Global, Layout};
fn main() {
let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
let vec = unsafe {
let mem = match Global.allocate(layout) {
Ok(mem) => mem.cast::<u32>(),
Err(AllocError) => return,
};
mem.write(1_000_000);
Vec::from_parts_in(mem, 1, 16, Global)
};
assert_eq!(vec, &[1_000_000]);
assert_eq!(vec.capacity(), 16);
}
Sourcepub fn into_raw_parts(self) -> (*mut T, usize, usize)
🔬This is a nightly-only experimental API. (vec_into_raw_parts
)
pub fn into_raw_parts(self) -> (*mut T, usize, usize)
vec_into_raw_parts
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity)
.
Returns the raw pointer to the underlying data, the length of
the vector (in elements), and the allocated capacity of the
data (in elements). These are the same arguments in the same
order as the arguments to from_raw_parts
.
After calling this function, the caller is responsible for the
memory previously managed by the Vec
. The only way to do
this is to convert the raw pointer, length, and capacity back
into a Vec
with the from_raw_parts
function, allowing
the destructor to perform the cleanup.
§Examples
#![feature(vec_into_raw_parts)]
let v: Vec<i32> = vec![-1, 0, 1];
let (ptr, len, cap) = v.into_raw_parts();
let rebuilt = unsafe {
// We can now make changes to the components, such as
// transmuting the raw pointer to a compatible type.
let ptr = ptr as *mut u32;
Vec::from_raw_parts(ptr, len, cap)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
Sourcepub fn into_parts(self) -> (NonNull<T>, usize, usize)
🔬This is a nightly-only experimental API. (box_vec_non_null
)
pub fn into_parts(self) -> (NonNull<T>, usize, usize)
box_vec_non_null
)Decomposes a Vec<T>
into its raw components: (NonNull pointer, length, capacity)
.
Returns the NonNull
pointer to the underlying data, the length of
the vector (in elements), and the allocated capacity of the
data (in elements). These are the same arguments in the same
order as the arguments to from_parts
.
After calling this function, the caller is responsible for the
memory previously managed by the Vec
. The only way to do
this is to convert the NonNull
pointer, length, and capacity back
into a Vec
with the from_parts
function, allowing
the destructor to perform the cleanup.
§Examples
#![feature(vec_into_raw_parts, box_vec_non_null)]
let v: Vec<i32> = vec![-1, 0, 1];
let (ptr, len, cap) = v.into_parts();
let rebuilt = unsafe {
// We can now make changes to the components, such as
// transmuting the raw pointer to a compatible type.
let ptr = ptr.cast::<u32>();
Vec::from_parts(ptr, len, cap)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
Sourcepub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A)
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A)
allocator_api
)Decomposes a Vec<T>
into its raw components: (pointer, length, capacity, allocator)
.
Returns the raw pointer to the underlying data, the length of the vector (in elements),
the allocated capacity of the data (in elements), and the allocator. These are the same
arguments in the same order as the arguments to from_raw_parts_in
.
After calling this function, the caller is responsible for the
memory previously managed by the Vec
. The only way to do
this is to convert the raw pointer, length, and capacity back
into a Vec
with the from_raw_parts_in
function, allowing
the destructor to perform the cleanup.
§Examples
#![feature(allocator_api, vec_into_raw_parts)]
use std::alloc::System;
let mut v: Vec<i32, System> = Vec::new_in(System);
v.push(-1);
v.push(0);
v.push(1);
let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
let rebuilt = unsafe {
// We can now make changes to the components, such as
// transmuting the raw pointer to a compatible type.
let ptr = ptr as *mut u32;
Vec::from_raw_parts_in(ptr, len, cap, alloc)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
Sourcepub fn into_parts_with_alloc(self) -> (NonNull<T>, usize, usize, A)
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn into_parts_with_alloc(self) -> (NonNull<T>, usize, usize, A)
allocator_api
)Decomposes a Vec<T>
into its raw components: (NonNull pointer, length, capacity, allocator)
.
Returns the NonNull
pointer to the underlying data, the length of the vector (in elements),
the allocated capacity of the data (in elements), and the allocator. These are the same
arguments in the same order as the arguments to from_parts_in
.
After calling this function, the caller is responsible for the
memory previously managed by the Vec
. The only way to do
this is to convert the NonNull
pointer, length, and capacity back
into a Vec
with the from_parts_in
function, allowing
the destructor to perform the cleanup.
§Examples
#![feature(allocator_api, vec_into_raw_parts, box_vec_non_null)]
use std::alloc::System;
let mut v: Vec<i32, System> = Vec::new_in(System);
v.push(-1);
v.push(0);
v.push(1);
let (ptr, len, cap, alloc) = v.into_parts_with_alloc();
let rebuilt = unsafe {
// We can now make changes to the components, such as
// transmuting the raw pointer to a compatible type.
let ptr = ptr.cast::<u32>();
Vec::from_parts_in(ptr, len, cap, alloc)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
1.0.0 (const: unstable) · Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the total number of elements the vector can hold without reallocating.
§Examples
let mut vec: Vec<i32> = Vec::with_capacity(10);
vec.push(42);
assert!(vec.capacity() >= 10);
1.0.0 · Sourcepub fn reserve(&mut self, additional: usize)
Available on non-no_global_oom_handling
only.
pub fn reserve(&mut self, additional: usize)
no_global_oom_handling
only.Reserves capacity for at least additional
more elements to be inserted
in the given Vec<T>
. The collection may reserve more space to
speculatively avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1];
vec.reserve(10);
assert!(vec.capacity() >= 11);
1.0.0 · Sourcepub fn reserve_exact(&mut self, additional: usize)
Available on non-no_global_oom_handling
only.
pub fn reserve_exact(&mut self, additional: usize)
no_global_oom_handling
only.Reserves the minimum capacity for at least additional
more elements to
be inserted in the given Vec<T>
. Unlike reserve
, this will not
deliberately over-allocate to speculatively avoid frequent allocations.
After calling reserve_exact
, capacity will be greater than or equal to
self.len() + additional
. Does nothing if the capacity is already
sufficient.
Note that the allocator may give the collection more space than it
requests. Therefore, capacity can not be relied upon to be precisely
minimal. Prefer reserve
if future insertions are expected.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1];
vec.reserve_exact(10);
assert!(vec.capacity() >= 11);
1.57.0 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the given Vec<T>
. The collection may reserve more space to speculatively avoid
frequent reallocations. After calling try_reserve
, capacity will be
greater than or equal to self.len() + additional
if it returns
Ok(())
. Does nothing if capacity is already sufficient. This method
preserves the contents even if an error occurs.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
use std::collections::TryReserveError;
fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
let mut output = Vec::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve(data.len())?;
// Now we know this can't OOM in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.57.0 · Sourcepub fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), TryReserveError>
pub fn try_reserve_exact( &mut self, additional: usize, ) -> Result<(), TryReserveError>
Tries to reserve the minimum capacity for at least additional
elements to be inserted in the given Vec<T>
. Unlike try_reserve
,
this will not deliberately over-allocate to speculatively avoid frequent
allocations. After calling try_reserve_exact
, capacity will be greater
than or equal to self.len() + additional
if it returns Ok(())
.
Does nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it
requests. Therefore, capacity can not be relied upon to be precisely
minimal. Prefer try_reserve
if future insertions are expected.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
use std::collections::TryReserveError;
fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
let mut output = Vec::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve_exact(data.len())?;
// Now we know this can't OOM in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.0.0 · Sourcepub fn shrink_to_fit(&mut self)
Available on non-no_global_oom_handling
only.
pub fn shrink_to_fit(&mut self)
no_global_oom_handling
only.Shrinks the capacity of the vector as much as possible.
The behavior of this method depends on the allocator, which may either shrink the vector
in-place or reallocate. The resulting vector might still have some excess capacity, just as
is the case for with_capacity
. See Allocator::shrink
for more details.
§Examples
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to_fit();
assert!(vec.capacity() >= 3);
1.56.0 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
Available on non-no_global_oom_handling
only.
pub fn shrink_to(&mut self, min_capacity: usize)
no_global_oom_handling
only.Shrinks the capacity of the vector with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
§Examples
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to(4);
assert!(vec.capacity() >= 4);
vec.shrink_to(0);
assert!(vec.capacity() >= 3);
1.0.0 · Sourcepub fn into_boxed_slice(self) -> Box<[T], A>
Available on non-no_global_oom_handling
only.
pub fn into_boxed_slice(self) -> Box<[T], A>
no_global_oom_handling
only.Converts the vector into Box<[T]>
.
Before doing the conversion, this method discards excess capacity like shrink_to_fit
.
§Examples
let v = vec![1, 2, 3];
let slice = v.into_boxed_slice();
Any excess capacity is removed:
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
let slice = vec.into_boxed_slice();
assert_eq!(slice.into_vec().capacity(), 3);
1.0.0 · Sourcepub fn truncate(&mut self, len: usize)
pub fn truncate(&mut self, len: usize)
Shortens the vector, keeping the first len
elements and dropping
the rest.
If len
is greater or equal to the vector’s current length, this has
no effect.
The drain
method can emulate truncate
, but causes the excess
elements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity of the vector.
§Examples
Truncating a five element vector to two elements:
let mut vec = vec![1, 2, 3, 4, 5];
vec.truncate(2);
assert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current
length:
let mut vec = vec![1, 2, 3];
vec.truncate(8);
assert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
method.
let mut vec = vec![1, 2, 3];
vec.truncate(0);
assert_eq!(vec, []);
1.7.0 (const: unstable) · Sourcepub fn as_slice(&self) -> &[T]
pub fn as_slice(&self) -> &[T]
Extracts a slice containing the entire vector.
Equivalent to &s[..]
.
§Examples
use std::io::{self, Write};
let buffer = vec![1, 2, 3, 5, 8];
io::sink().write(buffer.as_slice()).unwrap();
1.7.0 (const: unstable) · Sourcepub fn as_mut_slice(&mut self) -> &mut [T]
pub fn as_mut_slice(&mut self) -> &mut [T]
Extracts a mutable slice of the entire vector.
Equivalent to &mut s[..]
.
§Examples
use std::io::{self, Read};
let mut buffer = vec![0; 3];
io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1.37.0 (const: unstable) · Sourcepub fn as_ptr(&self) -> *const T
pub fn as_ptr(&self) -> *const T
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
The caller must also ensure that the memory the pointer (non-transitively) points to
is never written to (except inside an UnsafeCell
) using this pointer or any pointer
derived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize mutable references to the slice,
or mutable references to specific elements you are planning on accessing through this pointer,
as well as writing to those elements, may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
let x = vec![1, 2, 4];
let x_ptr = x.as_ptr();
unsafe {
for i in 0..x.len() {
assert_eq!(*x_ptr.add(i), 1 << i);
}
}
Due to the aliasing guarantee, the following code is legal:
unsafe {
let mut v = vec![0, 1, 2];
let ptr1 = v.as_ptr();
let _ = ptr1.read();
let ptr2 = v.as_mut_ptr().offset(2);
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`
// because it mutated a different element:
let _ = ptr1.read();
}
1.37.0 (const: unstable) · Sourcepub fn as_mut_ptr(&mut self) -> *mut T
pub fn as_mut_ptr(&mut self) -> *mut T
Returns a raw mutable pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize references to the slice,
or references to specific elements you are planning on accessing through this pointer,
may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_mut_ptr();
// Initialize elements via raw pointer writes, then set length.
unsafe {
for i in 0..size {
*x_ptr.add(i) = i as i32;
}
x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
unsafe {
let mut v = vec![0];
let ptr1 = v.as_mut_ptr();
ptr1.write(1);
let ptr2 = v.as_mut_ptr();
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`:
ptr1.write(3);
}
Sourcepub fn as_non_null(&mut self) -> NonNull<T>
🔬This is a nightly-only experimental API. (box_vec_non_null
)
pub fn as_non_null(&mut self) -> NonNull<T>
box_vec_non_null
)Returns a NonNull
pointer to the vector’s buffer, or a dangling
NonNull
pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize references to the slice,
or references to specific elements you are planning on accessing through this pointer,
may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
#![feature(box_vec_non_null)]
// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_non_null();
// Initialize elements via raw pointer writes, then set length.
unsafe {
for i in 0..size {
x_ptr.add(i).write(i as i32);
}
x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
#![feature(box_vec_non_null)]
unsafe {
let mut v = vec![0];
let ptr1 = v.as_non_null();
ptr1.write(1);
let ptr2 = v.as_non_null();
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`:
ptr1.write(3);
}
Sourcepub fn allocator(&self) -> &A
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn allocator(&self) -> &A
allocator_api
)Returns a reference to the underlying allocator.
1.0.0 · Sourcepub unsafe fn set_len(&mut self, new_len: usize)
pub unsafe fn set_len(&mut self, new_len: usize)
Forces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal
invariants of the type. Normally changing the length of a vector
is done using one of the safe operations instead, such as
truncate
, resize
, extend
, or clear
.
§Safety
new_len
must be less than or equal tocapacity()
.- The elements at
old_len..new_len
must be initialized.
§Examples
See spare_capacity_mut()
for an example with safe
initialization of capacity elements and use of this method.
set_len()
can be useful for situations in which the vector
is serving as a buffer for other code, particularly over FFI:
pub fn get_dictionary(&self) -> Option<Vec<u8>> {
// Per the FFI method's docs, "32768 bytes is always enough".
let mut dict = Vec::with_capacity(32_768);
let mut dict_length = 0;
// SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
// 1. `dict_length` elements were initialized.
// 2. `dict_length` <= the capacity (32_768)
// which makes `set_len` safe to call.
unsafe {
// Make the FFI call...
let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
if r == Z_OK {
// ...and update the length to what was initialized.
dict.set_len(dict_length);
Some(dict)
} else {
None
}
}
}
While the following example is sound, there is a memory leak since
the inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],
vec![0, 1, 0],
vec![0, 0, 1]];
// SAFETY:
// 1. `old_len..0` is empty so no elements need to be initialized.
// 2. `0 <= capacity` always holds whatever `capacity` is.
unsafe {
vec.set_len(0);
}
Normally, here, one would use clear
instead to correctly drop
the contents and thus not leak memory.
1.0.0 · Sourcepub fn swap_remove(&mut self, index: usize) -> T
pub fn swap_remove(&mut self, index: usize) -> T
Removes an element from the vector and returns it.
The removed element is replaced by the last element of the vector.
This does not preserve ordering of the remaining elements, but is O(1).
If you need to preserve the element order, use remove
instead.
§Panics
Panics if index
is out of bounds.
§Examples
let mut v = vec!["foo", "bar", "baz", "qux"];
assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);
assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);
1.0.0 · Sourcepub fn insert(&mut self, index: usize, element: T)
Available on non-no_global_oom_handling
only.
pub fn insert(&mut self, index: usize, element: T)
no_global_oom_handling
only.Inserts an element at position index
within the vector, shifting all
elements after it to the right.
§Panics
Panics if index > len
.
§Examples
let mut vec = vec!['a', 'b', 'c'];
vec.insert(1, 'd');
assert_eq!(vec, ['a', 'd', 'b', 'c']);
vec.insert(4, 'e');
assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
§Time complexity
Takes O(Vec::len
) time. All items after the insertion index must be
shifted to the right. In the worst case, all elements are shifted when
the insertion index is 0.
1.0.0 · Sourcepub fn remove(&mut self, index: usize) -> T
pub fn remove(&mut self, index: usize) -> T
Removes and returns the element at position index
within the vector,
shifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a
worst-case performance of O(n). If you don’t need the order of elements
to be preserved, use swap_remove
instead. If you’d like to remove
elements from the beginning of the Vec
, consider using
VecDeque::pop_front
instead.
§Panics
Panics if index
is out of bounds.
§Examples
let mut v = vec!['a', 'b', 'c'];
assert_eq!(v.remove(1), 'b');
assert_eq!(v, ['a', 'c']);
1.0.0 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns false
.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
§Examples
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
let mut vec = vec![1, 2, 3, 4, 5];
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
vec.retain(|_| *iter.next().unwrap());
assert_eq!(vec, [2, 3, 5]);
1.61.0 · Sourcepub fn retain_mut<F>(&mut self, f: F)
pub fn retain_mut<F>(&mut self, f: F)
Retains only the elements specified by the predicate, passing a mutable reference to it.
In other words, remove all elements e
such that f(&mut e)
returns false
.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
§Examples
let mut vec = vec![1, 2, 3, 4];
vec.retain_mut(|x| if *x <= 3 {
*x += 1;
true
} else {
false
});
assert_eq!(vec, [2, 3, 4]);
1.16.0 · Sourcepub fn dedup_by_key<F, K>(&mut self, key: F)
pub fn dedup_by_key<F, K>(&mut self, key: F)
Removes all but the first of consecutive elements in the vector that resolve to the same key.
If the vector is sorted, this removes all duplicates.
§Examples
let mut vec = vec![10, 20, 21, 30, 20];
vec.dedup_by_key(|i| *i / 10);
assert_eq!(vec, [10, 20, 30, 20]);
1.16.0 · Sourcepub fn dedup_by<F>(&mut self, same_bucket: F)
pub fn dedup_by<F>(&mut self, same_bucket: F)
Removes all but the first of consecutive elements in the vector satisfying a given equality relation.
The same_bucket
function is passed references to two elements from the vector and
must determine if the elements compare equal. The elements are passed in opposite order
from their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
§Examples
let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1.0.0 · Sourcepub fn push(&mut self, value: T)
Available on non-no_global_oom_handling
only.
pub fn push(&mut self, value: T)
no_global_oom_handling
only.Appends an element to the back of a collection.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);
§Time complexity
Takes amortized O(1) time. If the vector’s length would exceed its capacity after the push, O(capacity) time is taken to copy the vector’s elements to a larger allocation. This expensive operation is offset by the capacity O(1) insertions it allows.
Sourcepub fn push_within_capacity(&mut self, value: T) -> Result<(), T>
🔬This is a nightly-only experimental API. (vec_push_within_capacity
)
pub fn push_within_capacity(&mut self, value: T) -> Result<(), T>
vec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned with the element.
Unlike push
this method will not reallocate when there’s insufficient capacity.
The caller should use reserve
or try_reserve
to ensure that there is enough capacity.
§Examples
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]
use std::collections::TryReserveError;
fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
let mut vec = Vec::new();
for value in iter {
if let Err(value) = vec.push_within_capacity(value) {
vec.try_reserve(1)?;
// this cannot fail, the previous line either returned or added at least 1 free slot
let _ = vec.push_within_capacity(value);
}
}
Ok(vec)
}
assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
§Time complexity
Takes O(1) time.
1.0.0 · Sourcepub fn pop(&mut self) -> Option<T>
pub fn pop(&mut self) -> Option<T>
Removes the last element from a vector and returns it, or None
if it
is empty.
If you’d like to pop the first element, consider using
VecDeque::pop_front
instead.
§Examples
let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);
§Time complexity
Takes O(1) time.
Sourcepub fn pop_if<F>(&mut self, f: F) -> Option<T>
🔬This is a nightly-only experimental API. (vec_pop_if
)
pub fn pop_if<F>(&mut self, f: F) -> Option<T>
vec_pop_if
)Removes and returns the last element in a vector if the predicate
returns true
, or None
if the predicate returns false or the vector
is empty.
§Examples
#![feature(vec_pop_if)]
let mut vec = vec![1, 2, 3, 4];
let pred = |x: &mut i32| *x % 2 == 0;
assert_eq!(vec.pop_if(pred), Some(4));
assert_eq!(vec, [1, 2, 3]);
assert_eq!(vec.pop_if(pred), None);
1.4.0 · Sourcepub fn append(&mut self, other: &mut Vec<T, A>)
Available on non-no_global_oom_handling
only.
pub fn append(&mut self, other: &mut Vec<T, A>)
no_global_oom_handling
only.1.6.0 · Sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘwhere
R: RangeBounds<usize>,
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘwhere
R: RangeBounds<usize>,
Removes the specified range from the vector in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.
The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
§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.
§Leaking
If the returned iterator goes out of scope without being dropped (due to
mem::forget
, for example), the vector may have lost and leaked
elements arbitrarily, including elements outside the range.
§Examples
let mut v = vec![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);
// A full range clears the vector, like `clear()` does
v.drain(..);
assert_eq!(v, &[]);
1.0.0 · Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the vector, removing all values.
Note that this method has no effect on the allocated capacity of the vector.
§Examples
let mut v = vec![1, 2, 3];
v.clear();
assert!(v.is_empty());
1.0.0 (const: unstable) · Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the vector, also referred to as its ‘length’.
§Examples
let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);
1.0.0 (const: unstable) · Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the vector contains no elements.
§Examples
let mut v = Vec::new();
assert!(v.is_empty());
v.push(1);
assert!(!v.is_empty());
1.4.0 · Sourcepub fn split_off(&mut self, at: usize) -> Vec<T, A>where
A: Clone,
Available on non-no_global_oom_handling
only.
pub fn split_off(&mut self, at: usize) -> Vec<T, A>where
A: Clone,
no_global_oom_handling
only.Splits the collection into two at the given index.
Returns a newly allocated vector containing the elements in the range
[at, len)
. After the call, the original vector will be left containing
the elements [0, at)
with its previous capacity unchanged.
- If you want to take ownership of the entire contents and capacity of
the vector, see
mem::take
ormem::replace
. - If you don’t need the returned vector at all, see
Vec::truncate
. - If you want to take ownership of an arbitrary subslice, or you don’t
necessarily want to store the removed items in a vector, see
Vec::drain
.
§Panics
Panics if at > len
.
§Examples
let mut vec = vec!['a', 'b', 'c'];
let vec2 = vec.split_off(1);
assert_eq!(vec, ['a']);
assert_eq!(vec2, ['b', 'c']);
1.33.0 · Sourcepub fn resize_with<F>(&mut self, new_len: usize, f: F)where
F: FnMut() -> T,
Available on non-no_global_oom_handling
only.
pub fn resize_with<F>(&mut self, new_len: usize, f: F)where
F: FnMut() -> T,
no_global_oom_handling
only.Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the
difference, with each additional slot filled with the result of
calling the closure f
. The return values from f
will end up
in the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If
you’d rather Clone
a given value, use Vec::resize
. If you
want to use the Default
trait to generate values, you can
pass Default::default
as the second argument.
§Examples
let mut vec = vec![1, 2, 3];
vec.resize_with(5, Default::default);
assert_eq!(vec, [1, 2, 3, 0, 0]);
let mut vec = vec![];
let mut p = 1;
vec.resize_with(4, || { p *= 2; p });
assert_eq!(vec, [2, 4, 8, 16]);
1.47.0 · Sourcepub fn leak<'a>(self) -> &'a mut [T]where
A: 'a,
pub fn leak<'a>(self) -> &'a mut [T]where
A: 'a,
Consumes and leaks the Vec
, returning a mutable reference to the contents,
&'a mut [T]
.
Note that the type T
must outlive the chosen lifetime 'a
. If the type
has only static references, or none at all, then this may be chosen to be
'static
.
As of Rust 1.57, this method does not reallocate or shrink the Vec
,
so the leaked allocation may include unused capacity that is not part
of the returned slice.
This function is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak.
§Examples
Simple usage:
let x = vec![1, 2, 3];
let static_ref: &'static mut [usize] = x.leak();
static_ref[0] += 1;
assert_eq!(static_ref, &[2, 2, 3]);
1.60.0 · Sourcepub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]
Returns the remaining spare capacity of the vector as a slice of
MaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by
reading from a file) before marking the data as initialized using the
set_len
method.
§Examples
// Allocate vector big enough for 10 elements.
let mut v = Vec::with_capacity(10);
// Fill in the first 3 elements.
let uninit = v.spare_capacity_mut();
uninit[0].write(0);
uninit[1].write(1);
uninit[2].write(2);
// Mark the first 3 elements of the vector as being initialized.
unsafe {
v.set_len(3);
}
assert_eq!(&v, &[0, 1, 2]);
Sourcepub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])
🔬This is a nightly-only experimental API. (vec_split_at_spare
)
pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare
capacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data
(e.g. by reading from a file) before marking the data as initialized using
the set_len
method.
Note that this is a low-level API, which should be used with care for
optimization purposes. If you need to append data to a Vec
you can use push
, extend
, extend_from_slice
,
extend_from_within
, insert
, append
, resize
or
resize_with
, depending on your exact needs.
§Examples
#![feature(vec_split_at_spare)]
let mut v = vec![1, 1, 2];
// Reserve additional space big enough for 10 elements.
v.reserve(10);
let (init, uninit) = v.split_at_spare_mut();
let sum = init.iter().copied().sum::<u32>();
// Fill in the next 4 elements.
uninit[0].write(sum);
uninit[1].write(sum * 2);
uninit[2].write(sum * 3);
uninit[3].write(sum * 4);
// Mark the 4 elements of the vector as being initialized.
unsafe {
let len = v.len();
v.set_len(len + 4);
}
assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
Trait Implementations
§impl<'a, A> Arbitrary<'a> for Vec<A>where
A: Arbitrary<'a>,
impl<'a, A> Arbitrary<'a> for Vec<A>where
A: Arbitrary<'a>,
§fn arbitrary(u: &mut Unstructured<'a>) -> Result<Vec<A>, Error>
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Vec<A>, Error>
Self
from the given unstructured data. Read more§fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Vec<A>, Error>
fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Vec<A>, Error>
Self
from the entirety of the given
unstructured data. Read more§impl<A> Arbitrary for Vec<A>where
A: Arbitrary,
impl<A> Arbitrary for Vec<A>where
A: Arbitrary,
§type Parameters = (SizeRange, <A as Arbitrary>::Parameters)
type Parameters = (SizeRange, <A as Arbitrary>::Parameters)
arbitrary_with
accepts for configuration
of the generated Strategy
. Parameters must implement Default
.§type Strategy = VecStrategy<<A as Arbitrary>::Strategy>
type Strategy = VecStrategy<<A as Arbitrary>::Strategy>
Strategy
used to generate values of type Self
.§fn arbitrary_with(
args: <Vec<A> as Arbitrary>::Parameters,
) -> <Vec<A> as Arbitrary>::Strategy ⓘ
fn arbitrary_with( args: <Vec<A> as Arbitrary>::Parameters, ) -> <Vec<A> as Arbitrary>::Strategy ⓘ
§impl<A> ArbitraryF1<A> for Vec<A>where
A: Debug,
impl<A> ArbitraryF1<A> for Vec<A>where
A: Debug,
§type Parameters = SizeRange
type Parameters = SizeRange
lift1_with
accepts for
configuration of the lifted and generated Strategy
. Parameters
must implement Default
.§fn lift1_with<S>(
base: S,
args: <Vec<A> as ArbitraryF1<A>>::Parameters,
) -> BoxedStrategy<Vec<A>>where
S: Strategy<Value = A> + 'static,
fn lift1_with<S>(
base: S,
args: <Vec<A> as ArbitraryF1<A>>::Parameters,
) -> BoxedStrategy<Vec<A>>where
S: Strategy<Value = A> + 'static,
1.0.0 · Source§impl<T, A> BorrowMut<[T]> for Vec<T, A>where
A: Allocator,
impl<T, A> BorrowMut<[T]> for Vec<T, A>where
A: Allocator,
Source§fn borrow_mut(&mut self) -> &mut [T]
fn borrow_mut(&mut self) -> &mut [T]
1.0.0 · Source§impl<T, A> Clone for Vec<T, A>
Available on non-no_global_oom_handling
only.
impl<T, A> Clone for Vec<T, A>
no_global_oom_handling
only.Source§fn clone_from(&mut self, source: &Vec<T, A>)
fn clone_from(&mut self, source: &Vec<T, A>)
Overwrites the contents of self
with a clone of the contents of source
.
This method is preferred over simply assigning source.clone()
to self
,
as it avoids reallocation if possible. Additionally, if the element type
T
overrides clone_from()
, this will reuse the resources of self
’s
elements as well.
§Examples
let x = vec![5, 6, 7];
let mut y = vec![8, 9, 10];
let yp: *const i32 = y.as_ptr();
y.clone_from(&x);
// The value is the same
assert_eq!(x, y);
// And no reallocation occurred
assert_eq!(yp, y.as_ptr());
§impl<T> Codec for Vec<T>where
T: Codec + TlsListElement + Debug,
Implement Codec
for lists of elements that implement TlsListElement
.
impl<T> Codec for Vec<T>where
T: Codec + TlsListElement + Debug,
Implement Codec
for lists of elements that implement TlsListElement
.
TlsListElement
provides the size of the length prefix for the list.
§fn encode(&self, bytes: &mut Vec<u8>)
fn encode(&self, bytes: &mut Vec<u8>)
§fn read(r: &mut Reader<'_>) -> Result<Vec<T>, InvalidMessage>
fn read(r: &mut Reader<'_>) -> Result<Vec<T>, InvalidMessage>
§fn get_encoding(&self) -> Vec<u8> ⓘ
fn get_encoding(&self) -> Vec<u8> ⓘ
§fn read_bytes(bytes: &[u8]) -> Result<Self, InvalidMessage>
fn read_bytes(bytes: &[u8]) -> Result<Self, InvalidMessage>
§impl<'a, T> DecodeValue<'a> for Vec<T>where
T: Decode<'a>,
Available on crate feature alloc
only.
impl<'a, T> DecodeValue<'a> for Vec<T>where
T: Decode<'a>,
alloc
only.§fn decode_value<R>(reader: &mut R, header: Header) -> Result<Vec<T>, Error>where
R: Reader<'a>,
fn decode_value<R>(reader: &mut R, header: Header) -> Result<Vec<T>, Error>where
R: Reader<'a>,
Reader
].Source§impl<'de, T> Deserialize<'de> for Vec<T>where
T: Deserialize<'de>,
Available on crate features std
or alloc
only.
impl<'de, T> Deserialize<'de> for Vec<T>where
T: Deserialize<'de>,
std
or alloc
only.Source§fn deserialize<D>(
deserializer: D,
) -> Result<Vec<T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Vec<T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
§impl<T> EncodeAsVarULE<[T]> for Vec<T>where
T: ULE,
impl<T> EncodeAsVarULE<[T]> for Vec<T>where
T: ULE,
§fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
cb
with a piecewise list of byte slices that when concatenated
produce the memory pattern of the corresponding instance of T
. Read more§fn encode_var_ule_len(&self) -> usize
fn encode_var_ule_len(&self) -> usize
VarULE
] type§fn encode_var_ule_write(&self, dst: &mut [u8])
fn encode_var_ule_write(&self, dst: &mut [u8])
VarULE
] type to the dst
buffer. dst
should
be the size of [Self::encode_var_ule_len()
]§impl<T, E, F> EncodeAsVarULE<VarZeroSlice<T, F>> for Vec<E>where
T: VarULE + ?Sized,
E: EncodeAsVarULE<T>,
F: VarZeroVecFormat,
impl<T, E, F> EncodeAsVarULE<VarZeroSlice<T, F>> for Vec<E>where
T: VarULE + ?Sized,
E: EncodeAsVarULE<T>,
F: VarZeroVecFormat,
§fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R
fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R
cb
with a piecewise list of byte slices that when concatenated
produce the memory pattern of the corresponding instance of T
. Read more§fn encode_var_ule_len(&self) -> usize
fn encode_var_ule_len(&self) -> usize
VarULE
] type§fn encode_var_ule_write(&self, dst: &mut [u8])
fn encode_var_ule_write(&self, dst: &mut [u8])
VarULE
] type to the dst
buffer. dst
should
be the size of [Self::encode_var_ule_len()
]§impl<T> EncodeAsVarULE<ZeroSlice<T>> for Vec<T>where
T: AsULE + 'static,
impl<T> EncodeAsVarULE<ZeroSlice<T>> for Vec<T>where
T: AsULE + 'static,
§fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R
fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R
cb
with a piecewise list of byte slices that when concatenated
produce the memory pattern of the corresponding instance of T
. Read more§fn encode_var_ule_len(&self) -> usize
fn encode_var_ule_len(&self) -> usize
VarULE
] type§fn encode_var_ule_write(&self, dst: &mut [u8])
fn encode_var_ule_write(&self, dst: &mut [u8])
VarULE
] type to the dst
buffer. dst
should
be the size of [Self::encode_var_ule_len()
]§impl<T> EncodeValue for Vec<T>where
T: Encode,
Available on crate feature alloc
only.
impl<T> EncodeValue for Vec<T>where
T: Encode,
alloc
only.1.2.0 · Source§impl<'a, T, A> Extend<&'a T> for Vec<T, A>
Available on non-no_global_oom_handling
only.Extend implementation that copies elements out of references before pushing them onto the Vec.
impl<'a, T, A> Extend<&'a T> for Vec<T, A>
no_global_oom_handling
only.Extend implementation that copies elements out of references before pushing them onto the Vec.
This implementation is specialized for slice iterators, where it uses copy_from_slice
to
append the entire slice at once.
Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a T>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a T>,
Source§fn extend_one(&mut self, _: &'a T)
fn extend_one(&mut self, _: &'a T)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)1.0.0 · Source§impl<T, A> Extend<T> for Vec<T, A>where
A: Allocator,
Available on non-no_global_oom_handling
only.
impl<T, A> Extend<T> for Vec<T, A>where
A: Allocator,
no_global_oom_handling
only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = T>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = T>,
Source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)1.0.0 · Source§impl<T> From<&[T]> for Vec<T>where
T: Clone,
Available on non-no_global_oom_handling
only.
impl<T> From<&[T]> for Vec<T>where
T: Clone,
no_global_oom_handling
only.1.74.0 · Source§impl<T, const N: usize> From<&[T; N]> for Vec<T>where
T: Clone,
Available on non-no_global_oom_handling
only.
impl<T, const N: usize> From<&[T; N]> for Vec<T>where
T: Clone,
no_global_oom_handling
only.1.19.0 · Source§impl<T> From<&mut [T]> for Vec<T>where
T: Clone,
Available on non-no_global_oom_handling
only.
impl<T> From<&mut [T]> for Vec<T>where
T: Clone,
no_global_oom_handling
only.1.74.0 · Source§impl<T, const N: usize> From<&mut [T; N]> for Vec<T>where
T: Clone,
Available on non-no_global_oom_handling
only.
impl<T, const N: usize> From<&mut [T; N]> for Vec<T>where
T: Clone,
no_global_oom_handling
only.1.44.0 · Source§impl<T, const N: usize> From<[T; N]> for Vec<T>
Available on non-no_global_oom_handling
only.
impl<T, const N: usize> From<[T; N]> for Vec<T>
no_global_oom_handling
only.1.5.0 · Source§impl<T, A> From<BinaryHeap<T, A>> for Vec<T, A>where
A: Allocator,
impl<T, A> From<BinaryHeap<T, A>> for Vec<T, A>where
A: Allocator,
Source§fn from(heap: BinaryHeap<T, A>) -> Vec<T, A>
fn from(heap: BinaryHeap<T, A>) -> Vec<T, A>
Converts a BinaryHeap<T>
into a Vec<T>
.
This conversion requires no data movement or allocation, and has constant time complexity.
1.14.0 · Source§impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
Source§fn from(s: Cow<'a, [T]>) -> Vec<T>
fn from(s: Cow<'a, [T]>) -> Vec<T>
Converts a clone-on-write slice into a vector.
If s
already owns a Vec<T>
, it will be returned directly.
If s
is borrowing a slice, a new Vec<T>
will be allocated and
filled by cloning s
’s items into it.
§Examples
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
assert_eq!(Vec::from(o), Vec::from(b));
1.10.0 · Source§impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where
A: Allocator,
impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where
A: Allocator,
Source§fn from(other: VecDeque<T, A>) -> Vec<T, A>
fn from(other: VecDeque<T, A>) -> Vec<T, A>
Turn a VecDeque<T>
into a Vec<T>
.
This never needs to re-allocate, but does need to do O(n) data movement if the circular buffer doesn’t happen to be at the beginning of the allocation.
§Examples
use std::collections::VecDeque;
// This one is *O*(1).
let deque: VecDeque<_> = (1..5).collect();
let ptr = deque.as_slices().0.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);
// This one needs data rearranging.
let mut deque: VecDeque<_> = (1..5).collect();
deque.push_front(9);
deque.push_front(8);
let ptr = deque.as_slices().1.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);
1.0.0 · Source§impl<T> FromIterator<T> for Vec<T>
Available on non-no_global_oom_handling
only.Collects an iterator into a Vec, commonly called via Iterator::collect()
impl<T> FromIterator<T> for Vec<T>
no_global_oom_handling
only.Collects an iterator into a Vec, commonly called via Iterator::collect()
§Allocation behavior
In general Vec
does not guarantee any particular growth or allocation strategy.
That also applies to this trait impl.
Note: This section covers implementation details and is therefore exempt from stability guarantees.
Vec may use any or none of the following strategies, depending on the supplied iterator:
- preallocate based on
Iterator::size_hint()
- and panic if the number of items is outside the provided lower/upper bounds
- use an amortized growth strategy similar to
pushing
one item at a time - perform the iteration in-place on the original allocation backing the iterator
The last case warrants some attention. It is an optimization that in many cases reduces peak memory
consumption and improves cache locality. But when big, short-lived allocations are created,
only a small fraction of their items get collected, no further use is made of the spare capacity
and the resulting Vec
is moved into a longer-lived structure, then this can lead to the large
allocations having their lifetimes unnecessarily extended which can result in increased memory
footprint.
In cases where this is an issue, the excess capacity can be discarded with Vec::shrink_to()
,
Vec::shrink_to_fit()
or by collecting into Box<[T]>
instead, which additionally reduces
the size of the long-lived struct.
static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
for i in 0..10 {
let big_temporary: Vec<u16> = (0..1024).collect();
// discard most items
let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
// without this a lot of unused capacity might be moved into the global
result.shrink_to_fit();
LONG_LIVED.lock().unwrap().push(result);
}
§impl<T> FromParallelIterator<T> for Vec<T>where
T: Send,
Collects items from a parallel iterator into a vector.
impl<T> FromParallelIterator<T> for Vec<T>where
T: Send,
Collects items from a parallel iterator into a vector.
§fn from_par_iter<I>(par_iter: I) -> Vec<T>where
I: IntoParallelIterator<Item = T>,
fn from_par_iter<I>(par_iter: I) -> Vec<T>where
I: IntoParallelIterator<Item = T>,
par_iter
. Read more1.0.0 · Source§impl<T, A> Hash for Vec<T, A>
The hash of a vector is the same as that of the corresponding slice,
as required by the core::borrow::Borrow
implementation.
impl<T, A> Hash for Vec<T, A>
The hash of a vector is the same as that of the corresponding slice,
as required by the core::borrow::Borrow
implementation.
use std::hash::BuildHasher;
let b = std::hash::RandomState::new();
let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(v), b.hash_one(s));
Source§impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>where
T: IntoDeserializer<'de, E>,
E: Error,
Available on crate features std
or alloc
only.
impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>where
T: IntoDeserializer<'de, E>,
E: Error,
std
or alloc
only.Source§type Deserializer = SeqDeserializer<<Vec<T> as IntoIterator>::IntoIter, E>
type Deserializer = SeqDeserializer<<Vec<T> as IntoIterator>::IntoIter, E>
Source§fn into_deserializer(self) -> <Vec<T> as IntoDeserializer<'de, E>>::Deserializer ⓘ
fn into_deserializer(self) -> <Vec<T> as IntoDeserializer<'de, E>>::Deserializer ⓘ
1.0.0 · Source§impl<T, A> IntoIterator for Vec<T, A>where
A: Allocator,
impl<T, A> IntoIterator for Vec<T, A>where
A: Allocator,
Source§fn into_iter(self) -> <Vec<T, A> as IntoIterator>::IntoIter ⓘ
fn into_iter(self) -> <Vec<T, A> as IntoIterator>::IntoIter ⓘ
Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.
§Examples
let v = vec!["a".to_string(), "b".to_string()];
let mut v_iter = v.into_iter();
let first_element: Option<String> = v_iter.next();
assert_eq!(first_element, Some("a".to_string()));
assert_eq!(v_iter.next(), Some("b".to_string()));
assert_eq!(v_iter.next(), None);
§impl<T> JsonSchema for Vec<T>where
T: JsonSchema,
impl<T> JsonSchema for Vec<T>where
T: JsonSchema,
§fn is_referenceable() -> bool
fn is_referenceable() -> bool
$ref
keyword. Read more§fn schema_name() -> String
fn schema_name() -> String
§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
§fn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
1.0.0 · Source§impl<T, A> Ord for Vec<T, A>
Implements ordering of vectors, lexicographically.
impl<T, A> Ord for Vec<T, A>
Implements ordering of vectors, lexicographically.
§impl<'a, T> ParallelExtend<&'a T> for Vec<T>
Extends a vector with copied items from a parallel iterator.
impl<'a, T> ParallelExtend<&'a T> for Vec<T>
Extends a vector with copied items from a parallel iterator.
§fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = &'a T>,
fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = &'a T>,
par_iter
. Read more§impl<T> ParallelExtend<T> for Vec<T>where
T: Send,
Extends a vector with items from a parallel iterator.
impl<T> ParallelExtend<T> for Vec<T>where
T: Send,
Extends a vector with items from a parallel iterator.
§fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = T>,
fn par_extend<I>(&mut self, par_iter: I)where
I: IntoParallelIterator<Item = T>,
par_iter
. Read more1.0.0 · Source§impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
Implements comparison of vectors, lexicographically.
impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
Implements comparison of vectors, lexicographically.
Source§impl<T> Serialize for Vec<T>where
T: Serialize,
Available on crate features std
or alloc
only.
impl<T> Serialize for Vec<T>where
T: Serialize,
std
or alloc
only.Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
§impl<T> Shuffleable for Vec<T>
impl<T> Shuffleable for Vec<T>
§fn shuffle_len(&self) -> usize
fn shuffle_len(&self) -> usize
§fn shuffle_swap(&mut self, a: usize, b: usize)
fn shuffle_swap(&mut self, a: usize, b: usize)
§impl<T> Sink<T> for Vec<T>
impl<T> Sink<T> for Vec<T>
§type Error = Infallible
type Error = Infallible
§fn poll_ready(
self: Pin<&mut Vec<T>>,
_: &mut Context<'_>,
) -> Poll<Result<(), <Vec<T> as Sink<T>>::Error>>
fn poll_ready( self: Pin<&mut Vec<T>>, _: &mut Context<'_>, ) -> Poll<Result<(), <Vec<T> as Sink<T>>::Error>>
Sink
to receive a value. Read more§fn start_send(
self: Pin<&mut Vec<T>>,
item: T,
) -> Result<(), <Vec<T> as Sink<T>>::Error>
fn start_send( self: Pin<&mut Vec<T>>, item: T, ) -> Result<(), <Vec<T> as Sink<T>>::Error>
poll_ready
which returned Poll::Ready(Ok(()))
. Read more§impl<T> SolValue for Vec<T>where
T: SolValue,
impl<T> SolValue for Vec<T>where
T: SolValue,
§fn sol_type_name(&self) -> Cow<'static, str>
fn sol_type_name(&self) -> Cow<'static, str>
sol_name
instead§fn tokenize(&self) -> <Self::SolType as SolType>::Token<'_>
fn tokenize(&self) -> <Self::SolType as SolType>::Token<'_>
§fn detokenize(token: <Self::SolType as SolType>::Token<'_>) -> Selfwhere
Self: From<<Self::SolType as SolType>::RustType>,
fn detokenize(token: <Self::SolType as SolType>::Token<'_>) -> Selfwhere
Self: From<<Self::SolType as SolType>::RustType>,
§fn abi_encoded_size(&self) -> usize
fn abi_encoded_size(&self) -> usize
§fn eip712_data_word(&self) -> FixedBytes<32>
fn eip712_data_word(&self) -> FixedBytes<32>
encodeData
rules, and hash it
if necessary. Read more§fn abi_encode_packed_to(&self, out: &mut Vec<u8>)
fn abi_encode_packed_to(&self, out: &mut Vec<u8>)
§fn abi_encode_sequence(&self) -> Vec<u8> ⓘwhere
<Self::SolType as SolType>::Token<'a>: for<'a> TokenSeq<'a>,
fn abi_encode_sequence(&self) -> Vec<u8> ⓘwhere
<Self::SolType as SolType>::Token<'a>: for<'a> TokenSeq<'a>,
§fn abi_encode_params(&self) -> Vec<u8> ⓘwhere
<Self::SolType as SolType>::Token<'a>: for<'a> TokenSeq<'a>,
fn abi_encode_params(&self) -> Vec<u8> ⓘwhere
<Self::SolType as SolType>::Token<'a>: for<'a> TokenSeq<'a>,
§fn abi_decode(data: &[u8], validate: bool) -> Result<Self, Error>where
Self: From<<Self::SolType as SolType>::RustType>,
fn abi_decode(data: &[u8], validate: bool) -> Result<Self, Error>where
Self: From<<Self::SolType as SolType>::RustType>,
§impl<K, V> Store<K, V> for Vec<(K, V)>
impl<K, V> Store<K, V> for Vec<(K, V)>
§impl<K, V> StoreFromIterable<K, V> for Vec<(K, V)>where
K: Ord,
impl<K, V> StoreFromIterable<K, V> for Vec<(K, V)>where
K: Ord,
§fn lm_sort_from_iter<I>(iter: I) -> Vec<(K, V)>where
I: IntoIterator<Item = (K, V)>,
fn lm_sort_from_iter<I>(iter: I) -> Vec<(K, V)>where
I: IntoIterator<Item = (K, V)>,
iter
.§impl<K, V> StoreIntoIterator<K, V> for Vec<(K, V)>
impl<K, V> StoreIntoIterator<K, V> for Vec<(K, V)>
type KeyValueIntoIter = IntoIter<(K, V)>
§fn lm_into_iter(
self,
) -> <Vec<(K, V)> as StoreIntoIterator<K, V>>::KeyValueIntoIter ⓘ
fn lm_into_iter( self, ) -> <Vec<(K, V)> as StoreIntoIterator<K, V>>::KeyValueIntoIter ⓘ
§fn lm_extend_end(&mut self, other: Vec<(K, V)>)
fn lm_extend_end(&mut self, other: Vec<(K, V)>)
§fn lm_extend_start(&mut self, other: Vec<(K, V)>)
fn lm_extend_start(&mut self, other: Vec<(K, V)>)
§impl<K, V> StoreMut<K, V> for Vec<(K, V)>
impl<K, V> StoreMut<K, V> for Vec<(K, V)>
§fn lm_with_capacity(capacity: usize) -> Vec<(K, V)>
fn lm_with_capacity(capacity: usize) -> Vec<(K, V)>
§fn lm_reserve(&mut self, additional: usize)
fn lm_reserve(&mut self, additional: usize)
§fn lm_get_mut(&mut self, index: usize) -> Option<(&K, &mut V)>
fn lm_get_mut(&mut self, index: usize) -> Option<(&K, &mut V)>
§fn lm_insert(&mut self, index: usize, key: K, value: V)
fn lm_insert(&mut self, index: usize, key: K, value: V)
§impl<T> Strategy for Vec<T>where
T: Strategy,
impl<T> Strategy for Vec<T>where
T: Strategy,
§type Value = Vec<<T as Strategy>::Value>
type Value = Vec<<T as Strategy>::Value>
§fn new_tree(
&self,
runner: &mut TestRunner,
) -> Result<<Vec<T> as Strategy>::Tree, Reason>
fn new_tree( &self, runner: &mut TestRunner, ) -> Result<<Vec<T> as Strategy>::Tree, Reason>
§fn prop_map<O, F>(self, fun: F) -> Map<Self, F>
fn prop_map<O, F>(self, fun: F) -> Map<Self, F>
fun
. Read more§fn prop_map_into<O>(self) -> MapInto<Self, O>
fn prop_map_into<O>(self) -> MapInto<Self, O>
§fn prop_perturb<O, F>(self, fun: F) -> Perturb<Self, F>
fn prop_perturb<O, F>(self, fun: F) -> Perturb<Self, F>
fun
, which is additionally given a random number generator. Read more§fn prop_flat_map<S, F>(self, fun: F) -> Flatten<Map<Self, F>>
fn prop_flat_map<S, F>(self, fun: F) -> Flatten<Map<Self, F>>
§fn prop_ind_flat_map<S, F>(self, fun: F) -> IndFlatten<Map<Self, F>>
fn prop_ind_flat_map<S, F>(self, fun: F) -> IndFlatten<Map<Self, F>>
§fn prop_ind_flat_map2<S, F>(self, fun: F) -> IndFlattenMap<Self, F>
fn prop_ind_flat_map2<S, F>(self, fun: F) -> IndFlattenMap<Self, F>
prop_ind_flat_map()
, but produces 2-tuples with the input
generated from self
in slot 0 and the derived strategy in slot 1. Read more§fn prop_filter<R, F>(self, whence: R, fun: F) -> Filter<Self, F>
fn prop_filter<R, F>(self, whence: R, fun: F) -> Filter<Self, F>
fun
. Read more§fn prop_filter_map<F, O>(
self,
whence: impl Into<Reason>,
fun: F,
) -> FilterMap<Self, F>
fn prop_filter_map<F, O>( self, whence: impl Into<Reason>, fun: F, ) -> FilterMap<Self, F>
fun
returns Some(value)
and rejects those where fun
returns None
. Read more§fn prop_union(self, other: Self) -> Union<Self>where
Self: Sized,
fn prop_union(self, other: Self) -> Union<Self>where
Self: Sized,
§fn prop_recursive<R, F>(
self,
depth: u32,
desired_size: u32,
expected_branch_size: u32,
recurse: F,
) -> Recursive<Self::Value, F>
fn prop_recursive<R, F>( self, depth: u32, desired_size: u32, expected_branch_size: u32, recurse: F, ) -> Recursive<Self::Value, F>
self
items as leaves. Read more§fn prop_shuffle(self) -> Shuffle<Self>where
Self: Sized,
Self::Value: Shuffleable,
fn prop_shuffle(self) -> Shuffle<Self>where
Self: Sized,
Self::Value: Shuffleable,
§fn boxed(self) -> BoxedStrategy<Self::Value>where
Self: Sized + 'static,
fn boxed(self) -> BoxedStrategy<Self::Value>where
Self: Sized + 'static,
Strategy
so it can be passed around as a
simple trait object. Read more§impl<'a, T> Yokeable<'a> for Vec<T>where
T: 'static,
Available on crate feature alloc
only.
impl<'a, T> Yokeable<'a> for Vec<T>where
T: 'static,
alloc
only.§fn transform_owned(self) -> Vec<T>
fn transform_owned(self) -> Vec<T>
§unsafe fn make(from: Vec<T>) -> Vec<T>
unsafe fn make(from: Vec<T>) -> Vec<T>
Self<'a>
’s lifetime. Read more§fn transform_mut<F>(&'a mut self, f: F)
fn transform_mut<F>(&'a mut self, f: F)
self
between &'a mut Self<'static>
and &'a mut Self<'a>
,
and pass it to f
. Read moreimpl<T, A> DerefPure for Vec<T, A>where
A: Allocator,
impl<T, A> Eq for Vec<T, A>
impl<T> FromStream<T> for Vec<T>
impl<T> StableDeref for Vec<T>
alloc
only.impl<K, V> StoreFromIterator<K, V> for Vec<(K, V)>
impl<Z> ZeroizeOnDrop for Vec<Z>where
Z: ZeroizeOnDrop,
alloc
only.