In Rust firmware with no heap, how does `heapless::Vec<T, N>` differ from `alloc::vec::Vec<T>`, and what does `push` do once it is full?
answer
- capacity lives in the type
- storage inline, no allocator
- the rejected value comes back
- fmt::Write into a fixed string
- a view type erases N
basics
~20 sheapless::Vec<T, N> keeps its buffer inline with a capacity N fixed in the type, so it needs no allocator and never grows. push returns Result<(), T>: when full it returns Err(item), handing the value back.
solid answer
~40 s`heapless::Vec<T, N>` stores up to `N` elements inline, in the value itself, so it can sit on the stack, in a `static` or inside a driver struct with no allocator at all. Capacity is a const generic, so `Vec<u16, 4>` and `Vec<u16, 8>` are different types and `push` is constant time, never amortised. Because it cannot grow, every growing operation is fallible: `push` returns `Result<(), T>` and gives the rejected element back in `Err`, while `extend_from_slice`, `from_slice` and `heapless::String::push_str` return `Err(CapacityError)` in heapless 0.9. `heapless::String<N>` implements `core::fmt::Write`, so `write!` works and returns `fmt::Error` when the text does not fit. `alloc::vec::Vec` grows by reallocating, needs a `#[global_allocator]`, and reports exhaustion only through `handle_alloc_error`.
code
rust · 21 linesuse core::fmt::Write;
use heapless::{String, Vec};
fn main() {
// Capacity is part of the type: room for 4 readings, stored inline.
let mut readings: Vec<u16, 4> = Vec::new();
for r in [0x29B1, 0x31C3, 0x0000, 0xFFFF] {
readings.push(r).unwrap();
}
// A fifth push does not reallocate: it hands the value back.
match readings.push(0x1234) {
Ok(()) => println!("stored"),
Err(rejected) => println!("full, got back {rejected:#06x}"),
}
let mut line: String<16> = String::new();
write!(line, "crc={:04x}", readings[0]).unwrap();
println!("{line} ({} of {} bytes)", line.len(), line.capacity());
println!("push_str overflow: {:?}", line.push_str(" too long for it"));
println!("size_of Vec<u16, 4> = {}", core::mem::size_of::<Vec<u16, 4>>());
}go deeper
Know that heapless collections carry their capacity in the type, keep their storage inline, and return a Result from push instead of growing.
Explain Err(item) versus Err(CapacityError), what write! returns on a full heapless::String, and how size_of grows with N.
Size buffers from worst-case traffic, decide per call site whether a full buffer drops, counts or resets, and keep large buffers out of moves and stack frames.
Set a team rule for when firmware uses fixed-capacity collections versus a heap, trading predictable timing and memory for flexibility.
## Two ways to own a growable list | | `alloc::vec::Vec<T>` | `heapless::Vec<T, N>` | |---|---|---| | storage | heap buffer through the global allocator | inline array of `N` slots inside the value | | capacity | grows by reallocating | fixed by the type parameter `N` | | needs | `extern crate alloc` and a `#[global_allocator]` | nothing beyond `core` | | `push` | returns `()`, reallocates if needed | returns `Result<(), T>` | | out of room | `handle_alloc_error`, a panic in `no_std` | `Err(item)`, the caller decides | | `push` time | amortised constant | constant, no reallocation | The heapless crate's own documentation states the motivation: its structures are backed by memory reserved up front, so there is no out-of-memory condition and no unbounded worst-case time for a push, which matters for hard real-time code. ## Capacity is part of the type `N` is a const generic, so `heapless::Vec<u16, 4>` and `heapless::Vec<u16, 8>` are different types. Consequences: - The memory is reserved even when the vector is empty: `size_of::<heapless::Vec<u16, 4>>()` is 12 bytes on thumbv7em-none-eabihf (8 bytes of slots plus a 4-byte length) and 16 on a 64-bit host. - heapless 0.9 adds a third parameter, `LenT`, for the length's type: `heapless::Vec<u16, 4, u8>` is 10 bytes on the same target. - Functions that should accept any capacity take a slice (`&[T]`, through `Deref`), are generic over `const N: usize`, or take `&heapless::VecView<T>`, the unsized view returned by `as_view()`. - Because the value is the storage, moving it copies all `N` slots; large buffers usually live in a `static` or inside a long-lived driver struct. ## What happens when it is full Every operation that adds elements is fallible, and the error type tells you what you get back: 1. `push(item)` returns `Err(item)`: the element is handed back, so nothing is lost silently and the caller can retry, drop it or count it. 2. `extend_from_slice(&[T])` and `Vec::from_slice` return `Err(CapacityError)` and leave the vector unchanged when the slice does not fit. 3. `heapless::String::push_str` and `push` return `Err(CapacityError)`. Before 0.9 these, like `extend_from_slice` and `from_slice`, returned `Err(())`; the 0.9 changelog records the switch. 4. `write!` into a `heapless::String<N>` goes through its `core::fmt::Write` impl, which maps the failure to `core::fmt::Error`. The pieces that fitted before the failure stay in the string, so `write!(s, "crc={:04x}", 0x29B1)` into a `String<4>` returns `Err` and leaves `"crc="`. Treat `unwrap()` on these results as a design choice, not a habit: on firmware an `unwrap` is a panic, which ends in the panic handler. ## Reading the example - The fifth `push` prints "full, got back 0x1234": the rejected value travelled back inside `Err`. - `write!` used 8 of the string's 16 bytes, and `capacity()` reports `N`, not a growable figure. - `push_str` with 16 more bytes returns `Err(CapacityError)`, and the string keeps its earlier contents, "crc=29b1": a whole string that does not fit is not partially appended. - The size line prints 16 on the 64-bit host and would be 12 on thumbv7em-none-eabihf: the storage is part of the value. ## Everyday operations still work `heapless::Vec` dereferences to a slice, so `iter`, indexing, `contains`, `sort_unstable` and `binary_search` behave as they do on any `&[T]` or `&mut [T]`. `pop` returns an `Option`, `clear` empties the vector without freeing anything, and `from_slice` builds one from existing data in a single fallible step. ## Choosing between them - Use **heapless** when the maximum is known (a frame buffer, the last eight sensor readings, a log line) and you want no allocator and predictable timing. - Use **`alloc::vec::Vec`** when sizes genuinely vary and the device has a heap you trust, for example data loaded once at start-up. - Mixing is normal: heapless for the hot paths and interrupt-side buffers, `alloc` for configuration parsed at boot. Sharing a heapless buffer between an interrupt and the main loop still needs a critical section or a queue; the interrupts material covers that. heapless also ships fixed-capacity queues, maps and a deque, which follow the same fallible pattern.
- How do you write a Rust function that accepts a `heapless::Vec<u16, N>` of any capacity without making it generic?Take a slice, `&[u16]`, for read-only work, since `heapless::Vec` derefs to one. For code that must push, heapless 0.9 offers `VecView<T>`, the unsized view of any capacity: take `&mut heapless::VecView<u16>` and call `as_mut_view()` at the call site. Otherwise make the function generic over `const N: usize`.
- Why does heapless 0.9 add a length-type parameter to `heapless::Vec`?The length is stored inline next to the slots, and by default it is a `usize`, which is 4 bytes on a 32-bit microcontroller. For small capacities a `u8` length is enough, so `heapless::Vec<u16, 4, u8>` is 10 bytes instead of 12 on thumbv7em-none-eabihf, which adds up across many buffers in RAM.
- Saying `heapless::Vec` falls back to the heap once it is full.
- Calling `unwrap()` on every `heapless::Vec::push` in an interrupt handler.
- Assuming `heapless::Vec<T, N>` uses no memory until elements are pushed.
- Believing a full `push` drops the element and returns a bare error.
- Expecting `write!` into a full `heapless::String` to panic.