Skip to content

Commit

Permalink
Delegate newtype EOC (#163)
Browse files Browse the repository at this point in the history
* making newtype delegation work for complex inner types

* comment the test
  • Loading branch information
orthecreedence committed Sep 28, 2023
1 parent f4e692b commit aea08d0
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 11 deletions.
17 changes: 12 additions & 5 deletions macros/src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,18 @@ pub fn derive_struct_impl(
}
} else {
quote! {
<#ty as #crate_root::Decode>::decode_with_tag_and_constraints(
decoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints),
).map(Self)
match tag {
#crate_root::Tag::EOC => {
Ok(Self(<#ty>::decode(decoder)?))
}
_ => {
<#ty as #crate_root::Decode>::decode_with_tag_and_constraints(
decoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints),
).map(Self)
}
}
}
}
} else if config.set {
Expand Down
19 changes: 13 additions & 6 deletions macros/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,19 @@ pub fn derive_struct_impl(
}
} else {
quote!(
<#ty as #crate_root::Encode>::encode_with_tag_and_constraints(
&self.0,
encoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints)
)
match tag {
#crate_root::Tag::EOC => {
self.0.encode(encoder)
}
_ => {
<#ty as #crate_root::Encode>::encode_with_tag_and_constraints(
&self.0,
encoder,
tag,
<#ty as #crate_root::AsnType>::CONSTRAINTS.override_constraints(constraints)
)
}
}
)
}
} else {
Expand Down
27 changes: 27 additions & 0 deletions tests/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,33 @@ pub struct BasicConstraints {
pub path_len_constraint: Option<Integer>,
}

// This test makes sure that Newtype3(Newtype2(Newtype1(T))) results in serializing
// as T when using the #[rasn(delegate)] attribute when T is a non-universal type.
#[test]
fn delegated_newtype_wrapping() {
#[derive(AsnType, Debug, Decode, Encode, PartialEq)]
#[rasn(choice)]
enum Hash {
#[rasn(tag(explicit(0)))]
Sha256(String),
}

#[derive(AsnType, Debug, Decode, Encode, PartialEq)]
#[rasn(delegate)]
struct TransactionID(Hash);

#[derive(AsnType, Debug, Decode, Encode, PartialEq)]
#[rasn(delegate)]
struct PolicyID(TransactionID);

let policy_id1 = PolicyID(TransactionID(Hash::Sha256("abcdef".into())));

let ser = rasn::der::encode(&policy_id1).unwrap();
assert_eq!(&ser[..], &[160, 8, 12, 6, 97, 98, 99, 100, 101, 102]);
let policy_id2: PolicyID = rasn::der::decode(&ser[..]).unwrap();
assert_eq!(policy_id1, policy_id2);
}

// This test will fail to compile if `Result` is used in the derive/proc macros instead of
// `core::result::Result`
#[test]
Expand Down

0 comments on commit aea08d0

Please sign in to comment.