To begin, we have a Node struct that has two 32-bit unsigned integers in it. Each Node is 8 bytes. We have the "packed" repr to ensure the data has a consistent layout in memory.
use std::mem;
#[repr(packed)]
#[derive(Debug)]
struct Node {
id: u32,
data: u32,
}
fn main() {
// The input data containing the 2 structs in byte form.
let source = vec![0, 2, 10, 4, 200, 100, 2, 4,
0, 40, 10, 2, 1, 50, 20, 7];
// Use transmute_copy to convert the raw bytes into structs.
unsafe {
// First struct.
let offset = 0;
let node1 = mem::transmute_copy::<[u8; 8], Node>(&source[offset..offset+8].try_into().unwrap());
// Second struct (offset is 8).
let offset = 8;
let node2 = mem::transmute_copy::<[u8; 8], Node>(&source[offset..offset+8].try_into().unwrap());
// Print the structs.
println!(
"{:?}", node1);
println!(
"{:?}", node2);
}
}
Node { id: 67764736, data: 67265736 }
Node { id: 34220032, data: 118764033 }