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

Time:07-30

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.

CodePudding user response:

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.

CodePudding user response:

You can use std::mem::transmute. Mind the length of the slice.

    let a = [1u8, 2, 3, 4];
    let b: &[f32] = unsafe {
        &std::mem::transmute::<&[u8], &[f32]>(&a)[0..a.len() / 4]
    };

Playground

  • Related