danlehmann / arbitrary-int

A modern and lightweight implementation of arbitrary integers for Rust
MIT License
32 stars 13 forks source link

Why not save u1 as a bool? #2

Open veniamin-ilmer opened 2 years ago

veniamin-ilmer commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 1 year ago

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 commented 1 year ago

I agree, do we want to close this?

danlehmann commented 1 year ago

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.