Skip to content

Commit

Permalink
Add account(zero_copy(safe_bytemuck_derives)) feature.
Browse files Browse the repository at this point in the history
The default account(zero_copy) feature unsafe impls the bytemuck traits

The new one derives it instead, which runs desired sanity checks like
"struct has no padding".
  • Loading branch information
ckamm committed Dec 26, 2022
1 parent a97d04a commit 7e2a370
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions lang/attribute/account/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub fn account(
) -> proc_macro::TokenStream {
let mut namespace = "".to_string();
let mut is_zero_copy = false;
let mut safe_bytemuck = false;
let args_str = args.to_string();
let args: Vec<&str> = args_str.split(',').collect();
if args.len() > 2 {
Expand All @@ -80,6 +81,10 @@ pub fn account(
.collect();
if ns == "zero_copy" {
is_zero_copy = true;
safe_bytemuck = false;
} else if ns == "zero_copy(safe_bytemuck_derives)" {
is_zero_copy = true;
safe_bytemuck = true;
} else {
namespace = ns;
}
Expand Down Expand Up @@ -123,16 +128,37 @@ pub fn account(
}
};

let unsafe_bytemuck_impl = {
if !safe_bytemuck {
quote! {
#[automatically_derived]
unsafe impl #impl_gen anchor_lang::__private::bytemuck::Pod for #account_name #type_gen #where_clause {}
#[automatically_derived]
unsafe impl #impl_gen anchor_lang::__private::bytemuck::Zeroable for #account_name #type_gen #where_clause {}
}
} else {
quote! {}
}
};

let safe_bytemuck_derives = {
if safe_bytemuck {
quote! {
#[derive(bytemuck::Pod, bytemuck::Zeroable)]
}
} else {
quote! {}
}
};

proc_macro::TokenStream::from({
if is_zero_copy {
quote! {
#[zero_copy]
#safe_bytemuck_derives
#account_strct

#[automatically_derived]
unsafe impl #impl_gen anchor_lang::__private::bytemuck::Pod for #account_name #type_gen #where_clause {}
#[automatically_derived]
unsafe impl #impl_gen anchor_lang::__private::bytemuck::Zeroable for #account_name #type_gen #where_clause {}
#unsafe_bytemuck_impl

#[automatically_derived]
impl #impl_gen anchor_lang::ZeroCopy for #account_name #type_gen #where_clause {}
Expand Down

0 comments on commit 7e2a370

Please sign in to comment.