Week 22 - no_std, Custom Allocators, Embedded Targets¶
22.1 Conceptual Core¶
#![no_std]removes thestdprelude and the default allocator. Code becomes runnable on bare metal (no OS), in kernels, in WASM-without-runtime, and in embedded MCUs.core(no allocator) andalloc(allocator-required) are the layers belowstd.allocprovidesBox,Vec,String, etc., but requires you to nominate a#[global_allocator].- Custom allocators: implement
core::alloc::GlobalAlloc(for the global one) or the unstableAllocatortrait (for per-collection allocators, on nightly).
22.2 Mechanical Detail¶
- Cross-compilation:
rustup target add thumbv7em-none-eabihf(Cortex-M4F),rustup target add riscv64gc-unknown-linux-gnu,rustup target add wasm32-unknown-unknown.cargo build --target=...and the right linker via.cargo/config.toml. - Embedded toolchain:
cargo-binutils,probe-rsfor flashing,cortex-m,embedded-haltraits,rticorembassyfor concurrency. The embedded ecosystem is its own discipline; the goal here is fluency, not specialization. - Allocators worth knowing:
mimalloc,jemalloc(tikv-jemallocator),snmalloc,bumpalo(arena),linked_list_allocator(no_std heap). Switching the global allocator is one line inmain.rs. - Panic in
no_std: you must provide a#[panic_handler]. Common implementations: spin forever, write to a UART, reset the chip.
22.3 Lab-"Two Targets"¶
- Bare metal: blink an LED on a real or QEMU-emulated Cortex-M target using
embassy. Optional but recommended. - Custom allocator: write a simple bump allocator. Use it as
#[global_allocator]for a smallno_std + allocbenchmark and observe behavior.
22.4 Idiomatic & Clippy Drill¶
clippy::std_instead_of_alloc,clippy::std_instead_of_core,clippy::alloc_instead_of_core. These force the discipline of leveling imports correctly-ano_stdlibrary that imports fromstdwill not compile downstream.
22.5 Production Hardening Slice¶
- Add a CI matrix entry for
cargo build --target=thumbv7em-none-eabihf --no-default-features. Library crates should compile inno_stdmode (gated by a feature flag)-this is a real selling point and a frequent regression source.