What is the best way to parse binary protocols with Rust

前端 未结 1 977
离开以前
离开以前 2021-01-02 09:15

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.

1条回答
  •  长情又很酷
    2021-01-02 09:49

    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::(), 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::() 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.

    0 讨论(0)
提交回复
热议问题