Skip to main content

openstranded_plugin_api/
registry.rs

1use std::collections::HashMap;
2
3use crate::ServiceError;
4
5#[cfg(feature = "ron")]
6use crate::Value;
7#[cfg(feature = "ron")]
8use ron::value::Value as RonValue;
9
10/// A single file from a Content Pack, indexed in the Registry.
11#[derive(Clone, Debug)]
12pub struct RegistryEntry {
13    /// Filename (e.g. "`items_edible.ron`").
14    pub filename: String,
15
16    /// Raw file bytes.
17    pub data: Vec<u8>,
18}
19
20/// All data from a Content Pack, grouped by domain (from manifest.toml).
21///
22/// Registry is an "in-memory filesystem". It does not know the structure of
23/// the data inside files. Each plugin decides how to parse the bytes it receives.
24///
25/// # Structure
26///
27/// ```text
28/// domains: {
29///     "items"   → { "items_edible.ron": [...bytes...], "items_material.ron": [...bytes...] },
30///     "recipes" → { "combinations.ron": [...bytes...] },
31/// }
32/// ```
33#[derive(Clone, Debug, Default)]
34pub struct Registry {
35    /// Domain → { filename → raw bytes }
36    pub domains: HashMap<String, HashMap<String, Vec<u8>>>,
37}
38
39impl Registry {
40    /// Create an empty Registry.
41    #[must_use]
42    pub fn new() -> Self {
43        Self {
44            domains: HashMap::new(),
45        }
46    }
47
48    /// Get all files in a domain.
49    pub fn domain(&self, name: &str) -> Result<&HashMap<String, Vec<u8>>, ServiceError> {
50        self.domains
51            .get(name)
52            .ok_or_else(|| ServiceError::RegistryDomainNotFound(name.into()))
53    }
54
55    /// Get raw bytes of a specific file within a domain.
56    pub fn file(&self, domain: &str, filename: &str) -> Result<&[u8], ServiceError> {
57        self.domains
58            .get(domain)
59            .and_then(|files| files.get(filename))
60            .map(std::vec::Vec::as_slice)
61            .ok_or_else(|| ServiceError::FileNotFound {
62                domain: domain.into(),
63                filename: filename.into(),
64            })
65    }
66
67    /// Get all entries in a domain as `Vec<RegistryEntry>` (filename + data).
68    pub fn domain_entries(&self, name: &str) -> Result<Vec<RegistryEntry>, ServiceError> {
69        let files = self.domain(name)?;
70        Ok(files
71            .iter()
72            .map(|(filename, data)| RegistryEntry {
73                filename: filename.clone(),
74                data: data.clone(),
75            })
76            .collect())
77    }
78
79    /// Add a file to a domain.
80    pub fn add_file(&mut self, domain: &str, filename: &str, data: Vec<u8>) {
81        self.domains
82            .entry(domain.to_owned())
83            .or_default()
84            .insert(filename.to_owned(), data);
85    }
86
87    /// Check whether a domain exists.
88    #[must_use]
89    pub fn has_domain(&self, name: &str) -> bool {
90        self.domains.contains_key(name)
91    }
92
93    /// Iterate over all domain names.
94    pub fn domain_names(&self) -> impl Iterator<Item = &str> {
95        self.domains.keys().map(std::string::String::as_str)
96    }
97
98    /// Number of domains.
99    #[must_use]
100    pub fn len(&self) -> usize {
101        self.domains.len()
102    }
103
104    /// Whether the Registry is empty.
105    #[must_use]
106    pub fn is_empty(&self) -> bool {
107        self.domains.is_empty()
108    }
109}
110
111// ── Registry data parsing ──────────────────────────────────────────
112
113/// Parse raw .ron bytes into a Value tree.
114///
115/// Uses RON's dynamic value type internally, which handles both
116/// named structs (`ItemDef(id: 1)`) and anonymous data (`{ "id": 1 }`).
117///
118/// Single point of parsing: today .ron, tomorrow maybe .json or .bin.
119/// Plugins do not change code — just recompile with a newer plugin-api version.
120///
121/// # Examples
122///
123/// ```rust
124/// use openstranded_plugin_api::parse_registry_data;
125///
126/// // Named struct (common in .ron data files)
127/// let bytes = b"[ItemDef(id: 1, name: \"Wood\")]";
128/// let data = parse_registry_data(bytes).unwrap();
129/// ```
130#[cfg(feature = "ron")]
131pub fn parse_registry_data(bytes: &[u8]) -> Result<Value, ServiceError> {
132    let s = std::str::from_utf8(bytes).map_err(|e| {
133        ServiceError::ParseError(format!("registry data is not valid UTF-8: {e}"))
134    })?;
135    let ron_value: RonValue = ron::from_str(s).map_err(|e| {
136        ServiceError::ParseError(format!("failed to parse registry data: {e}"))
137    })?;
138    Ok(convert_ron_value(ron_value))
139}
140
141/// Convenience wrapper: parse bytes as an array and return elements.
142///
143/// Errors if the .ron root is not an array.
144///
145/// # Examples
146///
147/// ```rust
148/// use openstranded_plugin_api::parse_registry_list;
149///
150/// let bytes = b"[ItemDef(id: 1), ItemDef(id: 2)]";
151/// let items = parse_registry_list(bytes).unwrap();
152/// assert_eq!(items.len(), 2);
153/// ```
154#[cfg(feature = "ron")]
155pub fn parse_registry_list(bytes: &[u8]) -> Result<Vec<Value>, ServiceError> {
156    let root = parse_registry_data(bytes)?;
157    match root {
158        Value::Array(arr) => Ok(arr),
159        other => Err(ServiceError::TypeMismatch {
160            expected: "array".into(),
161            found: format!("{other:?}"),
162        }),
163    }
164}
165
166// ── RON value conversion ───────────────────────────────────────────
167
168/// Convert a RON dynamic value to our plugin-api Value.
169#[cfg(feature = "ron")]
170fn convert_ron_value(v: RonValue) -> Value {
171    match v {
172        RonValue::Unit => Value::Null,
173        RonValue::Bool(b) => Value::Bool(b),
174        RonValue::Number(n) => {
175            match n {
176                ron::value::Number::I32(i) => Value::I32(i),
177                ron::value::Number::I64(i) => {
178                    if let Ok(n) = i32::try_from(i) {
179                        Value::I32(n)
180                    } else {
181                        Value::F64(i as f64)
182                    }
183                }
184                ron::value::Number::F32(f) => Value::F64(f64::from(f.0)),
185                ron::value::Number::F64(f) => Value::F64(f.0),
186                ron::value::Number::U32(u) => Value::U32(u),
187                ron::value::Number::U64(u) => {
188                    if let Ok(n) = u32::try_from(u) {
189                        Value::U32(n)
190                    } else {
191                        Value::F64(u as f64)
192                    }
193                }
194                // Handle remaining integer types
195                ron::value::Number::I8(i) => Value::I32(i32::from(i)),
196                ron::value::Number::I16(i) => Value::I32(i32::from(i)),
197                ron::value::Number::U8(u) => Value::U32(u32::from(u)),
198                ron::value::Number::U16(u) => Value::U32(u32::from(u)),
199                #[allow(unreachable_patterns)]
200                _ => Value::Null,
201            }
202        }
203        RonValue::Char(c) => Value::String(c.to_string()),
204        RonValue::String(s) => Value::String(s),
205        RonValue::Bytes(b) => Value::Bytes(b),
206        RonValue::Seq(arr) => {
207            Value::Array(arr.into_iter().map(convert_ron_value).collect())
208        }
209        RonValue::Map(map) => {
210            Value::Map(
211                map.into_iter()
212                    .map(|(k, v)| (convert_ron_key(k), convert_ron_value(v)))
213                    .collect(),
214            )
215        }
216        RonValue::Option(Some(v)) => convert_ron_value(*v),
217        RonValue::Option(None) => Value::Null,
218    }
219}
220
221/// Convert a RON map key (which can be any Value) to a String.
222#[cfg(feature = "ron")]
223fn convert_ron_key(k: RonValue) -> String {
224    match k {
225        RonValue::String(s) => s,
226        RonValue::Char(c) => c.to_string(),
227        other => format!("{other:?}"),
228    }
229}
230
231// ── Tests ──────────────────────────────────────────────────────────
232
233#[cfg(test)]
234#[cfg(feature = "ron")]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn test_parse_registry_data_object() {
240        let ron = br#"ItemDef(id: 1, name: "Wood")"#;
241        let value = parse_registry_data(ron).unwrap();
242        assert_eq!(value.get("id").unwrap().as_u32().unwrap(), 1);
243        assert_eq!(value.get("name").unwrap().as_str().unwrap(), "Wood");
244    }
245
246    #[test]
247    fn test_parse_registry_data_array() {
248        let ron = br#"[1, 2, 3]"#;
249        let value = parse_registry_data(ron).unwrap();
250        assert_eq!(value.as_array().unwrap().len(), 3);
251    }
252
253    #[test]
254    fn test_parse_registry_list_ok() {
255        let ron = br#"[ItemDef(id: 1), ItemDef(id: 2)]"#;
256        let items = parse_registry_list(ron).unwrap();
257        assert_eq!(items.len(), 2);
258        assert_eq!(items[0].get("id").unwrap().as_u32().unwrap(), 1);
259    }
260
261    #[test]
262    fn test_parse_registry_list_not_array() {
263        let ron = br#"ItemDef(id: 1)"#;
264        let err = parse_registry_list(ron).unwrap_err();
265        assert!(matches!(err, ServiceError::TypeMismatch { .. }));
266    }
267
268    #[test]
269    fn test_parse_invalid_ron() {
270        let ron = b"not valid ron {{{";
271        assert!(parse_registry_data(ron).is_err());
272    }
273
274    #[test]
275    fn test_registry_add_and_get() {
276        let mut reg = Registry::new();
277        reg.add_file("items", "items_edible.ron", vec![1, 2, 3]);
278        reg.add_file("items", "items_material.ron", vec![4, 5, 6]);
279
280        assert_eq!(reg.file("items", "items_edible.ron").unwrap(), &[1, 2, 3]);
281        assert_eq!(reg.domain_entries("items").unwrap().len(), 2);
282    }
283
284    #[test]
285    fn test_registry_file_not_found() {
286        let reg = Registry::new();
287        let err = reg.file("nonexistent", "foo.ron").unwrap_err();
288        assert!(matches!(err, ServiceError::FileNotFound { .. }));
289    }
290
291    #[test]
292    fn test_registry_domain_not_found() {
293        let reg = Registry::new();
294        let err = reg.domain("nonexistent").unwrap_err();
295        assert!(matches!(err, ServiceError::RegistryDomainNotFound(..)));
296    }
297}