• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use serde::{ser, Serialize};
2 
3 use error::Error;
4 use token::Token;
5 
6 /// A `Serializer` that ensures that a value serializes to a given list of
7 /// tokens.
8 #[derive(Debug)]
9 pub struct Serializer<'a> {
10     tokens: &'a [Token],
11 }
12 
13 impl<'a> Serializer<'a> {
14     /// Creates the serializer.
new(tokens: &'a [Token]) -> Self15     pub fn new(tokens: &'a [Token]) -> Self {
16         Serializer { tokens: tokens }
17     }
18 
19     /// Pulls the next token off of the serializer, ignoring it.
next_token(&mut self) -> Option<Token>20     fn next_token(&mut self) -> Option<Token> {
21         if let Some((&first, rest)) = self.tokens.split_first() {
22             self.tokens = rest;
23             Some(first)
24         } else {
25             None
26         }
27     }
28 
remaining(&self) -> usize29     pub fn remaining(&self) -> usize {
30         self.tokens.len()
31     }
32 }
33 
34 macro_rules! assert_next_token {
35     ($ser:expr, $actual:ident) => {{
36         assert_next_token!($ser, stringify!($actual), Token::$actual, true);
37     }};
38     ($ser:expr, $actual:ident($v:expr)) => {{
39         assert_next_token!(
40             $ser,
41             format_args!(concat!(stringify!($actual), "({:?})"), $v),
42             Token::$actual(v),
43             v == $v
44         );
45     }};
46     ($ser:expr, $actual:ident { $($k:ident),* }) => {{
47         let compare = ($($k,)*);
48         let field_format = || {
49             use std::fmt::Write;
50             let mut buffer = String::new();
51             $(
52                 write!(&mut buffer, concat!(stringify!($k), ": {:?}, "), $k).unwrap();
53             )*
54             buffer
55         };
56         assert_next_token!(
57             $ser,
58             format_args!(concat!(stringify!($actual), " {{ {}}}"), field_format()),
59             Token::$actual { $($k),* },
60             ($($k,)*) == compare
61         );
62     }};
63     ($ser:expr, $actual:expr, $pat:pat, $guard:expr) => {
64         match $ser.next_token() {
65             Some($pat) if $guard => {}
66             Some(expected) => {
67                 panic!("expected Token::{} but serialized as {}",
68                        expected, $actual);
69             }
70             None => {
71                 panic!("expected end of tokens, but {} was serialized",
72                        $actual);
73             }
74         }
75     };
76 }
77 
78 impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
79     type Ok = ();
80     type Error = Error;
81 
82     type SerializeSeq = Self;
83     type SerializeTuple = Self;
84     type SerializeTupleStruct = Self;
85     type SerializeTupleVariant = Variant<'s, 'a>;
86     type SerializeMap = Self;
87     type SerializeStruct = Self;
88     type SerializeStructVariant = Variant<'s, 'a>;
89 
serialize_bool(self, v: bool) -> Result<(), Error>90     fn serialize_bool(self, v: bool) -> Result<(), Error> {
91         assert_next_token!(self, Bool(v));
92         Ok(())
93     }
94 
serialize_i8(self, v: i8) -> Result<(), Error>95     fn serialize_i8(self, v: i8) -> Result<(), Error> {
96         assert_next_token!(self, I8(v));
97         Ok(())
98     }
99 
serialize_i16(self, v: i16) -> Result<(), Error>100     fn serialize_i16(self, v: i16) -> Result<(), Error> {
101         assert_next_token!(self, I16(v));
102         Ok(())
103     }
104 
serialize_i32(self, v: i32) -> Result<(), Error>105     fn serialize_i32(self, v: i32) -> Result<(), Error> {
106         assert_next_token!(self, I32(v));
107         Ok(())
108     }
109 
serialize_i64(self, v: i64) -> Result<(), Error>110     fn serialize_i64(self, v: i64) -> Result<(), Error> {
111         assert_next_token!(self, I64(v));
112         Ok(())
113     }
114 
serialize_u8(self, v: u8) -> Result<(), Error>115     fn serialize_u8(self, v: u8) -> Result<(), Error> {
116         assert_next_token!(self, U8(v));
117         Ok(())
118     }
119 
serialize_u16(self, v: u16) -> Result<(), Error>120     fn serialize_u16(self, v: u16) -> Result<(), Error> {
121         assert_next_token!(self, U16(v));
122         Ok(())
123     }
124 
serialize_u32(self, v: u32) -> Result<(), Error>125     fn serialize_u32(self, v: u32) -> Result<(), Error> {
126         assert_next_token!(self, U32(v));
127         Ok(())
128     }
129 
serialize_u64(self, v: u64) -> Result<(), Error>130     fn serialize_u64(self, v: u64) -> Result<(), Error> {
131         assert_next_token!(self, U64(v));
132         Ok(())
133     }
134 
serialize_f32(self, v: f32) -> Result<(), Error>135     fn serialize_f32(self, v: f32) -> Result<(), Error> {
136         assert_next_token!(self, F32(v));
137         Ok(())
138     }
139 
serialize_f64(self, v: f64) -> Result<(), Error>140     fn serialize_f64(self, v: f64) -> Result<(), Error> {
141         assert_next_token!(self, F64(v));
142         Ok(())
143     }
144 
serialize_char(self, v: char) -> Result<(), Error>145     fn serialize_char(self, v: char) -> Result<(), Error> {
146         assert_next_token!(self, Char(v));
147         Ok(())
148     }
149 
serialize_str(self, v: &str) -> Result<(), Error>150     fn serialize_str(self, v: &str) -> Result<(), Error> {
151         match self.tokens.first() {
152             Some(&Token::BorrowedStr(_)) => assert_next_token!(self, BorrowedStr(v)),
153             Some(&Token::String(_)) => assert_next_token!(self, String(v)),
154             _ => assert_next_token!(self, Str(v)),
155         }
156         Ok(())
157     }
158 
serialize_bytes(self, v: &[u8]) -> Result<(), Self::Error>159     fn serialize_bytes(self, v: &[u8]) -> Result<(), Self::Error> {
160         match self.tokens.first() {
161             Some(&Token::BorrowedBytes(_)) => assert_next_token!(self, BorrowedBytes(v)),
162             Some(&Token::ByteBuf(_)) => assert_next_token!(self, ByteBuf(v)),
163             _ => assert_next_token!(self, Bytes(v)),
164         }
165         Ok(())
166     }
167 
serialize_unit(self) -> Result<(), Error>168     fn serialize_unit(self) -> Result<(), Error> {
169         assert_next_token!(self, Unit);
170         Ok(())
171     }
172 
serialize_unit_struct(self, name: &'static str) -> Result<(), Error>173     fn serialize_unit_struct(self, name: &'static str) -> Result<(), Error> {
174         assert_next_token!(self, UnitStruct { name });
175         Ok(())
176     }
177 
serialize_unit_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<(), Error>178     fn serialize_unit_variant(
179         self,
180         name: &'static str,
181         _variant_index: u32,
182         variant: &'static str,
183     ) -> Result<(), Error> {
184         if self.tokens.first() == Some(&Token::Enum { name: name }) {
185             self.next_token();
186             assert_next_token!(self, Str(variant));
187             assert_next_token!(self, Unit);
188         } else {
189             assert_next_token!(self, UnitVariant { name, variant });
190         }
191         Ok(())
192     }
193 
serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<(), Error> where T: Serialize,194     fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<(), Error>
195     where
196         T: Serialize,
197     {
198         assert_next_token!(self, NewtypeStruct { name });
199         value.serialize(self)
200     }
201 
serialize_newtype_variant<T: ?Sized>( self, name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<(), Error> where T: Serialize,202     fn serialize_newtype_variant<T: ?Sized>(
203         self,
204         name: &'static str,
205         _variant_index: u32,
206         variant: &'static str,
207         value: &T,
208     ) -> Result<(), Error>
209     where
210         T: Serialize,
211     {
212         if self.tokens.first() == Some(&Token::Enum { name: name }) {
213             self.next_token();
214             assert_next_token!(self, Str(variant));
215         } else {
216             assert_next_token!(self, NewtypeVariant { name, variant });
217         }
218         value.serialize(self)
219     }
220 
serialize_none(self) -> Result<(), Error>221     fn serialize_none(self) -> Result<(), Error> {
222         assert_next_token!(self, None);
223         Ok(())
224     }
225 
serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error> where T: Serialize,226     fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
227     where
228         T: Serialize,
229     {
230         assert_next_token!(self, Some);
231         value.serialize(self)
232     }
233 
serialize_seq(self, len: Option<usize>) -> Result<Self, Error>234     fn serialize_seq(self, len: Option<usize>) -> Result<Self, Error> {
235         assert_next_token!(self, Seq { len });
236         Ok(self)
237     }
238 
serialize_tuple(self, len: usize) -> Result<Self, Error>239     fn serialize_tuple(self, len: usize) -> Result<Self, Error> {
240         assert_next_token!(self, Tuple { len });
241         Ok(self)
242     }
243 
serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error>244     fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
245         assert_next_token!(self, TupleStruct { name, len });
246         Ok(self)
247     }
248 
serialize_tuple_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Error>249     fn serialize_tuple_variant(
250         self,
251         name: &'static str,
252         _variant_index: u32,
253         variant: &'static str,
254         len: usize,
255     ) -> Result<Self::SerializeTupleVariant, Error> {
256         if self.tokens.first() == Some(&Token::Enum { name: name }) {
257             self.next_token();
258             assert_next_token!(self, Str(variant));
259             let len = Some(len);
260             assert_next_token!(self, Seq { len });
261             Ok(Variant {
262                 ser: self,
263                 end: Token::SeqEnd,
264             })
265         } else {
266             assert_next_token!(self, TupleVariant { name, variant, len });
267             Ok(Variant {
268                 ser: self,
269                 end: Token::TupleVariantEnd,
270             })
271         }
272     }
273 
serialize_map(self, len: Option<usize>) -> Result<Self, Error>274     fn serialize_map(self, len: Option<usize>) -> Result<Self, Error> {
275         assert_next_token!(self, Map { len });
276         Ok(self)
277     }
278 
serialize_struct(self, name: &'static str, len: usize) -> Result<Self, Error>279     fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
280         assert_next_token!(self, Struct { name, len });
281         Ok(self)
282     }
283 
serialize_struct_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Error>284     fn serialize_struct_variant(
285         self,
286         name: &'static str,
287         _variant_index: u32,
288         variant: &'static str,
289         len: usize,
290     ) -> Result<Self::SerializeStructVariant, Error> {
291         if self.tokens.first() == Some(&Token::Enum { name: name }) {
292             self.next_token();
293             assert_next_token!(self, Str(variant));
294             let len = Some(len);
295             assert_next_token!(self, Map { len });
296             Ok(Variant {
297                 ser: self,
298                 end: Token::MapEnd,
299             })
300         } else {
301             assert_next_token!(self, StructVariant { name, variant, len });
302             Ok(Variant {
303                 ser: self,
304                 end: Token::StructVariantEnd,
305             })
306         }
307     }
308 
is_human_readable(&self) -> bool309     fn is_human_readable(&self) -> bool {
310         panic!(
311             "Types which have different human-readable and compact representations \
312              must explicitly mark their test cases with `serde_test::Configure`"
313         );
314     }
315 }
316 
317 pub struct Variant<'s, 'a: 's> {
318     ser: &'s mut Serializer<'a>,
319     end: Token,
320 }
321 
322 impl<'s, 'a> ser::SerializeSeq for &'s mut Serializer<'a> {
323     type Ok = ();
324     type Error = Error;
325 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: Serialize,326     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
327     where
328         T: Serialize,
329     {
330         value.serialize(&mut **self)
331     }
332 
end(self) -> Result<(), Error>333     fn end(self) -> Result<(), Error> {
334         assert_next_token!(self, SeqEnd);
335         Ok(())
336     }
337 }
338 
339 impl<'s, 'a> ser::SerializeTuple for &'s mut Serializer<'a> {
340     type Ok = ();
341     type Error = Error;
342 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: Serialize,343     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
344     where
345         T: Serialize,
346     {
347         value.serialize(&mut **self)
348     }
349 
end(self) -> Result<(), Error>350     fn end(self) -> Result<(), Error> {
351         assert_next_token!(self, TupleEnd);
352         Ok(())
353     }
354 }
355 
356 impl<'s, 'a> ser::SerializeTupleStruct for &'s mut Serializer<'a> {
357     type Ok = ();
358     type Error = Error;
359 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: Serialize,360     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
361     where
362         T: Serialize,
363     {
364         value.serialize(&mut **self)
365     }
366 
end(self) -> Result<(), Error>367     fn end(self) -> Result<(), Error> {
368         assert_next_token!(self, TupleStructEnd);
369         Ok(())
370     }
371 }
372 
373 impl<'s, 'a> ser::SerializeTupleVariant for Variant<'s, 'a> {
374     type Ok = ();
375     type Error = Error;
376 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: Serialize,377     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
378     where
379         T: Serialize,
380     {
381         value.serialize(&mut *self.ser)
382     }
383 
end(self) -> Result<(), Error>384     fn end(self) -> Result<(), Error> {
385         match self.end {
386             Token::TupleVariantEnd => assert_next_token!(self.ser, TupleVariantEnd),
387             Token::SeqEnd => assert_next_token!(self.ser, SeqEnd),
388             _ => unreachable!(),
389         }
390         Ok(())
391     }
392 }
393 
394 impl<'s, 'a> ser::SerializeMap for &'s mut Serializer<'a> {
395     type Ok = ();
396     type Error = Error;
397 
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize,398     fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
399     where
400         T: Serialize,
401     {
402         key.serialize(&mut **self)
403     }
404 
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize,405     fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
406     where
407         T: Serialize,
408     {
409         value.serialize(&mut **self)
410     }
411 
end(self) -> Result<(), Self::Error>412     fn end(self) -> Result<(), Self::Error> {
413         assert_next_token!(self, MapEnd);
414         Ok(())
415     }
416 }
417 
418 impl<'s, 'a> ser::SerializeStruct for &'s mut Serializer<'a> {
419     type Ok = ();
420     type Error = Error;
421 
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize,422     fn serialize_field<T: ?Sized>(
423         &mut self,
424         key: &'static str,
425         value: &T,
426     ) -> Result<(), Self::Error>
427     where
428         T: Serialize,
429     {
430         key.serialize(&mut **self)?;
431         value.serialize(&mut **self)
432     }
433 
end(self) -> Result<(), Self::Error>434     fn end(self) -> Result<(), Self::Error> {
435         assert_next_token!(self, StructEnd);
436         Ok(())
437     }
438 }
439 
440 impl<'s, 'a> ser::SerializeStructVariant for Variant<'s, 'a> {
441     type Ok = ();
442     type Error = Error;
443 
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize,444     fn serialize_field<T: ?Sized>(
445         &mut self,
446         key: &'static str,
447         value: &T,
448     ) -> Result<(), Self::Error>
449     where
450         T: Serialize,
451     {
452         key.serialize(&mut *self.ser)?;
453         value.serialize(&mut *self.ser)
454     }
455 
end(self) -> Result<(), Self::Error>456     fn end(self) -> Result<(), Self::Error> {
457         match self.end {
458             Token::StructVariantEnd => assert_next_token!(self.ser, StructVariantEnd),
459             Token::MapEnd => assert_next_token!(self.ser, MapEnd),
460             _ => unreachable!(),
461         }
462         Ok(())
463     }
464 }
465