Skip to content

Instantly share code, notes, and snippets.

@jeremie-j
Created December 25, 2023 22:28
Show Gist options
  • Save jeremie-j/56e95b18719c97aeb9dba618bdb7f517 to your computer and use it in GitHub Desktop.
Save jeremie-j/56e95b18719c97aeb9dba618bdb7f517 to your computer and use it in GitHub Desktop.
Read raw bytes to a struct
use std::io::Read;
use std::{mem, slice};
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
struct TextStruct {
u8_number: u8,
u16_number: u16,
utf_8_string: [u8; 7],
}
fn main() {
let buffer: Vec<u8> = vec![
0x71, // u8
0xb4, 0x50, // u16
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x21, // slice of utf 8 char
];
let mut config: TextStruct = unsafe { mem::zeroed() };
unsafe {
let config_slice = slice::from_raw_parts_mut(
&mut config as *mut _ as *mut u8,
mem::size_of::<TextStruct>(),
);
buffer.as_slice().read_exact(config_slice).unwrap();
}
println!("{:?}", config);
let result_string = String::from_utf8(config.utf_8_string.into()).unwrap();
println!("{:?}", result_string);
}
/* Output:
TextStruct { u8_number: 113, u16_number: 20660, utf_8_string: [72, 101, 108, 108, 111, 32, 33] }
"Hello !"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment