1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! Data structures and logic about the DMW2 breed formulae

use std::str;

use quick_xml::events::BytesStart;
use serde::Serialize;

use error::Error;
use crate::xml;

/// A parent in a breed formula.
#[derive(Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(Debug))]
pub enum Parent
{
    /// Any monster in this family could be the parent. Value
    /// indicates the name of the family.
    Family(String),
    /// The parent is this monster, whose name is the value.
    Monster(String),
}

/// A parent in a breed formula, with some extra requirements.
#[derive(Clone, Serialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct ParentRequirement
{
    /// The parent in the breed formula
    pub parent: Parent,
    /// The minimal +level of this parent. Usually this is just 0. But
    /// for some formulae (e.g. Slime + Slime = KingSlime) this is
    /// non-zero.
    pub min_plus: u8,
}

impl ParentRequirement
{
    fn fromXMLTag(e: &BytesStart) -> Result<Self, Error>
    {
        let min_plus = if let Some(attr) = e.try_get_attribute("min_plus")
            .map_err(|_| xmlerr!("Failed to get attribute 'min_plus'."))?
        {
            str::from_utf8(attr.value.as_ref()).map_err(
                |_| xmlerr!("Failed to decode min +level in XML"))?.parse()
                .map_err(|_| xmlerr!("Invalid min +level in XML"))?
        }
        else
        {
            0
        };

        if let Some(attr) = e.try_get_attribute("monster").map_err(
            |_| xmlerr!("Failed to get attribute 'monster'."))?
        {
            let monster = String::from_utf8(attr.value.into_owned()).map_err(
                |_| xmlerr!("Failed to decode monster name in XML"))?;
            Ok(Self {
                parent: Parent::Monster(monster),
                min_plus
            })
        }
        else if let Some(attr) = e.try_get_attribute("family").map_err(
            |_| xmlerr!("Failed to get attribute 'family'."))?
        {
            let family = String::from_utf8(attr.value.into_owned()).map_err(
                |_| xmlerr!("Failed to decode family name in XML"))?;
            Ok(Self {
                parent: Parent::Family(family),
                min_plus
            })
        }
        else
        {
            Err(xmlerr!("Invalid parent definition in XML"))
        }
    }
}

/// A breed formula
#[derive(Clone, Serialize)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct Formula
{
    /// The base monster in the formula.
    pub base: Vec<ParentRequirement>,
    /// The mate monster in the formula.
    pub mate: Vec<ParentRequirement>,
    /// The name of the offspring monster.
    pub offspring: String,
}

impl Formula
{
    pub fn fromXML(x: &[u8]) -> Result<Self, Error>
    {
        let mut offspring = String::new();
        let mut base = Vec::new();
        let mut mate = Vec::new();
        let mut parser = xml::Parser::new();

        parser.addBeginHandler("breed", |_, e: &BytesStart| {
            if let Some(attr) = e.try_get_attribute("target").map_err(
                |_| xmlerr!("Failed to get attribute 'target'."))?
            {
                offspring = String::from_utf8(attr.value.into_owned()).map_err(
                    |_| xmlerr!("Failed to decode breed target name in XML"))?;
                Ok(())
            }
            else
            {
                Err(xmlerr!("Found breed formula without target"))
            }
        });

        parser.addBeginHandler("breed-requirement", |path, e: &BytesStart| {
            if let Some(tag) = path.get(path.len() - 2)
            {
                match tag.as_str()
                {
                    "base" => base.push(ParentRequirement::fromXMLTag(e)?),
                    "mate" => mate.push(ParentRequirement::fromXMLTag(e)?),
                    _ => return Err(xmlerr!("Invalid tag '{}'", tag)),
                }
            }
            else
            {
                return Err(xmlerr!("Invalid breed requirement"));
            }
            Ok(())
        });
        parser.parse(x)?;
        drop(parser);
        let result = Self { base, mate, offspring };
        Ok(result)
    }
}

// ========== Tests =================================================>

#[cfg(test)]
mod tests {
    use super::*;

    use anyhow::Result;

    #[test]
    fn deserializeFormula() -> Result<()>
    {
        let xml = r#"<breed target="KingSlime">
      <base>
        <breed-requirement monster="SpotKing"/>
      </base>
      <mate>
        <breed-requirement monster="DeadNoble"/>
        <breed-requirement monster="Divinegon"/>
        <breed-requirement monster="Gigantes"/>
      </mate>
    </breed>"#;
        let p = Formula::fromXML(xml.as_bytes())?;
        assert_eq!(
            p,
            Formula {
                base: vec![ParentRequirement{ parent: Parent::Monster("SpotKing".to_owned()), min_plus: 0 }],
                mate: vec![ParentRequirement{ parent: Parent::Monster("DeadNoble".to_owned()), min_plus: 0 },
                           ParentRequirement{ parent: Parent::Monster("Divinegon".to_owned()), min_plus: 0 },
                           ParentRequirement{ parent: Parent::Monster("Gigantes".to_owned()), min_plus: 0},],
                offspring: "KingSlime".to_owned(),
            });

        let xml = r#"<breed target="Octogon">
      <base>
        <breed-requirement monster="Octoreach"/>
      </base>
      <mate>
        <breed-requirement monster="Octoreach" min_plus="4"/>
      </mate>
    </breed>"#;
        let p = Formula::fromXML(xml.as_bytes())?;
        assert_eq!(
            p,
            Formula {
                base: vec![ParentRequirement{ parent: Parent::Monster("Octoreach".to_owned()), min_plus: 0 }],
                mate: vec![ParentRequirement{ parent: Parent::Monster("Octoreach".to_owned()), min_plus: 4 }],
                offspring: "Octogon".to_owned(),
            });

        let xml = r#"<breed target="Moray">
      <base>
        <breed-requirement family="water"/>
      </base>
      <mate>
        <breed-requirement family="dragon"/>
      </mate>
    </breed>"#;
        let p = Formula::fromXML(xml.as_bytes())?;
        assert_eq!(
            p,
            Formula {
                base: vec![ParentRequirement{ parent: Parent::Family("water".to_owned()), min_plus: 0 }],
                mate: vec![ParentRequirement{ parent: Parent::Family("dragon".to_owned()), min_plus: 0 }],
                offspring: "Moray".to_owned(),
            });

        Ok(())
    }
}