wolfrpg_map_parser/db_parser/parsers/
common_events_parser.rs

1use crate::byte_utils::as_u32_le;
2use crate::db_parser::models::common_event::CommonEvent;
3use std::fs;
4use std::path::Path;
5use crate::db_parser::COMMON_EVENTS_MAGIC;
6
7/// Parse a .dat file containing information on a WolfRPG Editor common events database.
8///
9/// If you have already read the bytes, consider using [`parse_bytes`].
10///
11/// # Panics
12/// This function will panic if the given file does not represent a valid common events data structure.
13pub fn parse(data: &Path) -> std::io::Result<Vec<CommonEvent>> {
14    match fs::read(data) {
15        Ok(contents) => {
16            Ok(parse_bytes(&contents))
17        }
18        Err(e) => {
19            Err(e)
20        }
21    }
22}
23
24/// Parse bytes containing information on a WolfRPG Editor common events database.
25///
26/// If you need to read the file to call this function, consider using [`parse`].
27///
28/// # Panics
29/// This function will panic if the given bytes do not represent a valid common events data structure.
30pub fn parse_bytes(bytes: &[u8]) -> Vec<CommonEvent> {
31    let mut offset: usize = 0;
32
33    let signature: &[u8] = &bytes[offset..][..11];
34    offset += 11;
35
36    if signature != COMMON_EVENTS_MAGIC {
37        panic!("Invalid common events header.");
38    }
39
40    let event_count: usize = as_u32_le(&bytes[offset..offset+4]) as usize;
41    offset += 4;
42
43    let mut events: Vec<CommonEvent> = vec![];
44    for _ in 0..event_count {
45        let (bytes_read, event): (usize, CommonEvent)
46            = CommonEvent::parse(&bytes[offset..]);
47        offset += bytes_read;
48
49        events.push(event);
50    };
51
52    events
53}