Temporarily transmute [u8] to [u16]

2019-05-07 07:15发布

问题:

I have a [u8; 16384] and a u16. How would I "temporarily transmute" the array so I can set the two u8s at once, the first to the least significant byte and the second to the most significant byte?

回答1:

As DK suggests, you probably shouldn't really use unsafe code to reinterpret the memory... but you can if you want to.

If you really want to go that route, you should be aware of a couple of gotchas:

  • You could have an alignment problem. If you just take a &mut [u8] from somewhere and convert it to a &mut [u16], it could refer to some memory region that is not properly aligned to be accessed as a u16. Depending on what computer you run this code on, such an unaligned memory access might be illegal. In this case, the program would probably abort somehow. For example, the CPU could generate some kind of signal which the operating system responds to in order to kill the process.
  • It'll be non-portable. Even without the alignment issue, you'll get different results on different machines (little- versus big-endian machines).

If you can switch it around (creating a u16 array and temporarily dealing with it on a byte level), you would solve the potential memory alignment problem:

/// warning: The resulting byte view is system-specific
unsafe fn raw_byte_access(s16: &mut [u16]) -> &mut [u8] {
    use std::slice;
    slice::from_raw_parts_mut(s16.as_mut_ptr() as *mut u8, s16.len() * 2)
}

On a big-endian machine, this function will not do what you want; you want a little-endian byte order. You can only use this as an optimization for little-endian machines and need to stick with a solution like DK's for big- or mixed-endian machines.



回答2:

The obvious, safe and portable way is to just use math.

fn set_u16_le(a: &mut [u8], v: u16) {
    a[0] = v as u8;
    a[1] = (v >> 8) as u8;
}

If you want a higher-level interface, there's the byteorder crate which is designed to do this.

You should definitely not use transmute to turn a [u8] into a [u16], because that doesn't guarantee anything about the byte order.