jam1garner / binrw

A Rust crate for helping parse and rebuild binary data using ✨macro magic✨.
https://binrw.rs
MIT License
627 stars 37 forks source link

Support constant `MAGIC` #297

Closed boozook closed 4 weeks ago

boozook commented 4 weeks ago

Currently MAGIC attribute requires literal, but it possible to support constants too, using const resolving or just inlining maybe.

#[bw(magic = Profile::MAGIC)]
pub struct Profile {...}

impl Profile {
    pub const MAGIC: &[u8; 4] = b"ololo";
}

Now instead of use const I have to do something like that:

#[bw(magic = b"olol")]
pub struct Profile {...}

impl Profile {
    pub const MAGIC: &[u8; 4] = b"olol";
}

#[test]
fn magic() {
    assert_eq!(Profile::MAGIC, &<Profile as binrw::meta::WriteMagic>::MAGIC);
}

// or just impl:
impl binrw::meta::WriteMagic for Profile {
    type MagicType = &'static [u8; 4];
    const MAGIC: Self::MagicType = b"olol";
}
csnover commented 4 weeks ago

Hi, thanks for your report!

The WriteMagic trait is automatically generated by binrw when you provide a magic directive. You don’t implement it yourself. The literal type restriction on magic is required to generate a more efficient parsing strategy for mixed type enum variants since it is not possible for a macro to resolve symbolic types. Since you can get the magic literal from the auto-generated trait there is not a good reason to increase the complexity of the parser here. As such, I’m going to close this ticket.

Let me know if this makes sense or if you have any other questions, or if you feel like this is incorrect. Thanks!