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
