liveBook · Manning

Safe wrapper

As explained in Embedded Software with Rust

A safe wrapper is an interface that encapsulates operations requiring unsafe interaction behind safe-to-call abstractions.

A safe wrapper places operations that require unsafe Rust behind a narrow interface that callers can use safely. Its implementation must uphold the operation’s requirements, for example by validating inputs or documenting hardware setup assumptions. section 5.3.1 section 8.2.5

A wrapper can make an unsafe boundary easier to review by:

  • Keeping unsafe calls in a small, well-defined place instead of scattering them through application code. section 8.2.5
  • Checking inputs or hardware assumptions before performing the operation. section 5.3.1 section 8.2.5
  • Returning a Rust Result when the underlying operation can fail, so callers receive a clear success or error. section 8.2.5
unsafe extern "C" {
    fn hardware_write(address: u32, data: u8);
}

pub fn safe_hardware_write(address: u32, data: u8) -> Result<(), &'static str> {
    if !valid_address(address) {
        return Err("Invalid hardware address");
    }

    unsafe {
        hardware_write(address, data);
    }

    Ok(())
}

fn valid_address(addr: u32) -> bool {
    (addr >= 0x2000_0000) && (addr <= 0x2000_FFFF)
}

This wrapper checks the hardware address before calling an unsafe C function and reports invalid input with Result. section 8.2.5

How Embedded Software with Rust covers it

How deep it goes
Shows validation, error translation, and GPIO register selection, while noting manual MMIO wrappers remain device-specific.
Examples
Uses an STM32 GPIO BSRR write, a non-negative C addition wrapper, and a hardware-write wrapper with address validation.
What you can do after
Apply it by containing unsafe calls behind validated Rust functions and translating failures into Result where needed.
How it connects
Connects unsafe Rust with FFI, memory-mapped I/O, Result, and Peripheral Access Crates.

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.