Saltar a contenido

Week 22 - no_std, Custom Allocators, Embedded Targets

22.1 Conceptual Core

  • #![no_std] removes the std prelude 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) and alloc (allocator-required) are the layers below std. alloc provides Box, Vec, String, etc., but requires you to nominate a #[global_allocator].
  • Custom allocators: implement core::alloc::GlobalAlloc (for the global one) or the unstable Allocator trait (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-rs for flashing, cortex-m, embedded-hal traits, rtic or embassy for 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 in main.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 small no_std + alloc benchmark 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-a no_std library that imports from std will 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 in no_std mode (gated by a feature flag)-this is a real selling point and a frequent regression source.

Comments