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

Why not save u1 as a bool? #2

Open
veniamin-ilmer opened this issue Oct 27, 2022 · 6 comments
Open

Why not save u1 as a bool? #2

veniamin-ilmer opened this issue Oct 27, 2022 · 6 comments

Comments

@veniamin-ilmer
Copy link

This is more of a discussion/enhancement rather than an "issue". Reading through the code, I see u1 is saved in a u8.

I imagine Rust might be able to optimize a bool more effectively than a u8 in some situations. It would be interesting to see benchmarks over the effectiveness of bool vs u8 for u1.

I currently don't have a usecase for u1 however. Ordinarily when I want to store 1 bit, I would be using bool anyway.. I am not sure when it would be beneficial to use u1 over bool.

@danlehmann
Copy link
Owner

Switching to bool wouldn't be possible as that would be an API change. u1::new(1).value() currently returns u8 - if I change that to bool it could make applications incompatible.

I don't really have a usecase for it either. I use arbitrary-int's in my bitfield crate (bitbybit) which uses bool for single bits as well.

@danlehmann
Copy link
Owner

About whether it's more efficient: I can't think of a case where bool is actually more efficient than u8. Generally bools are stored in a byte, just like u8.

@veniamin-ilmer
Copy link
Author

I use bitbybit in my emulator as well. That is another great crate, thank you for making that as well. Indeed I used bool there as well. I do wonder if u1 is necessary at all.

@danlehmann
Copy link
Owner

So I found a use-case for u1: bitenums with a single bit. Consider this example

#[bitenum(u1)]
enum DataSize {
Bits7 = 0,
Bits8 = 1,
}

This definition is useful for example in the UART definition for the Raspberry Pi's miniUART.

u1 feels more natural here as Rust natively doesn't support true/false in enumerations. So I think it makes more sense to use u1 over bool for this case.

@hecatia-elegua
Copy link
Collaborator

I agree, do we want to close this?

@danlehmann
Copy link
Owner

Thinking about it more, it would be possible to build this without making the API incompatible. We can special-case u1 to internally use bool but have a constructor that takes a u8. To make it nicer, we can add another constructor that takes a bool.

Would it be any more efficient? Possibly in theory, but I doubt it would be noticeable in practice.

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

3 participants