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

Added from_bits and into_bits functions. #34

Merged
merged 1 commit into from
Feb 16, 2024

Conversation

Frostie314159
Copy link
Contributor

This PR modifies the bitfield attribute macro to automatically emit from_bits and into_bits functions for types on which it is applied. This makes nesting types a lot easier.

@Frostie314159
Copy link
Contributor Author

Just after creating this PR I noticed, that this doesn't work for nested types with different sizes, so basically all of them. This could be resolved, by converting the representation of the parent to the next highest power of two, from the bit length of the Child.

@wrenger
Copy link
Owner

wrenger commented Feb 16, 2024

Just after creating this PR I noticed, that this doesn't work for nested types with different sizes, so basically all of them. This could be resolved, by converting the representation of the parent to the next highest power of two, from the bit length of the Child.

Well, yes, this problem was pretty much the reason for not generating them automatically.

What do you mean by your second sentence?
A solution might be to use the member size (rounded up to the next int) instead of the size of the entire bitfield for (from|into)_bits. Or maybe this can be made more generic so that any type smaller than the bitfield size can be used for (from|into)_bits.

(Related to #33)

@Frostie314159
Copy link
Contributor Author

What I meant was, that since all bitfields are currently backed by integer types it's safe to assume that the type backing a bitfield is the nearest power of two to the bit count specified for the field it was used in.

@wrenger
Copy link
Owner

wrenger commented Feb 16, 2024

So I allowed the conversion functions (from/into) to return different ints from the underlying bitfield type. Now, nested bitfields like the following should be possible (with your PR).

#[bitfield(u8)]
#[derive(PartialEq)]
struct Child {
    contents: u8,
}
#[bitfield(u16)]
#[derive(PartialEq)]
struct Parent {
    #[bits(8)]
    child: Child,
    #[bits(8)]
    __: (),
}
let child = Child::new().with_contents(0xff);
let parent = Parent::new().with_child(child);
assert_eq!(child.into_bits(), 0xff);
assert_eq!(parent.into_bits(), 0xff);

@wrenger wrenger merged commit 90d1ff3 into wrenger:main Feb 16, 2024
3 checks passed
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

Successfully merging this pull request may close these issues.

2 participants