Skip to content

Commit

Permalink
allow Deserialize derive to handle generic unit structs
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptistemontan committed Jul 9, 2023
1 parent 6502838 commit 89c8d85
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
21 changes: 17 additions & 4 deletions serde_derive/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,16 +410,29 @@ fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fra
let this_type = &params.this_type;
let this_value = &params.this_value;
let type_name = cattrs.name().deserialize_name();
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params);
let delife = params.borrowed.de_lifetime();

let expecting = format!("unit struct {}", params.type_name());
let expecting = cattrs.expecting().unwrap_or(&expecting);

let visitor_expr = quote! {
__Visitor {
marker: _serde::__private::PhantomData::<#this_type #ty_generics>,
lifetime: _serde::__private::PhantomData,
}
};

quote_block! {
#[doc(hidden)]
struct __Visitor;
struct __Visitor #de_impl_generics #where_clause {
marker: _serde::__private::PhantomData<#this_type #ty_generics>,
lifetime: _serde::__private::PhantomData<&#delife ()>,
}

impl<'de> _serde::de::Visitor<'de> for __Visitor {
type Value = #this_type;
impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this_type #ty_generics;

fn expecting(&self, __formatter: &mut _serde::__private::Formatter) -> _serde::__private::fmt::Result {
_serde::__private::Formatter::write_str(__formatter, #expecting)
Expand All @@ -434,7 +447,7 @@ fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fra
}
}

_serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, __Visitor)
_serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, #visitor_expr)
}
}

Expand Down
14 changes: 14 additions & 0 deletions test_suite/tests/test_de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ mod macros;
#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
struct UnitStruct;

#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
struct GenericUnitStruct<const N: u8>;

#[derive(PartialEq, Debug, Deserialize)]
struct NewtypeStruct(i32);

Expand Down Expand Up @@ -883,6 +886,17 @@ fn test_unit_struct() {
test(UnitStruct, &[Token::UnitStruct { name: "UnitStruct" }]);
}

#[test]
fn test_generic_unit_struct() {
test(GenericUnitStruct::<8>, &[Token::Unit]);
test(
GenericUnitStruct::<8>,
&[Token::UnitStruct {
name: "GenericUnitStruct",
}],
);
}

#[test]
fn test_newtype_struct() {
test(
Expand Down

0 comments on commit 89c8d85

Please sign in to comment.