wolfrpg_map_parser/db_parser/parsers/
data_parser.rs

1use crate::byte_utils::as_u32_le;
2use crate::db_parser::table::Table;
3use std::fs;
4use std::io::Result;
5use std::path::Path;
6use crate::db_parser::DATA_MAGIC;
7
8/// Parse a .dat file containing information on a WolfRPG Editor internal database.
9///
10/// Returns the data inside a database table. For the DB schema, use [`project_parser::parse`].
11/// If you have already read the bytes, consider using [`parse_bytes`].
12/// 
13/// # Panics
14/// This function will panic if the given file does not represent a valid database data structure.
15/// 
16/// [`project_parser::parse`]: crate::project_parser::parse
17pub fn parse(data: &Path) -> Result<Vec<Table>> {
18    match fs::read(data) {
19        Ok(contents) => {
20            Ok(parse_bytes(&contents))
21        }
22        Err(e) => {
23            Err(e)
24        }
25    }
26}
27
28/// Parse bytes containing information on a WolfRPG Editor internal database.
29///
30/// Returns the data inside a database table. For the DB schema, use [`project_parser::parse_bytes`].
31/// If you need to read the file to call this function, consider using [`parse`].
32/// 
33/// # Panics
34/// This function will panic if the given bytes do not represent a valid database data structure.
35/// 
36/// [`project_parser::parse_bytes`]: crate::project_parser::parse_bytes
37#[allow(unused_assignments)]
38pub fn parse_bytes(bytes: &[u8]) -> Vec<Table> {
39    let mut offset: usize = 0;
40
41    let header: &[u8] = &bytes[0..11];
42    offset += 11;
43
44    if &header[..10] != DATA_MAGIC {
45        panic!("Invalid data header.");
46    }
47    
48    let type_count: usize = as_u32_le(&bytes[offset..]) as usize;
49    offset += 4;
50    
51    let mut tables: Vec<Table> = Vec::with_capacity(type_count);
52    
53    for i in 0..type_count {
54        let (bytes_read, table): (usize, Table) = Table::parse(&bytes[offset..], i);
55        offset += bytes_read;
56        tables.push(table);
57    }
58    
59    offset += 1; // Should be 0xc1
60    
61    tables
62}