Merge pull request #3861 from paulhauner/ssz-transparent-4844

Allow leading skipped tuple fields
This commit is contained in:
realbigsean 2023-01-09 09:50:00 -05:00 committed by GitHub
commit 680a5c7fc8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 5 deletions

View File

@ -147,7 +147,7 @@ use darling::{FromDeriveInput, FromMeta};
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use std::convert::TryInto; use std::convert::TryInto;
use syn::{parse_macro_input, DataEnum, DataStruct, DeriveInput, Ident}; use syn::{parse_macro_input, DataEnum, DataStruct, DeriveInput, Ident, Index};
/// The highest possible union selector value (higher values are reserved for backwards compatible /// The highest possible union selector value (higher values are reserved for backwards compatible
/// extensions). /// extensions).
@ -442,11 +442,15 @@ fn ssz_encode_derive_struct_transparent(
); );
} }
let (ty, ident, _field_opts) = ssz_fields let (index, (ty, ident, _field_opts)) = ssz_fields
.iter() .iter()
.find(|(_, _, field_opts)| !field_opts.skip_deserializing) .enumerate()
.find(|(_, (_, _, field_opts))| !field_opts.skip_deserializing)
.expect("\"transparent\" struct must have at least one non-skipped field"); .expect("\"transparent\" struct must have at least one non-skipped field");
// Remove the `_usize` suffix from the value to avoid a compiler warning.
let index = Index::from(index);
let output = if let Some(field_name) = ident { let output = if let Some(field_name) = ident {
quote! { quote! {
impl #impl_generics ssz::Encode for #name #ty_generics #where_clause { impl #impl_generics ssz::Encode for #name #ty_generics #where_clause {
@ -479,11 +483,11 @@ fn ssz_encode_derive_struct_transparent(
} }
fn ssz_bytes_len(&self) -> usize { fn ssz_bytes_len(&self) -> usize {
self.0.ssz_bytes_len() self.#index.ssz_bytes_len()
} }
fn ssz_append(&self, buf: &mut Vec<u8>) { fn ssz_append(&self, buf: &mut Vec<u8>) {
self.0.ssz_append(buf) self.#index.ssz_append(buf)
} }
} }
} }

View File

@ -213,3 +213,24 @@ fn transparent_struct_newtype_skipped_field() {
&vec![42_u8].as_ssz_bytes(), &vec![42_u8].as_ssz_bytes(),
); );
} }
#[derive(PartialEq, Debug, Encode, Decode)]
#[ssz(struct_behaviour = "transparent")]
struct TransparentStructNewTypeSkippedFieldReverse(
#[ssz(skip_serializing, skip_deserializing)] PhantomData<u64>,
Vec<u8>,
);
impl TransparentStructNewTypeSkippedFieldReverse {
fn new(inner: Vec<u8>) -> Self {
Self(PhantomData, inner)
}
}
#[test]
fn transparent_struct_newtype_skipped_field_reverse() {
assert_encode_decode(
&TransparentStructNewTypeSkippedFieldReverse::new(vec![42_u8]),
&vec![42_u8].as_ssz_bytes(),
);
}