dota/components/
buildings.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4use thiserror;
5
6#[derive(thiserror::Error, Debug)]
7pub enum BuildingsError {
8    #[error("attempted to parse an empty building")]
9    EmptyBuilding,
10}
11
12#[derive(Serialize, Deserialize, Debug)]
13pub struct BuildingInformation {
14    health: u32,
15    max_health: u32,
16}
17
18pub enum BuildingClass {
19    Rax,
20    Ancient,
21    Tower,
22}
23
24#[derive(Serialize, Deserialize, Debug)]
25pub struct Buildings {
26    #[serde(flatten)]
27    inner: HashMap<String, BuildingInformation>,
28}
29
30impl Buildings {
31    pub fn get_building_information(&self, name: &str) -> Option<&BuildingInformation> {
32        match self.inner.get(name) {
33            Some(i) => Some(i),
34            None => None,
35        }
36    }
37
38    pub fn contains_building(&self, name: &str) -> bool {
39        self.inner.contains_key(name)
40    }
41
42    pub fn len(&self) -> usize {
43        self.inner.len()
44    }
45
46    pub fn is_empty(&self) -> bool {
47        self.inner.is_empty()
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_buildings_deserialize() {
57        let json_str = r#"{
58    "bad_rax_melee_bot": {
59      "health": 2200,
60      "max_health": 2200
61    },
62    "bad_rax_melee_mid": {
63      "health": 2200,
64      "max_health": 2200
65    },
66    "bad_rax_melee_top": {
67      "health": 2200,
68      "max_health": 2200
69    },
70    "bad_rax_range_bot": {
71      "health": 1300,
72      "max_health": 1300
73    },
74    "bad_rax_range_mid": {
75      "health": 1300,
76      "max_health": 1300
77    },
78    "bad_rax_range_top": {
79      "health": 1300,
80      "max_health": 1300
81    },
82    "dota_badguys_fort": {
83      "health": 4500,
84      "max_health": 4500
85    },
86    "dota_badguys_tower1_bot": {
87      "health": 1752,
88      "max_health": 1800
89    },
90    "dota_badguys_tower2_bot": {
91      "health": 2500,
92      "max_health": 2500
93    },
94    "dota_badguys_tower2_mid": {
95      "health": 2395,
96      "max_health": 2500
97    },
98    "dota_badguys_tower2_top": {
99      "health": 2282,
100      "max_health": 2500
101    },
102    "dota_badguys_tower3_bot": {
103      "health": 2500,
104      "max_health": 2500
105    },
106    "dota_badguys_tower3_mid": {
107      "health": 2500,
108      "max_health": 2500
109    },
110    "dota_badguys_tower3_top": {
111      "health": 2500,
112      "max_health": 2500
113    },
114    "dota_badguys_tower4_bot": {
115      "health": 2600,
116      "max_health": 2600
117    },
118    "dota_badguys_tower4_top": {
119      "health": 2600,
120      "max_health": 2600
121    }
122  }"#;
123        let buildings: Buildings =
124            serde_json::from_str(json_str).expect("Failed to deserialize Buildings");
125
126        assert!(buildings.contains_building("dota_badguys_tower3_mid"));
127    }
128}