liveBook · Manning

Repr(u8)

As explained in Embedded Software with Rust

repr(u8) is a Rust representation attribute that gives an enum an unsigned 8-bit integer representation.

`#[repr(u8)]` gives a Rust enum an unsigned 8-bit representation. It can make a state’s size predictable when passing it between Rust and C. section 8.2.4

#[repr(u8)]
pub enum DeviceState {
    Idle = 0,
    Active = 1,
    Error = 2,
}

The three states have explicit byte values: 0, 1, and 2. section 8.2.4

On the C side, a `uint8_t` typedef and named constants can represent the same values. The typedef improves readability, but C can still assign an arbitrary byte such as 4. That byte is not a valid variant of the Rust enum. 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,
        }
    }
}

For input that may contain invalid bytes, a transparent `u8` wrapper can check the value before converting it to a Rust enum. The check returns `None` for unrecognized values. section 8.2.4

How Embedded Software with Rust covers it

How deep it goes
Explains byte layout and invalid-value risks, then demonstrates a checked transparent-wrapper alternative.
Examples
Uses a three-state device enum, a C state field, and a checked byte wrapper.
What you can do after
Apply it to a Rust-C state interface and choose a checked wrapper when incoming bytes may be invalid.
How it connects
Connects enum representation to C typedefs, foreign-function interfaces, and transparent wrappers.

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.