Encoding program invariants in the type system so that violating them is a compile error, not a runtime error.
Typestate pattern
A type carries its state as a type parameter. Operations that require a specific state can only be called when the type is in that state — enforced by the compiler.
// CAN controller states
struct Uninitialized;
struct Configured;
struct Active;
struct CanController<State> {
peripheral: CanPeripheral,
_state: PhantomData<State>,
}
impl CanController<Uninitialized> {
pub fn configure(self, bitrate: u32) -> CanController<Configured> {
// ... configure peripheral
CanController { peripheral: self.peripheral, _state: PhantomData }
}
}
impl CanController<Configured> {
pub fn activate(self) -> CanController<Active> { ... }
}
impl CanController<Active> {
pub fn transmit(&mut self, frame: &CanFrame) -> Result<(), Error> { ... }
// transmit is ONLY callable when Active — compile error otherwise
}You cannot call transmit on an unconfigured controller. The type system physically prevents it.
Used in SpaceCAN's CAN controller abstraction and throughout Cerberus-OS's resource management. The PMP configuration API uses typestate to enforce that PMP regions are fully configured before being activated.