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.
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.
Unfortunately, I don't know how to specify the buffer to be exactly
size_of::<YourProtoHeader>()
size; buffer length must be a constant, butsize_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.