Bitfields vs. bools in structs

Hey folks,

I’m currently working on a Rust project which is converting a pre-existing C implementation in to Rust. (Note that compatibility with the C data structures isn’t necessary.) The C implementation uses a bit field to capture a number of booleans within a struct, which I have replicated using the bitflags crate.

My question is this: for just storing boolean values in a struct, what are the trade-offs between bitflags and simple booleans?

bools are a byte each. A bitflag can go down to a bit per flag. Also, bitflags support | and & which may or may not be useful.

The optimizations I’m longing for most from Rust (some day) are related to merging bools in structs into bitfields automatically. (edit: good reasons given below for not doing this)

Also, relatedly, merging discriminants in nested enums.

Do you know of any RFC with this idea?

This would mean you couldn't take a reference to such a field. Maybe &bool could become a fat pointer that includes its bit offset, but that would be pretty weird...

This does happen to some extent since rust#45225, e.g. the given example Option<Option<bool>> is just one byte. In your linked example, Nested was 80 bytes on x86_64 and is now 56 bytes, vs. the Flat 32 bytes. So it's better, but there's still room for improvement. This might be served by further work like rust#46213.

1 Like

Or some kind of #[cannot_ref] field attribute that lets the compiler make optimisations that preclude taking a field’s address.

1 Like