Guest User

Untitled

a guest
Aug 25th, 2019
83
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,
  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. // Get a fixed-size array from the slice
  26. let byte_array: &[u8; std::mem::size_of::<Header>()] = byte_slice.try_into().unwrap();
  27.  
  28. let header_again: Header = unsafe { std::mem::transmute(*byte_array) };
  29. println!("{:?}", header_again);
  30. }
RAW Paste Data