1 use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer}; 2 use serde::de::{ 3 self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, 4 VariantAccess, Visitor, 5 }; 6 7 use error::Error; 8 use token::Token; 9 10 #[derive(Debug)] 11 pub struct Deserializer<'de> { 12 tokens: &'de [Token], 13 } 14 15 macro_rules! assert_next_token { 16 ($de:expr, $expected:expr) => { 17 match $de.next_token_opt() { 18 Some(token) if token == $expected => {} 19 Some(other) => panic!( 20 "expected Token::{} but deserialization wants Token::{}", 21 other, $expected 22 ), 23 None => panic!( 24 "end of tokens but deserialization wants Token::{}", 25 $expected 26 ), 27 } 28 }; 29 } 30 31 macro_rules! unexpected { 32 ($token:expr) => { 33 panic!("deserialization did not expect this token: {}", $token) 34 }; 35 } 36 37 macro_rules! end_of_tokens { 38 () => { 39 panic!("ran out of tokens to deserialize") 40 }; 41 } 42 43 impl<'de> Deserializer<'de> { new(tokens: &'de [Token]) -> Self44 pub fn new(tokens: &'de [Token]) -> Self { 45 Deserializer { tokens: tokens } 46 } 47 peek_token_opt(&self) -> Option<Token>48 fn peek_token_opt(&self) -> Option<Token> { 49 self.tokens.first().cloned() 50 } 51 peek_token(&self) -> Token52 fn peek_token(&self) -> Token { 53 match self.peek_token_opt() { 54 Some(token) => token, 55 None => end_of_tokens!(), 56 } 57 } 58 next_token_opt(&mut self) -> Option<Token>59 pub fn next_token_opt(&mut self) -> Option<Token> { 60 match self.tokens.split_first() { 61 Some((&first, rest)) => { 62 self.tokens = rest; 63 Some(first) 64 } 65 None => None, 66 } 67 } 68 next_token(&mut self) -> Token69 fn next_token(&mut self) -> Token { 70 match self.tokens.split_first() { 71 Some((&first, rest)) => { 72 self.tokens = rest; 73 first 74 } 75 None => end_of_tokens!(), 76 } 77 } 78 remaining(&self) -> usize79 pub fn remaining(&self) -> usize { 80 self.tokens.len() 81 } 82 visit_seq<V>( &mut self, len: Option<usize>, end: Token, visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,83 fn visit_seq<V>( 84 &mut self, 85 len: Option<usize>, 86 end: Token, 87 visitor: V, 88 ) -> Result<V::Value, Error> 89 where 90 V: Visitor<'de>, 91 { 92 let value = visitor.visit_seq(DeserializerSeqVisitor { 93 de: self, 94 len: len, 95 end: end, 96 })?; 97 assert_next_token!(self, end); 98 Ok(value) 99 } 100 visit_map<V>( &mut self, len: Option<usize>, end: Token, visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,101 fn visit_map<V>( 102 &mut self, 103 len: Option<usize>, 104 end: Token, 105 visitor: V, 106 ) -> Result<V::Value, Error> 107 where 108 V: Visitor<'de>, 109 { 110 let value = visitor.visit_map(DeserializerMapVisitor { 111 de: self, 112 len: len, 113 end: end, 114 })?; 115 assert_next_token!(self, end); 116 Ok(value) 117 } 118 } 119 120 impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> { 121 type Error = Error; 122 123 forward_to_deserialize_any! { 124 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string 125 bytes byte_buf unit seq map identifier ignored_any 126 } 127 deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,128 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> 129 where 130 V: Visitor<'de>, 131 { 132 let token = self.next_token(); 133 match token { 134 Token::Bool(v) => visitor.visit_bool(v), 135 Token::I8(v) => visitor.visit_i8(v), 136 Token::I16(v) => visitor.visit_i16(v), 137 Token::I32(v) => visitor.visit_i32(v), 138 Token::I64(v) => visitor.visit_i64(v), 139 Token::U8(v) => visitor.visit_u8(v), 140 Token::U16(v) => visitor.visit_u16(v), 141 Token::U32(v) => visitor.visit_u32(v), 142 Token::U64(v) => visitor.visit_u64(v), 143 Token::F32(v) => visitor.visit_f32(v), 144 Token::F64(v) => visitor.visit_f64(v), 145 Token::Char(v) => visitor.visit_char(v), 146 Token::Str(v) => visitor.visit_str(v), 147 Token::BorrowedStr(v) => visitor.visit_borrowed_str(v), 148 Token::String(v) => visitor.visit_string(v.to_owned()), 149 Token::Bytes(v) => visitor.visit_bytes(v), 150 Token::BorrowedBytes(v) => visitor.visit_borrowed_bytes(v), 151 Token::ByteBuf(v) => visitor.visit_byte_buf(v.to_vec()), 152 Token::None => visitor.visit_none(), 153 Token::Some => visitor.visit_some(self), 154 Token::Unit | Token::UnitStruct { .. } => visitor.visit_unit(), 155 Token::NewtypeStruct { .. } => visitor.visit_newtype_struct(self), 156 Token::Seq { len } => self.visit_seq(len, Token::SeqEnd, visitor), 157 Token::Tuple { len } => self.visit_seq(Some(len), Token::TupleEnd, visitor), 158 Token::TupleStruct { len, .. } => { 159 self.visit_seq(Some(len), Token::TupleStructEnd, visitor) 160 } 161 Token::Map { len } => self.visit_map(len, Token::MapEnd, visitor), 162 Token::Struct { len, .. } => self.visit_map(Some(len), Token::StructEnd, visitor), 163 Token::Enum { .. } => { 164 let variant = self.next_token(); 165 let next = self.peek_token(); 166 match (variant, next) { 167 (Token::Str(variant), Token::Unit) => { 168 self.next_token(); 169 visitor.visit_str(variant) 170 } 171 (Token::BorrowedStr(variant), Token::Unit) => { 172 self.next_token(); 173 visitor.visit_borrowed_str(variant) 174 } 175 (Token::String(variant), Token::Unit) => { 176 self.next_token(); 177 visitor.visit_string(variant.to_string()) 178 } 179 (Token::Bytes(variant), Token::Unit) => { 180 self.next_token(); 181 visitor.visit_bytes(variant) 182 } 183 (Token::BorrowedBytes(variant), Token::Unit) => { 184 self.next_token(); 185 visitor.visit_borrowed_bytes(variant) 186 } 187 (Token::ByteBuf(variant), Token::Unit) => { 188 self.next_token(); 189 visitor.visit_byte_buf(variant.to_vec()) 190 } 191 (Token::U8(variant), Token::Unit) => { 192 self.next_token(); 193 visitor.visit_u8(variant) 194 } 195 (Token::U16(variant), Token::Unit) => { 196 self.next_token(); 197 visitor.visit_u16(variant) 198 } 199 (Token::U32(variant), Token::Unit) => { 200 self.next_token(); 201 visitor.visit_u32(variant) 202 } 203 (Token::U64(variant), Token::Unit) => { 204 self.next_token(); 205 visitor.visit_u64(variant) 206 } 207 (variant, Token::Unit) => unexpected!(variant), 208 (variant, _) => { 209 visitor.visit_map(EnumMapVisitor::new(self, variant, EnumFormat::Any)) 210 } 211 } 212 } 213 Token::UnitVariant { variant, .. } => visitor.visit_str(variant), 214 Token::NewtypeVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( 215 self, 216 Token::Str(variant), 217 EnumFormat::Any, 218 )), 219 Token::TupleVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( 220 self, 221 Token::Str(variant), 222 EnumFormat::Seq, 223 )), 224 Token::StructVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( 225 self, 226 Token::Str(variant), 227 EnumFormat::Map, 228 )), 229 Token::SeqEnd 230 | Token::TupleEnd 231 | Token::TupleStructEnd 232 | Token::MapEnd 233 | Token::StructEnd 234 | Token::TupleVariantEnd 235 | Token::StructVariantEnd => { 236 unexpected!(token); 237 } 238 } 239 } 240 deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,241 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> 242 where 243 V: Visitor<'de>, 244 { 245 match self.peek_token() { 246 Token::Unit | Token::None => { 247 self.next_token(); 248 visitor.visit_none() 249 } 250 Token::Some => { 251 self.next_token(); 252 visitor.visit_some(self) 253 } 254 _ => self.deserialize_any(visitor), 255 } 256 } 257 deserialize_enum<V>( self, name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,258 fn deserialize_enum<V>( 259 self, 260 name: &'static str, 261 _variants: &'static [&'static str], 262 visitor: V, 263 ) -> Result<V::Value, Error> 264 where 265 V: Visitor<'de>, 266 { 267 match self.peek_token() { 268 Token::Enum { name: n } if name == n => { 269 self.next_token(); 270 271 visitor.visit_enum(DeserializerEnumVisitor { de: self }) 272 } 273 Token::UnitVariant { name: n, .. } 274 | Token::NewtypeVariant { name: n, .. } 275 | Token::TupleVariant { name: n, .. } 276 | Token::StructVariant { name: n, .. } 277 if name == n => 278 { 279 visitor.visit_enum(DeserializerEnumVisitor { de: self }) 280 } 281 _ => self.deserialize_any(visitor), 282 } 283 } 284 deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,285 fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Error> 286 where 287 V: Visitor<'de>, 288 { 289 match self.peek_token() { 290 Token::UnitStruct { .. } => { 291 assert_next_token!(self, Token::UnitStruct { name: name }); 292 visitor.visit_unit() 293 } 294 _ => self.deserialize_any(visitor), 295 } 296 } 297 deserialize_newtype_struct<V>( self, name: &'static str, visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,298 fn deserialize_newtype_struct<V>( 299 self, 300 name: &'static str, 301 visitor: V, 302 ) -> Result<V::Value, Error> 303 where 304 V: Visitor<'de>, 305 { 306 match self.peek_token() { 307 Token::NewtypeStruct { .. } => { 308 assert_next_token!(self, Token::NewtypeStruct { name: name }); 309 visitor.visit_newtype_struct(self) 310 } 311 _ => self.deserialize_any(visitor), 312 } 313 } 314 deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,315 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error> 316 where 317 V: Visitor<'de>, 318 { 319 match self.peek_token() { 320 Token::Unit | Token::UnitStruct { .. } => { 321 self.next_token(); 322 visitor.visit_unit() 323 } 324 Token::Seq { .. } => { 325 self.next_token(); 326 self.visit_seq(Some(len), Token::SeqEnd, visitor) 327 } 328 Token::Tuple { .. } => { 329 self.next_token(); 330 self.visit_seq(Some(len), Token::TupleEnd, visitor) 331 } 332 Token::TupleStruct { .. } => { 333 self.next_token(); 334 self.visit_seq(Some(len), Token::TupleStructEnd, visitor) 335 } 336 _ => self.deserialize_any(visitor), 337 } 338 } 339 deserialize_tuple_struct<V>( self, name: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,340 fn deserialize_tuple_struct<V>( 341 self, 342 name: &'static str, 343 len: usize, 344 visitor: V, 345 ) -> Result<V::Value, Error> 346 where 347 V: Visitor<'de>, 348 { 349 match self.peek_token() { 350 Token::Unit => { 351 self.next_token(); 352 visitor.visit_unit() 353 } 354 Token::UnitStruct { .. } => { 355 assert_next_token!(self, Token::UnitStruct { name: name }); 356 visitor.visit_unit() 357 } 358 Token::Seq { .. } => { 359 self.next_token(); 360 self.visit_seq(Some(len), Token::SeqEnd, visitor) 361 } 362 Token::Tuple { .. } => { 363 self.next_token(); 364 self.visit_seq(Some(len), Token::TupleEnd, visitor) 365 } 366 Token::TupleStruct { len: n, .. } => { 367 assert_next_token!(self, Token::TupleStruct { name: name, len: n }); 368 self.visit_seq(Some(len), Token::TupleStructEnd, visitor) 369 } 370 _ => self.deserialize_any(visitor), 371 } 372 } 373 deserialize_struct<V>( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,374 fn deserialize_struct<V>( 375 self, 376 name: &'static str, 377 fields: &'static [&'static str], 378 visitor: V, 379 ) -> Result<V::Value, Error> 380 where 381 V: Visitor<'de>, 382 { 383 match self.peek_token() { 384 Token::Struct { len: n, .. } => { 385 assert_next_token!(self, Token::Struct { name: name, len: n }); 386 self.visit_map(Some(fields.len()), Token::StructEnd, visitor) 387 } 388 Token::Map { .. } => { 389 self.next_token(); 390 self.visit_map(Some(fields.len()), Token::MapEnd, visitor) 391 } 392 _ => self.deserialize_any(visitor), 393 } 394 } 395 is_human_readable(&self) -> bool396 fn is_human_readable(&self) -> bool { 397 panic!( 398 "Types which have different human-readable and compact representations \ 399 must explicitly mark their test cases with `serde_test::Configure`" 400 ); 401 } 402 } 403 404 ////////////////////////////////////////////////////////////////////////// 405 406 struct DeserializerSeqVisitor<'a, 'de: 'a> { 407 de: &'a mut Deserializer<'de>, 408 len: Option<usize>, 409 end: Token, 410 } 411 412 impl<'de, 'a> SeqAccess<'de> for DeserializerSeqVisitor<'a, 'de> { 413 type Error = Error; 414 next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> where T: DeserializeSeed<'de>,415 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> 416 where 417 T: DeserializeSeed<'de>, 418 { 419 if self.de.peek_token_opt() == Some(self.end) { 420 return Ok(None); 421 } 422 self.len = self.len.map(|len| len.saturating_sub(1)); 423 seed.deserialize(&mut *self.de).map(Some) 424 } 425 size_hint(&self) -> Option<usize>426 fn size_hint(&self) -> Option<usize> { 427 self.len 428 } 429 } 430 431 ////////////////////////////////////////////////////////////////////////// 432 433 struct DeserializerMapVisitor<'a, 'de: 'a> { 434 de: &'a mut Deserializer<'de>, 435 len: Option<usize>, 436 end: Token, 437 } 438 439 impl<'de, 'a> MapAccess<'de> for DeserializerMapVisitor<'a, 'de> { 440 type Error = Error; 441 next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> where K: DeserializeSeed<'de>,442 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> 443 where 444 K: DeserializeSeed<'de>, 445 { 446 if self.de.peek_token_opt() == Some(self.end) { 447 return Ok(None); 448 } 449 self.len = self.len.map(|len| len.saturating_sub(1)); 450 seed.deserialize(&mut *self.de).map(Some) 451 } 452 next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> where V: DeserializeSeed<'de>,453 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> 454 where 455 V: DeserializeSeed<'de>, 456 { 457 seed.deserialize(&mut *self.de) 458 } 459 size_hint(&self) -> Option<usize>460 fn size_hint(&self) -> Option<usize> { 461 self.len 462 } 463 } 464 465 ////////////////////////////////////////////////////////////////////////// 466 467 struct DeserializerEnumVisitor<'a, 'de: 'a> { 468 de: &'a mut Deserializer<'de>, 469 } 470 471 impl<'de, 'a> EnumAccess<'de> for DeserializerEnumVisitor<'a, 'de> { 472 type Error = Error; 473 type Variant = Self; 474 variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error> where V: DeserializeSeed<'de>,475 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error> 476 where 477 V: DeserializeSeed<'de>, 478 { 479 match self.de.peek_token() { 480 Token::UnitVariant { variant: v, .. } 481 | Token::NewtypeVariant { variant: v, .. } 482 | Token::TupleVariant { variant: v, .. } 483 | Token::StructVariant { variant: v, .. } => { 484 let de = v.into_deserializer(); 485 let value = seed.deserialize(de)?; 486 Ok((value, self)) 487 } 488 _ => { 489 let value = seed.deserialize(&mut *self.de)?; 490 Ok((value, self)) 491 } 492 } 493 } 494 } 495 496 impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> { 497 type Error = Error; 498 unit_variant(self) -> Result<(), Error>499 fn unit_variant(self) -> Result<(), Error> { 500 match self.de.peek_token() { 501 Token::UnitVariant { .. } => { 502 self.de.next_token(); 503 Ok(()) 504 } 505 _ => Deserialize::deserialize(self.de), 506 } 507 } 508 newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: DeserializeSeed<'de>,509 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> 510 where 511 T: DeserializeSeed<'de>, 512 { 513 match self.de.peek_token() { 514 Token::NewtypeVariant { .. } => { 515 self.de.next_token(); 516 seed.deserialize(self.de) 517 } 518 _ => seed.deserialize(self.de), 519 } 520 } 521 tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>,522 fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Error> 523 where 524 V: Visitor<'de>, 525 { 526 match self.de.peek_token() { 527 Token::TupleVariant { len: enum_len, .. } => { 528 let token = self.de.next_token(); 529 530 if len == enum_len { 531 self.de 532 .visit_seq(Some(len), Token::TupleVariantEnd, visitor) 533 } else { 534 unexpected!(token); 535 } 536 } 537 Token::Seq { 538 len: Some(enum_len), 539 } => { 540 let token = self.de.next_token(); 541 542 if len == enum_len { 543 self.de.visit_seq(Some(len), Token::SeqEnd, visitor) 544 } else { 545 unexpected!(token); 546 } 547 } 548 _ => de::Deserializer::deserialize_any(self.de, visitor), 549 } 550 } 551 struct_variant<V>( self, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>,552 fn struct_variant<V>( 553 self, 554 fields: &'static [&'static str], 555 visitor: V, 556 ) -> Result<V::Value, Error> 557 where 558 V: Visitor<'de>, 559 { 560 match self.de.peek_token() { 561 Token::StructVariant { len: enum_len, .. } => { 562 let token = self.de.next_token(); 563 564 if fields.len() == enum_len { 565 self.de 566 .visit_map(Some(fields.len()), Token::StructVariantEnd, visitor) 567 } else { 568 unexpected!(token); 569 } 570 } 571 Token::Map { 572 len: Some(enum_len), 573 } => { 574 let token = self.de.next_token(); 575 576 if fields.len() == enum_len { 577 self.de 578 .visit_map(Some(fields.len()), Token::MapEnd, visitor) 579 } else { 580 unexpected!(token); 581 } 582 } 583 _ => de::Deserializer::deserialize_any(self.de, visitor), 584 } 585 } 586 } 587 588 ////////////////////////////////////////////////////////////////////////// 589 590 struct EnumMapVisitor<'a, 'de: 'a> { 591 de: &'a mut Deserializer<'de>, 592 variant: Option<Token>, 593 format: EnumFormat, 594 } 595 596 enum EnumFormat { 597 Seq, 598 Map, 599 Any, 600 } 601 602 impl<'a, 'de> EnumMapVisitor<'a, 'de> { new(de: &'a mut Deserializer<'de>, variant: Token, format: EnumFormat) -> Self603 fn new(de: &'a mut Deserializer<'de>, variant: Token, format: EnumFormat) -> Self { 604 EnumMapVisitor { 605 de: de, 606 variant: Some(variant), 607 format: format, 608 } 609 } 610 } 611 612 impl<'de, 'a> MapAccess<'de> for EnumMapVisitor<'a, 'de> { 613 type Error = Error; 614 next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> where K: DeserializeSeed<'de>,615 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> 616 where 617 K: DeserializeSeed<'de>, 618 { 619 match self.variant.take() { 620 Some(Token::Str(variant)) => seed.deserialize(variant.into_deserializer()).map(Some), 621 Some(Token::Bytes(variant)) => seed 622 .deserialize(BytesDeserializer { value: variant }) 623 .map(Some), 624 Some(Token::U32(variant)) => seed.deserialize(variant.into_deserializer()).map(Some), 625 Some(other) => unexpected!(other), 626 None => Ok(None), 627 } 628 } 629 next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> where V: DeserializeSeed<'de>,630 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> 631 where 632 V: DeserializeSeed<'de>, 633 { 634 match self.format { 635 EnumFormat::Seq => { 636 let value = { 637 let visitor = DeserializerSeqVisitor { 638 de: self.de, 639 len: None, 640 end: Token::TupleVariantEnd, 641 }; 642 seed.deserialize(SeqAccessDeserializer::new(visitor))? 643 }; 644 assert_next_token!(self.de, Token::TupleVariantEnd); 645 Ok(value) 646 } 647 EnumFormat::Map => { 648 let value = { 649 let visitor = DeserializerMapVisitor { 650 de: self.de, 651 len: None, 652 end: Token::StructVariantEnd, 653 }; 654 seed.deserialize(MapAccessDeserializer::new(visitor))? 655 }; 656 assert_next_token!(self.de, Token::StructVariantEnd); 657 Ok(value) 658 } 659 EnumFormat::Any => seed.deserialize(&mut *self.de), 660 } 661 } 662 } 663 664 struct BytesDeserializer { 665 value: &'static [u8], 666 } 667 668 impl<'de> de::Deserializer<'de> for BytesDeserializer { 669 type Error = Error; 670 deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: de::Visitor<'de>,671 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> 672 where 673 V: de::Visitor<'de>, 674 { 675 visitor.visit_bytes(self.value) 676 } 677 678 forward_to_deserialize_any! { 679 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string 680 bytes byte_buf option unit unit_struct newtype_struct seq tuple 681 tuple_struct map struct enum identifier ignored_any 682 } 683 } 684