tinyvec provides vector-like collections with inline storage. Its hybrid TinyVec keeps elements inline until capacity is exceeded, then moves them to a heap allocation. This avoids allocation in the common case while allowing a buffer to grow when needed. section 7.3.3
#![no_std]
extern crate alloc;
use tinyvec::TinyVec;
// (a global allocator must be installed as in section 7.2)
fn my_function() {
// Backed by an inline [u16; 8] array on the stack.
let mut samples: TinyVec<[u16; 8]> = TinyVec::new();
// The first eight pushes stay inline; no allocator involvement.
for value in [10, 20, 30, 40, 50, 60, 70, 80] {
samples.push(value);
}
// The ninth push triggers the transition.
samples.push(90);
// Subsequent pushes grow the heap buffer as needed.
samples.push(100);
}
A local TinyVec holds eight u16 samples inline. The ninth push triggers a heap allocation; the tenth appends to the heap-backed buffer. section 7.3.3
For this hybrid container in no_std firmware, the program still needs extern crate alloc and an installed global allocator. The heap may be used rarely, but allocation failure and fragmentation remain concerns. Use is_inline() and is_heap() to check the current storage mode. section 7.3.3 section 7.0
tinyvec uses safe Rust and requires its element type to implement Default. Primitive types such as u16 satisfy this requirement; a custom type can derive or implement Default when appropriate. If a type cannot reasonably have a default value, smallvec is an alternative that uses unsafe internally to avoid that requirement. section 7.3.3
Choose a hybrid container when typical buffers are small, much larger buffers are rare, and the project already has an allocator. For firmware that does not otherwise need a heap, heapless or arrayvec offers a fixed-capacity alternative without allocator overhead or fragmentation risk. section 7.3.4 section 7.3
