1

Assume I have an array of four u8, let's say - as a field of a struct:

#[repr(C, packed)]
#[derive(Debug)]
struct SomeStruct<'a> {
    header: [u8; 4],
    // ... other fields ...
}

I would like to efficiently read it as u32 and then reinterpret into such an array - instead of calling four successive read_u8. Currently, I'm using byteorder crate and transmute:

unsafe {
   let input = metadata_bytes.read_u32::<LittleEndian>().unwrap();
   data.header = std::mem::transmute::<u32, [u8; 4]>(input);
}

It works but I'm completely not sure whether it is not miserably convoluted approach. So the questions are:

  1. is my approach ok? Can it be done better/faster/more idiomatic?
  2. in the current approach, does transmute copy those 4 bytes or just reinterprets it?

PS. I can't use slice::from_raw_parts_mut for the whole struct as it contains dynamically sized fields inside.

Max Desiatov
  • 5,087
  • 3
  • 48
  • 56
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58

0 Answers0