`#[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
