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.
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:
All sequences of 4 bytes are valid f32
s but, for types without that property, to avoid UB you also need to make sure that all values are valid.