keri_core/event_message/
serializer.rs

1use crate::error::serializer_error::Error;
2use serde::{ser, Serialize};
3
4pub type Result<T> = std::result::Result<T, Error>;
5
6pub struct KeriJsonSerializer {
7    output: String,
8}
9
10pub fn to_string<T>(value: &T) -> Result<String>
11where
12    T: Serialize,
13{
14    let mut serializer = KeriJsonSerializer {
15        output: String::new(),
16    };
17    value.serialize(&mut serializer)?;
18    Ok(serializer.output)
19}
20
21impl<'a> ser::Serializer for &'a mut KeriJsonSerializer {
22    type Ok = ();
23    type Error = Error;
24    type SerializeSeq = Self;
25    type SerializeTuple = Self;
26    type SerializeTupleStruct = Self;
27    type SerializeTupleVariant = Self;
28    type SerializeMap = Self;
29    type SerializeStruct = Self;
30    type SerializeStructVariant = Self;
31
32    fn serialize_bool(self, v: bool) -> Result<()> {
33        self.output += if v { "true" } else { "false" };
34        Ok(())
35    }
36
37    fn serialize_i8(self, v: i8) -> Result<()> {
38        self.serialize_i64(i64::from(v))
39    }
40
41    fn serialize_i16(self, v: i16) -> Result<()> {
42        self.serialize_i64(i64::from(v))
43    }
44
45    fn serialize_i32(self, v: i32) -> Result<()> {
46        self.serialize_i64(i64::from(v))
47    }
48
49    fn serialize_i64(self, v: i64) -> Result<()> {
50        self.output += &v.to_string();
51        Ok(())
52    }
53
54    fn serialize_u8(self, v: u8) -> Result<()> {
55        self.serialize_u64(u64::from(v))
56    }
57
58    fn serialize_u16(self, v: u16) -> Result<()> {
59        self.serialize_u64(u64::from(v))
60    }
61
62    fn serialize_u32(self, v: u32) -> Result<()> {
63        self.serialize_u64(u64::from(v))
64    }
65
66    fn serialize_u64(self, v: u64) -> Result<()> {
67        self.output += &v.to_string();
68        Ok(())
69    }
70
71    fn serialize_f32(self, v: f32) -> Result<()> {
72        self.serialize_f64(f64::from(v))
73    }
74
75    fn serialize_f64(self, v: f64) -> Result<()> {
76        self.output += &v.to_string();
77        Ok(())
78    }
79
80    fn serialize_char(self, v: char) -> Result<()> {
81        self.serialize_str(&v.to_string())
82    }
83
84    // for KERI master codes we skip adding quotes
85    fn serialize_str(self, v: &str) -> Result<()> {
86        if v.starts_with('-') {
87            self.output += v;
88        } else {
89            self.output += "\"";
90            self.output += v;
91            self.output += "\"";
92        }
93        Ok(())
94    }
95
96    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
97        use serde::ser::SerializeSeq;
98        let mut seq = self.serialize_seq(Some(v.len()))?;
99        for byte in v {
100            seq.serialize_element(byte)?;
101        }
102        seq.end()
103    }
104
105    fn serialize_none(self) -> Result<()> {
106        self.serialize_unit()
107    }
108
109    fn serialize_some<T>(self, value: &T) -> Result<()>
110    where
111        T: ?Sized + Serialize,
112    {
113        value.serialize(self)
114    }
115
116    fn serialize_unit(self) -> Result<()> {
117        self.output += "null";
118        Ok(())
119    }
120
121    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
122        self.serialize_unit()
123    }
124
125    fn serialize_unit_variant(
126        self,
127        _name: &'static str,
128        _variant_index: u32,
129        variant: &'static str,
130    ) -> Result<()> {
131        self.serialize_str(variant)
132    }
133
134    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
135    where
136        T: ?Sized + Serialize,
137    {
138        value.serialize(self)
139    }
140
141    fn serialize_newtype_variant<T>(
142        self,
143        _name: &'static str,
144        _variant_index: u32,
145        variant: &'static str,
146        value: &T,
147    ) -> Result<()>
148    where
149        T: ?Sized + Serialize,
150    {
151        self.output += "{";
152        variant.serialize(&mut *self)?;
153        self.output += ":";
154        value.serialize(&mut *self)?;
155        self.output += "}";
156        Ok(())
157    }
158
159    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
160        self.output += "[";
161        Ok(self)
162    }
163
164    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
165        self.serialize_seq(Some(len))
166    }
167
168    fn serialize_tuple_struct(
169        self,
170        _name: &'static str,
171        len: usize,
172    ) -> Result<Self::SerializeTupleStruct> {
173        self.serialize_seq(Some(len))
174    }
175
176    fn serialize_tuple_variant(
177        self,
178        _name: &'static str,
179        _variant_index: u32,
180        variant: &'static str,
181        _len: usize,
182    ) -> Result<Self::SerializeTupleVariant> {
183        self.output += "{";
184        variant.serialize(&mut *self)?;
185        self.output += ":[";
186        Ok(self)
187    }
188
189    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
190        self.output += "{";
191        Ok(self)
192    }
193    // this is used to start serializing KERI struct, nothing more
194    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
195        Ok(self)
196    }
197
198    fn serialize_struct_variant(
199        self,
200        _name: &'static str,
201        _variant_index: u32,
202        variant: &'static str,
203        _len: usize,
204    ) -> Result<Self::SerializeStructVariant> {
205        self.output += "{";
206        variant.serialize(&mut *self)?;
207        self.output += ":{";
208        Ok(self)
209    }
210}
211
212// for KERI attachments this must be hacked
213impl<'a> ser::SerializeSeq for &'a mut KeriJsonSerializer {
214    // Must match the `Ok` type of the serializer.
215    type Ok = ();
216    // Must match the `Error` type of the serializer.
217    type Error = Error;
218
219    // Serialize a single element of the sequence.
220    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
221    where
222        T: ?Sized + Serialize,
223    {
224        if !self.output.ends_with('[') {
225            self.output += ",";
226        }
227        value.serialize(&mut **self)
228    }
229
230    fn end(self) -> Result<()> {
231        self.output += "]";
232        Ok(())
233    }
234}
235
236impl<'a> ser::SerializeTuple for &'a mut KeriJsonSerializer {
237    type Ok = ();
238    type Error = Error;
239
240    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
241    where
242        T: ?Sized + Serialize,
243    {
244        if !self.output.ends_with('[') {
245            self.output += ",";
246        }
247        value.serialize(&mut **self)
248    }
249
250    fn end(self) -> Result<()> {
251        self.output += "]";
252        Ok(())
253    }
254}
255
256impl<'a> ser::SerializeTupleStruct for &'a mut KeriJsonSerializer {
257    type Ok = ();
258    type Error = Error;
259
260    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
261    where
262        T: ?Sized + Serialize,
263    {
264        if !self.output.ends_with('[') {
265            self.output += ",";
266        }
267        value.serialize(&mut **self)
268    }
269
270    fn end(self) -> Result<()> {
271        self.output += "]";
272        Ok(())
273    }
274}
275
276impl<'a> ser::SerializeTupleVariant for &'a mut KeriJsonSerializer {
277    type Ok = ();
278    type Error = Error;
279
280    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
281    where
282        T: ?Sized + Serialize,
283    {
284        if !self.output.ends_with('[') {
285            self.output += ",";
286        }
287        value.serialize(&mut **self)
288    }
289
290    fn end(self) -> Result<()> {
291        self.output += "]}";
292        Ok(())
293    }
294}
295
296impl<'a> ser::SerializeMap for &'a mut KeriJsonSerializer {
297    type Ok = ();
298    type Error = Error;
299
300    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
301    where
302        T: ?Sized + Serialize,
303    {
304        if !self.output.ends_with('{') {
305            self.output += ",";
306        }
307        key.serialize(&mut **self)
308    }
309
310    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
311    where
312        T: ?Sized + Serialize,
313    {
314        self.output += ":";
315        value.serialize(&mut **self)
316    }
317
318    fn end(self) -> Result<()> {
319        self.output += "}";
320        Ok(())
321    }
322}
323
324// This part adds master code and attaches payload
325impl<'a> ser::SerializeStruct for &'a mut KeriJsonSerializer {
326    type Ok = ();
327    type Error = Error;
328
329    // for KERI master code `key` must start with `-`
330    // and value should be pre formatted `qb64` payload
331    // it will be appended as is
332    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
333    where
334        T: ?Sized + Serialize,
335    {
336        // KERI master code
337        // value must be concatenated with code upfront
338        if key.starts_with('-') {
339            value.serialize(&mut **self)?;
340        } else {
341            // regular field here
342            if !self.output.ends_with('{') && !self.output.is_empty() {
343                self.output += ",";
344                self.output += "{";
345            }
346            if !key.is_empty() {
347                key.serialize(&mut **self)?;
348            }
349            value.serialize(&mut **self)?;
350            if !self.output.ends_with('}') {
351                self.output += "}";
352            }
353        }
354        Ok(())
355    }
356
357    fn end(self) -> Result<()> {
358        Ok(())
359    }
360}
361
362impl<'a> ser::SerializeStructVariant for &'a mut KeriJsonSerializer {
363    type Ok = ();
364    type Error = Error;
365
366    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
367    where
368        T: ?Sized + Serialize,
369    {
370        if !self.output.ends_with('{') {
371            self.output += ",";
372        }
373        key.serialize(&mut **self)?;
374        self.output += ":";
375        value.serialize(&mut **self)
376    }
377
378    fn end(self) -> Result<()> {
379        self.output += "}}";
380        Ok(())
381    }
382}