Temporarily transmute [u8] to [u16]

前端 未结 3 768
鱼传尺愫
鱼传尺愫 2020-11-30 14:03

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 lea

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 14:51

    slice::align_to and slice::align_to_mut are stable as of Rust 1.30. These functions handle the alignment concerns that sellibitze brings up.

    The big- and little- endian problems are still yours to worry about. You may be able to use methods like u16::to_le to help with that. I don't have access to a big-endian computer to test with, however.

    fn example(blob: &mut [u8; 16], value: u16) {
       // I copied this example from Stack Overflow without providing 
       // rationale why my specific case is safe.
       let (head, body, tail) = unsafe { blob.align_to_mut::() };
    
       // This example simply does not handle the case where the input data
       // is misaligned such that there are bytes that cannot be correctly
       // reinterpreted as u16.
       assert!(head.is_empty());
       assert!(tail.is_empty());
    
       body[0] = value
    }
    
    fn main() {
       let mut data = [0; 16];
       example(&mut data, 500);
       println!("{:?}", data);
    }
    

提交回复
热议问题