Safe casting of primitives

#1

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?

3 Likes
#2

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

2 Likes
#3

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

#4

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

proof
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=915646ec8cead2f2bb2aaec46063d3ff

3 Likes
#5

Just checked - no, this is not the case:

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

outputs 232 (1000 mod 256).

#6

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

#7

yes

#8

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

1 Like
#9

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…)

#10

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

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=28f299e6fbe7225334d3f9977b580974

#11

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

2 Likes
#12

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