Rust: From<bool> for integers not implemented?

Created on 20 Nov 2017  路  4Comments  路  Source: rust-lang/rust

I would find it incredibly useful to being able to cast a bool to another type so I can shift it around to generate bitmasks but ALAS this is not possible at the moment due to missing From trait impls:

error[E0277]: the trait bound `u32: core::convert::From<bool>` is not satisfied

Using as instead works fine but is frowned upon by clippy if the type is not a bool but a different type instead:

warning: casting u16 to u32 may become silently lossy if types change

Since the code in question is automatically generated it would be great if there was one common implementation that can (and should) be used for all types.

C-feature-request T-libs

Most helpful comment

bools are always 0 or 1 in rust. The change you linked makes use of the other bytes (2 through 255), but has no bearing on valid bools (and it can't since true as u32 is already defined to be 1u32).

But none of this is really related to this issue. IMO clippy is being silly and you should just use as, but it might be good to have the From impl too.

All 4 comments

IIRC, the integer value of bool is meant to be undefined, I guess to allow possible optimizations with stuff like enum tags.

Addendum: in fact, the compiler is now taking advantage of this undefinedness: https://github.com/rust-lang/rust/pull/45225

I guess the impl could be as simple as if val { 1 } else { 0 }, but it really depends on your use-case. I believe C booleans are like "false if zero, true otherwise".

bools are always 0 or 1 in rust. The change you linked makes use of the other bytes (2 through 255), but has no bearing on valid bools (and it can't since true as u32 is already defined to be 1u32).

But none of this is really related to this issue. IMO clippy is being silly and you should just use as, but it might be good to have the From impl too.

Is this issue beginner-friendly? I could work on it with some guidance.

In #50597 I propose to use From<bool> for {integer} for the lossless conversion using if val { 1 } else { 0 } instead of as just in case something weird happened and true/false are not 1 and 0.
I also propose TryFrom<{Integer}> for bool to convert from an integer while checking for any data loss.

There is a discussion for this topic on internals.rust-lang.org and a use case here : https://github.com/ithinuel/rusty-printer

You'll need to build rust with the target thumbv7m-none-eabi to see it in action.
If you want to dive in, it is used in the set of macros register! defined in ./silica/src/register.rs and used in ./silica_arm_cortexm4/src/ppb/scb.rs.

Was this page helpful?
0 / 5 - 0 ratings