Safe casting of primitives

I was wondering if there has been any work on safe casting in rust. e.g. casting from u64 to u32 where you get a panic if you're over u32::max_value(), or u64 to f64 where you get a panic if your integer can't be exactly represented?


Actually I suppose this is what TryFrom is about, now I think about it.


this is exactly what as does. 1u64 as u8 works. 1000u64 as u8 will panic.

No, it doesn't, it wraps around with no panic. Not even on debug mode.



Just checked - no, this is not the case:

fn main() {
    let i = 1000u64 as u8;
    println!("{}", i);

outputs 232 (1000 mod 256).

yikes, I am rusty. so I guess only the binops +-*/ panic in debug?


While you're waiting for TryFrom to stabilize, num-traits has casting traits that return Option.

1 Like

I specifically remember some float->int casts panicking in the past. Has that changed?

(or actually, it might have been int->float, because I recall it was troublesome to detect the panic condition...)

Doesn't look like float to int or int to float panics

You might be remember the long-standing soundness bug that float to int casts can cause undefined behavior (unless you pass -Zsaturating-float-casts).


It will need to be fixed in some way or another. Hopefully next epoch.