1 // this module is based on the content module in serde::private::ser
2 use serde::ser::{self, Serialize, Serializer};
3 use std::marker::PhantomData;
4 
5 /// Represents variable typed content.
6 ///
7 /// This is used for the serialization system to represent values
8 /// before the actual snapshots are written and is also exposed to
9 /// dynamic redaction functions.
10 ///
11 /// Some enum variants are intentionally not exposed to user code.
12 /// It's generally recommended to construct content objects by
13 /// using the [`From`](std::convert::From) trait and by using the
14 /// accessor methods to assert on it.
15 ///
16 /// While matching on the content is possible in theory it is
17 /// recommended against.  The reason for this is that the content
18 /// enum holds variants that can "wrap" values where it's not
19 /// expected.  For instance if a field holds an `Option<String>`
20 /// you cannot use pattern matching to extract the string as it
21 /// will be contained in an internal `Some` variant that is not
22 /// exposed.  On the other hand the `as_str` method will
23 /// automatically resolve such internal wrappers.
24 ///
25 /// If you do need to pattern match you should use the
26 /// `resolve_inner` method to resolve such internal wrappers.
27 #[derive(Debug, Clone)]
28 pub enum Content {
29     Bool(bool),
30 
31     U8(u8),
32     U16(u16),
33     U32(u32),
34     U64(u64),
35     U128(u128),
36 
37     I8(i8),
38     I16(i16),
39     I32(i32),
40     I64(i64),
41     I128(i128),
42 
43     F32(f32),
44     F64(f64),
45 
46     Char(char),
47     String(String),
48     Bytes(Vec<u8>),
49 
50     #[doc(hidden)]
51     None,
52     #[doc(hidden)]
53     Some(Box<Content>),
54 
55     #[doc(hidden)]
56     Unit,
57     #[doc(hidden)]
58     UnitStruct(&'static str),
59     #[doc(hidden)]
60     UnitVariant(&'static str, u32, &'static str),
61     #[doc(hidden)]
62     NewtypeStruct(&'static str, Box<Content>),
63     #[doc(hidden)]
64     NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
65 
66     Seq(Vec<Content>),
67     #[doc(hidden)]
68     Tuple(Vec<Content>),
69     #[doc(hidden)]
70     TupleStruct(&'static str, Vec<Content>),
71     #[doc(hidden)]
72     TupleVariant(&'static str, u32, &'static str, Vec<Content>),
73     Map(Vec<(Content, Content)>),
74     #[doc(hidden)]
75     Struct(&'static str, Vec<(&'static str, Content)>),
76     #[doc(hidden)]
77     StructVariant(
78         &'static str,
79         u32,
80         &'static str,
81         Vec<(&'static str, Content)>,
82     ),
83 }
84 
85 #[derive(PartialEq, PartialOrd, Debug)]
86 pub enum Key<'a> {
87     Bool(bool),
88     U64(u64),
89     I64(i64),
90     F64(f64),
91     U128(u128),
92     I128(i128),
93     Str(&'a str),
94     Bytes(&'a [u8]),
95     Other,
96 }
97 
98 impl<'a> Eq for Key<'a> {}
99 
100 impl<'a> Ord for Key<'a> {
cmp(&self, other: &Self) -> std::cmp::Ordering101     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
102         self.partial_cmp(other).unwrap_or(std::cmp::Ordering::Less)
103     }
104 }
105 
106 macro_rules! impl_from {
107     ($ty:ty, $newty:ident) => {
108         impl From<$ty> for Content {
109             fn from(value: $ty) -> Content {
110                 Content::$newty(value)
111             }
112         }
113     };
114 }
115 
116 impl_from!(bool, Bool);
117 impl_from!(u8, U8);
118 impl_from!(u16, U16);
119 impl_from!(u32, U32);
120 impl_from!(u64, U64);
121 impl_from!(u128, U128);
122 impl_from!(i8, I8);
123 impl_from!(i16, I16);
124 impl_from!(i32, I32);
125 impl_from!(i64, I64);
126 impl_from!(i128, I128);
127 impl_from!(f32, F32);
128 impl_from!(f64, F64);
129 impl_from!(char, Char);
130 impl_from!(String, String);
131 impl_from!(Vec<u8>, Bytes);
132 
133 impl From<()> for Content {
from(_value: ()) -> Content134     fn from(_value: ()) -> Content {
135         Content::Unit
136     }
137 }
138 
139 impl<'a> From<&'a str> for Content {
from(value: &'a str) -> Content140     fn from(value: &'a str) -> Content {
141         Content::String(value.to_string())
142     }
143 }
144 
145 impl<'a> From<&'a [u8]> for Content {
from(value: &'a [u8]) -> Content146     fn from(value: &'a [u8]) -> Content {
147         Content::Bytes(value.to_vec())
148     }
149 }
150 
151 impl Content {
152     /// This resolves the innermost content in a chain of
153     /// wrapped content.
154     ///
155     /// For instance if you encounter an `Option<Option<String>>`
156     /// field the content will be wrapped twice in an internal
157     /// option wrapper.  If you need to pattern match you will
158     /// need in some situations to first resolve the inner value
159     /// before such matching can take place as there is no exposed
160     /// way to match on these wrappers.
161     ///
162     /// This method does not need to be called for the `as_`
163     /// methods which resolve automatically.
resolve_inner(&self) -> &Content164     pub fn resolve_inner(&self) -> &Content {
165         match *self {
166             Content::Some(ref v)
167             | Content::NewtypeStruct(_, ref v)
168             | Content::NewtypeVariant(_, _, _, ref v) => v.resolve_inner(),
169             ref other => other,
170         }
171     }
172 
173     /// Returns the value as string
as_str(&self) -> Option<&str>174     pub fn as_str(&self) -> Option<&str> {
175         match self.resolve_inner() {
176             Content::String(ref s) => Some(s.as_str()),
177             _ => None,
178         }
179     }
180 
181     /// Returns the value as bytes
as_bytes(&self) -> Option<&[u8]>182     pub fn as_bytes(&self) -> Option<&[u8]> {
183         match self.resolve_inner() {
184             Content::Bytes(ref b) => Some(&*b),
185             _ => None,
186         }
187     }
188 
189     /// Returns the value as slice of content values.
as_slice(&self) -> Option<&[Content]>190     pub fn as_slice(&self) -> Option<&[Content]> {
191         match self.resolve_inner() {
192             Content::Seq(ref v) | Content::Tuple(ref v) | Content::TupleVariant(_, _, _, ref v) => {
193                 Some(&v[..])
194             }
195             _ => None,
196         }
197     }
198 
199     /// Returns true if the value is nil.
is_nil(&self) -> bool200     pub fn is_nil(&self) -> bool {
201         if let Content::None | Content::Unit = self.resolve_inner() {
202             true
203         } else {
204             false
205         }
206     }
207 
as_key(&self) -> Key<'_>208     pub(crate) fn as_key(&self) -> Key<'_> {
209         match *self.resolve_inner() {
210             Content::Bool(val) => Key::Bool(val),
211             Content::Char(val) => Key::U64(val as u64),
212             Content::U16(val) => Key::U64(val.into()),
213             Content::U32(val) => Key::U64(val.into()),
214             Content::U64(val) => Key::U64(val),
215             Content::U128(val) => Key::U128(val),
216             Content::I16(val) => Key::I64(val.into()),
217             Content::I32(val) => Key::I64(val.into()),
218             Content::I64(val) => Key::I64(val),
219             Content::I128(val) => Key::I128(val),
220             Content::F32(val) => Key::F64(val.into()),
221             Content::F64(val) => Key::F64(val),
222             Content::String(ref val) => Key::Str(&val.as_str()),
223             Content::Bytes(ref val) => Key::Bytes(&val[..]),
224             _ => Key::Other,
225         }
226     }
227 
228     /// Returns the value as bool
as_bool(&self) -> Option<bool>229     pub fn as_bool(&self) -> Option<bool> {
230         match *self.resolve_inner() {
231             Content::Bool(val) => Some(val),
232             _ => None,
233         }
234     }
235 
236     /// Returns the value as u64
as_u64(&self) -> Option<u64>237     pub fn as_u64(&self) -> Option<u64> {
238         match *self.resolve_inner() {
239             Content::U8(v) => Some(u64::from(v)),
240             Content::U16(v) => Some(u64::from(v)),
241             Content::U32(v) => Some(u64::from(v)),
242             Content::U64(v) => Some(v),
243             Content::U128(v) => {
244                 let rv = v as u64;
245                 if rv as u128 == v {
246                     Some(rv)
247                 } else {
248                     None
249                 }
250             }
251             Content::I8(v) if v >= 0 => Some(v as u64),
252             Content::I16(v) if v >= 0 => Some(v as u64),
253             Content::I32(v) if v >= 0 => Some(v as u64),
254             Content::I64(v) if v >= 0 => Some(v as u64),
255             Content::I128(v) => {
256                 let rv = v as u64;
257                 if rv as i128 == v {
258                     Some(rv)
259                 } else {
260                     None
261                 }
262             }
263             _ => None,
264         }
265     }
266 
267     /// Returns the value as u128
as_u128(&self) -> Option<u128>268     pub fn as_u128(&self) -> Option<u128> {
269         match *self.resolve_inner() {
270             Content::U128(v) => Some(v),
271             Content::I128(v) if v >= 0 => Some(v as u128),
272             _ => self.as_u64().map(u128::from),
273         }
274     }
275 
276     /// Returns the value as i64
as_i64(&self) -> Option<i64>277     pub fn as_i64(&self) -> Option<i64> {
278         match *self.resolve_inner() {
279             Content::U8(v) => Some(i64::from(v)),
280             Content::U16(v) => Some(i64::from(v)),
281             Content::U32(v) => Some(i64::from(v)),
282             Content::U64(v) => {
283                 let rv = v as i64;
284                 if rv as u64 == v {
285                     Some(rv)
286                 } else {
287                     None
288                 }
289             }
290             Content::U128(v) => {
291                 let rv = v as i64;
292                 if rv as u128 == v {
293                     Some(rv)
294                 } else {
295                     None
296                 }
297             }
298             Content::I8(v) => Some(i64::from(v)),
299             Content::I16(v) => Some(i64::from(v)),
300             Content::I32(v) => Some(i64::from(v)),
301             Content::I64(v) => Some(v),
302             Content::I128(v) => {
303                 let rv = v as i64;
304                 if rv as i128 == v {
305                     Some(rv)
306                 } else {
307                     None
308                 }
309             }
310             _ => None,
311         }
312     }
313 
314     /// Returns the value as i128
as_i128(&self) -> Option<i128>315     pub fn as_i128(&self) -> Option<i128> {
316         match *self.resolve_inner() {
317             Content::U128(v) => {
318                 let rv = v as i128;
319                 if rv as u128 == v {
320                     Some(rv)
321                 } else {
322                     None
323                 }
324             }
325             Content::I128(v) => Some(v),
326             _ => self.as_i64().map(i128::from),
327         }
328     }
329 
330     /// Returns the value as f64
as_f64(&self) -> Option<f64>331     pub fn as_f64(&self) -> Option<f64> {
332         match *self.resolve_inner() {
333             Content::F32(v) => Some(f64::from(v)),
334             Content::F64(v) => Some(v),
335             _ => None,
336         }
337     }
338 
sort_maps(&mut self)339     pub(crate) fn sort_maps(&mut self) {
340         self.walk(&mut |content| {
341             if let Content::Map(ref mut items) = content {
342                 items.sort_by(|a, b| a.0.as_key().cmp(&b.0.as_key()));
343             }
344             true
345         })
346     }
347 
348     /// Recursively walks the content structure mutably.
349     ///
350     /// The callback is invoked for every content in the tree.
walk<F: FnMut(&mut Content) -> bool>(&mut self, visit: &mut F)351     pub fn walk<F: FnMut(&mut Content) -> bool>(&mut self, visit: &mut F) {
352         if !visit(self) {
353             return;
354         }
355 
356         match *self {
357             Content::Some(ref mut inner) => {
358                 Self::walk(&mut *inner, visit);
359             }
360             Content::NewtypeStruct(_, ref mut inner) => {
361                 Self::walk(&mut *inner, visit);
362             }
363             Content::NewtypeVariant(_, _, _, ref mut inner) => {
364                 Self::walk(&mut *inner, visit);
365             }
366             Content::Seq(ref mut vec) => {
367                 for inner in vec.iter_mut() {
368                     Self::walk(inner, visit);
369                 }
370             }
371             Content::Map(ref mut vec) => {
372                 for inner in vec.iter_mut() {
373                     Self::walk(&mut inner.0, visit);
374                     Self::walk(&mut inner.1, visit);
375                 }
376             }
377             Content::Struct(_, ref mut vec) => {
378                 for inner in vec.iter_mut() {
379                     Self::walk(&mut inner.1, visit);
380                 }
381             }
382             Content::StructVariant(_, _, _, ref mut vec) => {
383                 for inner in vec.iter_mut() {
384                     Self::walk(&mut inner.1, visit);
385                 }
386             }
387             Content::Tuple(ref mut vec) => {
388                 for inner in vec.iter_mut() {
389                     Self::walk(inner, visit);
390                 }
391             }
392             Content::TupleStruct(_, ref mut vec) => {
393                 for inner in vec.iter_mut() {
394                     Self::walk(inner, visit);
395                 }
396             }
397             Content::TupleVariant(_, _, _, ref mut vec) => {
398                 for inner in vec.iter_mut() {
399                     Self::walk(inner, visit);
400                 }
401             }
402             _ => {}
403         }
404     }
405 }
406 
407 impl Serialize for Content {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,408     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
409     where
410         S: Serializer,
411     {
412         match *self {
413             Content::Bool(b) => serializer.serialize_bool(b),
414             Content::U8(u) => serializer.serialize_u8(u),
415             Content::U16(u) => serializer.serialize_u16(u),
416             Content::U32(u) => serializer.serialize_u32(u),
417             Content::U64(u) => serializer.serialize_u64(u),
418             Content::U128(u) => serializer.serialize_u128(u),
419             Content::I8(i) => serializer.serialize_i8(i),
420             Content::I16(i) => serializer.serialize_i16(i),
421             Content::I32(i) => serializer.serialize_i32(i),
422             Content::I64(i) => serializer.serialize_i64(i),
423             Content::I128(i) => serializer.serialize_i128(i),
424             Content::F32(f) => serializer.serialize_f32(f),
425             Content::F64(f) => serializer.serialize_f64(f),
426             Content::Char(c) => serializer.serialize_char(c),
427             Content::String(ref s) => serializer.serialize_str(s),
428             Content::Bytes(ref b) => serializer.serialize_bytes(b),
429             Content::None => serializer.serialize_none(),
430             Content::Some(ref c) => serializer.serialize_some(&**c),
431             Content::Unit => serializer.serialize_unit(),
432             Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
433             Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
434             Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
435             Content::NewtypeVariant(n, i, v, ref c) => {
436                 serializer.serialize_newtype_variant(n, i, v, &**c)
437             }
438             Content::Seq(ref elements) => elements.serialize(serializer),
439             Content::Tuple(ref elements) => {
440                 use serde::ser::SerializeTuple;
441                 let mut tuple = serializer.serialize_tuple(elements.len())?;
442                 for e in elements {
443                     tuple.serialize_element(e)?;
444                 }
445                 tuple.end()
446             }
447             Content::TupleStruct(n, ref fields) => {
448                 use serde::ser::SerializeTupleStruct;
449                 let mut ts = serializer.serialize_tuple_struct(n, fields.len())?;
450                 for f in fields {
451                     ts.serialize_field(f)?;
452                 }
453                 ts.end()
454             }
455             Content::TupleVariant(n, i, v, ref fields) => {
456                 use serde::ser::SerializeTupleVariant;
457                 let mut tv = serializer.serialize_tuple_variant(n, i, v, fields.len())?;
458                 for f in fields {
459                     tv.serialize_field(f)?;
460                 }
461                 tv.end()
462             }
463             Content::Map(ref entries) => {
464                 use serde::ser::SerializeMap;
465                 let mut map = serializer.serialize_map(Some(entries.len()))?;
466                 for &(ref k, ref v) in entries {
467                     map.serialize_entry(k, v)?;
468                 }
469                 map.end()
470             }
471             Content::Struct(n, ref fields) => {
472                 use serde::ser::SerializeStruct;
473                 let mut s = serializer.serialize_struct(n, fields.len())?;
474                 for &(k, ref v) in fields {
475                     s.serialize_field(k, v)?;
476                 }
477                 s.end()
478             }
479             Content::StructVariant(n, i, v, ref fields) => {
480                 use serde::ser::SerializeStructVariant;
481                 let mut sv = serializer.serialize_struct_variant(n, i, v, fields.len())?;
482                 for &(k, ref v) in fields {
483                     sv.serialize_field(k, v)?;
484                 }
485                 sv.end()
486             }
487         }
488     }
489 }
490 
491 pub struct ContentSerializer<E> {
492     error: PhantomData<E>,
493 }
494 
495 impl<E> ContentSerializer<E> {
new() -> Self496     pub fn new() -> Self {
497         ContentSerializer { error: PhantomData }
498     }
499 }
500 
501 impl<E> Serializer for ContentSerializer<E>
502 where
503     E: ser::Error,
504 {
505     type Ok = Content;
506     type Error = E;
507 
508     type SerializeSeq = SerializeSeq<E>;
509     type SerializeTuple = SerializeTuple<E>;
510     type SerializeTupleStruct = SerializeTupleStruct<E>;
511     type SerializeTupleVariant = SerializeTupleVariant<E>;
512     type SerializeMap = SerializeMap<E>;
513     type SerializeStruct = SerializeStruct<E>;
514     type SerializeStructVariant = SerializeStructVariant<E>;
515 
serialize_bool(self, v: bool) -> Result<Content, E>516     fn serialize_bool(self, v: bool) -> Result<Content, E> {
517         Ok(Content::Bool(v))
518     }
519 
serialize_i8(self, v: i8) -> Result<Content, E>520     fn serialize_i8(self, v: i8) -> Result<Content, E> {
521         Ok(Content::I8(v))
522     }
523 
serialize_i16(self, v: i16) -> Result<Content, E>524     fn serialize_i16(self, v: i16) -> Result<Content, E> {
525         Ok(Content::I16(v))
526     }
527 
serialize_i32(self, v: i32) -> Result<Content, E>528     fn serialize_i32(self, v: i32) -> Result<Content, E> {
529         Ok(Content::I32(v))
530     }
531 
serialize_i64(self, v: i64) -> Result<Content, E>532     fn serialize_i64(self, v: i64) -> Result<Content, E> {
533         Ok(Content::I64(v))
534     }
535 
serialize_i128(self, v: i128) -> Result<Content, E>536     fn serialize_i128(self, v: i128) -> Result<Content, E> {
537         Ok(Content::I128(v))
538     }
539 
serialize_u8(self, v: u8) -> Result<Content, E>540     fn serialize_u8(self, v: u8) -> Result<Content, E> {
541         Ok(Content::U8(v))
542     }
543 
serialize_u16(self, v: u16) -> Result<Content, E>544     fn serialize_u16(self, v: u16) -> Result<Content, E> {
545         Ok(Content::U16(v))
546     }
547 
serialize_u32(self, v: u32) -> Result<Content, E>548     fn serialize_u32(self, v: u32) -> Result<Content, E> {
549         Ok(Content::U32(v))
550     }
551 
serialize_u64(self, v: u64) -> Result<Content, E>552     fn serialize_u64(self, v: u64) -> Result<Content, E> {
553         Ok(Content::U64(v))
554     }
555 
serialize_u128(self, v: u128) -> Result<Content, E>556     fn serialize_u128(self, v: u128) -> Result<Content, E> {
557         Ok(Content::U128(v))
558     }
559 
serialize_f32(self, v: f32) -> Result<Content, E>560     fn serialize_f32(self, v: f32) -> Result<Content, E> {
561         Ok(Content::F32(v))
562     }
563 
serialize_f64(self, v: f64) -> Result<Content, E>564     fn serialize_f64(self, v: f64) -> Result<Content, E> {
565         Ok(Content::F64(v))
566     }
567 
serialize_char(self, v: char) -> Result<Content, E>568     fn serialize_char(self, v: char) -> Result<Content, E> {
569         Ok(Content::Char(v))
570     }
571 
serialize_str(self, value: &str) -> Result<Content, E>572     fn serialize_str(self, value: &str) -> Result<Content, E> {
573         Ok(Content::String(value.to_owned()))
574     }
575 
serialize_bytes(self, value: &[u8]) -> Result<Content, E>576     fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
577         Ok(Content::Bytes(value.to_owned()))
578     }
579 
serialize_none(self) -> Result<Content, E>580     fn serialize_none(self) -> Result<Content, E> {
581         Ok(Content::None)
582     }
583 
serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E> where T: Serialize,584     fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E>
585     where
586         T: Serialize,
587     {
588         Ok(Content::Some(Box::new(value.serialize(self)?)))
589     }
590 
serialize_unit(self) -> Result<Content, E>591     fn serialize_unit(self) -> Result<Content, E> {
592         Ok(Content::Unit)
593     }
594 
serialize_unit_struct(self, name: &'static str) -> Result<Content, E>595     fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> {
596         Ok(Content::UnitStruct(name))
597     }
598 
serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result<Content, E>599     fn serialize_unit_variant(
600         self,
601         name: &'static str,
602         variant_index: u32,
603         variant: &'static str,
604     ) -> Result<Content, E> {
605         Ok(Content::UnitVariant(name, variant_index, variant))
606     }
607 
serialize_newtype_struct<T: ?Sized>( self, name: &'static str, value: &T, ) -> Result<Content, E> where T: Serialize,608     fn serialize_newtype_struct<T: ?Sized>(
609         self,
610         name: &'static str,
611         value: &T,
612     ) -> Result<Content, E>
613     where
614         T: Serialize,
615     {
616         Ok(Content::NewtypeStruct(
617             name,
618             Box::new(value.serialize(self)?),
619         ))
620     }
621 
serialize_newtype_variant<T: ?Sized>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<Content, E> where T: Serialize,622     fn serialize_newtype_variant<T: ?Sized>(
623         self,
624         name: &'static str,
625         variant_index: u32,
626         variant: &'static str,
627         value: &T,
628     ) -> Result<Content, E>
629     where
630         T: Serialize,
631     {
632         Ok(Content::NewtypeVariant(
633             name,
634             variant_index,
635             variant,
636             Box::new(value.serialize(self)?),
637         ))
638     }
639 
serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E>640     fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
641         Ok(SerializeSeq {
642             elements: Vec::with_capacity(len.unwrap_or(0)),
643             error: PhantomData,
644         })
645     }
646 
serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E>647     fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
648         Ok(SerializeTuple {
649             elements: Vec::with_capacity(len),
650             error: PhantomData,
651         })
652     }
653 
serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, E>654     fn serialize_tuple_struct(
655         self,
656         name: &'static str,
657         len: usize,
658     ) -> Result<Self::SerializeTupleStruct, E> {
659         Ok(SerializeTupleStruct {
660             name,
661             fields: Vec::with_capacity(len),
662             error: PhantomData,
663         })
664     }
665 
serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, E>666     fn serialize_tuple_variant(
667         self,
668         name: &'static str,
669         variant_index: u32,
670         variant: &'static str,
671         len: usize,
672     ) -> Result<Self::SerializeTupleVariant, E> {
673         Ok(SerializeTupleVariant {
674             name,
675             variant_index,
676             variant,
677             fields: Vec::with_capacity(len),
678             error: PhantomData,
679         })
680     }
681 
serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E>682     fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> {
683         Ok(SerializeMap {
684             entries: Vec::with_capacity(len.unwrap_or(0)),
685             key: None,
686             error: PhantomData,
687         })
688     }
689 
serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, E>690     fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, E> {
691         Ok(SerializeStruct {
692             name,
693             fields: Vec::with_capacity(len),
694             error: PhantomData,
695         })
696     }
697 
serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, E>698     fn serialize_struct_variant(
699         self,
700         name: &'static str,
701         variant_index: u32,
702         variant: &'static str,
703         len: usize,
704     ) -> Result<Self::SerializeStructVariant, E> {
705         Ok(SerializeStructVariant {
706             name,
707             variant_index,
708             variant,
709             fields: Vec::with_capacity(len),
710             error: PhantomData,
711         })
712     }
713 }
714 
715 pub struct SerializeSeq<E> {
716     elements: Vec<Content>,
717     error: PhantomData<E>,
718 }
719 
720 impl<E> ser::SerializeSeq for SerializeSeq<E>
721 where
722     E: ser::Error,
723 {
724     type Ok = Content;
725     type Error = E;
726 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,727     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
728     where
729         T: Serialize,
730     {
731         let value = value.serialize(ContentSerializer::<E>::new())?;
732         self.elements.push(value);
733         Ok(())
734     }
735 
end(self) -> Result<Content, E>736     fn end(self) -> Result<Content, E> {
737         Ok(Content::Seq(self.elements))
738     }
739 }
740 
741 pub struct SerializeTuple<E> {
742     elements: Vec<Content>,
743     error: PhantomData<E>,
744 }
745 
746 impl<E> ser::SerializeTuple for SerializeTuple<E>
747 where
748     E: ser::Error,
749 {
750     type Ok = Content;
751     type Error = E;
752 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,753     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
754     where
755         T: Serialize,
756     {
757         let value = value.serialize(ContentSerializer::<E>::new())?;
758         self.elements.push(value);
759         Ok(())
760     }
761 
end(self) -> Result<Content, E>762     fn end(self) -> Result<Content, E> {
763         Ok(Content::Tuple(self.elements))
764     }
765 }
766 
767 pub struct SerializeTupleStruct<E> {
768     name: &'static str,
769     fields: Vec<Content>,
770     error: PhantomData<E>,
771 }
772 
773 impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E>
774 where
775     E: ser::Error,
776 {
777     type Ok = Content;
778     type Error = E;
779 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,780     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
781     where
782         T: Serialize,
783     {
784         let value = value.serialize(ContentSerializer::<E>::new())?;
785         self.fields.push(value);
786         Ok(())
787     }
788 
end(self) -> Result<Content, E>789     fn end(self) -> Result<Content, E> {
790         Ok(Content::TupleStruct(self.name, self.fields))
791     }
792 }
793 
794 pub struct SerializeTupleVariant<E> {
795     name: &'static str,
796     variant_index: u32,
797     variant: &'static str,
798     fields: Vec<Content>,
799     error: PhantomData<E>,
800 }
801 
802 impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E>
803 where
804     E: ser::Error,
805 {
806     type Ok = Content;
807     type Error = E;
808 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,809     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
810     where
811         T: Serialize,
812     {
813         let value = value.serialize(ContentSerializer::<E>::new())?;
814         self.fields.push(value);
815         Ok(())
816     }
817 
end(self) -> Result<Content, E>818     fn end(self) -> Result<Content, E> {
819         Ok(Content::TupleVariant(
820             self.name,
821             self.variant_index,
822             self.variant,
823             self.fields,
824         ))
825     }
826 }
827 
828 pub struct SerializeMap<E> {
829     entries: Vec<(Content, Content)>,
830     key: Option<Content>,
831     error: PhantomData<E>,
832 }
833 
834 impl<E> ser::SerializeMap for SerializeMap<E>
835 where
836     E: ser::Error,
837 {
838     type Ok = Content;
839     type Error = E;
840 
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E> where T: Serialize,841     fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E>
842     where
843         T: Serialize,
844     {
845         let key = key.serialize(ContentSerializer::<E>::new())?;
846         self.key = Some(key);
847         Ok(())
848     }
849 
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,850     fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
851     where
852         T: Serialize,
853     {
854         let key = self
855             .key
856             .take()
857             .expect("serialize_value called before serialize_key");
858         let value = value.serialize(ContentSerializer::<E>::new())?;
859         self.entries.push((key, value));
860         Ok(())
861     }
862 
end(self) -> Result<Content, E>863     fn end(self) -> Result<Content, E> {
864         Ok(Content::Map(self.entries))
865     }
866 
serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E> where K: Serialize, V: Serialize,867     fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E>
868     where
869         K: Serialize,
870         V: Serialize,
871     {
872         let key = key.serialize(ContentSerializer::<E>::new())?;
873         let value = value.serialize(ContentSerializer::<E>::new())?;
874         self.entries.push((key, value));
875         Ok(())
876     }
877 }
878 
879 pub struct SerializeStruct<E> {
880     name: &'static str,
881     fields: Vec<(&'static str, Content)>,
882     error: PhantomData<E>,
883 }
884 
885 impl<E> ser::SerializeStruct for SerializeStruct<E>
886 where
887     E: ser::Error,
888 {
889     type Ok = Content;
890     type Error = E;
891 
serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> where T: Serialize,892     fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
893     where
894         T: Serialize,
895     {
896         let value = value.serialize(ContentSerializer::<E>::new())?;
897         self.fields.push((key, value));
898         Ok(())
899     }
900 
end(self) -> Result<Content, E>901     fn end(self) -> Result<Content, E> {
902         Ok(Content::Struct(self.name, self.fields))
903     }
904 }
905 
906 pub struct SerializeStructVariant<E> {
907     name: &'static str,
908     variant_index: u32,
909     variant: &'static str,
910     fields: Vec<(&'static str, Content)>,
911     error: PhantomData<E>,
912 }
913 
914 impl<E> ser::SerializeStructVariant for SerializeStructVariant<E>
915 where
916     E: ser::Error,
917 {
918     type Ok = Content;
919     type Error = E;
920 
serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> where T: Serialize,921     fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
922     where
923         T: Serialize,
924     {
925         let value = value.serialize(ContentSerializer::<E>::new())?;
926         self.fields.push((key, value));
927         Ok(())
928     }
929 
end(self) -> Result<Content, E>930     fn end(self) -> Result<Content, E> {
931         Ok(Content::StructVariant(
932             self.name,
933             self.variant_index,
934             self.variant,
935             self.fields,
936         ))
937     }
938 }
939