Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to parse binary protocols with Rust

Tags:

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.

like image 290
Matt Avatar asked Sep 05 '14 20:09

Matt


1 Answers

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.

like image 65
Vladimir Matveev Avatar answered Oct 22 '22 20:10

Vladimir Matveev