Essentially I have a tcp based network protocol to parse.
In C I can just cast some memory to the type that I want. How can I accomplish something similar with Rust.
You can do the same thing in Rust too. You just have to be little careful when you define the structure.
use std::mem;
#[repr(C)]
#[packed]
struct YourProtoHeader {
magic: u8,
len: u32
}
let mut buf = [0u8, ..1024]; // large enough buffer
// read header from some Reader (a socket, perhaps)
reader.read_at_least(mem::size_of::<YourProtoHeader>(), buf.as_mut_slice()).unwrap();
let ptr: *const u8 = buf.as_ptr();
let ptr: *const YourProtoHeader = ptr as *const YourProtoHeader;
let ptr: &YourProtoHeader = unsafe { &*ptr };
println!("Data length: {}", ptr.len);
Unfortunately, I don't know how to specify the buffer to be exactly size_of::<YourProtoHeader>()
size; buffer length must be a constant, but size_of()
call is technically a function, so Rust complains when I use it in the array initializer. Nevertheless, large enough buffer will work too.
Here we're converting a pointer to the beginning of the buffer to a pointer to your structure. This is the same thing you would do in C. The structure itself should be annotated with #[repr(C)]
and #[pack]
attributes: the first one disallows possible field reordering, the second disables padding for field alignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With