An exact-width integer type specifies its bit width instead of leaving the choice to an implementation default. At a Rust–C boundary, matching widths helps prevent layout mismatches that can cause later struct fields to be read from the wrong memory locations. section 8.2.4
For a shared state value, give the Rust enum an explicit representation and use a fixed-width integer typedef with named constants in C. Here, Rust’s u8 representation matches C’s uint8_t. section 8.2.4
#[repr(u8)]
pub enum DeviceState {
Idle = 0,
Active = 1,
Error = 2,
}
The Rust enum uses a one-byte representation and assigns each variant a value. section 8.2.4
// C side typedef uint8_t DeviceState; #define DEVICE_STATE_IDLE 0 #define DEVICE_STATE_ACTIVE 1 #define DEVICE_STATE_ERROR 2
The C typedef names the same one-byte integer type; the constants supply the corresponding values. section 8.2.4
The C typedef is an alias, not a distinct enum: it can hold any byte. If C may supply an invalid value, a transparent Rust wrapper can check the byte before converting it to a checked 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,
}
}
}
This wrapper accepts a byte and checks whether it matches a defined state. section 8.2.4
