arma_rs/value/loadout/
extended.rs

1use std::collections::HashMap;
2
3use crate::{FromArma, FromArmaError, Value};
4
5#[derive(Debug, Default, Clone, PartialEq)]
6/// CBA Extended Loadout
7///
8/// <https://github.com/CBATeam/CBA_A3/pull/1503>
9pub struct CBAExtended(Option<HashMap<String, Value>>);
10
11impl CBAExtended {
12    /// Create a new CBA Extended Loadout Array
13    pub fn new() -> Self {
14        Self::default()
15    }
16
17    /// The map has no data or does not exist
18    pub fn is_empty(&self) -> bool {
19        self.0.is_none() || self.0.as_ref().unwrap().is_empty()
20    }
21
22    /// Get a value from the map
23    pub fn get(&self, key: &str) -> Option<&Value> {
24        self.0.as_ref().and_then(|map| map.get(key))
25    }
26
27    /// Get a mutable value from the map
28    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
29        self.0.as_mut().and_then(|map| map.get_mut(key))
30    }
31
32    /// Insert a value into the map
33    pub fn insert(&mut self, key: String, value: Value) -> Option<Value> {
34        self.0.get_or_insert_with(HashMap::new).insert(key, value)
35    }
36
37    /// Remove a value from the map
38    pub fn remove(&mut self, key: &str) -> Option<Value> {
39        self.0.as_mut().and_then(|map| map.remove(key))
40    }
41
42    /// Iterate over the keys in the map
43    pub fn values(&self) -> impl Iterator<Item = &Value> {
44        self.0.iter().flat_map(|map| map.values())
45    }
46}
47
48impl FromArma for CBAExtended {
49    fn from_arma(s: String) -> Result<Self, FromArmaError> {
50        let value = <Vec<(String, Value)>>::from_arma(s);
51        match value {
52            Ok(value) => Ok(Self(Some(value.into_iter().collect()))),
53            Err(_) => Ok(Self(None)),
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_from_arma() {
64        let value = CBAExtended::from_arma("[]".to_string());
65        assert!(value.is_ok());
66        assert_eq!(value.unwrap(), CBAExtended(Some(HashMap::new())));
67
68        let value = CBAExtended::from_arma("[[\"cba_xeh_enabled\",true]]".to_string());
69        assert!(value.is_ok());
70        assert_eq!(
71            value.unwrap(),
72            CBAExtended(Some(
73                vec![("cba_xeh_enabled".to_string(), Value::Boolean(true))]
74                    .into_iter()
75                    .collect()
76            ))
77        );
78    }
79}