Automatically use enum discriminants as magic?
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 853
- Forks
- 56
- PR merge metrics
- No merged PRs in 30d
Description
In our code base we often have the following patterns, where we heavily use the discriminants of the enum variants elsewhere.
```rust
#[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`).
```rust
#[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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing how the BinRead and BinWrite derives handle enum magic attributes and Rust enum discriminants. Determine whether the discriminant can become the magic value without duplicating annotations; done means the feature's feasibility and expected behavior are established, ideally with coverage for the shown explicit and implicit discriminants.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100