heapless provides fixed-capacity collections for Rust programs that cannot or do not want to use a heap. Their backing storage is inline, so they need no allocator and avoid heap fragmentation. This is useful in embedded firmware, where RAM is limited and allocation failure can be difficult to recover from. section 7.3 section 7.0
Capacity is part of each type: Vec<u8, 64> and Vec<u8, 128> are different types. The library also provides String, Deque, BinaryHeap, maps, sets, and queues. Its Vec and String types are not interchangeable with their alloc counterparts. section 7.3.1
A fixed-capacity buffer cannot grow when full. Operations that may exceed its capacity return a Result: Vec::push returns the rejected value on error, while String::push_str reports an error. Choose a capacity for the task and handle overflow explicitly; inline storage also consumes memory wherever the container is placed, including the stack. section 7.3.1 section 7.5
#![no_std]
#![no_main]
use core::fmt::Write;
use heapless::{String, Vec};
const LINE_LEN: usize = 64;
const RESP_LEN: usize = 32;
// Append one byte to the line buffer. Returns Some(response) when a
// complete line has been processed, None while still accumulating.
fn feed_byte(
line: &mut Vec<u8, LINE_LEN>,
byte: u8,
) -> Option<String<RESP_LEN>> {
if byte == b'\n' {
let response = handle_command(line.as_slice());
line.clear();
return Some(response);
}
if line.push(byte).is_err() {
// The line buffer filled before a newline arrived.
// Discard the partial line and report the overflow.
line.clear();
let mut err = String::<RESP_LEN>::new();
let _ = err.push_str("ERR overflow");
return Some(err);
}
None
}
fn handle_command(line: &[u8]) -> String<RESP_LEN> {
let mut response = String::<RESP_LEN>::new();
match line {
b"HELLO" => {
let _ = response.push_str("HOW DO YOU DO?");
}
b"VERSION" => {
let _ = write!(response, "v{}.{}", 1, 0);
}
_ => {
let _ = response.push_str("ERR unknown");
}
}
response
}
This UART command parser accumulates bytes in a 64-byte heapless Vec and produces a 32-byte heapless String. On overflow it clears the partial line and reports an error; after a newline it clears and reuses the buffer. section 7.3.1
For communication between an interrupt handler and a main loop, spsc::Queue is a fixed-capacity, lock-free single-producer single-consumer queue that can be split into producer and consumer halves. section 7.3.1
Use arrayvec when only a fixed-capacity vector or string is needed and a smaller dependency is preferable. Its basic push operations panic on overflow, though fallible variants are available. Hybrid containers such as smallvec and tinyvec can use inline storage for typical cases and an allocator for rare larger cases, but are less attractive when firmware otherwise needs no heap. section 7.3.2 section 7.3.4
