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