liveBook · Manning

Fixed-capacity structure

As explained in Embedded Software with Rust

A fixed-capacity container is a container whose maximum number of stored elements is bounded in advance and whose storage can be provided without dynamic allocation.

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

How Embedded Software with Rust covers it

How deep it goes
Explains inline storage, capacity-dependent types, and fallible operations, with a worked parser and a queue use case.
Examples
Uses a 32-byte array buffer and a UART command parser that discards an overflowing line.
What you can do after
Apply it via heapless to build bounded buffers and handle capacity errors in firmware.
How it connects
Connects fixed capacity to no_std, arrays, dynamic allocation, memory fragmentation, and single-producer single-consumer queues.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.