如何从Rust中的文件中读取结构?

时间:2014-08-20 16:36:10

标签: io rust

有没有办法可以直接从Rust的文件中读取结构?我的代码是:

use std::fs::File;

struct Configuration {
    item1: u8,
    item2: u16,
    item3: i32,
    item4: [char; 8],
}

fn main() {
    let file = File::open("config_file").unwrap();

    let mut config: Configuration;
    // How to read struct from file?
}

如何从文件中直接将我的配置读入config?这甚至可能吗?

3 个答案:

答案 0 :(得分:7)

注意:针对稳定的Rust(目前为1.10)进行了更新。

你走了:

use std::io::Read;
use std::mem;
use std::slice;

#[repr(C, packed)]
#[derive(Debug)]
struct Configuration {
   item1: u8,
   item2: u16,
   item3: i32,
   item4: [char; 8]
}

const CONFIG_DATA: &'static [u8] = &[
  0xfd, 0xb4, 0x50, 0x45, 0xcd, 0x3c, 0x15, 0x71, 0x3c, 0x87, 0xff, 0xe8,
  0x5d, 0x20, 0xe7, 0x5f, 0x38, 0x05, 0x4a, 0xc4, 0x58, 0x8f, 0xdc, 0x67,
  0x1d, 0xb4, 0x64, 0xf2, 0xc5, 0x2c, 0x15, 0xd8, 0x9a, 0xae, 0x23, 0x7d,
  0xce, 0x4b, 0xeb
];

fn main() {
    let mut buffer = CONFIG_DATA;

    let mut config: Configuration = unsafe { mem::zeroed() };

    let config_size = mem::size_of::<Configuration>();
    unsafe {
        let config_slice = slice::from_raw_parts_mut(
            &mut config as *mut _ as *mut u8,
            config_size
        );
        // `read_exact()` comes from `Read` impl for `&[u8]`
        buffer.read_exact(config_slice).unwrap();
    }

    println!("Read structure: {:#?}", config);
}

Try it here

但是,您需要小心,因为不安全的代码是不安全的。特别是在slice::from_raw_parts_mut()调用之后,同时存在两个对同一数据的可变句柄,这违反了Rust别名规则。因此,您希望在最短的时间内保持从结构中创建的可变切片。我还假设你知道有关字节序的问题 - 上面的代码绝不是可移植的,如果在不同类型的机器上编译和运行(例如ARM vs x86),它将返回不同的结果。

如果您可以选择格式并且想要一个紧凑的二进制格式,请考虑使用bincode。否则,如果您需要,例如要解析一些预先定义的二进制结构,byteorder crate是可行的方法。

答案 1 :(得分:5)

注意以下代码未考虑任何endiannesspadding问题,旨在与POD types一起使用。在这种情况下,struct Configuration应该是安全的。

这是一个可以从文件中读取(pod类型)结构的函数:

use std::io::{self, BufReader, Read};
use std::fs::{self, File};
use std::path::Path;
use std::slice;

fn read_struct<T, R: Read>(mut read: R) -> io::Result<T> {
    let num_bytes = ::std::mem::size_of::<T>();
    unsafe {
        let mut s = ::std::mem::uninitialized();
        let mut buffer = slice::from_raw_parts_mut(&mut s as *mut T as *mut u8, num_bytes);
        match read.read_exact(buffer) {
            Ok(()) => Ok(s),
            Err(e) => {
                ::std::mem::forget(s);
                Err(e)
            }
        }
    }
}

// use
// read_struct::<Configuration>(reader)

如果要从文件中读取一系列结构,可以多次执行read_struct或一次读取所有文件:

fn read_structs<T, P: AsRef<Path>>(path: P) -> io::Result<Vec<T>> {
    let path = path.as_ref();
    let struct_size = ::std::mem::size_of::<T>();
    let num_bytes = try!(fs::metadata(path)).len() as usize;
    let num_structs = num_bytes / struct_size;
    let mut reader = BufReader::new(try!(File::open(path)));
    let mut r = Vec::<T>::with_capacity(num_structs);
    unsafe {
        let mut buffer = slice::from_raw_parts_mut(r.as_mut_ptr() as *mut u8, num_bytes);
        try!(reader.read_exact(buffer));
        r.set_len(num_structs);
    }
    Ok(r)
}

// use
// read_structs::<StructName, _>("path/to/file"))

答案 2 :(得分:2)

https://help.github.com/articles/splitting-a-subfolder-out-into-a-new-repository/一样,使用Vladimir Matveev mentions通常是最好的解决方案。这样,您就可以解决字节顺序问题,不必处理任何不安全的代码,也不必担心对齐或填充:

use byteorder::{LittleEndian, ReadBytesExt}; // 1.2.7
use std::{
    fs::File,
    io::{self, Read},
};

struct Configuration {
    item1: u8,
    item2: u16,
    item3: i32,
}

impl Configuration {
    fn from_reader(mut rdr: impl Read) -> io::Result<Self> {
        let item1 = rdr.read_u8()?;
        let item2 = rdr.read_u16::<LittleEndian>()?;
        let item3 = rdr.read_i32::<LittleEndian>()?;

        Ok(Configuration {
            item1,
            item2,
            item3,
        })
    }
}

fn main() {
    let file = File::open("/dev/random").unwrap();

    let config = Configuration::from_reader(file);
    // How to read struct from file?
}

出于某些原因,我忽略了[char; 8]

  1. Rust的char是32位类型,尚不清楚您的文件是否具有实际的Unicode代码点或C样式的8位值。
  2. 您不能轻松地按字节顺序解析数组,必须解析N个值然后自己构建数组。
相关问题