# Design Contracts

In our last chapter, we wrote an interface that didn't enforce design contracts. Let's take another look at our imaginary GPIO configuration register:

Name | Bit Number(s) | Value | Meaning | Notes
--- | --- | --- | --- | ---
enable | 0 | 0 | disabled | Disables the GPIO
|  | 1 | enabled | Enables the GPIO
direction | 1 | 0 | input | Sets the direction to Input
|  | 1 | output | Sets the direction to Output
input_mode | 2..3 | 00 | hi-z | Sets the input as high resistance
|  | 01 | pull-low | Input pin is pulled low
|  | 10 | pull-high | Input pin is pulled high
|  | 11 | n/a | Invalid state. Do not set
output_mode | 4 | 0 | set-low | Output pin is driven low
|  | 1 | set-high | Output pin is driven high
input_status | 5 | x | in-val | 0 if input is < 1.5v, 1 if input >= 1.5v

If we instead checked the state before making use of the underlying hardware, enforcing our design contracts at runtime, we might write code that looks like this instead:

    /// GPIO interface
    struct GpioConfig {
        /// GPIO Configuration structure generated by svd2rust
        periph: GPIO_CONFIG,
    }

    impl GpioConfig {
        pub fn set_enable(&mut self, is_enabled: bool) {
            self.periph.modify(|_r, w| {
                w.enable().set_bit(is_enabled)
            });
        }

        pub fn set_direction(&mut self, is_output: bool) -> Result<(), ()> {
            if self.periph.read().enable().bit_is_clear() {
                // Must be enabled to set direction
                return Err(());
            }

            self.periph.modify(|r, w| {
                w.direction().set_bit(is_output)
            });

            Ok(())
        }

        pub fn set_input_mode(&mut self, variant: InputMode) -> Result<(), ()> {
            if self.periph.read().enable().bit_is_clear() {
                // Must be enabled to set input mode
                return Err(());
            }

            if self.periph.read().direction().bit_is_set() {
                // Direction must be input
                return Err(());
            }

            self.periph.modify(|_r, w| {
                w.input_mode().variant(variant)
            });

            Ok(())
        }

        pub fn set_output_status(&mut self, is_high: bool) -> Result<(), ()> {
            if self.periph.read().enable().bit_is_clear() {
                // Must be enabled to set output status
                return Err(());
            }

            if self.periph.read().direction().bit_is_clear() {
                // Direction must be output
                return Err(());
            }

            self.periph.modify(|_r, w| {
                w.output_mode.set_bit(is_high)
            });

            Ok(())
        }

        pub fn get_input_status(&self) -> Result<bool, ()> {
            if self.periph.read().enable().bit_is_clear() {
                // Must be enabled to get status
                return Err(());
            }

            if self.periph.read().direction().bit_is_set() {
                // Direction must be input
                return Err(());
            }

            Ok(self.periph.read().input_status().bit_is_set())
        }
    }

Because we need to enforce the restrictions on the hardware, we end up doing a lot of runtime checking which wastes time and resources, and this code will be much less pleasant for the developer to use.

## Type States

But what if instead, we used Rust's type system to enforce the state transition rules? Take this example:

    /// GPIO interface
    struct GpioConfig<ENABLED, DIRECTION, MODE> {
        /// GPIO Configuration structure generated by svd2rust
        periph: GPIO_CONFIG,
        enabled: ENABLED,
        direction: DIRECTION,
        mode: MODE,
    }

    // Type states for MODE in GpioConfig
    struct Disabled;
    struct Enabled;
    struct Output;
    struct Input;
    struct PulledLow;
    struct PulledHigh;
    struct HighZ;
    struct DontCare;

    /// These functions may be used on any GPIO Pin
    impl<EN, DIR, IN_MODE> GpioConfig<EN, DIR, IN_MODE> {
        pub fn into_disabled(self) -> GpioConfig<Disabled, DontCare, DontCare> {
            self.periph.modify(|_r, w| w.enable.disabled());
            GpioConfig {
                periph: self.periph,
                enabled: Disabled,
                direction: DontCare,
                mode: DontCare,
            }
        }

        pub fn into_enabled_input(self) -> GpioConfig<Enabled, Input, HighZ> {
            self.periph.modify(|_r, w| {
                w.enable.enabled()
                 .direction.input()
                 .input_mode.high_z()
            });
            GpioConfig {
                periph: self.periph,
                enabled: Enabled,
                direction: Input,
                mode: HighZ,
            }
        }

        pub fn into_enabled_output(self) -> GpioConfig<Enabled, Output, DontCare> {
            self.periph.modify(|_r, w| {
                w.enable.enabled()
                 .direction.output()
                 .input_mode.set_high()
            });
            GpioConfig {
                periph: self.periph,
                enabled: Enabled,
                direction: Output,
                mode: DontCare,
            }
        }
    }

    /// This function may be used on an Output Pin
    impl GpioConfig<Enabled, Output, DontCare> {
        pub fn set_bit(&mut self, set_high: bool) {
            self.periph.modify(|_r, w| w.output_mode.set_bit(set_high));
        }
    }

    /// These methods may be used on any enabled input GPIO
    impl<IN_MODE> GpioConfig<Enabled, Input, IN_MODE> {
        pub fn bit_is_set(&self) -> bool {
            self.periph.read().input_status.bit_is_set()
        }

        pub fn into_input_high_z(self) -> GpioConfig<Enabled, Input, HighZ> {
            self.periph.modify(|_r, w| w.input_mode().high_z());
            GpioConfig {
                periph: self.periph,
                enabled: Enabled,
                direction: Input,
                mode: HighZ,
            }
        }

        pub fn into_input_pull_down(self) -> GpioConfig<Enabled, Input, PulledLow> {
            self.periph.modify(|_r, w| w.input_mode().pull_low());
            GpioConfig {
                periph: self.periph,
                enabled: Enabled,
                direction: Input,
                mode: PulledLow,
            }
        }

        pub fn into_input_pull_up(self) -> GpioConfig<Enabled, Input, PulledHigh> {
            self.periph.modify(|_r, w| w.input_mode().pull_high());
            GpioConfig {
                periph: self.periph,
                enabled: Enabled,
                direction: Input,
                mode: PulledHigh,
            }
        }
    }

Now let's see what the code using this would look like:

    /*
     * Example 1: Unconfigured to High-Z input
     */
    let pin: GpioConfig<Disabled, _, _> = get_gpio();

    // Can't do this, pin isn't enabled!
    // pin.into_input_pull_down();

    // Now turn the pin from unconfigured to a high-z input
    let input_pin = pin.into_enabled_input();

    // Read from the pin
    let pin_state = input_pin.bit_is_set();

    // Can't do this, input pins don't have this interface!
    // input_pin.set_bit(true);

    /*
     * Example 2: High-Z input to Pulled Low input
     */
    let pulled_low = input_pin.into_input_pull_down();
    let pin_state = pulled_low.bit_is_set();

    /*
     * Example 3: Pulled Low input to Output, set high
     */
    let output_pin = pulled_low.into_enabled_output();
    output_pin.set_bit(true);

    // Can't do this, output pins don't have this interface!
    // output_pin.into_input_pull_down();

This is definitely a convenient way to store the state of the pin, but why do it this way? Why is this better than storing the state as an `enum` inside of our `GpioConfig` structure?

## Compile Time Functional Safety

Because we are enforcing our design constraints entirely at compile time, this incurs no runtime cost. It is impossible to set an output mode when you have a pin in an input mode. Instead, you must walk through the states by converting it to an output pin, and then setting the output mode. Because of this, there is no runtime penalty due to checking the current state before executing a function.

Also, because these states are enforced by the type system, there is no longer room for errors by consumers of this interface. If they try to perform an illegal state transition, the code will not compile!