Skip to content

Instantly share code, notes, and snippets.

@adrena-orex
Created January 1, 2025 12:17
Show Gist options
  • Select an option

  • Save adrena-orex/99992c9a7679d8d59298271ea097cc6d to your computer and use it in GitHub Desktop.

Select an option

Save adrena-orex/99992c9a7679d8d59298271ea097cc6d to your computer and use it in GitHub Desktop.
Display how to load a zero_copy account in rust integration test
let position_account = utils::get_zero_copy_account::<Position>(program_test_ctx, *position_pda).await;
fn align_buffer(data: &[u8], align_to: usize) -> Vec<u8> {
let layout = Layout::from_size_align(data.len(), align_to).expect("Invalid layout");
unsafe {
let aligned_buf = std::alloc::alloc(layout);
std::ptr::copy_nonoverlapping(data.as_ptr(), aligned_buf, data.len());
Vec::from_raw_parts(aligned_buf, data.len(), data.len())
}
}
pub async fn get_zero_copy_account<T: bytemuck::Pod>(
program_test_ctx: &RwLock<ProgramTestContext>,
key: Pubkey,
) -> T {
let mut ctx = program_test_ctx.write().await;
let banks_client = &mut ctx.banks_client;
let account = banks_client.get_account(key).await.unwrap().unwrap();
// Have to have the data to be of the same alignment as the struct
let data = &account.data.clone()[8..];
let aligned_data = align_buffer(data, std::mem::align_of::<T>());
*bytemuck::try_from_bytes::<T>(aligned_data.as_slice()).unwrap()
}
pub async fn try_get_zero_copy_account<T: bytemuck::Pod>(
program_test_ctx: &RwLock<ProgramTestContext>,
key: Pubkey,
) -> Option<T> {
let mut ctx = program_test_ctx.write().await;
let banks_client = &mut ctx.banks_client;
let account = banks_client.get_account(key).await.unwrap();
// Have to have the data to be of the same alignment as the struct
let data = &account.as_ref()?.data.clone()[8..];
let aligned_data = align_buffer(data, std::mem::align_of::<T>());
let tried = bytemuck::try_from_bytes::<T>(aligned_data.as_slice());
if let Ok(tried) = tried {
Some(*tried)
} else {
None
}
}
#[account(zero_copy)]
#[derive(Default, Debug)]
#[repr(C)]
pub struct Position {
pub bump: u8,
pub side: u8,
pub _padding: [u8; 6],
pub owner: Pubkey,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment