What is the best way to parse binary protocols with Rust

Essentially, I have a tcp-based network protocol for parsing.

In C, I can just add some memory to the type I want. How can I do something similar with Rust.

+7
rust
source share
1 answer

You can do the same in Rust. You just have to be careful when defining 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 do not know how to specify the buffer exactly size_of::<YourProtoHeader>() size; the length of the buffer should be constant, but calling size_of() is technically a function, so Rust complains when I use it in an array initializer. However, a sufficiently large buffer will also work.

Here we convert the pointer to the beginning of the buffer to the pointer to your structure. This is the same thing you would do in C. The structure itself should be annotated with the attributes #[repr(C)] and #[pack] : the first eliminates the possible reordering of the field, the second disables the filling to align the fields.

+7
source share

All Articles