(no title)
rockmeamedee | 5 years ago
The new API to cast in an unsafe manner is:
let x: f32 = 1.0;
let y: u8 = unsafe { x.to_int_unchecked() };
But as always, you should only use this method as a last resort. Just like with array access, the compiler can often optimize the checks away, making the safe and unsafe versions equivalent when the compiler can prove it.
I believe for array access you can elide the bounds checking with an assert like assert!(len(arr) <= 255)
let mut sum = 0;
for i in 0..255 {
sum += arr[i];//this access doesn't emit bounds checks in the compiled code
}
I'm guessing it would work like this with casts? assert!(x <= 255. && x >= 0);
let y: u8 = x as u8; // no check
steveklabnik|5 years ago
Here's an example of how when it can detect it, it does the right thing: https://godbolt.org/z/hPqf69
I am not an expert in these hints, maybe someone else knows!
laszlokorte|5 years ago
wtetzner|5 years ago
swagonomixxx|5 years ago
laszlokorte|5 years ago