1 // Copyright 2017 Serde Developers
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 use lib::*;
10 
11 use ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer};
12 
13 #[cfg(any(feature = "std", feature = "alloc"))]
14 use self::content::{SerializeStructVariantAsMapValue, SerializeTupleVariantAsMapValue};
15 
16 /// Used to check that serde(getter) attributes return the expected type.
17 /// Not public API.
constrain<T: ?Sized>(t: &T) -> &T18 pub fn constrain<T: ?Sized>(t: &T) -> &T {
19     t
20 }
21 
22 /// Not public API.
serialize_tagged_newtype<S, T>( serializer: S, type_ident: &'static str, variant_ident: &'static str, tag: &'static str, variant_name: &'static str, value: &T, ) -> Result<S::Ok, S::Error> where S: Serializer, T: Serialize,23 pub fn serialize_tagged_newtype<S, T>(
24     serializer: S,
25     type_ident: &'static str,
26     variant_ident: &'static str,
27     tag: &'static str,
28     variant_name: &'static str,
29     value: &T,
30 ) -> Result<S::Ok, S::Error>
31 where
32     S: Serializer,
33     T: Serialize,
34 {
35     value.serialize(TaggedSerializer {
36         type_ident: type_ident,
37         variant_ident: variant_ident,
38         tag: tag,
39         variant_name: variant_name,
40         delegate: serializer,
41     })
42 }
43 
44 struct TaggedSerializer<S> {
45     type_ident: &'static str,
46     variant_ident: &'static str,
47     tag: &'static str,
48     variant_name: &'static str,
49     delegate: S,
50 }
51 
52 enum Unsupported {
53     Boolean,
54     Integer,
55     Float,
56     Char,
57     String,
58     ByteArray,
59     Optional,
60     Unit,
61     Sequence,
62     Tuple,
63     TupleStruct,
64     #[cfg(not(any(feature = "std", feature = "alloc")))]
65     Enum,
66 }
67 
68 impl Display for Unsupported {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result69     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
70         match *self {
71             Unsupported::Boolean => formatter.write_str("a boolean"),
72             Unsupported::Integer => formatter.write_str("an integer"),
73             Unsupported::Float => formatter.write_str("a float"),
74             Unsupported::Char => formatter.write_str("a char"),
75             Unsupported::String => formatter.write_str("a string"),
76             Unsupported::ByteArray => formatter.write_str("a byte array"),
77             Unsupported::Optional => formatter.write_str("an optional"),
78             Unsupported::Unit => formatter.write_str("unit"),
79             Unsupported::Sequence => formatter.write_str("a sequence"),
80             Unsupported::Tuple => formatter.write_str("a tuple"),
81             Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
82             #[cfg(not(any(feature = "std", feature = "alloc")))]
83             Unsupported::Enum => formatter.write_str("an enum"),
84         }
85     }
86 }
87 
88 impl<S> TaggedSerializer<S>
89 where
90     S: Serializer,
91 {
bad_type(self, what: Unsupported) -> S::Error92     fn bad_type(self, what: Unsupported) -> S::Error {
93         ser::Error::custom(format_args!(
94             "cannot serialize tagged newtype variant {}::{} containing {}",
95             self.type_ident, self.variant_ident, what
96         ))
97     }
98 }
99 
100 impl<S> Serializer for TaggedSerializer<S>
101 where
102     S: Serializer,
103 {
104     type Ok = S::Ok;
105     type Error = S::Error;
106 
107     type SerializeSeq = Impossible<S::Ok, S::Error>;
108     type SerializeTuple = Impossible<S::Ok, S::Error>;
109     type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
110     type SerializeMap = S::SerializeMap;
111     type SerializeStruct = S::SerializeStruct;
112 
113     #[cfg(not(any(feature = "std", feature = "alloc")))]
114     type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
115     #[cfg(any(feature = "std", feature = "alloc"))]
116     type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
117 
118     #[cfg(not(any(feature = "std", feature = "alloc")))]
119     type SerializeStructVariant = Impossible<S::Ok, S::Error>;
120     #[cfg(any(feature = "std", feature = "alloc"))]
121     type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
122 
serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error>123     fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
124         Err(self.bad_type(Unsupported::Boolean))
125     }
126 
serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error>127     fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
128         Err(self.bad_type(Unsupported::Integer))
129     }
130 
serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error>131     fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
132         Err(self.bad_type(Unsupported::Integer))
133     }
134 
serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error>135     fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
136         Err(self.bad_type(Unsupported::Integer))
137     }
138 
serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error>139     fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
140         Err(self.bad_type(Unsupported::Integer))
141     }
142 
serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error>143     fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
144         Err(self.bad_type(Unsupported::Integer))
145     }
146 
serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error>147     fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
148         Err(self.bad_type(Unsupported::Integer))
149     }
150 
serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error>151     fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
152         Err(self.bad_type(Unsupported::Integer))
153     }
154 
serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error>155     fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
156         Err(self.bad_type(Unsupported::Integer))
157     }
158 
serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error>159     fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
160         Err(self.bad_type(Unsupported::Float))
161     }
162 
serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error>163     fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
164         Err(self.bad_type(Unsupported::Float))
165     }
166 
serialize_char(self, _: char) -> Result<Self::Ok, Self::Error>167     fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
168         Err(self.bad_type(Unsupported::Char))
169     }
170 
serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error>171     fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
172         Err(self.bad_type(Unsupported::String))
173     }
174 
serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error>175     fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
176         Err(self.bad_type(Unsupported::ByteArray))
177     }
178 
serialize_none(self) -> Result<Self::Ok, Self::Error>179     fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
180         Err(self.bad_type(Unsupported::Optional))
181     }
182 
serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> where T: Serialize,183     fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
184     where
185         T: Serialize,
186     {
187         Err(self.bad_type(Unsupported::Optional))
188     }
189 
serialize_unit(self) -> Result<Self::Ok, Self::Error>190     fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
191         Err(self.bad_type(Unsupported::Unit))
192     }
193 
serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error>194     fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
195         let mut map = try!(self.delegate.serialize_map(Some(1)));
196         try!(map.serialize_entry(self.tag, self.variant_name));
197         map.end()
198     }
199 
serialize_unit_variant( self, _: &'static str, _: u32, inner_variant: &'static str, ) -> Result<Self::Ok, Self::Error>200     fn serialize_unit_variant(
201         self,
202         _: &'static str,
203         _: u32,
204         inner_variant: &'static str,
205     ) -> Result<Self::Ok, Self::Error> {
206         let mut map = try!(self.delegate.serialize_map(Some(2)));
207         try!(map.serialize_entry(self.tag, self.variant_name));
208         try!(map.serialize_entry(inner_variant, &()));
209         map.end()
210     }
211 
serialize_newtype_struct<T: ?Sized>( self, _: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize,212     fn serialize_newtype_struct<T: ?Sized>(
213         self,
214         _: &'static str,
215         value: &T,
216     ) -> Result<Self::Ok, Self::Error>
217     where
218         T: Serialize,
219     {
220         value.serialize(self)
221     }
222 
serialize_newtype_variant<T: ?Sized>( self, _: &'static str, _: u32, inner_variant: &'static str, inner_value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize,223     fn serialize_newtype_variant<T: ?Sized>(
224         self,
225         _: &'static str,
226         _: u32,
227         inner_variant: &'static str,
228         inner_value: &T,
229     ) -> Result<Self::Ok, Self::Error>
230     where
231         T: Serialize,
232     {
233         let mut map = try!(self.delegate.serialize_map(Some(2)));
234         try!(map.serialize_entry(self.tag, self.variant_name));
235         try!(map.serialize_entry(inner_variant, inner_value));
236         map.end()
237     }
238 
serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>239     fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
240         Err(self.bad_type(Unsupported::Sequence))
241     }
242 
serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error>243     fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
244         Err(self.bad_type(Unsupported::Tuple))
245     }
246 
serialize_tuple_struct( self, _: &'static str, _: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>247     fn serialize_tuple_struct(
248         self,
249         _: &'static str,
250         _: usize,
251     ) -> Result<Self::SerializeTupleStruct, Self::Error> {
252         Err(self.bad_type(Unsupported::TupleStruct))
253     }
254 
255     #[cfg(not(any(feature = "std", feature = "alloc")))]
serialize_tuple_variant( self, _: &'static str, _: u32, _: &'static str, _: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>256     fn serialize_tuple_variant(
257         self,
258         _: &'static str,
259         _: u32,
260         _: &'static str,
261         _: usize,
262     ) -> Result<Self::SerializeTupleVariant, Self::Error> {
263         // Lack of push-based serialization means we need to buffer the content
264         // of the tuple variant, so it requires std.
265         Err(self.bad_type(Unsupported::Enum))
266     }
267 
268     #[cfg(any(feature = "std", feature = "alloc"))]
serialize_tuple_variant( self, _: &'static str, _: u32, inner_variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>269     fn serialize_tuple_variant(
270         self,
271         _: &'static str,
272         _: u32,
273         inner_variant: &'static str,
274         len: usize,
275     ) -> Result<Self::SerializeTupleVariant, Self::Error> {
276         let mut map = try!(self.delegate.serialize_map(Some(2)));
277         try!(map.serialize_entry(self.tag, self.variant_name));
278         try!(map.serialize_key(inner_variant));
279         Ok(SerializeTupleVariantAsMapValue::new(
280             map,
281             inner_variant,
282             len,
283         ))
284     }
285 
serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>286     fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
287         let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
288         try!(map.serialize_entry(self.tag, self.variant_name));
289         Ok(map)
290     }
291 
serialize_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, Self::Error>292     fn serialize_struct(
293         self,
294         name: &'static str,
295         len: usize,
296     ) -> Result<Self::SerializeStruct, Self::Error> {
297         let mut state = try!(self.delegate.serialize_struct(name, len + 1));
298         try!(state.serialize_field(self.tag, self.variant_name));
299         Ok(state)
300     }
301 
302     #[cfg(not(any(feature = "std", feature = "alloc")))]
serialize_struct_variant( self, _: &'static str, _: u32, _: &'static str, _: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>303     fn serialize_struct_variant(
304         self,
305         _: &'static str,
306         _: u32,
307         _: &'static str,
308         _: usize,
309     ) -> Result<Self::SerializeStructVariant, Self::Error> {
310         // Lack of push-based serialization means we need to buffer the content
311         // of the struct variant, so it requires std.
312         Err(self.bad_type(Unsupported::Enum))
313     }
314 
315     #[cfg(any(feature = "std", feature = "alloc"))]
serialize_struct_variant( self, _: &'static str, _: u32, inner_variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>316     fn serialize_struct_variant(
317         self,
318         _: &'static str,
319         _: u32,
320         inner_variant: &'static str,
321         len: usize,
322     ) -> Result<Self::SerializeStructVariant, Self::Error> {
323         let mut map = try!(self.delegate.serialize_map(Some(2)));
324         try!(map.serialize_entry(self.tag, self.variant_name));
325         try!(map.serialize_key(inner_variant));
326         Ok(SerializeStructVariantAsMapValue::new(
327             map,
328             inner_variant,
329             len,
330         ))
331     }
332 
333     #[cfg(not(any(feature = "std", feature = "alloc")))]
collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> where T: Display,334     fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
335     where
336         T: Display,
337     {
338         Err(self.bad_type(Unsupported::String))
339     }
340 }
341 
342 /// Used only by Serde doc tests. Not public API.
343 #[doc(hidden)]
344 #[derive(Debug)]
345 pub struct Error;
346 
347 impl ser::Error for Error {
custom<T>(_: T) -> Self where T: Display,348     fn custom<T>(_: T) -> Self
349     where
350         T: Display,
351     {
352         unimplemented!()
353     }
354 }
355 
356 #[cfg(feature = "std")]
357 impl error::Error for Error {
description(&self) -> &str358     fn description(&self) -> &str {
359         unimplemented!()
360     }
361 }
362 
363 impl Display for Error {
fmt(&self, _: &mut fmt::Formatter) -> fmt::Result364     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
365         unimplemented!()
366     }
367 }
368 
369 #[cfg(any(feature = "std", feature = "alloc"))]
370 mod content {
371     use lib::*;
372 
373     use ser::{self, Serialize, Serializer};
374 
375     pub struct SerializeTupleVariantAsMapValue<M> {
376         map: M,
377         name: &'static str,
378         fields: Vec<Content>,
379     }
380 
381     impl<M> SerializeTupleVariantAsMapValue<M> {
new(map: M, name: &'static str, len: usize) -> Self382         pub fn new(map: M, name: &'static str, len: usize) -> Self {
383             SerializeTupleVariantAsMapValue {
384                 map: map,
385                 name: name,
386                 fields: Vec::with_capacity(len),
387             }
388         }
389     }
390 
391     impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M>
392     where
393         M: ser::SerializeMap,
394     {
395         type Ok = M::Ok;
396         type Error = M::Error;
397 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error> where T: Serialize,398         fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error>
399         where
400             T: Serialize,
401         {
402             let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
403             self.fields.push(value);
404             Ok(())
405         }
406 
end(mut self) -> Result<M::Ok, M::Error>407         fn end(mut self) -> Result<M::Ok, M::Error> {
408             try!(
409                 self.map
410                     .serialize_value(&Content::TupleStruct(self.name, self.fields))
411             );
412             self.map.end()
413         }
414     }
415 
416     pub struct SerializeStructVariantAsMapValue<M> {
417         map: M,
418         name: &'static str,
419         fields: Vec<(&'static str, Content)>,
420     }
421 
422     impl<M> SerializeStructVariantAsMapValue<M> {
new(map: M, name: &'static str, len: usize) -> Self423         pub fn new(map: M, name: &'static str, len: usize) -> Self {
424             SerializeStructVariantAsMapValue {
425                 map: map,
426                 name: name,
427                 fields: Vec::with_capacity(len),
428             }
429         }
430     }
431 
432     impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M>
433     where
434         M: ser::SerializeMap,
435     {
436         type Ok = M::Ok;
437         type Error = M::Error;
438 
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), M::Error> where T: Serialize,439         fn serialize_field<T: ?Sized>(
440             &mut self,
441             key: &'static str,
442             value: &T,
443         ) -> Result<(), M::Error>
444         where
445             T: Serialize,
446         {
447             let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
448             self.fields.push((key, value));
449             Ok(())
450         }
451 
end(mut self) -> Result<M::Ok, M::Error>452         fn end(mut self) -> Result<M::Ok, M::Error> {
453             try!(
454                 self.map
455                     .serialize_value(&Content::Struct(self.name, self.fields))
456             );
457             self.map.end()
458         }
459     }
460 
461     #[derive(Debug)]
462     enum Content {
463         Bool(bool),
464 
465         U8(u8),
466         U16(u16),
467         U32(u32),
468         U64(u64),
469 
470         I8(i8),
471         I16(i16),
472         I32(i32),
473         I64(i64),
474 
475         F32(f32),
476         F64(f64),
477 
478         Char(char),
479         String(String),
480         Bytes(Vec<u8>),
481 
482         None,
483         Some(Box<Content>),
484 
485         Unit,
486         UnitStruct(&'static str),
487         UnitVariant(&'static str, u32, &'static str),
488         NewtypeStruct(&'static str, Box<Content>),
489         NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
490 
491         Seq(Vec<Content>),
492         Tuple(Vec<Content>),
493         TupleStruct(&'static str, Vec<Content>),
494         TupleVariant(&'static str, u32, &'static str, Vec<Content>),
495         Map(Vec<(Content, Content)>),
496         Struct(&'static str, Vec<(&'static str, Content)>),
497         StructVariant(
498             &'static str,
499             u32,
500             &'static str,
501             Vec<(&'static str, Content)>,
502         ),
503     }
504 
505     impl Serialize for Content {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,506         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
507         where
508             S: Serializer,
509         {
510             match *self {
511                 Content::Bool(b) => serializer.serialize_bool(b),
512                 Content::U8(u) => serializer.serialize_u8(u),
513                 Content::U16(u) => serializer.serialize_u16(u),
514                 Content::U32(u) => serializer.serialize_u32(u),
515                 Content::U64(u) => serializer.serialize_u64(u),
516                 Content::I8(i) => serializer.serialize_i8(i),
517                 Content::I16(i) => serializer.serialize_i16(i),
518                 Content::I32(i) => serializer.serialize_i32(i),
519                 Content::I64(i) => serializer.serialize_i64(i),
520                 Content::F32(f) => serializer.serialize_f32(f),
521                 Content::F64(f) => serializer.serialize_f64(f),
522                 Content::Char(c) => serializer.serialize_char(c),
523                 Content::String(ref s) => serializer.serialize_str(s),
524                 Content::Bytes(ref b) => serializer.serialize_bytes(b),
525                 Content::None => serializer.serialize_none(),
526                 Content::Some(ref c) => serializer.serialize_some(&**c),
527                 Content::Unit => serializer.serialize_unit(),
528                 Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
529                 Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
530                 Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
531                 Content::NewtypeVariant(n, i, v, ref c) => {
532                     serializer.serialize_newtype_variant(n, i, v, &**c)
533                 }
534                 Content::Seq(ref elements) => elements.serialize(serializer),
535                 Content::Tuple(ref elements) => {
536                     use ser::SerializeTuple;
537                     let mut tuple = try!(serializer.serialize_tuple(elements.len()));
538                     for e in elements {
539                         try!(tuple.serialize_element(e));
540                     }
541                     tuple.end()
542                 }
543                 Content::TupleStruct(n, ref fields) => {
544                     use ser::SerializeTupleStruct;
545                     let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len()));
546                     for f in fields {
547                         try!(ts.serialize_field(f));
548                     }
549                     ts.end()
550                 }
551                 Content::TupleVariant(n, i, v, ref fields) => {
552                     use ser::SerializeTupleVariant;
553                     let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len()));
554                     for f in fields {
555                         try!(tv.serialize_field(f));
556                     }
557                     tv.end()
558                 }
559                 Content::Map(ref entries) => {
560                     use ser::SerializeMap;
561                     let mut map = try!(serializer.serialize_map(Some(entries.len())));
562                     for &(ref k, ref v) in entries {
563                         try!(map.serialize_entry(k, v));
564                     }
565                     map.end()
566                 }
567                 Content::Struct(n, ref fields) => {
568                     use ser::SerializeStruct;
569                     let mut s = try!(serializer.serialize_struct(n, fields.len()));
570                     for &(k, ref v) in fields {
571                         try!(s.serialize_field(k, v));
572                     }
573                     s.end()
574                 }
575                 Content::StructVariant(n, i, v, ref fields) => {
576                     use ser::SerializeStructVariant;
577                     let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len()));
578                     for &(k, ref v) in fields {
579                         try!(sv.serialize_field(k, v));
580                     }
581                     sv.end()
582                 }
583             }
584         }
585     }
586 
587     struct ContentSerializer<E> {
588         error: PhantomData<E>,
589     }
590 
591     impl<E> ContentSerializer<E> {
new() -> Self592         fn new() -> Self {
593             ContentSerializer { error: PhantomData }
594         }
595     }
596 
597     impl<E> Serializer for ContentSerializer<E>
598     where
599         E: ser::Error,
600     {
601         type Ok = Content;
602         type Error = E;
603 
604         type SerializeSeq = SerializeSeq<E>;
605         type SerializeTuple = SerializeTuple<E>;
606         type SerializeTupleStruct = SerializeTupleStruct<E>;
607         type SerializeTupleVariant = SerializeTupleVariant<E>;
608         type SerializeMap = SerializeMap<E>;
609         type SerializeStruct = SerializeStruct<E>;
610         type SerializeStructVariant = SerializeStructVariant<E>;
611 
serialize_bool(self, v: bool) -> Result<Content, E>612         fn serialize_bool(self, v: bool) -> Result<Content, E> {
613             Ok(Content::Bool(v))
614         }
615 
serialize_i8(self, v: i8) -> Result<Content, E>616         fn serialize_i8(self, v: i8) -> Result<Content, E> {
617             Ok(Content::I8(v))
618         }
619 
serialize_i16(self, v: i16) -> Result<Content, E>620         fn serialize_i16(self, v: i16) -> Result<Content, E> {
621             Ok(Content::I16(v))
622         }
623 
serialize_i32(self, v: i32) -> Result<Content, E>624         fn serialize_i32(self, v: i32) -> Result<Content, E> {
625             Ok(Content::I32(v))
626         }
627 
serialize_i64(self, v: i64) -> Result<Content, E>628         fn serialize_i64(self, v: i64) -> Result<Content, E> {
629             Ok(Content::I64(v))
630         }
631 
serialize_u8(self, v: u8) -> Result<Content, E>632         fn serialize_u8(self, v: u8) -> Result<Content, E> {
633             Ok(Content::U8(v))
634         }
635 
serialize_u16(self, v: u16) -> Result<Content, E>636         fn serialize_u16(self, v: u16) -> Result<Content, E> {
637             Ok(Content::U16(v))
638         }
639 
serialize_u32(self, v: u32) -> Result<Content, E>640         fn serialize_u32(self, v: u32) -> Result<Content, E> {
641             Ok(Content::U32(v))
642         }
643 
serialize_u64(self, v: u64) -> Result<Content, E>644         fn serialize_u64(self, v: u64) -> Result<Content, E> {
645             Ok(Content::U64(v))
646         }
647 
serialize_f32(self, v: f32) -> Result<Content, E>648         fn serialize_f32(self, v: f32) -> Result<Content, E> {
649             Ok(Content::F32(v))
650         }
651 
serialize_f64(self, v: f64) -> Result<Content, E>652         fn serialize_f64(self, v: f64) -> Result<Content, E> {
653             Ok(Content::F64(v))
654         }
655 
serialize_char(self, v: char) -> Result<Content, E>656         fn serialize_char(self, v: char) -> Result<Content, E> {
657             Ok(Content::Char(v))
658         }
659 
serialize_str(self, value: &str) -> Result<Content, E>660         fn serialize_str(self, value: &str) -> Result<Content, E> {
661             Ok(Content::String(value.to_owned()))
662         }
663 
serialize_bytes(self, value: &[u8]) -> Result<Content, E>664         fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
665             Ok(Content::Bytes(value.to_owned()))
666         }
667 
serialize_none(self) -> Result<Content, E>668         fn serialize_none(self) -> Result<Content, E> {
669             Ok(Content::None)
670         }
671 
serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E> where T: Serialize,672         fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E>
673         where
674             T: Serialize,
675         {
676             Ok(Content::Some(Box::new(try!(value.serialize(self)))))
677         }
678 
serialize_unit(self) -> Result<Content, E>679         fn serialize_unit(self) -> Result<Content, E> {
680             Ok(Content::Unit)
681         }
682 
serialize_unit_struct(self, name: &'static str) -> Result<Content, E>683         fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> {
684             Ok(Content::UnitStruct(name))
685         }
686 
serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result<Content, E>687         fn serialize_unit_variant(
688             self,
689             name: &'static str,
690             variant_index: u32,
691             variant: &'static str,
692         ) -> Result<Content, E> {
693             Ok(Content::UnitVariant(name, variant_index, variant))
694         }
695 
serialize_newtype_struct<T: ?Sized>( self, name: &'static str, value: &T, ) -> Result<Content, E> where T: Serialize,696         fn serialize_newtype_struct<T: ?Sized>(
697             self,
698             name: &'static str,
699             value: &T,
700         ) -> Result<Content, E>
701         where
702             T: Serialize,
703         {
704             Ok(Content::NewtypeStruct(
705                 name,
706                 Box::new(try!(value.serialize(self))),
707             ))
708         }
709 
serialize_newtype_variant<T: ?Sized>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<Content, E> where T: Serialize,710         fn serialize_newtype_variant<T: ?Sized>(
711             self,
712             name: &'static str,
713             variant_index: u32,
714             variant: &'static str,
715             value: &T,
716         ) -> Result<Content, E>
717         where
718             T: Serialize,
719         {
720             Ok(Content::NewtypeVariant(
721                 name,
722                 variant_index,
723                 variant,
724                 Box::new(try!(value.serialize(self))),
725             ))
726         }
727 
serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E>728         fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
729             Ok(SerializeSeq {
730                 elements: Vec::with_capacity(len.unwrap_or(0)),
731                 error: PhantomData,
732             })
733         }
734 
serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E>735         fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
736             Ok(SerializeTuple {
737                 elements: Vec::with_capacity(len),
738                 error: PhantomData,
739             })
740         }
741 
serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, E>742         fn serialize_tuple_struct(
743             self,
744             name: &'static str,
745             len: usize,
746         ) -> Result<Self::SerializeTupleStruct, E> {
747             Ok(SerializeTupleStruct {
748                 name: name,
749                 fields: Vec::with_capacity(len),
750                 error: PhantomData,
751             })
752         }
753 
serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, E>754         fn serialize_tuple_variant(
755             self,
756             name: &'static str,
757             variant_index: u32,
758             variant: &'static str,
759             len: usize,
760         ) -> Result<Self::SerializeTupleVariant, E> {
761             Ok(SerializeTupleVariant {
762                 name: name,
763                 variant_index: variant_index,
764                 variant: variant,
765                 fields: Vec::with_capacity(len),
766                 error: PhantomData,
767             })
768         }
769 
serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E>770         fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> {
771             Ok(SerializeMap {
772                 entries: Vec::with_capacity(len.unwrap_or(0)),
773                 key: None,
774                 error: PhantomData,
775             })
776         }
777 
serialize_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, E>778         fn serialize_struct(
779             self,
780             name: &'static str,
781             len: usize,
782         ) -> Result<Self::SerializeStruct, E> {
783             Ok(SerializeStruct {
784                 name: name,
785                 fields: Vec::with_capacity(len),
786                 error: PhantomData,
787             })
788         }
789 
serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, E>790         fn serialize_struct_variant(
791             self,
792             name: &'static str,
793             variant_index: u32,
794             variant: &'static str,
795             len: usize,
796         ) -> Result<Self::SerializeStructVariant, E> {
797             Ok(SerializeStructVariant {
798                 name: name,
799                 variant_index: variant_index,
800                 variant: variant,
801                 fields: Vec::with_capacity(len),
802                 error: PhantomData,
803             })
804         }
805     }
806 
807     struct SerializeSeq<E> {
808         elements: Vec<Content>,
809         error: PhantomData<E>,
810     }
811 
812     impl<E> ser::SerializeSeq for SerializeSeq<E>
813     where
814         E: ser::Error,
815     {
816         type Ok = Content;
817         type Error = E;
818 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,819         fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
820         where
821             T: Serialize,
822         {
823             let value = try!(value.serialize(ContentSerializer::<E>::new()));
824             self.elements.push(value);
825             Ok(())
826         }
827 
end(self) -> Result<Content, E>828         fn end(self) -> Result<Content, E> {
829             Ok(Content::Seq(self.elements))
830         }
831     }
832 
833     struct SerializeTuple<E> {
834         elements: Vec<Content>,
835         error: PhantomData<E>,
836     }
837 
838     impl<E> ser::SerializeTuple for SerializeTuple<E>
839     where
840         E: ser::Error,
841     {
842         type Ok = Content;
843         type Error = E;
844 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,845         fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
846         where
847             T: Serialize,
848         {
849             let value = try!(value.serialize(ContentSerializer::<E>::new()));
850             self.elements.push(value);
851             Ok(())
852         }
853 
end(self) -> Result<Content, E>854         fn end(self) -> Result<Content, E> {
855             Ok(Content::Tuple(self.elements))
856         }
857     }
858 
859     struct SerializeTupleStruct<E> {
860         name: &'static str,
861         fields: Vec<Content>,
862         error: PhantomData<E>,
863     }
864 
865     impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E>
866     where
867         E: ser::Error,
868     {
869         type Ok = Content;
870         type Error = E;
871 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,872         fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
873         where
874             T: Serialize,
875         {
876             let value = try!(value.serialize(ContentSerializer::<E>::new()));
877             self.fields.push(value);
878             Ok(())
879         }
880 
end(self) -> Result<Content, E>881         fn end(self) -> Result<Content, E> {
882             Ok(Content::TupleStruct(self.name, self.fields))
883         }
884     }
885 
886     struct SerializeTupleVariant<E> {
887         name: &'static str,
888         variant_index: u32,
889         variant: &'static str,
890         fields: Vec<Content>,
891         error: PhantomData<E>,
892     }
893 
894     impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E>
895     where
896         E: ser::Error,
897     {
898         type Ok = Content;
899         type Error = E;
900 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,901         fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
902         where
903             T: Serialize,
904         {
905             let value = try!(value.serialize(ContentSerializer::<E>::new()));
906             self.fields.push(value);
907             Ok(())
908         }
909 
end(self) -> Result<Content, E>910         fn end(self) -> Result<Content, E> {
911             Ok(Content::TupleVariant(
912                 self.name,
913                 self.variant_index,
914                 self.variant,
915                 self.fields,
916             ))
917         }
918     }
919 
920     struct SerializeMap<E> {
921         entries: Vec<(Content, Content)>,
922         key: Option<Content>,
923         error: PhantomData<E>,
924     }
925 
926     impl<E> ser::SerializeMap for SerializeMap<E>
927     where
928         E: ser::Error,
929     {
930         type Ok = Content;
931         type Error = E;
932 
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E> where T: Serialize,933         fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E>
934         where
935             T: Serialize,
936         {
937             let key = try!(key.serialize(ContentSerializer::<E>::new()));
938             self.key = Some(key);
939             Ok(())
940         }
941 
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E> where T: Serialize,942         fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
943         where
944             T: Serialize,
945         {
946             let key = self.key
947                 .take()
948                 .expect("serialize_value called before serialize_key");
949             let value = try!(value.serialize(ContentSerializer::<E>::new()));
950             self.entries.push((key, value));
951             Ok(())
952         }
953 
end(self) -> Result<Content, E>954         fn end(self) -> Result<Content, E> {
955             Ok(Content::Map(self.entries))
956         }
957 
serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E> where K: Serialize, V: Serialize,958         fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E>
959         where
960             K: Serialize,
961             V: Serialize,
962         {
963             let key = try!(key.serialize(ContentSerializer::<E>::new()));
964             let value = try!(value.serialize(ContentSerializer::<E>::new()));
965             self.entries.push((key, value));
966             Ok(())
967         }
968     }
969 
970     struct SerializeStruct<E> {
971         name: &'static str,
972         fields: Vec<(&'static str, Content)>,
973         error: PhantomData<E>,
974     }
975 
976     impl<E> ser::SerializeStruct for SerializeStruct<E>
977     where
978         E: ser::Error,
979     {
980         type Ok = Content;
981         type Error = E;
982 
serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> where T: Serialize,983         fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
984         where
985             T: Serialize,
986         {
987             let value = try!(value.serialize(ContentSerializer::<E>::new()));
988             self.fields.push((key, value));
989             Ok(())
990         }
991 
end(self) -> Result<Content, E>992         fn end(self) -> Result<Content, E> {
993             Ok(Content::Struct(self.name, self.fields))
994         }
995     }
996 
997     struct SerializeStructVariant<E> {
998         name: &'static str,
999         variant_index: u32,
1000         variant: &'static str,
1001         fields: Vec<(&'static str, Content)>,
1002         error: PhantomData<E>,
1003     }
1004 
1005     impl<E> ser::SerializeStructVariant for SerializeStructVariant<E>
1006     where
1007         E: ser::Error,
1008     {
1009         type Ok = Content;
1010         type Error = E;
1011 
serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> where T: Serialize,1012         fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
1013         where
1014             T: Serialize,
1015         {
1016             let value = try!(value.serialize(ContentSerializer::<E>::new()));
1017             self.fields.push((key, value));
1018             Ok(())
1019         }
1020 
end(self) -> Result<Content, E>1021         fn end(self) -> Result<Content, E> {
1022             Ok(Content::StructVariant(
1023                 self.name,
1024                 self.variant_index,
1025                 self.variant,
1026                 self.fields,
1027             ))
1028         }
1029     }
1030 }
1031