Skip to content

Automatically use enum discriminants as magic? #343

@drelatgithub

Description

@drelatgithub

In our code base we often have the following patterns, where we heavily use the discriminants of the enum variants elsewhere.

#[repr(u8}]
pub enum Enum {
    V1(T1) = 0x01,
    V2(T2), // 0x02
    V3(T3) = 0xFF,
    // ...
}

Now we want to equip this enum with binary serialization using binrw, and a natural way of discriminating among variants are via the magic value, so we would simply use the discriminant as the magic number as follows (assuming all Tx types are equipped with BinRead and BinWrite).

#[derive(BinRead, BinWrite)]
#[repr(u8)]
#[brw(big)]
pub enum Enum {
    #[brw(magic = 0x01u8)]
    V1(T1) = 0x01,
    #[brw(magic = 0x02u8)]
    V2(T2), // 0x02
    #[brw(magic = 0xFFu8)]
    V3(T3) = 0xFF,
    // ...
}

However, doing this is tedious and introduces two sources of truth for each magic number. Is there any option we can use in binrw that directly uses the discriminant of enum values as magic numbers?

If not, do you think adding this feature is possible, or useful?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions