vdf_serde/
ser.rs

1//! Serialize a Rust data structure into VDF data
2
3use serde::{ser::{self, Impossible}, Serialize};
4
5use crate::error::{Error, Result};
6use serde::ser::SerializeMap;
7
8/// A structure for serializing Rust values into VDF
9pub struct Serializer {
10    output: String,
11    indent_level: usize,
12}
13
14/// Serialize the given data structure as a String of VDF
15///
16/// # Errors
17///
18/// If `T` uses an unsupported Serde data type, or `T`'s `Serialize` implementation
19/// itself returns an error, an error will be returned.
20///
21/// Notably, if `T` has a map with a non-atomic key, an error will not be returned.
22/// In these cases, this behavior is likely incompatible with other VDF parsers.
23pub fn to_string<T>(value: &T) -> Result<String>
24    where
25        T: Serialize,
26{
27    let mut serializer = Serializer {
28        output: String::new(),
29        indent_level: 0,
30    };
31    value.serialize(&mut serializer)?;
32    Ok(serializer.output)
33}
34
35impl<'a> ser::Serializer for &'a mut Serializer {
36    type Ok = ();
37
38    type Error = Error;
39
40    type SerializeSeq = Impossible<(), Error>;
41    type SerializeTuple = Impossible<(), Error>;
42    type SerializeTupleStruct = Impossible<(), Error>;
43    type SerializeTupleVariant = Impossible<(), Error>;
44    type SerializeMap = Self;
45    type SerializeStruct = Self;
46    type SerializeStructVariant = Impossible<(), Error>;
47
48    fn serialize_bool(self, v: bool) -> Result<()> {
49        self.output += if v { r#""1""# } else { r#""0""# };
50        Ok(())
51    }
52
53    fn serialize_i8(self, v: i8) -> Result<()> {
54        self.serialize_i64(i64::from(v))
55    }
56
57    fn serialize_i16(self, v: i16) -> Result<()> {
58        self.serialize_i64(i64::from(v))
59    }
60
61    fn serialize_i32(self, v: i32) -> Result<()> {
62        self.serialize_i64(i64::from(v))
63    }
64
65    fn serialize_i64(self, v: i64) -> Result<()> {
66        self.output += "\"";
67        self.output += &v.to_string();
68        self.output += "\"";
69        Ok(())
70    }
71
72    fn serialize_u8(self, v: u8) -> Result<()> {
73        self.serialize_u64(u64::from(v))
74    }
75
76    fn serialize_u16(self, v: u16) -> Result<()> {
77        self.serialize_u64(u64::from(v))
78    }
79
80    fn serialize_u32(self, v: u32) -> Result<()> {
81        self.serialize_u64(u64::from(v))
82    }
83
84    fn serialize_u64(self, v: u64) -> Result<()> {
85        self.output += "\"";
86        self.output += &v.to_string();
87        self.output += "\"";
88        Ok(())
89    }
90
91    fn serialize_f32(self, v: f32) -> Result<()> {
92        self.serialize_f64(f64::from(v))
93    }
94
95    fn serialize_f64(self, v: f64) -> Result<()> {
96        self.output += "\"";
97        self.output += &v.to_string();
98        self.output += "\"";
99        Ok(())
100    }
101
102    fn serialize_char(self, v: char) -> Result<()> {
103        self.serialize_str(&v.to_string())
104    }
105
106    fn serialize_str(self, v: &str) -> Result<()> {
107        let escaped = v
108            .replace('\\', r"\\")
109            .replace('\n', r"\n")
110            .replace('\t', r"\t")
111            .replace('"', r#"\""#);
112        self.output += "\"";
113        self.output += &escaped;
114        self.output += "\"";
115        Ok(())
116    }
117
118    fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
119        Err(Error::UnsupportedType("byte array"))
120    }
121
122    fn serialize_none(self) -> Result<()> {
123        Err(Error::UnsupportedType("option"))
124    }
125
126    fn serialize_some<T>(self, _value: &T) -> Result<()>
127        where
128            T: ?Sized + Serialize,
129    {
130        Err(Error::UnsupportedType("option"))
131    }
132
133    fn serialize_unit(self) -> Result<()> {
134        Err(Error::UnsupportedType("unit"))
135    }
136
137    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
138        Err(Error::UnsupportedType("unit_struct"))
139    }
140
141    fn serialize_unit_variant(
142        self,
143        _name: &'static str,
144        _variant_index: u32,
145        variant: &'static str,
146    ) -> Result<()> {
147        self.serialize_str(variant)
148    }
149
150    fn serialize_newtype_struct<T>(
151        self,
152        name: &'static str,
153        value: &T,
154    ) -> Result<()>
155        where
156            T: ?Sized + Serialize,
157    {
158        if self.indent_level == 0 {
159            self.output += &format!("\"{}\"\t", name);
160        }
161        value.serialize(self)
162    }
163
164    fn serialize_newtype_variant<T>(
165        self,
166        _name: &'static str,
167        _variant_index: u32,
168        _variant: &'static str,
169        _value: &T,
170    ) -> Result<()>
171        where
172            T: ?Sized + Serialize,
173    {
174        Err(Error::UnsupportedType("newtype_variant"))
175    }
176
177    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
178        Err(Error::UnsupportedType("seq"))
179    }
180
181    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
182        Err(Error::UnsupportedType("tuple"))
183    }
184
185    fn serialize_tuple_struct(
186        self,
187        _name: &'static str,
188        _len: usize,
189    ) -> Result<Self::SerializeTupleStruct> {
190        Err(Error::UnsupportedType("tuple_struct"))
191    }
192
193    fn serialize_tuple_variant(
194        self,
195        _name: &'static str,
196        _variant_index: u32,
197        _variant: &'static str,
198        _len: usize,
199    ) -> Result<Self::SerializeTupleVariant> {
200        Err(Error::UnsupportedType("tuple_variant"))
201    }
202
203    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
204        if self.output.ends_with('\t') {
205            self.output.pop();
206        }
207        self.output += "\n";
208        self.output += &"\t".repeat(self.indent_level);
209        self.output += "{\n";
210        self.indent_level += 1;
211        Ok(self)
212    }
213
214    fn serialize_struct(
215        self,
216        name: &'static str,
217        len: usize,
218    ) -> Result<Self::SerializeStruct> {
219        if self.indent_level == 0 {
220            self.output += &format!("\"{}\"", name);
221        }
222        self.serialize_map(Some(len))
223    }
224
225    fn serialize_struct_variant(
226        self,
227        _name: &'static str,
228        _variant_index: u32,
229        _variant: &'static str,
230        _len: usize,
231    ) -> Result<Self::SerializeStructVariant> {
232        Err(Error::UnsupportedType("struct_variant"))
233    }
234
235    fn collect_str<T: ?Sized>(self, value: &T) -> Result<()> where
236        T: std::fmt::Display {
237        self.serialize_str(&value.to_string())
238    }
239}
240
241impl<'a> ser::SerializeMap for &'a mut Serializer {
242    type Ok = ();
243    type Error = Error;
244
245    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
246        where
247            T: ?Sized + Serialize,
248    {
249        self.output += &"\t".repeat(self.indent_level);
250        key.serialize(&mut **self)?;
251        self.output += "\t";
252        Ok(())
253    }
254
255    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
256        where
257            T: ?Sized + Serialize,
258    {
259        value.serialize(&mut **self)?;
260        self.output += "\n";
261        Ok(())
262    }
263
264    fn end(self) -> Result<()> {
265        self.indent_level = self.indent_level.saturating_sub(1);
266        self.output += &"\t".repeat(self.indent_level);
267        self.output += "}";
268        Ok(())
269    }
270}
271
272impl<'a> ser::SerializeStruct for &'a mut Serializer
273{
274    type Ok = ();
275    type Error = Error;
276
277    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
278        where
279            T: ?Sized + Serialize,
280    {
281        self.serialize_key(key)?;
282        self.serialize_value(value)
283    }
284
285    fn end(self) -> Result<()> {
286        ser::SerializeMap::end(self)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn test_struct() {
296        #[derive(Serialize)]
297        struct Inner {
298            foo: String,
299            bar: bool,
300        }
301
302        #[derive(Serialize)]
303        struct Test {
304            int: u32,
305            inner: Inner,
306        }
307
308        let test = Test {
309            int: 1,
310            inner: Inner {
311                foo: "baz".to_string(),
312                bar: false,
313            },
314        };
315        let expected = concat!(
316            "\"Test\"\n",
317            "{\n",
318            "\t\"int\"\t\"1\"\n",
319            "\t\"inner\"\n",
320            "\t{\n",
321            "\t\t\"foo\"\t\"baz\"\n",
322            "\t\t\"bar\"\t\"0\"\n",
323            "\t}\n",
324            "}"
325        );
326        assert_eq!(to_string(&test).unwrap(), expected);
327    }
328}