by rockmeamedee · 6y ago · 0 comments
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 checkHere'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!
If the array size is definitely greater than or equal to 255 then all the array accesses in the loop will be in bounds and no further bounds check is required.
[0] https://doc.rust-lang.org/stable/rust-by-example/flow_contro... [1] https://play.rust-lang.org/?version=stable&mode=debug&editio...