Feature request: #[repr(bool)]

Every "zero cost" abstraction has a potential cost if the compiler doesn't eliminate conversations.

The only additional guarantees #[repr(bool)] has over #[repr(u8)] w.r.t. zero-cost-ness is that an &Enum to &bool transmute is guaranteed valid.

Everything else relies on the same amount of inlining to remove overhead.

Doesn't it also eliminate the conversion with regard to Enum to bool that would be needed in the case where Rust's decision about the bit patterns for both variants doesn't match Rust's decision about the bit patterns for true and false?

This is relevant in the two -> bool methods in the original post, which would effectively be a no-op or a simple NOT operation with #[repr(bool)].

Given that other repr(X) attributes enable as it is probably unavoidable for repr(bool). I would certainly like to be able to write if is_probable_prime(n).into() { ... } instead, but currently that kind of functionality lives outside of std.

It looks like encouraging repr(bool) disables selecting (currently unexploited) alternate niches for 2-ary enums, for stuff like:

#[repr(u8)]
enum A { W, X }
#[repr(u8)]
enum B { Y, Z }
enum C { A(A), B(B) } //               would be nice ↓
const _: () = const { assert!(mem::size_of::<C>() == 1) };

It is kind of oddly inconsistent that the other primitive types work in repr, so repr(bool) does make sense. I don't think it makes sense for the provided example: the functionality I want is automatic Into/TryInto for primitive-ish enums. For whatever reason this has stayed outside of std.

You can set the bit patterns of the #[repr(u8)] enum, and the bit patterns that bool takes are documented.

I would even think that given #[repr(u8)] enum Enum { False = 0x00, True = 0x01 } an &Enum to/from &bool transmute would be valid (since bool is documented to have the same size/align as u8, and Enum constrains it to the same set of valid values).

3 Likes

Ahh, that documentation is very useful information. Thank you.

1 Like

On the contrary, any C-like enum can be cast using as, regardless of #[repr]. Casts to bool are not allowed in any situation, and I personally don't think allowing it (regardless of why) is the right thing to do.

4 Likes

FWIW this has been sitting stalled in Automatically implement AsRepr and allow deriving FromRepr for fieldless enums by illicitonion · Pull Request #81642 · rust-lang/rust · GitHub for a while :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.