liveBook · Manning

Smallvec

As explained in Embedded Software with Rust

A Rust crate providing vector-like collections that store a limited number of elements inline before spilling to the heap.

smallvec provides SmallVec, a vector-like collection that stores a limited number of elements inline and moves them to the heap when that capacity is exceeded. This avoids allocation in the common case while allowing the collection to grow beyond its inline capacity. section 7.3.3

In embedded firmware, this is useful when buffers are usually small but occasionally much larger. A no_std program still needs extern crate alloc and an installed global allocator: smallvec avoids some allocations, not all of them. section 7.3.3 section 7.3.4

#![no_std]
extern crate alloc;

use smallvec::SmallVec;

let mut samples: SmallVec<[u16; 8]> = SmallVec::new();
samples.push(512);
samples.push(1024);
// ...
samples.push(4096); // may transition to heap after eight items

This SmallVec holds up to eight u16 values inline; adding more than eight causes it to transition to heap storage. section 7.3.3

Unlike tinyvec, smallvec uses unsafe internally and does not require its element type to implement Default. Prefer tinyvec when Default is available; use smallvec when it is not. If a known fixed capacity is sufficient, heapless or arrayvec avoids the allocator entirely. A hybrid container is rarely worthwhile when the firmware otherwise has no heap. section 7.3.3 section 7.3.4

How Embedded Software with Rust covers it

How deep it goes
Explains inline-to-heap transitions and allocator requirements without detailing the internal implementation.
Examples
Demonstrates a SmallVec of u16 values with capacity for eight inline elements.
What it assumes
Assumes a no_std project can install a global allocator and use alloc.
What you can do after
Apply it via SmallVec to keep a typical small buffer inline while permitting heap-backed growth.
How it connects
Connects SmallVec with alloc, tinyvec, heapless, and arrayvec through memory and safety trade-offs.

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.