allow Deserialize derive to handle generic unit structs

This commit is contained in:
Baptiste de Montangon 2023-07-10 01:31:40 +02:00
parent 6502838f27
commit 89c8d85de9
2 changed files with 31 additions and 4 deletions

View File

@ -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)
@ -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)
}
}

View File

@ -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);
@ -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(