hashmismatch / packed_struct.rs

Bit-level packing and unpacking for Rust
MIT License
164 stars 30 forks source link

`PrimitiveEnum::from_primitive` wrong when discriminant unspecified. #71

Closed qm3ster closed 3 years ago

qm3ster commented 3 years ago

The following code:

use packed_struct::prelude::*;
use packed_struct_codegen::*;

#[derive(PrimitiveEnum_u8, Clone, Copy, Debug, PartialEq)]
pub enum Enum {
    Zero,
    One,
}

fn main() {
    for x in Enum::all_variants().iter() {
        let prim = x.to_primitive();
        let parsed = Enum::from_primitive(prim);
        println!("{:?} {} {:?}", x, prim, parsed);
    }
}

prints

Zero 0 None
One 1 Some(Zero)

instead of the expected

Zero 0 Some(Zero)
One 1 Some(One)

This is caused by mut d being set to 0 https://github.com/hashmismatch/packed_struct.rs/blob/51f779d923c48eed1b321d46181c5ef848fd05a0/packed_struct_codegen/src/primitive_enum.rs#L233 and immediately incremented on the first iteration https://github.com/hashmismatch/packed_struct.rs/blob/51f779d923c48eed1b321d46181c5ef848fd05a0/packed_struct_codegen/src/primitive_enum.rs#L271

rudib commented 3 years ago

The fix was released with 0.6.0: https://github.com/hashmismatch/packed_struct.rs/releases/tag/v0.6.0 Thanks for the report!