Skip to content

Commit

Permalink
Allow to deserialize unit structs from the empty sequences and maps
Browse files Browse the repository at this point in the history
Otherwise the following tests will fail:
- test_internally_tagged_enum
- test_internally_tagged_newtype_variant_containing_unit_struct
- test_internally_tagged_struct_variant_containing_unit_variant

This reverts commit 1986c17.
  • Loading branch information
Mingun committed Feb 23, 2021
1 parent 54409e4 commit 50fc381
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 7 deletions.
37 changes: 37 additions & 0 deletions serde_derive/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,43 @@ fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fra
{
_serde::__private::Ok(#this)
}

#[inline]
fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private::Result<Self::Value, __A::Error>
where
__A: _serde::de::SeqAccess<'de>,
{
// Allow to deserialize unit from empty sequence
if try!(_serde::de::SeqAccess::next_element::<
_serde::de::IgnoredAny,
>(&mut __seq)).is_some() {
_serde::__private::Err(_serde::de::Error::invalid_type(
_serde::de::Unexpected::Seq,
&self
))
} else {
_serde::__private::Ok(#this)
}
}

#[inline]
fn visit_map<__A>(self, mut __map: __A) -> _serde::__private::Result<Self::Value, __A::Error>
where
__A: _serde::de::MapAccess<'de>,
{
// Allow to deserialize unit from empty map
if try!(_serde::de::MapAccess::next_entry::<
_serde::de::IgnoredAny,
_serde::de::IgnoredAny,
>(&mut __map)).is_some() {
_serde::__private::Err(_serde::de::Error::invalid_type(
_serde::de::Unexpected::Map,
&self
))
} else {
_serde::__private::Ok(#this)
}
}
}

_serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, __Visitor)
Expand Down
27 changes: 20 additions & 7 deletions test_suite/tests/test_de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,26 @@ declare_tests! {
UnitStruct => &[
Token::UnitStruct { name: "UnitStruct" },
],
UnitStruct => &[
Token::Seq { len: Some(0) },
Token::SeqEnd,
],
UnitStruct => &[
Token::Seq { len: None },
Token::SeqEnd,
],
UnitStruct => &[
Token::Map { len: Some(0) },
Token::MapEnd,
],
UnitStruct => &[
Token::Map { len: None },
Token::MapEnd,
],
UnitStruct => &[
Token::Struct { name: "ZeroStruct", len: 0 },
Token::StructEnd,
],
}
test_newtype_struct {
NewtypeStruct(1) => &[
Expand Down Expand Up @@ -1593,13 +1613,6 @@ declare_error_tests! {
],
"invalid type: floating point `0`, expected isize",
}
test_unit_struct_from_seq<UnitStruct> {
&[
Token::Seq { len: Some(0) },
Token::SeqEnd,
],
"invalid type: sequence, expected unit struct UnitStruct",
}
test_wrapping_overflow<Wrapping<u16>> {
&[
Token::U32(65_536),
Expand Down

0 comments on commit 50fc381

Please sign in to comment.