wolfrpg_map_parser/db_parser/parsers/
tileset_parser.rs

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