Unsafe Rust permits operations whose safety the compiler cannot verify. An unsafe block does not turn off Rust’s checks; it marks a place where the programmer must verify that safety guarantees hold. Such operations include dereferencing raw pointers, calling unsafe functions or methods, and accessing mutable static variables. section 5.2.1
Keep unsafe operations small and review them carefully. A narrow wrapper can isolate raw register access so the rest of the firmware does not need to handle pointers. Peripheral Access Crates (PACs) and Hardware Abstraction Layers (HALs) extend this idea by hiding low-level operations behind safer abstractions. section 5.2.1 section 5.3.1
use core::ptr;
// # Safety
// - The caller must ensure the RCC clock for GPIOA is enabled and GPIOA pin 0
// is configured as a push-pull output.
// - The pointer must be valid for the target MCU (here: STM32F103 GPIOA).
fn set_gpioa_pin0_high() {
// STM32F103 GPIOA base = 0x4001_0800
// BSRR offset = 0x10 (lower 16 bits: set, upper 16 bits: reset)
const GPIOA_BSRR: *mut u32 = (0x4001_0800 + 0x10) as *mut u32;
unsafe {
// Set PA0 (bit 0) atomically.
ptr::write_volatile(GPIOA_BSRR, 1 << 0);
}
}
This STM32F103 example confines a volatile write to an unsafe block. The BSRR register sets a pin without the read-modify-write race possible with ODR. The listing assumes the correct device, enabled GPIO clock, and pin configuration; its safe function signature does not enforce those assumptions. section 5.3.1
A wrapper still requires correct addresses, offsets, and peripheral setup. Atomic register behavior avoids a particular race; it does not remove the need to check the wrapper’s assumptions. Manual wrappers also remain tied to a device family. section 5.3.1
The same isolation principle applies at a Rust–C boundary: keep the interface small, use fixed-layout types and simple error codes, and carefully review the unsafe boundary while keeping the implementation behind it safe. Layout checks and tests help detect problems during migration. section 8.6




