Skip to content

Commit

Permalink
Add try_from macro
Browse files Browse the repository at this point in the history
  • Loading branch information
acheroncrypto committed Jan 12, 2024
1 parent b293663 commit b67c537
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
14 changes: 11 additions & 3 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,9 +393,10 @@ pub mod prelude {
context::Context, context::CpiContext, declare_id, emit, err, error, event, program,
require, require_eq, require_gt, require_gte, require_keys_eq, require_keys_neq,
require_neq, solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source,
system_program::System, zero_copy, AccountDeserialize, AccountSerialize, Accounts,
AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Id, InitSpace, Key,
Lamports, Owner, ProgramData, Result, Space, ToAccountInfo, ToAccountInfos, ToAccountMetas,
system_program::System, try_from, zero_copy, AccountDeserialize, AccountSerialize,
Accounts, AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Id, InitSpace,
Key, Lamports, Owner, ProgramData, Result, Space, ToAccountInfo, ToAccountInfos,
ToAccountMetas,
};
pub use anchor_attribute_error::*;
pub use borsh;
Expand Down Expand Up @@ -727,3 +728,10 @@ macro_rules! source {
}
};
}

#[macro_export]
macro_rules! try_from {
($ty: ty, $acc: expr) => {
<$ty>::try_from(unsafe { core::mem::transmute::<_, &AccountInfo<'info>>($acc.as_ref()) })
};
}
4 changes: 2 additions & 2 deletions tests/misc/programs/try-from/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ pub mod try_from {
Ok(())
}

pub fn try_from(ctx: Context<TryFrom>, field: u8) -> Result<()> {
let my_account = Account::<MyAccount>::try_from(&ctx.accounts.my_account)?;
pub fn try_from<'info>(ctx: Context<TryFrom>, field: u8) -> Result<()> {
let my_account = try_from!(Account::<MyAccount>, ctx.accounts.my_account)?;
msg!("Field: {}", my_account.field);
require_eq!(my_account.field, field);

Expand Down

0 comments on commit b67c537

Please sign in to comment.