In a Rust HAL, why does turning a GPIO pin into an output consume the pin, and how does that make `set_high` on an input a compile error?
answer
- the mode as a type parameter
- self by value, a new type back
- a trait impl for one mode only
- zero bytes at run time
- drivers bound on OutputPin
basics
~20 sHALs put a pin's mode in its type. The conversion takes self by value and returns the pin with its new mode, and OutputPin is implemented only for output modes, so set_high on an input pin does not compile.
solid answer
~40 sA HAL pin type carries its mode as a type parameter, for example `Pa5<Input>` and `Pa5<Output>`, where the mode types are zero-sized. `into_push_pull_output(self) -> Pa5<Output>` writes the mode register and **consumes** the input pin, so the old value is gone: using it again is `E0382`, and no two parts of the program can hold the same pin in different modes. The HAL implements `embedded_hal::digital::OutputPin` only for the output type, so `set_high()` on a `Pa5<Input>` fails with `E0599`, and passing it to a driver bounded on `P: OutputPin` fails with `E0277`. The mode costs nothing at run time: `size_of::<Pa5<Output>>()` is 0 for a pin holding only `PhantomData`. Drivers stay portable because they ask for the trait, not for the HAL's pin type.
code
rust · 39 linesuse core::convert::Infallible;
use core::marker::PhantomData;
use embedded_hal::digital::{ErrorType, OutputPin};
pub struct Input;
pub struct Output;
/// GPIO pin PA5; MODE is a zero-sized type that exists only at compile time.
pub struct Pa5<MODE> {
_mode: PhantomData<MODE>,
}
impl Pa5<Input> {
/// Consumes the input pin; the mode register write is elided in this sketch.
pub fn into_push_pull_output(self) -> Pa5<Output> {
Pa5 { _mode: PhantomData }
}
}
impl<MODE> ErrorType for Pa5<MODE> {
type Error = Infallible;
}
impl OutputPin for Pa5<Output> {
fn set_high(&mut self) -> Result<(), Infallible> { Ok(()) } // write the set bit
fn set_low(&mut self) -> Result<(), Infallible> { Ok(()) } // write the reset bit
}
fn blink<P: OutputPin>(led: &mut P) -> Result<(), P::Error> {
led.set_high()?;
led.set_low()
}
fn main() {
let pin: Pa5<Input> = Pa5 { _mode: PhantomData };
let mut led = pin.into_push_pull_output();
blink(&mut led).unwrap();
println!("{} bytes", core::mem::size_of::<Pa5<Output>>());
}go deeper
Recall that HAL pins carry their mode in the type and that a conversion such as into_push_pull_output returns a new pin value.
Explain self by value, OutputPin implemented only for output modes, and the E0599 and E0382 errors that misuse produces.
Weigh compile-time pin modes against arrays of pins and run-time mode switches, and know the erased or dynamic pin types HALs offer for those cases.
Keep drivers bound on embedded-hal pin traits and leave mode typestate to the HAL, so pin assignments can change per board without touching drivers.
## The hardware rule being enforced A GPIO pin is configured through mode registers: input, push-pull output, open-drain output, an alternate function for a peripheral, analog. Driving an input pin high does nothing useful, and two parts of the firmware configuring the same pin differently is a classic board bring-up bug. Many Rust HAL crates move this rule into the type system with **typestate**: the pin's current mode is part of its type, so the compiler knows it. ## How a HAL encodes the mode 1. Each mode is a **zero-sized type**: `struct Input;`, `struct Output;`. Real HALs often nest them, such as an output mode parameterised by push-pull or open-drain. 2. The pin is generic over the mode and stores it only as `PhantomData<MODE>`, so the type carries the mode while the value holds no data. 3. Conversion methods are implemented for one mode and take `self` **by value**: `impl Pa5<Input> { fn into_push_pull_output(self) -> Pa5<Output> { ... } }`. The body writes the mode register, then returns a value of the new type. 4. Trait impls are chosen per mode: `impl OutputPin for Pa5<Output>`, and `InputPin` only for the input modes. Because the conversion consumes the old value, the borrow checker treats the input pin as moved. A later use is `` error[E0382]: use of moved value: `pin` ``, and there is no way to keep an input handle and an output handle to the same pin. ## What the compiler rejects | Mistake | rustc error | |---|---| | `pin.set_high()` on a `Pa5<Input>` | `E0599`: no method named `set_high` found; the help names `OutputPin` | | `blink(&mut pin)` where `blink<P: OutputPin>` | `E0277`: the trait bound `Pa5<Input>: OutputPin` is not satisfied | | using the input pin after `into_push_pull_output()` | `E0382`: use of moved value | All three are compile-time errors; none of them adds a run-time mode check. ## The cost at run time `core::mem::size_of::<Pa5<Output>>()` prints `0` for the sketch in the code example: the mode parameter exists only in the type, and the method calls inline to the same register writes hand-written register code would perform. The checks are free; what typestate costs is flexibility, covered below. ## How it meets embedded-hal - `embedded_hal::digital::OutputPin` has `set_low`, `set_high` and a provided `set_state`; `StatefulOutputPin` adds `is_set_high`, `is_set_low` and `toggle`; `InputPin` has `is_high` and `is_low`. - In 1.0 the `InputPin` and `StatefulOutputPin` methods take `&mut self` (the 1.0.0-rc.3 changelog entry), so reading a pin needs mutable access to it. - `set_state` takes a `PinState` (`Low` or `High`), which converts from and to `bool` and implements `!`, so `led.set_state(on.into())` sets a pin from a `bool` without a branch; `StatefulOutputPin::toggle` has a default body built on `is_set_low`. - Every method returns `Result<_, Self::Error>`. A HAL whose pins cannot fail sets `type Error = core::convert::Infallible` through `ErrorType`. - `OutputPin` and `InputPin` are also implemented for `&mut T`, so an application can lend a pin to a driver and take it back. - A driver asks for `P: OutputPin`, never for the HAL's pin type, so an LED or reset-line driver compiles against any HAL whose pin is configured as an output. ## Where typestate gets in the way - **Arrays of pins.** `Pa5<Output>` and `Pb3<Output>` are different types, so they cannot share one array. Many HALs offer a way to erase the pin number or port into a single type indexed at run time. - **Modes that change at run time.** A bidirectional data line flips between input and output during a protocol. Each conversion consumes and returns, so the code must thread the pin through every switch, or use a dynamic-mode pin type that checks the mode at run time and reports misuse as an error. - **Alternate functions.** A pin handed to a HAL's I2C or SPI constructor is usually converted into an alternate-function mode type first, so it cannot also be driven as a plain GPIO while the peripheral owns it. - **Owners that outlive a mode.** A struct holding the pin changes type with the pin's mode, which pushes generics up into the owner. So typestate pins are a default, not an absolute: the HAL gives a compile-time-checked path for the common case and an escape hatch with run-time checks for the rest.
- In a Rust HAL, how can two drivers both need the same output pin, such as a shared reset line?Ownership allows one owner. Either one driver takes the pin and exposes the operation, or the application keeps the pin and lends it with `&mut pin` for each call, since embedded-hal implements `OutputPin` for `&mut T` where `T: OutputPin`. Truly concurrent sharing, such as from an interrupt handler, needs a lock and belongs with interrupts and shared state.
- How do typed pins get from a PAC's GPIO port into a HAL in Rust?A HAL typically takes the PAC's GPIO port peripheral by value and splits it into one value per pin, each typed with its reset mode. Because the PAC port was moved into the HAL, no code outside the HAL can rewrite that port's mode register, so the type of each pin stays truthful.
- The mode parameter adds a byte per pin to track the mode at run time.
- Calling set_high on an input pin compiles and returns an error at run time.
- into_push_pull_output borrows the pin, so the input handle stays usable.
- A portable driver should take the HAL's concrete pin type as its parameter.
- embedded-hal 1.0's InputPin::is_high takes &self, so pins read through shared references.