lang/syn: Simplify accounts parsing

This commit is contained in:
Armani Ferrante 2021-02-11 15:25:13 +08:00
parent 4980d8ab3f
commit 16c998ab43
No known key found for this signature in database
GPG Key ID: D597A80BCF8E12B7
3 changed files with 24 additions and 52 deletions

View File

@ -322,11 +322,8 @@ pub fn generate_constraint_belongs_to(
f: &Field,
c: &ConstraintBelongsTo,
) -> proc_macro2::TokenStream {
// todo: assert the field type.
let target = c.join_target.clone();
let ident = &f.ident;
// todo: would be nice if target could be an account info object.
quote! {
if &#ident.#target != #target.to_account_info().key {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(1)); // todo: error codes

View File

@ -78,21 +78,6 @@ impl Hash {
Hash(<[u8; HASH_BYTES]>::try_from(hash_slice).unwrap())
}
pub const fn new_from_array(hash_array: [u8; HASH_BYTES]) -> Self {
Self(hash_array)
}
/// unique Hash for tests and benchmarks.
pub fn new_unique() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static I: AtomicU64 = AtomicU64::new(1);
let mut b = [0u8; HASH_BYTES];
let i = I.fetch_add(1, Ordering::Relaxed);
b[0..8].copy_from_slice(&i.to_le_bytes());
Self::new(&b)
}
pub fn to_bytes(self) -> [u8; HASH_BYTES] {
self.0
}
@ -130,10 +115,3 @@ pub fn hashv(vals: &[&[u8]]) -> Hash {
pub fn hash(val: &[u8]) -> Hash {
hashv(&[val])
}
/// Return the hash of the given hash extended with the given value.
pub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {
let mut hash_data = id.as_ref().to_vec();
hash_data.extend_from_slice(val);
hash(&hash_data)
}

View File

@ -6,15 +6,18 @@ use crate::{
pub fn parse(strct: &syn::ItemStruct) -> AccountsStruct {
let fields = match &strct.fields {
syn::Fields::Named(fields) => fields,
syn::Fields::Named(fields) => fields.named.iter().map(parse_account_field).collect(),
_ => panic!("invalid input"),
};
AccountsStruct::new(strct.clone(), fields)
}
let fields: Vec<AccountField> = fields
.named
.iter()
.map(|f: &syn::Field| {
let anchor_attr = {
fn parse_account_field(f: &syn::Field) -> AccountField {
let anchor_attr = parse_account_attr(f);
parse_field(f, anchor_attr)
}
fn parse_account_attr(f: &syn::Field) -> Option<&syn::Attribute> {
let anchor_attrs: Vec<&syn::Attribute> = f
.attrs
.iter()
@ -31,14 +34,8 @@ pub fn parse(strct: &syn::ItemStruct) -> AccountsStruct {
match anchor_attrs.len() {
0 => None,
1 => Some(anchor_attrs[0]),
_ => panic!("invalid syntax: only one account attribute is allowed"),
_ => panic!("Invalid syntax: please specify one account attribute."),
}
};
parse_field(f, anchor_attr)
})
.collect();
AccountsStruct::new(strct.clone(), fields)
}
fn parse_field(f: &syn::Field, anchor: Option<&syn::Attribute>) -> AccountField {