Skip to content

Commit

Permalink
Fix MaxEncodedLen derive macro for enum with skipped variant (#622)
Browse files Browse the repository at this point in the history
* fix enum skip variant max encoded len

* trigger CI

* trigger CI

This reverts commit 40f632b90663e49ef79b1d19d054c672d46b22d5.

* fmt

* fix warnings
  • Loading branch information
gui1117 authored Aug 23, 2024
1 parent bc65979 commit 1dba1fa
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
15 changes: 9 additions & 6 deletions derive/src/max_encoded_len.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,15 @@ fn data_length_expr(data: &Data, crate_path: &syn::Path) -> proc_macro2::TokenSt
//
// Each variant expression's sum is computed the way an equivalent struct's would be.

let expansion = data.variants.iter().map(|variant| {
let variant_expression = fields_length_expr(&variant.fields, crate_path);
quote! {
.max(#variant_expression)
}
});
let expansion =
data.variants.iter().filter(|variant| !should_skip(&variant.attrs)).map(
|variant| {
let variant_expression = fields_length_expr(&variant.fields, crate_path);
quote! {
.max(#variant_expression)
}
},
);

quote! {
0_usize #( #expansion )* .saturating_add(1)
Expand Down
38 changes: 38 additions & 0 deletions tests/max_encoded_len.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,41 @@ fn skip_type_params() {

assert_eq!(SomeData::<u32, SomeStruct>::max_encoded_len(), 4);
}

#[test]
fn skip_enum_struct_test() {
#[derive(Default)]
struct NoCodecType;

struct NoCodecNoDefaultType;

#[derive(Encode, Decode, MaxEncodedLen)]
enum Enum<T = NoCodecType, S = NoCodecNoDefaultType> {
#[codec(skip)]
A(S),
B {
#[codec(skip)]
_b1: T,
b2: u32,
},
C(#[codec(skip)] T, u32),
}

#[derive(Encode, Decode, MaxEncodedLen)]
struct StructNamed<T = NoCodecType> {
#[codec(skip)]
a: T,
b: u32,
}

#[derive(Encode, Decode, MaxEncodedLen)]
struct StructUnnamed<T = NoCodecType>(#[codec(skip)] T, u32);

assert_eq!(Enum::<NoCodecType, NoCodecNoDefaultType>::max_encoded_len(), 5);
assert_eq!(StructNamed::<NoCodecType>::max_encoded_len(), 4);
assert_eq!(StructUnnamed::<NoCodecType>::max_encoded_len(), 4);

// Use the fields to avoid unused warnings.
let _ = Enum::<NoCodecType, NoCodecNoDefaultType>::A(NoCodecNoDefaultType);
let _ = StructNamed::<NoCodecType> { a: NoCodecType, b: 0 }.a;
}

0 comments on commit 1dba1fa

Please sign in to comment.