lloydmeta / frunk

Funktional generic type-level programming in Rust: HList, Coproduct, Generic, LabelledGeneric, Validated, Monoid and friends.
https://beachape.com/frunk/
MIT License
1.29k stars 58 forks source link

Add `#[derive(ListBuild)]` #223

Open Ben-PH opened 1 year ago

Ben-PH commented 1 year ago

This allows a struct to be annotated with a ListBuild derive. Essentially, all it does is create a hl_new function for the struct it's annotating. hl_new constructs the type by plucking a value from the passed-in list for each field in the struct, returning the new struct, and the post-plucked list.

The motivation is for it to be used in esp32-hal crate. Currently, managing pins is done with a struct. These pins are zero-sized, const-generic separated types. In order to build a peripheral, you need to be careful partial moves. This is not feasable:

impl Peripheral {
    fn new(pins: Pins) -> (Self, Pins) { 
        (Self {
            pins.gpio1
        }, pins)
    }
}

This PR allows for code like this:

#[derive(ListBuild)]
struct Peripheral {
    pin1: GpioPin<1>,
}

let (periph, list) = Peripheral::hl_new(list);

...this makes helpers, constructors, etc. an option, opening the posibility for much more idiomatic organisation of code.

It also allows for correctness of managing resources to be easily encapsulated at the type-level. The global set of resources (pins, clocks, etc.) could be encapsulated as a type, and all resources get rolled-up into a single HList. You cannot pluck the same type from this HList more than once. You always have on hand a list of available resources.

Future work: