Skip to content

Commit

Permalink
Avoid Vec allocation in Event::data derived implementation
Browse files Browse the repository at this point in the history
Rather than creating a Vec with the discriminant, then another where
the event object is serialised, to finally merge the two, construct
a temporary `(discriminant, event)` tuple which can be serialised
by borsh in one go.  This avoids the temporary vector allocation and
also simplifies the code.

While at it, make other minor refactoring to the event derive function.
  • Loading branch information
mina86 committed Oct 31, 2023
1 parent 150fc3e commit 88e121f
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions lang/attribute/event/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,9 @@ pub fn event(
let event_name = &event_strct.ident;

let discriminator: proc_macro2::TokenStream = {
let discriminator_preimage = format!("event:{event_name}");
let mut discriminator = [0u8; 8];
discriminator.copy_from_slice(
&anchor_syn::hash::hash(discriminator_preimage.as_bytes()).to_bytes()[..8],
);
format!("{discriminator:?}").parse().unwrap()
let discriminator_preimage = format!("event:{event_name}").into_bytes();
let discriminator = anchor_syn::hash::hash(&discriminator_preimage);
format!("{:?}", &discriminator.0[..8]).parse().unwrap()
};

let ret = quote! {
Expand All @@ -35,9 +32,7 @@ pub fn event(

impl anchor_lang::Event for #event_name {
fn data(&self) -> Vec<u8> {
let mut d = #discriminator.to_vec();
d.append(&mut self.try_to_vec().unwrap());
d
(Self::DISCRIMINATOR, self).try_to_vec().unwrap()
}
}

Expand All @@ -47,13 +42,13 @@ pub fn event(
};

#[cfg(feature = "idl-build")]
{
let ret = {
let idl_build = anchor_syn::idl::build::gen_idl_print_function_for_event(&event_strct);
return proc_macro::TokenStream::from(quote! {
quote! {
#ret
#idl_build
});
}
}
};

#[allow(unreachable_code)]
proc_macro::TokenStream::from(ret)
Expand Down

0 comments on commit 88e121f

Please sign in to comment.