Skip to content

Commit

Permalink
Fix Display proc macro, revert some changes, update test
Browse files Browse the repository at this point in the history
Signed-off-by: Patrik Stas <patrik.stas@absa.africa>
  • Loading branch information
Patrik-Stas committed Nov 29, 2023
1 parent 0565c52 commit 2fb38bc
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 29 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

use crate::{decorators::thread::Thread, misc::NoDecorators, msg_parts::MsgParts};
use crate::{decorators::thread::Thread, msg_parts::MsgParts};

/// https://github.com/hyperledger/aries-rfcs/blob/main/features/0211-route-coordination/README.md#key-list-query
pub type KeylistQuery = MsgParts<KeylistQueryContent, NoDecorators>;
pub type KeylistQuery = MsgParts<KeylistQueryContent>;

#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)]
pub struct KeylistQueryContent {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

use crate::{decorators::thread::Thread, misc::NoDecorators, msg_parts::MsgParts};
use crate::{decorators::thread::Thread, msg_parts::MsgParts};

/// https://github.com/hyperledger/aries-rfcs/blob/main/features/0211-route-coordination/README.md#keylist-update
pub type KeylistUpdate = MsgParts<KeylistUpdateContent, NoDecorators>;
pub type KeylistUpdate = MsgParts<KeylistUpdateContent>;

#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)]
pub struct KeylistUpdateContent {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

use crate::{decorators::thread::Thread, misc::NoDecorators, msg_parts::MsgParts};
use crate::{decorators::thread::Thread, msg_parts::MsgParts};

/// https://github.com/hyperledger/aries-rfcs/blob/main/features/0211-route-coordination/README.md#mediation-request
pub type MediateRequest = MsgParts<MediateRequestContent, NoDecorators>;
pub type MediateRequest = MsgParts<MediateRequestContent>;

#[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)]
pub struct MediateRequestContent {}
Expand Down
5 changes: 2 additions & 3 deletions aries/messages/src/msg_fields/protocols/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ use serde_json::Value;
use typed_builder::TypedBuilder;

use crate::{
misc::{utils::into_msg_with_type, NoDecorators},
msg_parts::MsgParts,
misc::utils::into_msg_with_type, msg_parts::MsgParts,
msg_types::protocols::routing::RoutingTypeV1_0,
};

pub type Forward = MsgParts<ForwardContent, NoDecorators>;
pub type Forward = MsgParts<ForwardContent>;

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder)]
pub struct ForwardContent {
Expand Down
10 changes: 5 additions & 5 deletions aries/messages/src/msg_parts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use display_as_json::Display;
use serde::{Deserialize, Serialize};
// Bind `shared::misc::serde_ignored::SerdeIgnored` type as `NoDecorators`.
use shared::misc::serde_ignored::SerdeIgnored as NoDecorators;
use typed_builder::TypedBuilder;

/// Struct representing a complete message (apart from the `@type` field) as defined in a protocol
Expand All @@ -16,7 +16,7 @@ use typed_builder::TypedBuilder;
/// `~timing`).
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, TypedBuilder, Display)]
#[builder(build_method(vis = "", name = __build))]
pub struct MsgParts<C, D> {
pub struct MsgParts<C, D = NoDecorators> {
/// All standalone messages have an `id` field.
#[serde(rename = "@id")]
pub id: String,
Expand Down Expand Up @@ -81,8 +81,8 @@ pub mod tests {
.content(request_content())
.decorators(RequestDecorators::default())
.build();
let printed = format!("{}", msg);
let expected = r#"{"@id":"test_id","label":"test_request_label","goal_code":"aries.rel.build","goal":"test_goal","did":"","did_doc~attach":{"data":{"json":{"@context":"https://w3id.org/did/v1","authentication":[],"id":"","publicKey":[],"service":[{"id":"did:example:123456789abcdefghi;indy","priority":0,"recipientKeys":[],"routingKeys":[],"serviceEndpoint":"https://dummy.dummy/dummy","type":"IndyAgent"}]}}}}"#;
assert_eq!(expected, printed);
let printed_json = format!("{}", msg);
let parsed_request: Request = serde_json::from_str(&printed_json).unwrap();
assert_eq!(msg, parsed_request);
}
}
40 changes: 25 additions & 15 deletions misc/display_as_json/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,35 @@ fn impl_display(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let generics = &ast.generics;

// Create new where clause with Serialize bounds for each generic type
let where_clause = generics.params.iter().map(|param| {
let ident = match param {
syn::GenericParam::Type(type_param) => &type_param.ident,
_ => return quote!(), // Skip non-type parameters
};
quote! { #ident: serde::Serialize }
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

// For each of the generics parameter G, we prepare addition trait bound "G: serde::Serialize"
let serialize_bounds = generics.params.iter().filter_map(|param| {
match param {
syn::GenericParam::Type(type_param) => {
let ident = &type_param.ident;
Some(quote! { #ident: serde::Serialize })
},
_ => None, // Skip non-type parameters, eg lifetimes
}
});

// Combine the original where clause with additional bounds we prepared above
// See quote! macro docs for more info on the #() syntax https://docs.rs/quote/1.0.33/quote/macro.quote.html
let combined_where_clause = if where_clause.is_none() {
quote! { where #(#serialize_bounds),* }
} else {
quote! { #where_clause, #(#serialize_bounds),* }
};

// Generate the actual impl
let gen = quote! {
impl #generics std::fmt::Display for #name #generics
where
#(#where_clause),*
{
impl #impl_generics std::fmt::Display for #name #ty_generics #combined_where_clause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let json = serde_json::to_string(self).unwrap_or_else(|e| {
format!("Error serializing {}: {}", stringify!(#name), e)
});
write!(f, "{}", json)
match serde_json::to_string(self) {
Ok(json) => write!(f, "{}", json),
Err(e) => write!(f, "Error serializing {}: {}", stringify!(#name), e),
}
}
}
};
Expand Down

0 comments on commit 2fb38bc

Please sign in to comment.