Skip to main content

serde_reflection/
ser.rs

1// Copyright (c) Facebook, Inc. and its affiliates
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use crate::{
5    error::{Error, Result},
6    format::*,
7    trace::{Samples, Tracer},
8    value::Value,
9};
10use serde::{ser, Serialize};
11
12/// Serialize a single value.
13/// The lifetime 'a is set by the serialization call site and the `&'a mut`
14/// references used to return tracing results and serialization samples.
15pub struct Serializer<'a> {
16    tracer: &'a mut Tracer,
17    samples: &'a mut Samples,
18}
19
20impl<'a> Serializer<'a> {
21    /// Create a new Serializer
22    pub fn new(tracer: &'a mut Tracer, samples: &'a mut Samples) -> Self {
23        Self { tracer, samples }
24    }
25}
26
27impl<'a> ser::Serializer for Serializer<'a> {
28    type Ok = (Format, Value);
29    type Error = Error;
30    type SerializeSeq = SeqSerializer<'a>;
31    type SerializeTuple = TupleSerializer<'a>;
32    type SerializeTupleStruct = TupleStructSerializer<'a>;
33    type SerializeTupleVariant = TupleVariantSerializer<'a>;
34    type SerializeMap = MapSerializer<'a>;
35    type SerializeStruct = StructSerializer<'a>;
36    type SerializeStructVariant = StructVariantSerializer<'a>;
37
38    fn serialize_bool(self, content: bool) -> Result<(Format, Value)> {
39        Ok((Format::Bool, Value::Bool(content)))
40    }
41
42    fn serialize_i8(self, content: i8) -> Result<(Format, Value)> {
43        Ok((Format::I8, Value::I8(content)))
44    }
45
46    fn serialize_i16(self, content: i16) -> Result<(Format, Value)> {
47        Ok((Format::I16, Value::I16(content)))
48    }
49
50    fn serialize_i32(self, content: i32) -> Result<(Format, Value)> {
51        Ok((Format::I32, Value::I32(content)))
52    }
53
54    fn serialize_i64(self, content: i64) -> Result<(Format, Value)> {
55        Ok((Format::I64, Value::I64(content)))
56    }
57
58    fn serialize_i128(self, content: i128) -> Result<(Format, Value)> {
59        Ok((Format::I128, Value::I128(content)))
60    }
61
62    fn serialize_u8(self, content: u8) -> Result<(Format, Value)> {
63        Ok((Format::U8, Value::U8(content)))
64    }
65
66    fn serialize_u16(self, content: u16) -> Result<(Format, Value)> {
67        Ok((Format::U16, Value::U16(content)))
68    }
69
70    fn serialize_u32(self, content: u32) -> Result<(Format, Value)> {
71        Ok((Format::U32, Value::U32(content)))
72    }
73
74    fn serialize_u64(self, content: u64) -> Result<(Format, Value)> {
75        Ok((Format::U64, Value::U64(content)))
76    }
77
78    fn serialize_u128(self, content: u128) -> Result<(Format, Value)> {
79        Ok((Format::U128, Value::U128(content)))
80    }
81
82    fn serialize_f32(self, content: f32) -> Result<(Format, Value)> {
83        Ok((Format::F32, Value::F32(content)))
84    }
85
86    fn serialize_f64(self, content: f64) -> Result<(Format, Value)> {
87        Ok((Format::F64, Value::F64(content)))
88    }
89
90    fn serialize_char(self, content: char) -> Result<(Format, Value)> {
91        Ok((Format::Char, Value::Char(content)))
92    }
93
94    fn serialize_str(self, content: &str) -> Result<(Format, Value)> {
95        Ok((Format::Str, Value::Str(content.into())))
96    }
97
98    fn serialize_bytes(self, content: &[u8]) -> Result<(Format, Value)> {
99        Ok((Format::Bytes, Value::Bytes(content.into())))
100    }
101
102    fn serialize_none(self) -> Result<(Format, Value)> {
103        Ok((Format::unknown(), Value::Option(None)))
104    }
105
106    fn serialize_some<T>(self, content: &T) -> Result<(Format, Value)>
107    where
108        T: ?Sized + Serialize,
109    {
110        let (format, value) = content.serialize(self)?;
111        Ok((
112            Format::Option(Box::new(format)),
113            Value::Option(Some(Box::new(value))),
114        ))
115    }
116
117    fn serialize_unit(self) -> Result<(Format, Value)> {
118        Ok((Format::Unit, Value::Unit))
119    }
120
121    fn serialize_unit_struct(self, name: &'static str) -> Result<(Format, Value)> {
122        self.tracer.record_container(
123            self.samples,
124            name,
125            ContainerFormat::UnitStruct,
126            Value::Unit,
127            false,
128        )
129    }
130
131    fn serialize_unit_variant(
132        self,
133        name: &'static str,
134        variant_index: u32,
135        variant_name: &'static str,
136    ) -> Result<(Format, Value)> {
137        self.tracer.record_variant(
138            self.samples,
139            name,
140            variant_index,
141            variant_name,
142            VariantFormat::Unit,
143            Value::Unit,
144        )
145    }
146
147    fn serialize_newtype_struct<T>(self, name: &'static str, content: &T) -> Result<(Format, Value)>
148    where
149        T: ?Sized + Serialize,
150    {
151        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
152        self.tracer.record_container(
153            self.samples,
154            name,
155            ContainerFormat::NewTypeStruct(Box::new(format)),
156            value,
157            self.tracer.config.record_samples_for_newtype_structs,
158        )
159    }
160
161    fn serialize_newtype_variant<T>(
162        self,
163        name: &'static str,
164        variant_index: u32,
165        variant_name: &'static str,
166        content: &T,
167    ) -> Result<(Format, Value)>
168    where
169        T: ?Sized + Serialize,
170    {
171        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
172        self.tracer.record_variant(
173            self.samples,
174            name,
175            variant_index,
176            variant_name,
177            VariantFormat::NewType(Box::new(format)),
178            value,
179        )
180    }
181
182    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
183        Ok(SeqSerializer {
184            tracer: self.tracer,
185            samples: self.samples,
186            format: Format::unknown(),
187            values: Vec::new(),
188        })
189    }
190
191    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
192        Ok(TupleSerializer {
193            tracer: self.tracer,
194            samples: self.samples,
195            formats: Vec::new(),
196            values: Vec::new(),
197        })
198    }
199
200    fn serialize_tuple_struct(
201        self,
202        name: &'static str,
203        _len: usize,
204    ) -> Result<Self::SerializeTupleStruct> {
205        Ok(TupleStructSerializer {
206            tracer: self.tracer,
207            samples: self.samples,
208            name,
209            formats: Vec::new(),
210            values: Vec::new(),
211        })
212    }
213
214    fn serialize_tuple_variant(
215        self,
216        name: &'static str,
217        variant_index: u32,
218        variant_name: &'static str,
219        _len: usize,
220    ) -> Result<Self::SerializeTupleVariant> {
221        Ok(TupleVariantSerializer {
222            tracer: self.tracer,
223            samples: self.samples,
224            name,
225            variant_index,
226            variant_name,
227            formats: Vec::new(),
228            values: Vec::new(),
229        })
230    }
231
232    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
233        Ok(MapSerializer {
234            tracer: self.tracer,
235            samples: self.samples,
236            key_format: Format::unknown(),
237            value_format: Format::unknown(),
238            values: Vec::new(),
239        })
240    }
241
242    fn serialize_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
243        Ok(StructSerializer {
244            tracer: self.tracer,
245            samples: self.samples,
246            name,
247            fields: Vec::new(),
248            values: Vec::new(),
249        })
250    }
251
252    fn serialize_struct_variant(
253        self,
254        name: &'static str,
255        variant_index: u32,
256        variant_name: &'static str,
257        _len: usize,
258    ) -> Result<Self::SerializeStructVariant> {
259        Ok(StructVariantSerializer {
260            tracer: self.tracer,
261            samples: self.samples,
262            name,
263            variant_index,
264            variant_name,
265            fields: Vec::new(),
266            values: Vec::new(),
267        })
268    }
269
270    fn is_human_readable(&self) -> bool {
271        self.tracer.config.is_human_readable
272    }
273}
274
275pub struct SeqSerializer<'a> {
276    tracer: &'a mut Tracer,
277    samples: &'a mut Samples,
278
279    format: Format,
280    values: Vec<Value>,
281}
282
283impl<'a> ser::SerializeSeq for SeqSerializer<'a> {
284    type Ok = (Format, Value);
285    type Error = Error;
286
287    fn serialize_element<T>(&mut self, content: &T) -> Result<()>
288    where
289        T: ?Sized + Serialize,
290    {
291        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
292        self.format.unify(format)?;
293        self.values.push(value);
294        Ok(())
295    }
296
297    fn end(self) -> Result<(Format, Value)> {
298        Ok((Format::Seq(Box::new(self.format)), Value::Seq(self.values)))
299    }
300}
301
302pub struct TupleSerializer<'a> {
303    tracer: &'a mut Tracer,
304    samples: &'a mut Samples,
305
306    formats: Vec<Format>,
307    values: Vec<Value>,
308}
309
310impl<'a> ser::SerializeTuple for TupleSerializer<'a> {
311    type Ok = (Format, Value);
312    type Error = Error;
313
314    fn serialize_element<T>(&mut self, content: &T) -> Result<()>
315    where
316        T: ?Sized + Serialize,
317    {
318        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
319        self.formats.push(format);
320        self.values.push(value);
321        Ok(())
322    }
323
324    fn end(self) -> Result<(Format, Value)> {
325        Ok((Format::Tuple(self.formats), Value::Seq(self.values)))
326    }
327}
328
329pub struct TupleStructSerializer<'a> {
330    tracer: &'a mut Tracer,
331    samples: &'a mut Samples,
332
333    name: &'static str,
334    formats: Vec<Format>,
335    values: Vec<Value>,
336}
337
338impl<'a> ser::SerializeTupleStruct for TupleStructSerializer<'a> {
339    type Ok = (Format, Value);
340    type Error = Error;
341
342    fn serialize_field<T>(&mut self, content: &T) -> Result<()>
343    where
344        T: ?Sized + Serialize,
345    {
346        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
347        self.formats.push(format);
348        self.values.push(value);
349        Ok(())
350    }
351
352    fn end(self) -> Result<(Format, Value)> {
353        let format = ContainerFormat::TupleStruct(self.formats);
354        let value = Value::Seq(self.values);
355        self.tracer.record_container(
356            self.samples,
357            self.name,
358            format,
359            value,
360            self.tracer.config.record_samples_for_tuple_structs,
361        )
362    }
363}
364
365pub struct TupleVariantSerializer<'a> {
366    tracer: &'a mut Tracer,
367    samples: &'a mut Samples,
368
369    name: &'static str,
370    variant_index: u32,
371    variant_name: &'static str,
372    formats: Vec<Format>,
373    values: Vec<Value>,
374}
375
376impl<'a> ser::SerializeTupleVariant for TupleVariantSerializer<'a> {
377    type Ok = (Format, Value);
378    type Error = Error;
379
380    fn serialize_field<T>(&mut self, content: &T) -> Result<()>
381    where
382        T: ?Sized + Serialize,
383    {
384        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
385        self.formats.push(format);
386        self.values.push(value);
387        Ok(())
388    }
389
390    fn end(self) -> Result<(Format, Value)> {
391        let variant = VariantFormat::Tuple(self.formats);
392        let value = Value::Seq(self.values);
393        self.tracer.record_variant(
394            self.samples,
395            self.name,
396            self.variant_index,
397            self.variant_name,
398            variant,
399            value,
400        )
401    }
402}
403
404pub struct MapSerializer<'a> {
405    tracer: &'a mut Tracer,
406    samples: &'a mut Samples,
407
408    key_format: Format,
409    value_format: Format,
410    values: Vec<Value>,
411}
412
413impl<'a> ser::SerializeMap for MapSerializer<'a> {
414    type Ok = (Format, Value);
415    type Error = Error;
416
417    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
418    where
419        T: ?Sized + Serialize,
420    {
421        let (format, value) = key.serialize(Serializer::new(self.tracer, self.samples))?;
422        self.key_format.unify(format)?;
423        self.values.push(value);
424        Ok(())
425    }
426
427    fn serialize_value<T>(&mut self, content: &T) -> Result<()>
428    where
429        T: ?Sized + Serialize,
430    {
431        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
432        self.value_format.unify(format)?;
433        self.values.push(value);
434        Ok(())
435    }
436
437    fn end(self) -> Result<(Format, Value)> {
438        let format = Format::Map {
439            key: Box::new(self.key_format),
440            value: Box::new(self.value_format),
441        };
442        let value = Value::Seq(self.values);
443        Ok((format, value))
444    }
445}
446
447pub struct StructSerializer<'a> {
448    tracer: &'a mut Tracer,
449    samples: &'a mut Samples,
450
451    name: &'static str,
452    fields: Vec<Named<Format>>,
453    values: Vec<Value>,
454}
455
456impl<'a> ser::SerializeStruct for StructSerializer<'a> {
457    type Ok = (Format, Value);
458    type Error = Error;
459
460    fn serialize_field<T>(&mut self, name: &'static str, content: &T) -> Result<()>
461    where
462        T: ?Sized + Serialize,
463    {
464        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
465        self.fields.push(Named {
466            name: name.into(),
467            value: format,
468        });
469        self.values.push(value);
470        Ok(())
471    }
472
473    fn end(self) -> Result<(Format, Value)> {
474        let format = ContainerFormat::Struct(self.fields);
475        let value = Value::Seq(self.values);
476        self.tracer.record_container(
477            self.samples,
478            self.name,
479            format,
480            value,
481            self.tracer.config.record_samples_for_structs,
482        )
483    }
484}
485
486pub struct StructVariantSerializer<'a> {
487    tracer: &'a mut Tracer,
488    samples: &'a mut Samples,
489    name: &'static str,
490    variant_index: u32,
491    variant_name: &'static str,
492    fields: Vec<Named<Format>>,
493    values: Vec<Value>,
494}
495
496impl<'a> ser::SerializeStructVariant for StructVariantSerializer<'a> {
497    type Ok = (Format, Value);
498    type Error = Error;
499
500    fn serialize_field<T>(&mut self, name: &'static str, content: &T) -> Result<()>
501    where
502        T: ?Sized + Serialize,
503    {
504        let (format, value) = content.serialize(Serializer::new(self.tracer, self.samples))?;
505        self.fields.push(Named {
506            name: name.into(),
507            value: format,
508        });
509        self.values.push(value);
510        Ok(())
511    }
512
513    fn end(self) -> Result<(Format, Value)> {
514        let variant = VariantFormat::Struct(self.fields);
515        let value = Value::Seq(self.values);
516        self.tracer.record_variant(
517            self.samples,
518            self.name,
519            self.variant_index,
520            self.variant_name,
521            variant,
522            value,
523        )
524    }
525}