Expand description
A heap-backed vector with fixed maximum capacity for no_std environments.
CapVec<T, N> stores up to N values of type T contiguously in
a backing buffer. Unlike alloc::vec::Vec, its maximum capacity is fixed
at compile time and never grows after construction. Its logical length can
still change dynamically from 0 to N.
This is useful when a fixed upper bound is part of the program design, but a
stack-allocated [T; N] would be too large or too inflexible. The crate uses
alloc and is compatible with #![no_std] targets that provide a global
allocator.
§Allocation model
CapVec::new creates an empty vector without allocating. The backing buffer
is created on the first successful push,
insert, extend, or when constructing
from a full array. For non-zero-sized buffers this allocates heap storage for
exactly N elements; zero-sized buffers use a dangling non-null sentinel.
The buffer is reused by operations such as clear. Use
shrink_to_fit on an empty vector to drop the
backing buffer.
§Capacity
Maximum capacity is encoded in the const generic parameter N. The
capacity method returns the currently-created backing
buffer size: 0 before the buffer is created, otherwise N. Use
max_capacity to get the fixed upper bound and
spare_capacity to get the remaining room before
the vector is full. Operations that would exceed the maximum capacity return
the provided element instead of reallocating. CapVec<T, 0> is valid and can
never hold an element.
use cap_vec::CapVec;
let mut v = CapVec::<i32, 4>::new();
assert!(v.is_empty());
v.push(10).unwrap();
v.push(20).unwrap();
v.push(30).unwrap();
assert_eq!(v.len(), 3);
assert_eq!(v.first(), Some(&10));
assert_eq!(v.get(1), Some(&20));
assert_eq!(v.last(), Some(&30));
assert_eq!(&v[..], &[10, 20, 30]);
assert_eq!(v.remove(1), Some(20));
assert_eq!(v.pop(), Some(30));
assert_eq!(v.pop(), Some(10));Structs§
- CapVec
- A heap-backed vector with compile-time fixed maximum capacity.
- Drain
- An iterator over elements removed by
CapVec::drain. - Into
Iter - A consuming iterator over a
CapVec.