Skip to main content

moonproof_runtime_ir/
ser.rs

1//! Serialize any `T: Serialize` directly into an in-memory [`RuntimeValue`]
2//! tree — the symmetric counterpart to [`crate::de::from_runtime_value`].
3//!
4//! Avoids intermediate `serde_json::Value` allocations and preserves
5//! [`RuntimeValue::Bytes`] natively (`is_human_readable() == false`, so
6//! byte buffers stay raw bytes rather than being hex-encoded into strings).
7
8use std::collections::BTreeMap;
9use std::fmt;
10
11use serde::ser::{
12    self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
13    SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer,
14};
15
16use crate::value::RuntimeValue;
17
18/// Error from serializing a typed value into a [`RuntimeValue`].
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct ToValueError(String);
21
22impl fmt::Display for ToValueError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.write_str(&self.0)
25    }
26}
27
28impl std::error::Error for ToValueError {}
29
30impl ser::Error for ToValueError {
31    fn custom<T: fmt::Display>(msg: T) -> Self {
32        ToValueError(msg.to_string())
33    }
34}
35
36/// Serialize `value` directly into a [`RuntimeValue`], preserving raw
37/// byte strings and avoiding any JSON/CBOR buffer round-trip.
38pub fn to_runtime_value<T: Serialize + ?Sized>(value: &T) -> Result<RuntimeValue, ToValueError> {
39    value.serialize(RuntimeValueSerializer)
40}
41
42struct RuntimeValueSerializer;
43
44impl Serializer for RuntimeValueSerializer {
45    type Ok = RuntimeValue;
46    type Error = ToValueError;
47
48    type SerializeSeq = SeqSer;
49    type SerializeTuple = SeqSer;
50    type SerializeTupleStruct = SeqSer;
51    type SerializeTupleVariant = TupleVariantSer;
52    type SerializeMap = MapSer;
53    type SerializeStruct = StructSer;
54    type SerializeStructVariant = StructVariantSer;
55
56    fn is_human_readable(&self) -> bool {
57        false
58    }
59
60    fn serialize_bool(self, v: bool) -> Result<RuntimeValue, ToValueError> {
61        Ok(RuntimeValue::Bool(v))
62    }
63
64    fn serialize_i8(self, v: i8) -> Result<RuntimeValue, ToValueError> {
65        Ok(RuntimeValue::Int(i128::from(v)))
66    }
67
68    fn serialize_i16(self, v: i16) -> Result<RuntimeValue, ToValueError> {
69        Ok(RuntimeValue::Int(i128::from(v)))
70    }
71
72    fn serialize_i32(self, v: i32) -> Result<RuntimeValue, ToValueError> {
73        Ok(RuntimeValue::Int(i128::from(v)))
74    }
75
76    fn serialize_i64(self, v: i64) -> Result<RuntimeValue, ToValueError> {
77        Ok(RuntimeValue::Int(i128::from(v)))
78    }
79
80    fn serialize_i128(self, v: i128) -> Result<RuntimeValue, ToValueError> {
81        Ok(RuntimeValue::Int(v))
82    }
83
84    fn serialize_u8(self, v: u8) -> Result<RuntimeValue, ToValueError> {
85        Ok(RuntimeValue::Int(i128::from(v)))
86    }
87
88    fn serialize_u16(self, v: u16) -> Result<RuntimeValue, ToValueError> {
89        Ok(RuntimeValue::Int(i128::from(v)))
90    }
91
92    fn serialize_u32(self, v: u32) -> Result<RuntimeValue, ToValueError> {
93        Ok(RuntimeValue::Int(i128::from(v)))
94    }
95
96    fn serialize_u64(self, v: u64) -> Result<RuntimeValue, ToValueError> {
97        Ok(RuntimeValue::Int(i128::from(v)))
98    }
99
100    fn serialize_u128(self, v: u128) -> Result<RuntimeValue, ToValueError> {
101        Ok(RuntimeValue::from(v))
102    }
103
104    fn serialize_f32(self, v: f32) -> Result<RuntimeValue, ToValueError> {
105        Ok(RuntimeValue::String(format!("{v}")))
106    }
107
108    fn serialize_f64(self, v: f64) -> Result<RuntimeValue, ToValueError> {
109        Ok(RuntimeValue::String(format!("{v}")))
110    }
111
112    fn serialize_char(self, v: char) -> Result<RuntimeValue, ToValueError> {
113        Ok(RuntimeValue::String(v.to_string()))
114    }
115
116    fn serialize_str(self, v: &str) -> Result<RuntimeValue, ToValueError> {
117        Ok(RuntimeValue::String(v.to_owned()))
118    }
119
120    fn serialize_bytes(self, v: &[u8]) -> Result<RuntimeValue, ToValueError> {
121        Ok(RuntimeValue::Bytes(v.to_vec()))
122    }
123
124    fn serialize_none(self) -> Result<RuntimeValue, ToValueError> {
125        Ok(RuntimeValue::Null)
126    }
127
128    fn serialize_some<T: Serialize + ?Sized>(
129        self,
130        value: &T,
131    ) -> Result<RuntimeValue, ToValueError> {
132        value.serialize(self)
133    }
134
135    fn serialize_unit(self) -> Result<RuntimeValue, ToValueError> {
136        Ok(RuntimeValue::Null)
137    }
138
139    fn serialize_unit_struct(self, _name: &'static str) -> Result<RuntimeValue, ToValueError> {
140        Ok(RuntimeValue::Null)
141    }
142
143    fn serialize_unit_variant(
144        self,
145        _name: &'static str,
146        _variant_index: u32,
147        variant: &'static str,
148    ) -> Result<RuntimeValue, ToValueError> {
149        Ok(RuntimeValue::String(variant.to_owned()))
150    }
151
152    fn serialize_newtype_struct<T: Serialize + ?Sized>(
153        self,
154        _name: &'static str,
155        value: &T,
156    ) -> Result<RuntimeValue, ToValueError> {
157        value.serialize(self)
158    }
159
160    fn serialize_newtype_variant<T: Serialize + ?Sized>(
161        self,
162        _name: &'static str,
163        _variant_index: u32,
164        variant: &'static str,
165        value: &T,
166    ) -> Result<RuntimeValue, ToValueError> {
167        let mut map = BTreeMap::new();
168        map.insert(variant.to_owned(), value.serialize(self)?);
169        Ok(RuntimeValue::Object(map))
170    }
171
172    fn serialize_seq(self, len: Option<usize>) -> Result<SeqSer, ToValueError> {
173        Ok(SeqSer(Vec::with_capacity(len.unwrap_or(0))))
174    }
175
176    fn serialize_tuple(self, len: usize) -> Result<SeqSer, ToValueError> {
177        Ok(SeqSer(Vec::with_capacity(len)))
178    }
179
180    fn serialize_tuple_struct(
181        self,
182        _name: &'static str,
183        len: usize,
184    ) -> Result<SeqSer, ToValueError> {
185        Ok(SeqSer(Vec::with_capacity(len)))
186    }
187
188    fn serialize_tuple_variant(
189        self,
190        _name: &'static str,
191        _variant_index: u32,
192        variant: &'static str,
193        len: usize,
194    ) -> Result<TupleVariantSer, ToValueError> {
195        Ok(TupleVariantSer {
196            variant: variant.to_owned(),
197            items: Vec::with_capacity(len),
198        })
199    }
200
201    fn serialize_map(self, _len: Option<usize>) -> Result<MapSer, ToValueError> {
202        Ok(MapSer {
203            map: BTreeMap::new(),
204            next_key: None,
205        })
206    }
207
208    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<StructSer, ToValueError> {
209        Ok(StructSer(BTreeMap::new()))
210    }
211
212    fn serialize_struct_variant(
213        self,
214        _name: &'static str,
215        _variant_index: u32,
216        variant: &'static str,
217        _len: usize,
218    ) -> Result<StructVariantSer, ToValueError> {
219        Ok(StructVariantSer {
220            variant: variant.to_owned(),
221            map: BTreeMap::new(),
222        })
223    }
224}
225
226struct SeqSer(Vec<RuntimeValue>);
227
228impl SerializeSeq for SeqSer {
229    type Ok = RuntimeValue;
230    type Error = ToValueError;
231
232    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), ToValueError> {
233        self.0.push(value.serialize(RuntimeValueSerializer)?);
234        Ok(())
235    }
236
237    fn end(self) -> Result<RuntimeValue, ToValueError> {
238        Ok(RuntimeValue::Array(self.0))
239    }
240}
241
242impl SerializeTuple for SeqSer {
243    type Ok = RuntimeValue;
244    type Error = ToValueError;
245
246    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), ToValueError> {
247        self.0.push(value.serialize(RuntimeValueSerializer)?);
248        Ok(())
249    }
250
251    fn end(self) -> Result<RuntimeValue, ToValueError> {
252        Ok(RuntimeValue::Array(self.0))
253    }
254}
255
256impl SerializeTupleStruct for SeqSer {
257    type Ok = RuntimeValue;
258    type Error = ToValueError;
259
260    fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), ToValueError> {
261        self.0.push(value.serialize(RuntimeValueSerializer)?);
262        Ok(())
263    }
264
265    fn end(self) -> Result<RuntimeValue, ToValueError> {
266        Ok(RuntimeValue::Array(self.0))
267    }
268}
269
270struct TupleVariantSer {
271    variant: String,
272    items: Vec<RuntimeValue>,
273}
274
275impl SerializeTupleVariant for TupleVariantSer {
276    type Ok = RuntimeValue;
277    type Error = ToValueError;
278
279    fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), ToValueError> {
280        self.items.push(value.serialize(RuntimeValueSerializer)?);
281        Ok(())
282    }
283
284    fn end(self) -> Result<RuntimeValue, ToValueError> {
285        let mut map = BTreeMap::new();
286        map.insert(self.variant, RuntimeValue::Array(self.items));
287        Ok(RuntimeValue::Object(map))
288    }
289}
290
291struct MapSer {
292    map: BTreeMap<String, RuntimeValue>,
293    next_key: Option<String>,
294}
295
296impl SerializeMap for MapSer {
297    type Ok = RuntimeValue;
298    type Error = ToValueError;
299
300    fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), ToValueError> {
301        let k = match key.serialize(RuntimeValueSerializer)? {
302            RuntimeValue::String(s) => s,
303            other => {
304                return Err(ToValueError(format!(
305                    "RuntimeValue map key must be a string, got {}",
306                    other.type_label()
307                )));
308            }
309        };
310        self.next_key = Some(k);
311        Ok(())
312    }
313
314    fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), ToValueError> {
315        let k = self
316            .next_key
317            .take()
318            .ok_or_else(|| ToValueError("serialize_value called before serialize_key".into()))?;
319        self.map.insert(k, value.serialize(RuntimeValueSerializer)?);
320        Ok(())
321    }
322
323    fn end(self) -> Result<RuntimeValue, ToValueError> {
324        Ok(RuntimeValue::Object(self.map))
325    }
326}
327
328struct StructSer(BTreeMap<String, RuntimeValue>);
329
330impl SerializeStruct for StructSer {
331    type Ok = RuntimeValue;
332    type Error = ToValueError;
333
334    fn serialize_field<T: Serialize + ?Sized>(
335        &mut self,
336        key: &'static str,
337        value: &T,
338    ) -> Result<(), ToValueError> {
339        self.0
340            .insert(key.to_owned(), value.serialize(RuntimeValueSerializer)?);
341        Ok(())
342    }
343
344    fn end(self) -> Result<RuntimeValue, ToValueError> {
345        Ok(RuntimeValue::Object(self.0))
346    }
347}
348
349struct StructVariantSer {
350    variant: String,
351    map: BTreeMap<String, RuntimeValue>,
352}
353
354impl SerializeStructVariant for StructVariantSer {
355    type Ok = RuntimeValue;
356    type Error = ToValueError;
357
358    fn serialize_field<T: Serialize + ?Sized>(
359        &mut self,
360        key: &'static str,
361        value: &T,
362    ) -> Result<(), ToValueError> {
363        self.map
364            .insert(key.to_owned(), value.serialize(RuntimeValueSerializer)?);
365        Ok(())
366    }
367
368    fn end(self) -> Result<RuntimeValue, ToValueError> {
369        let mut outer = BTreeMap::new();
370        outer.insert(self.variant, RuntimeValue::Object(self.map));
371        Ok(RuntimeValue::Object(outer))
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::de::from_runtime_value;
379    use crate::ir::{Expression, Statement, TypeDescriptor};
380
381    #[test]
382    fn round_trips_bytes_literal_without_hex_degradation() {
383        let expr = Expression::Literal {
384            value: RuntimeValue::Bytes(vec![0xde, 0xad, 0xbe, 0xef]),
385        };
386        let rv = to_runtime_value(&expr).unwrap();
387        assert_eq!(
388            rv.get("value"),
389            Some(&RuntimeValue::Bytes(vec![0xde, 0xad, 0xbe, 0xef]))
390        );
391        let back: Expression = from_runtime_value(&rv).unwrap();
392        match back {
393            Expression::Literal {
394                value: RuntimeValue::Bytes(b),
395            } => assert_eq!(b, vec![0xde, 0xad, 0xbe, 0xef]),
396            other => panic!("expected raw Bytes literal, got {other:?}"),
397        }
398    }
399
400    #[test]
401    fn round_trips_statement_and_descriptor() {
402        let stmt = Statement::Expr {
403            value: Expression::Default {
404                of_type: TypeDescriptor::Bytes { length: 32 },
405            },
406        };
407        let rv = to_runtime_value(&stmt).unwrap();
408        let back: Statement = from_runtime_value(&rv).unwrap();
409        assert_eq!(to_runtime_value(&back).unwrap(), rv);
410    }
411}