liveBook · Manning

Exact-width integer type

As explained in Embedded Software with Rust

A fixed-width integer type is an integer type whose bit width is specified rather than selected by implementation defaults.

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

How Embedded Software with Rust covers it

How deep it goes
Explains enum-size mismatches, matching representations, typedef semantics, and checked wrappers through focused examples.
Examples
Shows a device-state enum, C typedef and constants, state-transition function, struct field, and checked wrapper.
What you can do after
Apply explicit representations and fixed-width typedefs to match shared Rust–C state values, and check incoming bytes with a wrapper.
How it connects
Connects integer widths with enum representation, typedefs, struct layout, transparent wrappers, and value validation.

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.