[][src]Struct static_alloc::fixed_vec::FixedVec

pub struct FixedVec<'a, T> { /* fields omitted */ }

A Vec-like structure that does not manage its allocation.

This vector type will never (re-)allocate but it can also not free underused memory. As opposed to other similar crates, it does require and additional bounds on its type parameter as it truly manages uninitialized memory to store instances.

Basic Usage

It is easy to use a local array or slice of MaybeUninit for the storage of a FixedVec. Note that, similar to the allocated standard Vec, the underlying memory not being stored inline makes moves and splitting much cheaper.

use core::mem::MaybeUninit;
use static_alloc::FixedVec;

let mut memory: [MaybeUninit<usize>; 15] = [MaybeUninit::uninit(); 15];
let mut stack = FixedVec::new((&mut memory[..]).into());

stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
    // Prints 3, 2, 1
    println!("{}", top);
}

With Slab

One focus of the library is composability. It should not be surprising that FixedVec interacts with the Slab allocator, which implements a specialized interface providing the Uninit type instead of a raw *const u8. Hence, the FixedVec can use this instead of its own local stack variables.

use static_alloc::{FixedVec, Slab};

let alloc: Slab<[u8; 1 << 12]> = Slab::uninit();
let some_usize = alloc.leak(0_usize).unwrap();

// Allocate a vector with capacity `1` from the slab.
let mut vec = alloc.fixed_vec(1).unwrap();

// Push the reference to the other allocation.
vec.push(&mut *some_usize);

// … do something else

// Ensure lifetimes work out.
drop(vec);

// Hooray, now once again unborrowed.
*some_usize = 0;

The from_unaligned constructor

It is possible to place a FixedVec into an uninitialized memory, not only the Uninit<[T]> that the new constructor requires. This will align the underlying memory suitably and substitute a dangling empty slice if that is not possible.

use core::mem::MaybeUninit;
use static_alloc::{FixedVec, Uninit};

struct MyStruct {
    // ..
}

let mut memory: MaybeUninit<[u8; 1024]> = MaybeUninit::uninit();
let uninit = Uninit::from(&mut memory);

// NO guarantees about space lost from required additional aligning.
let mut vec: FixedVec<MyStruct> = FixedVec::from_unaligned(uninit);

Methods

impl<'_, T> FixedVec<'_, T>[src]

pub fn truncate(&mut self, len: usize)[src]

Shorten the vector to a maximum length.

If the length is not larger than len this has no effect.

The tail of the vector is dropped starting from the last element. This order is opposite to .drain(len..).for_each(drop). truncate provides the extra guarantee that a panic during Drop of one element effectively stops the truncation at that point, instead of leaking unspecified other content of the vector. This means that other elements are still dropped when unwinding eventually drops the FixedVec itself.

Example


let mut memory: [MaybeUninit<usize>; 4] = [MaybeUninit::uninit(); 4];
let mut vec = FixedVec::new(Uninit::from(&mut memory[..]));

vec.push(0usize);
vec.push(1usize);
vec.push(2usize);

assert_eq!(vec.as_slice(), [0, 1, 2]);
vec.truncate(1);
assert_eq!(vec.as_slice(), [0]);

pub fn as_slice(&self) -> &[T][src]

Extracts a slice containing the entire vector.

pub fn as_mut_slice(&mut self) -> &mut [T][src]

Extracts the mutable slice containing the entire vector.

pub fn clear(&mut self)[src]

Remove all elements.

This is an alias for truncate(0).

pub fn len(&self) -> usize[src]

Returns the number of elements in the vector.

pub unsafe fn set_len(&mut self, new_len: usize)[src]

Set the raw length.

Safety

  • new_len must be smaller or equal self.capacity()
  • The caller must ensure that all newly referenced elements are properly initialized.

pub fn capacity(&self) -> usize[src]

Returns the number of elements the vector can hold.

pub fn is_empty(&self) -> bool[src]

Returns true if the vector contains no elements.

pub fn push(&mut self, val: T) -> Result<(), T>[src]

Appends an element to the back of a collection.

Return Err(val) if it is not possible to append the element.

use static_alloc::{FixedVec, Uninit};
use core::mem::MaybeUninit;

// Only enough storage for one element.
let mut allocation: [MaybeUninit<u32>; 1] = [MaybeUninit::uninit()];
let mut vec = FixedVec::new(Uninit::from(&mut allocation[..]));

// First push succeeds.
assert_eq!(vec.push(1), Ok(()));

// The second push fails.
assert_eq!(vec.push(2), Err(2));

pub fn pop(&mut self) -> Option<T>[src]

Removes the last element from a vector and returns it, or None if it is empty.

#[must_use = "Elements in the split tail will be dropped. Prefer `truncate(at)` or `drain(at..)` if there is no other use."] pub fn split_borrowed(&mut self, at: usize) -> FixedVec<T>[src]

Split the capacity into a borrowed other vector.

The other vector borrows the underlying memory resource while it is alive.

This is a specialized method not found in the standard Vec as it relies on FixedVec not owning the allocation itself. This avoids splitting the underlying allocation which would require unsafe to mend the parts together.

Panics

This method panics if at > self.capacity().

Examples

use static_alloc::{FixedVec, Slab};

let mut memory: Slab<[usize; 8]> = Slab::uninit();
let mut vec = memory.fixed_vec::<usize>(8).unwrap();
vec.fill(0..7);

// Can use like a vector:
let mut part = vec.split_borrowed(4);
assert!(part.push(7).is_ok());
assert!((4..8).eq(part.drain(..)));

// Drop to rescind the borrow on `vec`.
drop(part);

// All split elements are gone
assert_eq!(vec.len(), 4);
// But retained all capacity
assert_eq!(vec.capacity(), 8);

pub fn split_and_shrink_to(&mut self, at: usize) -> Self[src]

Split the capacity of the collection into two at a given index.

In contrast to Vec::split_off calling this method reduces the capacity of self to at.

Panics

This method panics if at > self.capacity().

pub fn fill<I: IntoIterator<Item = T>>(&mut self, iter: I) -> I::IntoIter[src]

Extend the vector with as many elements as fit.

Returns the iterator with all elements that were not pushed into the vector.

Important traits for Drain<'_, T>
pub fn drain<R>(&mut self, range: R) -> Drain<T> where
    R: RangeBounds<usize>, 
[src]

Creates a draining iterator that yields and removes elements a given range.

It is unspecified which elements are removed if the Drain is never dropped. If you require precise semantics even in this case you might be able to swap the range to the back of the vector and invoke split_and_shrink_to.

impl<'a, T> FixedVec<'a, T>[src]

pub fn new(uninit: Uninit<'a, [T]>) -> Self[src]

Create a FixedVec in a pre-allocated region.

The capacity will be that of the underlying allocation.

pub fn from_unaligned<U: ?Sized>(generic: Uninit<'a, U>) -> Self[src]

Create a FixedVec with as large of a capacity as available.

When no aligned slice can be create within the provided memory then the constructor will fallback to an empty dangling slice.

This is only a utility function which may be lossy as data before the alignment is discarded. Prefer an explicit Uninit::cast_slice followed by error handling if this is undesirable.

pub fn shrink_to_fit(&mut self) -> Uninit<'a, ()>[src]

Return trailing bytes that can not be used by the FixedVec.

This operation is idempotent.

Trait Implementations

impl<'a, 'b, T: PartialEq> PartialEq<FixedVec<'b, T>> for FixedVec<'a, T>[src]

impl<'_, T: Eq> Eq for FixedVec<'_, T>[src]

impl<'_, T: Ord> Ord for FixedVec<'_, T>[src]

impl<'a, 'b, T: PartialOrd> PartialOrd<FixedVec<'b, T>> for FixedVec<'a, T>[src]

impl<'_, T> Deref for FixedVec<'_, T>[src]

type Target = [T]

The resulting type after dereferencing.

impl<'_, T> DerefMut for FixedVec<'_, T>[src]

impl<'_, T> Drop for FixedVec<'_, T>[src]

impl<'_, T, I> Index<I> for FixedVec<'_, T> where
    I: SliceIndex<[T]>, 
[src]

type Output = I::Output

The returned type after indexing.

impl<'_, T, I> IndexMut<I> for FixedVec<'_, T> where
    I: SliceIndex<[T]>, 
[src]

impl<'_, T: Hash> Hash for FixedVec<'_, T>[src]

impl<'_, T> Extend<T> for FixedVec<'_, T>[src]

Extend the vector to the extent the allocation allows it.

Appends elements from the iterator until the capacity of the vector is exhausted. Then drops the remaining iterator without iterating through all remaining elements. This allows the caller to decide the fate or all other elements by passing the iterator by reference.

Examples

Some iterators will drain themselves on drop, for example Drain. This will empty the source vector even if the target has not enough space.


let mut memory: [MaybeUninit<usize>; 15] = [MaybeUninit::uninit(); 15];
let mut source = FixedVec::new((&mut memory[..]).into());
source.extend(0..15);

let mut memory: [MaybeUninit<usize>; 3] = [MaybeUninit::uninit(); 3];
let mut target = FixedVec::new((&mut memory[..]).into());
target.extend(source.drain(..));

assert!(source.is_empty());
assert_eq!(target.len(), target.capacity());

impl<'_, T> AsRef<[T]> for FixedVec<'_, T>[src]

impl<'_, T> AsMut<[T]> for FixedVec<'_, T>[src]

impl<'_, T> Borrow<[T]> for FixedVec<'_, T>[src]

impl<'_, T> BorrowMut<[T]> for FixedVec<'_, T>[src]

Auto Trait Implementations

impl<'a, T> Unpin for FixedVec<'a, T>

impl<'a, T> !Send for FixedVec<'a, T>

impl<'a, T> !Sync for FixedVec<'a, T>

Blanket Implementations

impl<T> From<T> for T[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]