wolfrpg_map_parser/command/
number_condition_command.rs

1#[cfg(feature = "serde")]
2use serde::{Serialize, Deserialize};
3use crate::command::common::case::Case;
4use crate::command::common::CASES_END_SIGNATURE;
5use crate::command::number_condition_command::condition::Condition;
6
7pub mod condition;
8pub mod operator;
9
10#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11#[derive(PartialEq, Clone)]
12pub struct NumberConditionCommand {
13    else_case: bool,
14    conditions: Vec<Condition>,
15    cases: Vec<Case>,
16}
17
18impl NumberConditionCommand {
19    pub(crate) fn parse(bytes: &[u8]) -> (usize, u32, Self) {
20        let mut offset: usize = 0;
21
22        let (case_count, else_case): (u8, bool) = Self::parse_case_count(bytes[offset]);
23        offset += 1;
24
25        offset += 3; // padding
26
27        let (bytes_read, conditions): (usize, Vec<Condition>)
28            = Self::parse_conditions(&bytes[offset..], case_count as usize);
29
30        offset += bytes_read;
31
32        offset += 3; // Command end
33
34        let case_count: usize = case_count as usize + else_case as usize;
35        let (bytes_read, mut commands_read, cases): (usize, u32, Vec<Case>)
36            = Case::parse_multiple(&bytes[offset..], case_count);
37
38        offset += bytes_read;
39
40        let cases_end: &[u8] = &bytes[offset..offset+8];
41        offset += 8;
42        commands_read += 1;
43
44        if &cases_end[..4] != CASES_END_SIGNATURE {
45            panic!("Invalid cases end.");
46        }
47
48        (offset, commands_read, Self {
49            else_case,
50            conditions,
51            cases
52        })
53    }
54
55    fn parse_case_count(cases: u8) -> (u8, bool) {
56        (cases & 0x0f, cases & 0b00010000 != 0)
57    }
58
59    fn parse_conditions(bytes: &[u8], condition_count: usize) -> (usize, Vec<Condition>) {
60        let mut offset: usize = 0;
61        let mut conditions: Vec<Condition> = Vec::with_capacity(condition_count);
62
63        for _ in 0..condition_count {
64            let (bytes_read, condition): (usize, Condition)
65                = Condition::parse(&bytes[offset..]);
66            conditions.push(condition);
67            offset += bytes_read;
68        }
69
70        (offset, conditions)
71    }
72
73    pub fn else_case(&self) -> bool {
74        self.else_case
75    }
76
77    pub fn else_case_mut(&mut self) -> &mut bool {
78        &mut self.else_case
79    }
80
81    pub fn conditions(&self) -> &Vec<Condition> {
82        &self.conditions
83    }
84
85    pub fn conditions_mut(&mut self) -> &mut Vec<Condition> {
86        &mut self.conditions
87    }
88
89    pub fn cases(&self) -> &Vec<Case> {
90        &self.cases
91    }
92
93    pub fn cases_mut(&mut self) -> &mut Vec<Case> {
94        &mut self.cases
95    }
96}