Search code examples
arraysrustcasting

Rust, how to slice into a byte array as if it were a float array?


I have some byte data stred in a &[u8] I know for a fact the data contained in the slice is float data. I want to do the equivalent of auto float_ptr = (float*)char_ptr;

I tried:

let data_silce = &body[buffer_offset..(buffer_offset + buffer_length)] as &[f32];

But you are not allowed to execute this kind of casting in rust.


Solution

  • You will need to use unsafe Rust to interpret one type of data as if it is another.

    You can do:

    let bytes = &body[buffer_offset..(buffer_offset + buffer_length)];
    
    let len = bytes.len();
    let ptr = bytes.as_ptr() as *const f32;
    let floats: &[f32] = unsafe { std::slice::from_raw_parts(ptr, len / 4)};
    

    Note that this is Undefined Behaviour if any of these are true:

    • the size of the original slice is not a multiple of 4 bytes
    • the alignment of the slice is not a multiple of 4 bytes

    All sequences of 4 bytes are valid f32s but, for types without that property, to avoid UB you also need to make sure that all values are valid.