Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

panic with 32 bit signed int in 64b bitfield #24

Closed
jerrinot opened this issue Nov 10, 2023 · 3 comments
Closed

panic with 32 bit signed int in 64b bitfield #24

jerrinot opened this issue Nov 10, 2023 · 3 comments

Comments

@jerrinot
Copy link

jerrinot commented Nov 10, 2023

Thanks for this cool macro!

This code is panicking with value out of bounds:

#[test]
fn negative_signed() {
    #[bitfield(u64)]
    struct MyBitfield {
        negative: i32,
        #[bits(32)]
        __: u32,
    }

    let _ = MyBitfield::new().with_negative(-1);
}

When I change it to

#[test]
fn negative_signed() {
    #[bitfield(u32)]
    struct MyBitfield {
        negative: i32,
    }

    let f = MyBitfield::new().with_negative(-1);
    assert_eq!(-1, f.negative())
}

then it's working fine.

@jerrinot jerrinot changed the title panic with 32 bit signed int panic with 32 bit signed int in 64b bitfield Nov 10, 2023
@jerrinot
Copy link
Author

I've been looking at this for a bit. It seems the root cause is in signed casting which extends the signed bit.

This demonstrates the idea: https://github.com/wrenger/bitfield-struct-rs/compare/main...jerrinot:bitfield-struct-rs:sign_shifting?expand=1#diff-b1a35a68f14e696205874893c07fd24fdb88882b47c23cc0e0c80a30c7d53759R733-R761

I am fairly sure there is a better fix, I have no idea what am I doing :)

wrenger added a commit that referenced this issue Nov 11, 2023
Coincidentally, this also fixes #22
@wrenger
Copy link
Owner

wrenger commented Nov 11, 2023

Oh yes, thanks for catching this. This happens when the fields have the same bit size as their signed type. I've redesigned the bounds check accordingly in 8de2078, which will land in 5.5.

@jerrinot
Copy link
Author

many thanks for a super quick fix and release! I just included the latest version in my project and it works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants