sharksforarms / deku

Declarative binary reading and writing: bit-level, symmetric, serialization/deserialization
Apache License 2.0
1.11k stars 54 forks source link

Single value enum #372

Closed yanshay closed 11 months ago

yanshay commented 11 months ago

I have the following enum:

enum LightLevel {
    Off,
    On,
    Range(u8)
}

This at the bytes level should translate to a single u8, with Off=0, On=100, Range is represented by the value it contains.

I couldn't find a way to implement this with Deku (need both read and write). Is it doable?

Maybe with a writer I can do that, but I want to define it at the enum level and not at the field level (since it will be used as field in many structs).

Maybe map attribute could help but it is only for read and I need also write (I couldn't find a reverse map).

wcampbell0x2a commented 11 months ago

You want https://docs.rs/deku/latest/deku/attributes/index.html#id_pat

#[derive(DekuRead, DekuWrite)]
#[deku(type = "u16")]
enum DekuTest {
    #[deku(id = "0x01")]
    VariantA,

    #[deku(id = "0x100")]
    VariantB,

    #[deku(id_pat = "_")]
    Range(u16),
}
yanshay commented 11 months ago

Thanks, exactly what I was looking for.