bluetooth_traits

Type Alias BluetoothDescriptorsMsg

source
pub type BluetoothDescriptorsMsg = Vec<BluetoothDescriptorMsg>;

Aliased Type§

struct BluetoothDescriptorsMsg { /* private fields */ }

Implementations

source§

impl<T> Vec<T>

1.0.0 (const: 1.39.0) · source

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 · source

pub fn with_capacity(capacity: usize) -> Vec<T>

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 0, 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);
source

pub fn try_with_capacity(capacity: usize) -> Result<Vec<T>, TryReserveError>

🔬This is a nightly-only experimental API. (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 0, 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 · source

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 the alloc::alloc function.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (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 layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • 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 of pointer::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);
}
source

pub unsafe fn from_parts( ptr: NonNull<T>, length: usize, capacity: usize, ) -> Vec<T>

🔬This is a nightly-only experimental API. (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 the alloc::alloc function.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (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 layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • 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 of pointer::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>
where T: Clone, A: Allocator,

1.5.0 · source

pub fn resize(&mut self, new_len: usize, value: T)

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![1, 2, 3, 4];
vec.resize(2, 0);
assert_eq!(vec, [1, 2]);
1.6.0 · source

pub fn extend_from_slice(&mut self, other: &[T])

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 · source

pub fn extend_from_within<R>(&mut self, src: R)
where R: RangeBounds<usize>,

Copies elements from src range to the end of the vector.

§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 vec = vec![0, 1, 2, 3, 4];

vec.extend_from_within(2..);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);

vec.extend_from_within(..2);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);

vec.extend_from_within(4..8);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
source§

impl<T, A> Vec<T, A>
where T: PartialEq, A: Allocator,

1.0.0 · source

pub fn dedup(&mut self)

Removes consecutive repeated elements in the vector according to the PartialEq trait implementation.

If the vector is sorted, this removes all duplicates.

§Examples
let mut vec = vec![1, 2, 2, 3, 2];

vec.dedup();

assert_eq!(vec, [1, 2, 3, 2]);
source§

impl<T, A> Vec<T, A>
where A: Allocator,

1.21.0 · source

pub fn splice<R, I>( &mut self, range: R, replace_with: I, ) -> Splice<'_, <I as IntoIterator>::IntoIter, A>
where R: RangeBounds<usize>, I: IntoIterator<Item = T>,

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 than range’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]);
source

pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, T, F, A>
where F: FnMut(&mut T) -> bool,

🔬This is a nightly-only experimental API. (extract_if)

Creates an iterator which uses a closure to determine if an element 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.

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 = 0;
while i < vec.len() {
    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 every element in the filter closure, regardless of whether you choose to keep or remove it.

§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]);
source§

impl<T, A> Vec<T, A>
where A: Allocator,

source

pub const fn new_in(alloc: A) -> Vec<T, A>

🔬This is a nightly-only experimental API. (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);
source

pub fn with_capacity_in(capacity: usize, alloc: A) -> Vec<T, A>

🔬This is a nightly-only experimental API. (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 0, 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);
source

pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result<Vec<T, A>, TryReserveError>

🔬This is a nightly-only experimental API. (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 0, the vector will not allocate.

§Errors

Returns an error if the capacity exceeds isize::MAX bytes, or if the allocator reports allocation failure.

source

pub 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)

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 allocator alloc.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (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 layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • 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 of pointer::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);
}
source

pub 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)

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 allocator alloc.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (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 layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • 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 of pointer::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);
}
source

pub fn into_raw_parts(self) -> (*mut T, usize, usize)

🔬This is a nightly-only experimental API. (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]);
source

pub fn into_parts(self) -> (NonNull<T>, usize, usize)

🔬This is a nightly-only experimental API. (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]);
source

pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A)

🔬This is a nightly-only experimental API. (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]);
source

pub fn into_parts_with_alloc(self) -> (NonNull<T>, usize, usize, A)

🔬This is a nightly-only experimental API. (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) · source

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 · source

pub fn reserve(&mut self, additional: usize)

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 · source

pub fn reserve_exact(&mut self, additional: usize)

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 · source

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 · source

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 · source

pub fn shrink_to_fit(&mut self)

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 · source

pub fn shrink_to(&mut self, min_capacity: usize)

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 · source

pub fn into_boxed_slice(self) -> Box<[T], A>

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 · source

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) · source

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) · source

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) · source

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) · source

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);
}
source

pub fn as_non_null(&mut self) -> NonNull<T>

🔬This is a nightly-only experimental API. (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);
}
source

pub fn allocator(&self) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

1.0.0 · source

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 to capacity().
  • The elements at old_len..new_len must be initialized.
§Examples

This method 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 · source

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 · source

pub fn insert(&mut self, index: usize, element: T)

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![1, 2, 3];
vec.insert(1, 4);
assert_eq!(vec, [1, 4, 2, 3]);
vec.insert(4, 5);
assert_eq!(vec, [1, 4, 2, 3, 5]);
§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 · source

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![1, 2, 3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);
1.0.0 · source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&T) -> bool,

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 · source

pub fn retain_mut<F>(&mut self, f: F)
where F: FnMut(&mut T) -> bool,

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 · source

pub fn dedup_by_key<F, K>(&mut self, key: F)
where F: FnMut(&mut T) -> K, K: PartialEq,

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 · source

pub fn dedup_by<F>(&mut self, same_bucket: F)
where F: FnMut(&mut T, &mut T) -> bool,

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 · source

pub fn push(&mut self, value: T)

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.

source

pub fn push_within_capacity(&mut self, value: T) -> Result<(), T>

🔬This is a nightly-only experimental API. (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 · source

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.

source

pub fn pop_if<F>(&mut self, f: F) -> Option<T>
where F: FnOnce(&mut T) -> bool,

🔬This is a nightly-only experimental API. (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 · source

pub fn append(&mut self, other: &mut Vec<T, A>)

Moves all the elements of other into self, leaving other empty.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);
1.6.0 · source

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 · source

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) · source

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) · source

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 · source

pub fn split_off(&mut self, at: usize) -> Vec<T, A>
where A: Clone,

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 or mem::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![1, 2, 3];
let vec2 = vec.split_off(1);
assert_eq!(vec, [1]);
assert_eq!(vec2, [2, 3]);
1.33.0 · source

pub fn resize_with<F>(&mut self, new_len: usize, f: F)
where F: FnMut() -> T,

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 · source

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 · source

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]);
source

pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])

🔬This is a nightly-only experimental API. (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

source§

impl<T> ArrayLike for Vec<T>

source§

type Item = T

Type of the elements being stored.
1.5.0 · source§

impl<T, A> AsMut<[T]> for Vec<T, A>
where A: Allocator,

source§

fn as_mut(&mut self) -> &mut [T]

Converts this type into a mutable reference of the (usually inferred) input type.
1.5.0 · source§

impl<T, A> AsMut<Vec<T, A>> for Vec<T, A>
where A: Allocator,

source§

fn as_mut(&mut self) -> &mut Vec<T, A>

Converts this type into a mutable reference of the (usually inferred) input type.
1.0.0 · source§

impl<T, A> AsRef<[T]> for Vec<T, A>
where A: Allocator,

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 · source§

impl<T, A> AsRef<Vec<T, A>> for Vec<T, A>
where A: Allocator,

source§

fn as_ref(&self) -> &Vec<T, A>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T> AsRef<ZeroSlice<T>> for Vec<<T as AsULE>::ULE>
where T: AsULE,

source§

fn as_ref(&self) -> &ZeroSlice<T>

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 · source§

impl<T, A> Borrow<[T]> for Vec<T, A>
where A: Allocator,

source§

fn borrow(&self) -> &[T]

Immutably borrows from an owned value. Read more
1.0.0 · source§

impl<T, A> BorrowMut<[T]> for Vec<T, A>
where A: Allocator,

source§

fn borrow_mut(&mut self) -> &mut [T]

Mutably borrows from an owned value. Read more
1.0.0 · source§

impl<T, A> Clone for Vec<T, A>
where T: Clone, A: Allocator + Clone,

source§

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());
source§

fn clone(&self) -> Vec<T, A>

Returns a copy of the value. Read more
1.0.0 · source§

impl<T, A> Debug for Vec<T, A>
where T: Debug, A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
1.0.0 · source§

impl<T> Default for Vec<T>

source§

fn default() -> Vec<T>

Creates an empty Vec<T>.

The vector will not allocate until elements are pushed onto it.

1.0.0 · source§

impl<T, A> Deref for Vec<T, A>
where A: Allocator,

source§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
1.0.0 · source§

impl<T, A> DerefMut for Vec<T, A>
where A: Allocator,

source§

fn deref_mut(&mut self) -> &mut [T]

Mutably dereferences the value.
source§

impl<'de, T> Deserialize<'de> for Vec<T>
where T: Deserialize<'de>,

source§

fn deserialize<D>( deserializer: D, ) -> Result<Vec<T>, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
1.0.0 · source§

impl<T, A> Drop for Vec<T, A>
where A: Allocator,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<T> EncodeAsVarULE<[T]> for Vec<T>
where T: ULE,

source§

fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R

Calls cb with a piecewise list of byte slices that when concatenated produce the memory pattern of the corresponding instance of T. Read more
source§

fn encode_var_ule_len(&self) -> usize

Return the length, in bytes, of the corresponding VarULE type
source§

fn encode_var_ule_write(&self, dst: &mut [u8])

Write the corresponding VarULE type to the dst buffer. dst should be the size of Self::encode_var_ule_len()
source§

impl<T, E, F> EncodeAsVarULE<VarZeroSlice<T, F>> for Vec<E>

source§

fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R

Calls cb with a piecewise list of byte slices that when concatenated produce the memory pattern of the corresponding instance of T. Read more
source§

fn encode_var_ule_len(&self) -> usize

Return the length, in bytes, of the corresponding VarULE type
source§

fn encode_var_ule_write(&self, dst: &mut [u8])

Write the corresponding VarULE type to the dst buffer. dst should be the size of Self::encode_var_ule_len()
source§

impl<T> EncodeAsVarULE<ZeroSlice<T>> for Vec<T>
where T: AsULE + 'static,

source§

fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R

Calls cb with a piecewise list of byte slices that when concatenated produce the memory pattern of the corresponding instance of T. Read more
source§

fn encode_var_ule_len(&self) -> usize

Return the length, in bytes, of the corresponding VarULE type
source§

fn encode_var_ule_write(&self, dst: &mut [u8])

Write the corresponding VarULE type to the dst buffer. dst should be the size of Self::encode_var_ule_len()
1.2.0 · source§

impl<'a, T, A> Extend<&'a T> for Vec<T, A>
where T: Copy + 'a, A: Allocator,

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>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, _: &'a T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.0.0 · source§

impl<T, A> Extend<T> for Vec<T, A>
where A: Allocator,

source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.0.0 · source§

impl<T> From<&[T]> for Vec<T>
where T: Clone,

source§

fn from(s: &[T]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s’s items.

§Examples
assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
1.74.0 · source§

impl<T, const N: usize> From<&[T; N]> for Vec<T>
where T: Clone,

source§

fn from(s: &[T; N]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s’s items.

§Examples
assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
1.19.0 · source§

impl<T> From<&mut [T]> for Vec<T>
where T: Clone,

source§

fn from(s: &mut [T]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s’s items.

§Examples
assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
1.74.0 · source§

impl<T, const N: usize> From<&mut [T; N]> for Vec<T>
where T: Clone,

source§

fn from(s: &mut [T; N]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s’s items.

§Examples
assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
1.44.0 · source§

impl<T, const N: usize> From<[T; N]> for Vec<T>

source§

fn from(s: [T; N]) -> Vec<T>

Allocates a Vec<T> and moves s’s items into it.

§Examples
assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
1.5.0 · source§

impl<T, A> From<BinaryHeap<T, A>> for Vec<T, A>
where A: Allocator,

source§

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.18.0 · source§

impl<T, A> From<Box<[T], A>> for Vec<T, A>
where A: Allocator,

source§

fn from(s: Box<[T], A>) -> Vec<T, A>

Converts a boxed slice into a vector by transferring ownership of the existing heap allocation.

§Examples
let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
assert_eq!(Vec::from(b), vec![1, 2, 3]);
1.14.0 · source§

impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
where [T]: ToOwned<Owned = Vec<T>>,

source§

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));
source§

impl<T> From<ThinVec<T>> for Vec<T>

source§

fn from(s: ThinVec<T>) -> Vec<T>

Convert a ThinVec into a std::Vec.

NOTE: this must reallocate to change the layout!

§Examples
use thin_vec::{ThinVec, thin_vec};

let b: ThinVec<i32> = thin_vec![1, 2, 3];
assert_eq!(Vec::from(b), vec![1, 2, 3]);
1.10.0 · source§

impl<T, A> From<VecDeque<T, A>> for Vec<T, A>
where A: Allocator,

source§

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>

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);
}
source§

fn from_iter<I>(iter: I) -> Vec<T>
where I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<T> FromParallelIterator<T> for Vec<T>
where T: Send,

Collects items from a parallel iterator into a vector.

source§

fn from_par_iter<I>(par_iter: I) -> Vec<T>
where I: IntoParallelIterator<Item = T>,

Creates an instance of the collection from the parallel iterator par_iter. Read more
1.0.0 · source§

impl<T, A> Hash for Vec<T, A>
where T: Hash, A: Allocator,

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§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
1.0.0 · source§

impl<T, I, A> Index<I> for Vec<T, A>
where I: SliceIndex<[T]>, A: Allocator,

source§

type Output = <I as SliceIndex<[T]>>::Output

The returned type after indexing.
source§

fn index(&self, index: I) -> &<Vec<T, A> as Index<I>>::Output

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<PatternID> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: PatternID) -> &T

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<PatternID> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: PatternID) -> &T

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<SmallIndex> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: SmallIndex) -> &T

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<SmallIndex> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: SmallIndex) -> &T

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<StateID> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: StateID) -> &T

Performs the indexing (container[index]) operation. Read more
source§

impl<T> Index<StateID> for Vec<T>

source§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: StateID) -> &T

Performs the indexing (container[index]) operation. Read more
1.0.0 · source§

impl<T, I, A> IndexMut<I> for Vec<T, A>
where I: SliceIndex<[T]>, A: Allocator,

source§

fn index_mut(&mut self, index: I) -> &mut <Vec<T, A> as Index<I>>::Output

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<PatternID> for Vec<T>

source§

fn index_mut(&mut self, index: PatternID) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<PatternID> for Vec<T>

source§

fn index_mut(&mut self, index: PatternID) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<SmallIndex> for Vec<T>

source§

fn index_mut(&mut self, index: SmallIndex) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<SmallIndex> for Vec<T>

source§

fn index_mut(&mut self, index: SmallIndex) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<StateID> for Vec<T>

source§

fn index_mut(&mut self, index: StateID) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<StateID> for Vec<T>

source§

fn index_mut(&mut self, index: StateID) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>
where T: IntoDeserializer<'de, E>, E: Error,

source§

type Deserializer = SeqDeserializer<<Vec<T> as IntoIterator>::IntoIter, E>

The type of the deserializer being converted into.
source§

fn into_deserializer(self) -> <Vec<T> as IntoDeserializer<'de, E>>::Deserializer

Convert this value into a deserializer.
1.0.0 · source§

impl<T, A> IntoIterator for Vec<T, A>
where A: Allocator,

source§

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);
source§

type Item = T

The type of the elements being iterated over.
source§

type IntoIter = IntoIter<T, A>

Which kind of iterator are we turning this into?
source§

impl<T> IntoParallelIterator for Vec<T>
where T: Send,

source§

type Item = T

The type of item that the parallel iterator will produce.
source§

type Iter = IntoIter<T>

The parallel iterator type that will be created.
source§

fn into_par_iter(self) -> <Vec<T> as IntoParallelIterator>::Iter

Converts self into a parallel iterator. Read more
source§

impl<T> MallocShallowSizeOf for Vec<T>

source§

fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of immediate heap-allocated descendant structures, but not the space taken up by the value itself. Anything beyond the immediate descendants must be measured separately, using iteration.
source§

impl<T> MallocShallowSizeOf for Vec<T>

source§

fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of immediate heap-allocated descendant structures, but not the space taken up by the value itself. Anything beyond the immediate descendants must be measured separately, using iteration.
source§

impl<T> MallocShallowSizeOf for Vec<T>

source§

fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of immediate heap-allocated descendant structures, but not the space taken up by the value itself. Anything beyond the immediate descendants must be measured separately, using iteration.
source§

impl<T> MallocSizeOf for Vec<T>
where T: MallocSizeOf,

source§

fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of all descendant heap-allocated structures, but not the space taken up by the value itself.
source§

impl<T> MallocSizeOf for Vec<T>
where T: MallocSizeOf,

source§

fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of all descendant heap-allocated structures, but not the space taken up by the value itself.
source§

impl<T> MallocSizeOf for Vec<T>
where T: MallocSizeOf,

source§

fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize

Measure the heap usage of all descendant heap-allocated structures, but not the space taken up by the value itself.
1.0.0 · source§

impl<T, A> Ord for Vec<T, A>
where T: Ord, A: Allocator,

Implements ordering of vectors, lexicographically.

source§

fn cmp(&self, other: &Vec<T, A>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl<'a, T> ParallelExtend<&'a T> for Vec<T>
where T: 'a + Copy + Send + Sync,

Extends a vector with copied items from a parallel iterator.

source§

fn par_extend<I>(&mut self, par_iter: I)
where I: IntoParallelIterator<Item = &'a T>,

Extends an instance of the collection with the elements drawn from the parallel iterator par_iter. Read more
source§

impl<T> ParallelExtend<T> for Vec<T>
where T: Send,

Extends a vector with items from a parallel iterator.

source§

fn par_extend<I>(&mut self, par_iter: I)
where I: IntoParallelIterator<Item = T>,

Extends an instance of the collection with the elements drawn from the parallel iterator par_iter. Read more
source§

impl<T> Parse for Vec<T>

source§

fn parse<'i, 't>( context: &ParserContext<'_>, input: &mut Parser<'i, 't>, ) -> Result<Vec<T>, ParseError<'i, StyleParseErrorKind<'i>>>

Parse a value of this type. Read more
1.0.0 · source§

impl<T, U, A> PartialEq<&[U]> for Vec<T, A>
where A: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &&[U]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &&[U]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 · source§

impl<T, U, A, const N: usize> PartialEq<&[U; N]> for Vec<T, A>
where A: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &&[U; N]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &&[U; N]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 · source§

impl<T, U, A> PartialEq<&mut [U]> for Vec<T, A>
where A: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &&mut [U]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &&mut [U]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.48.0 · source§

impl<T, U, A> PartialEq<[U]> for Vec<T, A>
where A: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &[U]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &[U]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 · source§

impl<T, U, A, const N: usize> PartialEq<[U; N]> for Vec<T, A>
where A: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &[U; N]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &[U; N]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 · source§

impl<T, U, A1, A2> PartialEq<Vec<U, A2>> for Vec<T, A1>
where A1: Allocator, A2: Allocator, T: PartialEq<U>,

source§

fn eq(&self, other: &Vec<U, A2>) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &Vec<U, A2>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 · source§

impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
where T: PartialOrd, A1: Allocator, A2: Allocator,

Implements comparison of vectors, lexicographically.

source§

fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T> Push<T> for Vec<T>

source§

fn push(&mut self, value: T)

Push a value into self.
source§

impl<T> Serialize for Vec<T>
where T: Serialize,

source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<T> Sink<T> for Vec<T>

source§

type Error = Infallible

The type of value produced by the sink when an error occurs.
source§

fn poll_ready( self: Pin<&mut Vec<T>>, _: &mut Context<'_>, ) -> Poll<Result<(), <Vec<T> as Sink<T>>::Error>>

Attempts to prepare the Sink to receive a value. Read more
source§

fn start_send( self: Pin<&mut Vec<T>>, item: T, ) -> Result<(), <Vec<T> as Sink<T>>::Error>

Begin the process of sending a value to the sink. Each call to this function must be preceded by a successful call to poll_ready which returned Poll::Ready(Ok(())). Read more
source§

fn poll_flush( self: Pin<&mut Vec<T>>, _: &mut Context<'_>, ) -> Poll<Result<(), <Vec<T> as Sink<T>>::Error>>

Flush any remaining output from this sink. Read more
source§

fn poll_close( self: Pin<&mut Vec<T>>, _: &mut Context<'_>, ) -> Poll<Result<(), <Vec<T> as Sink<T>>::Error>>

Flush any remaining output and close this sink, if necessary. Read more
source§

impl<T> SpecifiedValueInfo for Vec<T>

source§

const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES

Supported CssTypes by the given value type. Read more
source§

fn collect_completion_keywords(f: &mut dyn FnMut(&[&'static str]))

Collect value starting words for the given specified value type. This includes keyword and function names which can appear at the beginning of a value of this type. Read more
source§

impl<T> ToAnimatedValue for Vec<T>
where T: ToAnimatedValue,

source§

type AnimatedValue = Vec<<T as ToAnimatedValue>::AnimatedValue>

The type of the animated value.
source§

fn to_animated_value( self, context: &Context<'_>, ) -> <Vec<T> as ToAnimatedValue>::AnimatedValue

Converts this value to an animated value.
source§

fn from_animated_value( animated: <Vec<T> as ToAnimatedValue>::AnimatedValue, ) -> Vec<T>

Converts back an animated value into a computed value.
source§

impl<T> ToAnimatedZero for Vec<T>
where T: ToAnimatedZero,

source§

fn to_animated_zero(&self) -> Result<Vec<T>, ()>

Returns a value that, when added with an underlying value, will produce the underlying value. This is used for SMIL animation’s “by-animation” where SMIL first interpolates from the zero value to the ‘by’ value, and then adds the result to the underlying value. Read more
source§

impl<T> ToComputedValue for Vec<T>
where T: ToComputedValue,

source§

type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>

The computed value type we’re going to be converted to.
source§

fn to_computed_value( &self, context: &Context<'_>, ) -> <Vec<T> as ToComputedValue>::ComputedValue

Convert a specified value to a computed value, using itself and the data inside the Context.
source§

fn from_computed_value( computed: &<Vec<T> as ToComputedValue>::ComputedValue, ) -> Vec<T>

Convert a computed value to specified value form. Read more
source§

impl<T> ToCss for Vec<T>

source§

fn to_css<W>(&self, dest: &mut CssWriter<'_, W>) -> Result<(), Error>
where W: Write,

Serialize self in CSS syntax, writing to dest.
source§

fn to_css_string(&self) -> String

Serialize self in CSS syntax and return a string. Read more
source§

impl<T> ToResolvedValue for Vec<T>
where T: ToResolvedValue,

source§

type ResolvedValue = Vec<<T as ToResolvedValue>::ResolvedValue>

The resolved value type we’re going to be converted to.
source§

fn to_resolved_value( self, context: &Context<'_>, ) -> <Vec<T> as ToResolvedValue>::ResolvedValue

Convert a resolved value to a resolved value.
source§

fn from_resolved_value( resolved: <Vec<T> as ToResolvedValue>::ResolvedValue, ) -> Vec<T>

Convert a resolved value to resolved value form.
source§

impl<T> ToShmem for Vec<T>
where T: ToShmem,

source§

fn to_shmem( &self, builder: &mut SharedMemoryBuilder, ) -> Result<ManuallyDrop<Vec<T>>, String>

Clones this value into a form suitable for writing into a SharedMemoryBuilder. Read more
source§

impl<'a, T> Yokeable<'a> for Vec<T>
where T: 'static,

source§

type Output = Vec<T>

This type MUST be Self with the 'static replaced with 'a, i.e. Self<'a>
source§

fn transform(&'a self) -> &'a Vec<T>

This method must cast self between &'a Self<'static> and &'a Self<'a>. Read more
source§

fn transform_owned(self) -> Vec<T>

This method must cast self between Self<'static> and Self<'a>. Read more
source§

unsafe fn make(from: Vec<T>) -> Vec<T>

This method can be used to cast away Self<'a>’s lifetime. Read more
source§

fn transform_mut<F>(&'a mut self, f: F)
where F: 'static + for<'b> FnOnce(&'b mut <Vec<T> as Yokeable<'a>>::Output),

This method must cast self between &'a mut Self<'static> and &'a mut Self<'a>, and pass it to f. Read more
source§

impl<T, A> DerefPure for Vec<T, A>
where A: Allocator,

1.0.0 · source§

impl<T, A> Eq for Vec<T, A>
where T: Eq, A: Allocator,

source§

impl<T> StableDeref for Vec<T>