Skip to content

Commit

Permalink
Merge pull request #3861 from paulhauner/ssz-transparent-4844
Browse files Browse the repository at this point in the history
Allow leading skipped tuple fields
  • Loading branch information
realbigsean authored Jan 9, 2023
2 parents ba410c3 + 026b5af commit 680a5c7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
14 changes: 9 additions & 5 deletions consensus/ssz_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ use darling::{FromDeriveInput, FromMeta};
use proc_macro::TokenStream;
use quote::quote;
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
/// extensions).
Expand Down Expand Up @@ -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()
.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");

// 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 {
quote! {
impl #impl_generics ssz::Encode for #name #ty_generics #where_clause {
Expand Down Expand Up @@ -479,11 +483,11 @@ fn ssz_encode_derive_struct_transparent(
}

fn ssz_bytes_len(&self) -> usize {
self.0.ssz_bytes_len()
self.#index.ssz_bytes_len()
}

fn ssz_append(&self, buf: &mut Vec<u8>) {
self.0.ssz_append(buf)
self.#index.ssz_append(buf)
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions consensus/ssz_derive/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,24 @@ fn transparent_struct_newtype_skipped_field() {
&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(),
);
}

0 comments on commit 680a5c7

Please sign in to comment.