SHARE
TWEET

Untitled

a guest Aug 25th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::convert::TryInto;
  2.  
  3. #[derive(Default, Debug, Clone, Copy)]
  4. #[repr(C, packed)]
  5. struct Header {
  6.     timestamp_ns: i64,
  7.     message_id: u16,
  8.     message_version: u16,
  9.     sequence_number: u16,
  10.     reserved: [u32;10],
  11.     length_bytes: u16,
  12. }
  13.  
  14. fn main() {
  15.     let mut header = Header::default();
  16.     header.message_id = 4;
  17.     header.length_bytes = 42;
  18.    
  19.     let bytes: [u8; std::mem::size_of::<Header>()] = unsafe { std::mem::transmute(header) };
  20.     // println!("{:?}", bytes);
  21.    
  22.     // Now say you only have a byte slice
  23.     let byte_slice: &[u8] = &bytes[..];
  24.    
  25.     let header_again: &Header = unsafe { std::mem::transmute(byte_slice.as_ptr()) };
  26.     println!("{:?}", header_again);
  27. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top