从文件流中读取结构化数字

时间:2019-01-22 23:32:15

标签: rust

我有一种文件格式,我已经用多种不同的语言阅读过,并且需要添加rust支持。在这种文件格式中,存在格式为bp的结构化数据的斑点

struct Widget {
    pub number_of_screws: u32,
    pub number_of_nails: u32,
    pub number_of_thingys: u16,
}

struct WidgetFile {
    pub widgets: Vec<Widget>,
}

我想有效地阅读这些内容。在C ++中,我可以轻松地从流中读取u32。在Swift中,我可以轻松地从Data中读取数据,但是在Rust中,我不确定最好的方法,因为我想避免无缘无故地复制数据。

这就是我所拥有的:

pub fn read_widgets() -> WidgetFile {
    let f = File::open("foo.widgetfile").expect("file");
    let reader = BufReader::new(f);
    // Somehow read bytes into a variable called buffer
    let number_of_widgets = u32::read_from_bytes(buffer);
}

如何从u32一遍又一遍地读取单个u32u16reader,而不继续消耗缓冲区?

0 个答案:

没有答案