1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
extern crate proc_macro;
use quote::quote;
use syn::parse_macro_input;
#[proc_macro_attribute]
pub fn state(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let item_struct = parse_macro_input!(input as syn::ItemStruct);
let struct_ident = &item_struct.ident;
let is_zero_copy = args.to_string() == "zero_copy";
let size_override = {
if args.is_empty() {
quote! {
impl anchor_lang::__private::AccountSize for #struct_ident {
fn size(&self) -> std::result::Result<u64, anchor_lang::solana_program::program_error::ProgramError> {
Ok(8 + self
.try_to_vec()
.map_err(|_| anchor_lang::__private::ErrorCode::AccountDidNotSerialize)?
.len() as u64)
}
}
}
} else {
if is_zero_copy {
quote! {
impl anchor_lang::__private::AccountSize for #struct_ident {
fn size(&self) -> std::result::Result<u64, anchor_lang::solana_program::program_error::ProgramError> {
let len = anchor_lang::__private::bytemuck::bytes_of(self).len() as u64;
Ok(8 + len)
}
}
}
} else {
let size = proc_macro2::TokenStream::from(args.clone());
quote! {
impl anchor_lang::__private::AccountSize for #struct_ident {
fn size(&self) -> std::result::Result<u64, anchor_lang::solana_program::program_error::ProgramError> {
Ok(#size)
}
}
}
}
}
};
let attribute = match is_zero_copy {
false => quote! {#[account("state")]},
true => quote! {#[account("state", zero_copy)]},
};
proc_macro::TokenStream::from(quote! {
#attribute
#item_struct
#size_override
})
}