serial: Port to syn2, and enforce enums to be max u8 for FFI compat.

This commit is contained in:
parazyd
2023-07-10 15:18:38 +02:00
parent 835935eaac
commit eae28e888d
3 changed files with 24 additions and 19 deletions

View File

@@ -82,7 +82,7 @@ fn named_fields(
);
variant_body.extend(quote! {
#field_ident.encode(writer)?;
len += #field_ident.encode(&mut s)?;
})
}
}
@@ -125,7 +125,7 @@ fn unnamed_fields(
);
variant_body.extend(quote! {
#field_ident.encode(writer)?;
len += #field_ident.encode(&mut s)?;
})
}
}
@@ -192,16 +192,16 @@ pub fn enum_ser(input: &ItemEnum, cratename: Ident) -> syn::Result<TokenStream>
#all_variants_idx_body
};
let mut len = 0;
let bytes = variant_idx.to_le_bytes();
writer.write_all(&bytes)?;
s.write_all(&bytes)?;
len += bytes.len();
match self {
#fields_body
}
Ok(bytes.len())
Ok(len)
}
}
})
@@ -214,6 +214,7 @@ pub fn enum_de(input: &ItemEnum, cratename: Ident) -> syn::Result<TokenStream> {
|| WhereClause { where_token: Default::default(), predicates: Default::default() },
Clone::clone,
);
let init_method = contains_initialize_with(&input.attrs);
let mut variant_arms = TokenStream::new();
let discriminants = discriminant_map(&input.variants);
@@ -284,14 +285,18 @@ pub fn enum_de(input: &ItemEnum, cratename: Ident) -> syn::Result<TokenStream> {
Ok(quote! {
impl #impl_generics #cratename::Decodable for #name #ty_generics #where_clause {
fn decode<D: std::io::Read>(mut d: D) -> ::core::result::Result<Self, std::io::Error> {
let variant_tag: u8 = #cratename::Decodable::decode(&mut d)?;
let mut return_value =
#variant_arms {
let msg = format!("Unexpected variant index: {:?}", variant_idx);
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg));
}
};
#init
Ok(return_value)
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Unexpected variant tag: {:?}", variant_tag),
))
};
#init
Ok(return_value)
}
}
})
}

View File

@@ -13,7 +13,7 @@ proc-macro = true
[dependencies]
proc-macro-crate = "1.3.1"
proc-macro2 = "1.0.63"
syn = {version = "1.0.109", features = ["full", "fold"]}
proc-macro2 = "1.0.64"
syn = {version = "2.0.25", features = ["full", "fold"]}
darkfi-derive-internal = {version = "0.4.1", path = "../derive-internal"}

View File

@@ -861,7 +861,7 @@ mod tests {
First = 0x01,
Second = 0x03,
Third = 0xf1,
Fourth = 0xfefe,
Fourth = 0xfe,
}
#[test]
@@ -877,10 +877,10 @@ mod tests {
let second = serialize(&TestEnum1::Second);
let third = serialize(&TestEnum1::Third);
let fourth = serialize(&TestEnum1::Fourth);
assert_eq!(first, [0]);
assert_eq!(second, [1]);
assert_eq!(third, [2]);
assert_eq!(fourth, [3]);
assert_eq!(first, [0x01]);
assert_eq!(second, [0x03]);
assert_eq!(third, [0xf1]);
assert_eq!(fourth, [0xfe]);
}
#[derive(Debug, PartialEq, SerialEncodable, SerialDecodable)]