Is this the most natural way to read structs from a binary file?

怎甘沉沦 提交于 2020-07-21 04:21:11

问题


I just realized this is quite similar to What is the best way to parse binary protocols with Rust

Is this the most natural way to read structs from a binary file using Rust? It works but seems a bit odd (why can't I just fill the struct wholesale?).

extern crate byteorder;
use byteorder::{ByteOrder, LittleEndian};

struct Record {
    latch: u32,
    total_energy: f32,
    x_cm: f32,
    y_cm: f32,
    x_cos: f32,
    y_cos: f32,
    weight: f32
}

impl Record {
    fn make_from_bytes(buffer: &[u8]) -> Record {
        Record {
            latch: LittleEndian::read_u32(&buffer[0..4]),
            total_energy: LittleEndian::read_f32(&buffer[4..8]),
            x_cm: LittleEndian::read_f32(&buffer[8..12]),
            y_cm: LittleEndian::read_f32(&buffer[12..16]),
            x_cos: LittleEndian::read_f32(&buffer[16..20]),
            y_cos: LittleEndian::read_f32(&buffer[20..24]),
            weight: LittleEndian::read_f32(&buffer[24..28]),
        }
    }
}

回答1:


Have a look a the nom crate: it is very useful to parse binary data.

With nom, you could write your parser with something like the following (not tested):

named!(record<Record>, chain!
    ( latch: le_u32
    ~ total_energy: le_f32
    ~ x_cm: le_f32
    ~ y_cm: le_f32
    ~ x_cos: le_f32
    ~ y_cos: le_f32
    ~ weight: le_f32
    , {
        Record {
            latch: latch,
            total_energy: total_energy,
            x_cm: x_cm,
            y_cm: y_cm,
            x_cos: x_cos,
            y_cos: y_cos,
            weight: weight,
        }
    }
    )
);


来源:https://stackoverflow.com/questions/40144526/is-this-the-most-natural-way-to-read-structs-from-a-binary-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!