Skip to main content

openstranded_plugin_api/
registry.rs

1use crate::ServiceError;
2
3#[cfg(feature = "parse")]
4use crate::Value;
5#[cfg(feature = "parse")]
6use ron::value::Value as RonValue;
7
8/// A single file from a Content Pack, indexed in the Registry.
9///
10/// This is a data-transfer object that crosses the WASM boundary.
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// ── Registry data parsing ──────────────────────────────────────────
21
22/// Parse registry data bytes into a Value tree.
23///
24/// The parsing backend is version-dependent (currently RON).
25/// This function is the single point of parsing: plugins that use it
26/// automatically get support for new data formats when the plugin-api
27/// crate is upgraded.
28///
29/// # Examples
30///
31/// ```rust
32/// use openstranded_plugin_api::parse_registry_data;
33///
34/// // Named struct (common in data files)
35/// let bytes = b"[ItemDef(id: 1, name: \"Wood\")]";
36/// let data = parse_registry_data(bytes).unwrap();
37/// ```
38#[cfg(feature = "parse")]
39pub fn parse_registry_data(bytes: &[u8]) -> Result<Value, ServiceError> {
40    let s = std::str::from_utf8(bytes).map_err(|e| {
41        ServiceError::ParseError(format!("registry data is not valid UTF-8: {e}"))
42    })?;
43    let ron_value: RonValue = ron::from_str(s).map_err(|e| {
44        ServiceError::ParseError(format!("failed to parse registry data: {e}"))
45    })?;
46    Ok(convert_ron_value(ron_value))
47}
48
49/// Convenience wrapper: parse bytes as an array and return elements.
50///
51/// Errors if the root value is not an array.
52///
53/// # Examples
54///
55/// ```rust
56/// use openstranded_plugin_api::parse_registry_list;
57///
58/// let bytes = b"[ItemDef(id: 1), ItemDef(id: 2)]";
59/// let items = parse_registry_list(bytes).unwrap();
60/// assert_eq!(items.len(), 2);
61/// ```
62#[cfg(feature = "parse")]
63pub fn parse_registry_list(bytes: &[u8]) -> Result<Vec<Value>, ServiceError> {
64    let root = parse_registry_data(bytes)?;
65    match root {
66        Value::Array(arr) => Ok(arr),
67        other => Err(ServiceError::TypeMismatch {
68            expected: "array".into(),
69            found: format!("{other:?}"),
70        }),
71    }
72}
73
74// ── RON value conversion ───────────────────────────────────────────
75
76/// Convert a RON dynamic value to our plugin-api Value.
77#[cfg(feature = "parse")]
78fn convert_ron_value(v: RonValue) -> Value {
79    match v {
80        RonValue::Unit => Value::Null,
81        RonValue::Bool(b) => Value::Bool(b),
82        RonValue::Number(n) => {
83            match n {
84                ron::value::Number::I32(i) => Value::I32(i),
85                ron::value::Number::I64(i) => {
86                    if let Ok(n) = i32::try_from(i) {
87                        Value::I32(n)
88                    } else {
89                        Value::F64(i as f64)
90                    }
91                }
92                ron::value::Number::F32(f) => Value::F64(f64::from(f.0)),
93                ron::value::Number::F64(f) => Value::F64(f.0),
94                ron::value::Number::U32(u) => Value::U32(u),
95                ron::value::Number::U64(u) => {
96                    if let Ok(n) = u32::try_from(u) {
97                        Value::U32(n)
98                    } else {
99                        Value::F64(u as f64)
100                    }
101                }
102                // Handle remaining integer types
103                ron::value::Number::I8(i) => Value::I32(i32::from(i)),
104                ron::value::Number::I16(i) => Value::I32(i32::from(i)),
105                ron::value::Number::U8(u) => Value::U32(u32::from(u)),
106                ron::value::Number::U16(u) => Value::U32(u32::from(u)),
107                #[allow(unreachable_patterns)]
108                _ => Value::Null,
109            }
110        }
111        RonValue::Char(c) => Value::String(c.to_string()),
112        RonValue::String(s) => Value::String(s),
113        RonValue::Bytes(b) => Value::Bytes(b),
114        RonValue::Seq(arr) => {
115            Value::Array(arr.into_iter().map(convert_ron_value).collect())
116        }
117        RonValue::Map(map) => {
118            Value::Map(
119                map.into_iter()
120                    .map(|(k, v)| (convert_ron_key(k), convert_ron_value(v)))
121                    .collect(),
122            )
123        }
124        RonValue::Option(Some(v)) => convert_ron_value(*v),
125        RonValue::Option(None) => Value::Null,
126    }
127}
128
129/// Convert a RON map key (which can be any Value) to a String.
130#[cfg(feature = "parse")]
131fn convert_ron_key(k: RonValue) -> String {
132    match k {
133        RonValue::String(s) => s,
134        RonValue::Char(c) => c.to_string(),
135        other => format!("{other:?}"),
136    }
137}
138
139// ── Tests ──────────────────────────────────────────────────────────
140
141#[cfg(test)]
142#[cfg(feature = "parse")]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn test_parse_registry_data_object() {
148        let ron = br#"ItemDef(id: 1, name: "Wood")"#;
149        let value = parse_registry_data(ron).unwrap();
150        assert_eq!(value.get("id").unwrap().as_u32().unwrap(), 1);
151        assert_eq!(value.get("name").unwrap().as_str().unwrap(), "Wood");
152    }
153
154    #[test]
155    fn test_parse_registry_data_array() {
156        let ron = br#"[1, 2, 3]"#;
157        let value = parse_registry_data(ron).unwrap();
158        assert_eq!(value.as_array().unwrap().len(), 3);
159    }
160
161    #[test]
162    fn test_parse_registry_list_ok() {
163        let ron = br#"[ItemDef(id: 1), ItemDef(id: 2)]"#;
164        let items = parse_registry_list(ron).unwrap();
165        assert_eq!(items.len(), 2);
166        assert_eq!(items[0].get("id").unwrap().as_u32().unwrap(), 1);
167    }
168
169    #[test]
170    fn test_parse_registry_list_not_array() {
171        let ron = br#"ItemDef(id: 1)"#;
172        let err = parse_registry_list(ron).unwrap_err();
173        assert!(matches!(err, ServiceError::TypeMismatch { .. }));
174    }
175
176    #[test]
177    fn test_parse_invalid_ron() {
178        let ron = b"not valid ron {{{";
179        assert!(parse_registry_data(ron).is_err());
180    }
181}