What is the best way to parse binary protocols wit

2019-02-09 05:25发布

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.

标签: rust
1条回答
别忘想泡老子
2楼-- · 2019-02-09 05:42

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.

查看更多
登录 后发表回答