A fixed-capacity structure stores up to a predetermined number of elements without dynamically allocating its backing storage. In embedded Rust, it offers a predictable, heap-free alternative when the maximum buffer size is known. section 7.3 section 7.0
A no_std program can use arrays from core without a global allocator. For a collection-like API, heapless provides inline-storage types such as Vec, String, Deque, and queues. Capacity is part of the type: Vec<u8, 64> and Vec<u8, 128> are distinct types. section 1.3.1 section 7.3.1
#![no_std]
fn my_function() {
// Will not compile in pure `no_std` (no allocator available):
// let v: Vec<u8> = Vec::new();
// Use fixed-capacity data instead:
let mut buf: [u8; 32] = [0; 32];
let mut len = 0;
if len < buf.len() { buf[len] = 0xAB; len += 1; }
}
This array-backed buffer tracks its current length separately and checks capacity before adding a byte. section 1.3.1
The limit must be handled explicitly. A heapless Vec push returns Result<(), T>, returning the rejected value on failure; String::push_str also returns a Result. Choose what to do when the structure is full rather than silently losing data. section 7.3.1
UART command buffer
A serial parser accumulates incoming bytes in a fixed-capacity Vec. On newline, it processes the line and clears the buffer for reuse. If the buffer fills first, it clears the partial line and returns an error response. section 7.3.1
#![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
}
The parser uses separate capacities for its input buffer and response string. section 7.3.1
For passing data between an interrupt handler and a main loop, heapless also provides a fixed-capacity single-producer single-consumer queue that can be split into producer and consumer halves. section 7.3.1
