liveBook · Manning

Repr(transparent)

As explained in Embedded Software with Rust

repr(transparent) is a Rust representation attribute that gives a single-field wrapper the same memory representation as its field.

#[repr(transparent)] gives a single-field Rust wrapper the same memory representation as its field. The wrapper remains a distinct Rust type, so the compiler can catch accidental mix-ups without changing how the value appears in memory. section 8.2.4

#[repr(transparent)]
pub struct SensorId(pub u16);

SensorId is distinct from u16 in Rust but has the same representation as its u16 field. This lets C use a corresponding uint16_t without adding wrapper data. section 8.2.4

A transparent wrapper does not validate the value inside it. When C can supply an unexpected byte, check that byte before treating it as a known state. section 8.2.4

#[repr(transparent)]
pub struct DeviceState(pub u8);

pub const DEVICE_STATE_IDLE: DeviceState = DeviceState(0);
pub const DEVICE_STATE_ACTIVE: DeviceState = DeviceState(1);
pub const DEVICE_STATE_ERROR: DeviceState = DeviceState(2);

enum CheckedDeviceState {
    Idle,
    Active,
    Error,
}

impl DeviceState {
    fn checked(self) -> Option<CheckedDeviceState> {
        match self.0 {
            0 => Some(CheckedDeviceState::Idle),
            1 => Some(CheckedDeviceState::Active),
            2 => Some(CheckedDeviceState::Error),
            _ => None,
        }
    }
}

DeviceState wraps a u8 for the C boundary. Its checked method maps known bytes to internal enum variants and returns None for other values. section 8.2.4

How Embedded Software with Rust covers it

How deep it goes
Explains the layout guarantee and demonstrates checked conversion of incoming byte values.
Examples
Shows a u16 sensor identifier and a u8 device state wrapper with validation.
What you can do after
Apply it using Rust's #[repr(transparent)] to create distinct wrappers for C-facing values.
How it connects
Connects representation attributes with newtypes, enums, and Rust-C interoperability.

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.