top | item 23860549

(no title)

rockmeamedee | 5 years ago

The post says

  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

discuss

order

laszlokorte|5 years ago

It should be `assert!(len(arr) >= 255)` (greater instead of less than), right?

wtetzner|5 years ago

If you want to omit a bounds check, the compiler needs to know that the length of the array covers the upper bound of the loop, right?

swagonomixxx|5 years ago

Assuming a unsigned byte, that range of values is between 0 and 255 inclusive, so `len(arr) <= 255` is correct.

laszlokorte|5 years ago

actually >, not >=