smbioslib/
file_io.rs

1//! Loads files containing raw bios binary data.
2//!
3//! When testing this library it is useful to read stored
4//! raw data and then load it into the structures.
5use crate::core::SMBiosData;
6use crate::windows::WinSMBiosData;
7use std::io::{BufWriter, Error, Write};
8use std::{
9    fs::{read, read_dir, File},
10    path::Path,
11};
12
13/// Loads raw smbios data from a file and returns [SMBiosData] or [std::io::Error] on error.
14///
15/// Currently supports reading raw files containing only SMBIOS table data or
16/// Windows raw files containing the windows header and SMBIOS table data.
17pub fn load_smbios_data_from_file(file_path: &Path) -> Result<SMBiosData, Error> {
18    let data = read(file_path)?;
19    if WinSMBiosData::is_valid_win_smbios_data(&data) {
20        let win_smbios = WinSMBiosData::new(data)
21            .expect("Structure shouldn't be invalid it was already checked.");
22        Ok(win_smbios.smbios_data)
23    } else {
24        Ok(SMBiosData::from_vec_and_version(data, None))
25    }
26}
27
28/// Loads raw smbios data files from a given _folder_ and returns [Vec<SMBiosStructTable>]
29pub fn load_raw_files(folder: &Path) -> Vec<SMBiosData> {
30    assert!(folder.is_dir());
31    let mut result = Vec::new();
32
33    let entries = read_dir(folder)
34        .expect("valid files")
35        .map(|res| res.map(|e| e.path()))
36        .collect::<Result<Vec<_>, Error>>()
37        .expect("msg");
38
39    for elem in entries {
40        let smbios_table_data = load_smbios_data_from_file(&elem);
41        match smbios_table_data {
42            Ok(data) => result.push(data),
43            Err(_) => {}
44        }
45    }
46
47    result
48}
49
50/// dumps raw data into a file
51pub fn dump_raw(data: Vec<u8>, out_path: &Path) -> Result<(), Error> {
52    let f = File::create(&out_path)?;
53    let mut f = BufWriter::new(f);
54    f.write_all(&data)?;
55    Ok(())
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use std::path::PathBuf;
62
63    #[test]
64    fn test_load_smbios_table_data() {
65        let mut path = PathBuf::new();
66        path.push(".");
67        path.push("tests");
68        path.push("jeffgerlap_3_2_0");
69        path.set_extension("dat");
70
71        match load_smbios_data_from_file(&path.as_path()) {
72            Ok(table_data) => {
73                for parts in table_data.into_iter() {
74                    println!("{:?}", parts.defined_struct());
75                }
76            }
77            _ => panic!("Expected data!"),
78        }
79    }
80}